index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/test/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/test/java/javax/mail/event/AllEventTests.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* @version $Rev$ $Date$
*/
public class AllEventTests {
public static Test suite() {
final TestSuite suite = new TestSuite("Test for javax.mail.event");
//$JUnit-BEGIN$
suite.addTest(new TestSuite(ConnectionEventTest.class));
suite.addTest(new TestSuite(FolderEventTest.class));
suite.addTest(new TestSuite(MessageChangedEventTest.class));
suite.addTest(new TestSuite(StoreEventTest.class));
suite.addTest(new TestSuite(MessageCountEventTest.class));
suite.addTest(new TestSuite(TransportEventTest.class));
//$JUnit-END$
return suite;
}
}
| 1,900 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/test/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/test/java/javax/mail/event/FolderEventTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import junit.framework.TestCase;
/**
* @version $Rev$ $Date$
*/
public class FolderEventTest extends TestCase {
public FolderEventTest(final String name) {
super(name);
}
public void testEvent() {
doEventTests(FolderEvent.CREATED);
doEventTests(FolderEvent.RENAMED);
doEventTests(FolderEvent.DELETED);
}
private void doEventTests(final int type) {
final FolderEvent event = new FolderEvent(this, null, type);
assertEquals(this, event.getSource());
assertEquals(type, event.getType());
final FolderListenerTest listener = new FolderListenerTest();
event.dispatch(listener);
assertEquals("Unexpcted method dispatched", type, listener.getState());
}
public static class FolderListenerTest implements FolderListener {
private int state = 0;
public void folderCreated(final FolderEvent event) {
if (state != 0) {
fail("Recycled Listener");
}
state = FolderEvent.CREATED;
}
public void folderDeleted(final FolderEvent event) {
if (state != 0) {
fail("Recycled Listener");
}
state = FolderEvent.DELETED;
}
public void folderRenamed(final FolderEvent event) {
if (state != 0) {
fail("Recycled Listener");
}
state = FolderEvent.RENAMED;
}
public int getState() {
return state;
}
}
}
| 1,901 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/test/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/test/java/javax/mail/event/MessageCountEventTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import javax.mail.Folder;
import javax.mail.TestData;
import junit.framework.TestCase;
/**
* @version $Rev$ $Date$
*/
public class MessageCountEventTest extends TestCase {
public MessageCountEventTest(final String name) {
super(name);
}
public void testEvent() {
doEventTests(MessageCountEvent.ADDED);
doEventTests(MessageCountEvent.REMOVED);
try {
doEventTests(-12345);
fail("Expected exception due to invalid type -12345");
} catch (final IllegalArgumentException e) {
}
}
private void doEventTests(final int type) {
final Folder folder = TestData.getTestFolder();
final MessageCountEvent event =
new MessageCountEvent(folder, type, false, null);
assertEquals(folder, event.getSource());
assertEquals(type, event.getType());
final MessageCountListenerTest listener = new MessageCountListenerTest();
event.dispatch(listener);
assertEquals("Unexpcted method dispatched", type, listener.getState());
}
public static class MessageCountListenerTest
implements MessageCountListener {
private int state = 0;
public void messagesAdded(final MessageCountEvent event) {
if (state != 0) {
fail("Recycled Listener");
}
state = MessageCountEvent.ADDED;
}
public void messagesRemoved(final MessageCountEvent event) {
if (state != 0) {
fail("Recycled Listener");
}
state = MessageCountEvent.REMOVED;
}
public int getState() {
return state;
}
}
}
| 1,902 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/test/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/test/java/javax/mail/event/ConnectionEventTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import junit.framework.TestCase;
/**
* @version $Rev$ $Date$
*/
public class ConnectionEventTest extends TestCase {
public static class ConnectionListenerTest implements ConnectionListener {
private int state = 0;
public void closed(final ConnectionEvent event) {
if (state != 0) {
fail("Recycled ConnectionListener");
}
state = ConnectionEvent.CLOSED;
}
public void disconnected(final ConnectionEvent event) {
if (state != 0) {
fail("Recycled ConnectionListener");
}
state = ConnectionEvent.DISCONNECTED;
}
public int getState() {
return state;
}
public void opened(final ConnectionEvent event) {
if (state != 0) {
fail("Recycled ConnectionListener");
}
state = ConnectionEvent.OPENED;
}
}
public ConnectionEventTest(final String name) {
super(name);
}
private void doEventTests(final int type) {
final ConnectionEvent event = new ConnectionEvent(this, type);
assertEquals(this, event.getSource());
assertEquals(type, event.getType());
final ConnectionListenerTest listener = new ConnectionListenerTest();
event.dispatch(listener);
assertEquals("Unexpcted method dispatched", type, listener.getState());
}
public void testEvent() {
doEventTests(ConnectionEvent.CLOSED);
doEventTests(ConnectionEvent.OPENED);
doEventTests(ConnectionEvent.DISCONNECTED);
}
}
| 1,903 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/MailProviderBundleTrackerCustomizer.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;
import org.osgi.util.tracker.BundleTrackerCustomizer;
public class MailProviderBundleTrackerCustomizer implements BundleTrackerCustomizer {
// our base Activator (used as a service source)
private final Activator activator;
// the bundle hosting the activation code
private final Bundle activationBundle;
public MailProviderBundleTrackerCustomizer(final Activator a, final Bundle b) {
activator = a;
activationBundle = b;
}
/**
* Handle the activation of a new bundle.
*
* @param bundle The source bundle.
* @param event The bundle event information.
*
* @return A return object.
*/
public Object addingBundle(final Bundle bundle, final BundleEvent event) {
if (bundle.equals(activationBundle)) {
return null;
}
return MailProviderRegistry.registerBundle(bundle);
}
public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Object object) {
// this will update for the new bundle
MailProviderRegistry.registerBundle(bundle);
}
public void removedBundle(final Bundle bundle, final BundleEvent event, final Object object) {
MailProviderRegistry.unregisterBundle(bundle);
}
private void log(final int level, final String message) {
activator.log(level, message);
}
private void log(final int level, final String message, final Throwable th) {
activator.log(level, message, th);
}
}
| 1,904 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/Activator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail;
import java.util.ArrayList;
import java.util.List;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.BundleTracker;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
/**
* The activator that starts and manages the tracking of
* JAF activation command maps
*/
public class Activator extends org.apache.geronimo.osgi.locator.Activator {
// tracker to watch for bundle updates
protected BundleTracker bt;
// service tracker for a logging service
protected ServiceTracker lst;
// an array of all active logging services.
protected List<LogService> logServices = new ArrayList<LogService>();
@Override
public synchronized void start(final BundleContext context) throws Exception {
super.start(context);
lst = new LogServiceTracker(context, LogService.class.getName(), null);
lst.open();
bt = new BundleTracker(context, Bundle.ACTIVE, new MailProviderBundleTrackerCustomizer(this, context.getBundle()));
bt.open();
}
@Override
public synchronized void stop(final BundleContext context) throws Exception {
bt.close();
lst.close();
super.stop(context);
}
void log(final int level, final String message) {
synchronized (logServices) {
for (final LogService log : logServices) {
log.log(level, message);
}
}
}
void log(final int level, final String message, final Throwable th) {
synchronized (logServices) {
for (final LogService log : logServices) {
log.log(level, message, th);
}
}
}
private final class LogServiceTracker extends ServiceTracker {
private LogServiceTracker(final BundleContext context, final String clazz,
final ServiceTrackerCustomizer customizer) {
super(context, clazz, customizer);
}
@Override
public Object addingService(final ServiceReference reference) {
final Object svc = super.addingService(reference);
if (svc instanceof LogService) {
synchronized (logServices) {
logServices.add((LogService) svc);
}
}
return svc;
}
@Override
public void removedService(final ServiceReference reference, final Object service) {
synchronized (logServices) {
logServices.remove(service);
}
super.removedService(reference, service);
}
}
}
| 1,905 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/MailProviderRegistry.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail;
import java.net.URL;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.osgi.framework.Bundle;
/**
* The activator that starts and manages the tracking of
* JAF activation command maps
*/
public class MailProviderRegistry {
// a list of all active mail provider config files
static ConcurrentMap<Long, URL> providers = new ConcurrentHashMap<Long, URL>();
// a list of all active default provider config files
static ConcurrentMap<Long, URL> defaultProviders = new ConcurrentHashMap<Long, URL>();
/**
* Perform the check for an existing mailcap file when
* a bundle is registered.
*
* @param bundle The potential provider bundle.
*
* @return A URL object if this bundle contains a mailcap file.
*/
static Object registerBundle(final Bundle bundle) {
// potential tracker return result
Object result = null;
// a given bundle might have a javamail.providers definition and/or a
// default providers definition.
URL url = bundle.getResource("META-INF/javamail.providers");
if (url != null) {
providers.put(bundle.getBundleId(), url);
// this indicates our interest
result = url;
}
url = bundle.getResource("META-INF/javamail.default.providers");
if (url != null) {
defaultProviders.put(bundle.getBundleId(), url);
// this indicates our interest
result = url;
}
// the url marks our interest in additional activity for this
// bundle.
return result;
}
/**
* Remove a bundle from our potential mailcap pool.
*
* @param bundle The potential source bundle.
*/
static void unregisterBundle(final Bundle bundle) {
// remove these items
providers.remove(bundle.getBundleId());
defaultProviders.remove(bundle.getBundleId());
}
/**
* Retrieve any located provider definitions
* from bundles.
*
* @return A collection of the provider definition file
* URLs.
*/
public static Collection<URL> getProviders() {
return providers.values();
}
/**
* Retrieve any located default provider definitions
* from bundles.
*
* @return A collection of the default provider definition file
* URLs.
*/
public static Collection<URL> getDefaultProviders() {
return defaultProviders.values();
}
}
| 1,906 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/ASCIIUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Set of utility classes for handling common encoding-related
* manipulations.
*/
public class ASCIIUtil {
/**
* Test to see if this string contains only US-ASCII (i.e., 7-bit
* ASCII) charactes.
*
* @param s The test string.
*
* @return true if this is a valid 7-bit ASCII encoding, false if it
* contains any non-US ASCII characters.
*/
static public boolean isAscii(final String s) {
for (int i = 0; i < s.length(); i++) {
if (!isAscii(s.charAt(i))) {
return false;
}
}
return true;
}
/**
* Test to see if a given character can be considered "valid" ASCII.
* The excluded characters are the control characters less than
* 32, 8-bit characters greater than 127, EXCEPT the CR, LF and
* tab characters ARE considered value (all less than 32).
*
* @param ch The test character.
*
* @return true if this character meets the "ascii-ness" criteria, false
* otherwise.
*/
static public boolean isAscii(final int ch) {
// these are explicitly considered valid.
if (ch == '\r' || ch == '\n' || ch == '\t') {
return true;
}
// anything else outside the range is just plain wrong.
if (ch >= 127 || ch < 32) {
return false;
}
return true;
}
/**
* Examine a stream of text and make a judgement on what encoding
* type should be used for the text. Ideally, we want to use 7bit
* encoding to determine this, but we may need to use either quoted-printable
* or base64. The choice is made on the ratio of 7-bit characters to non-7bit.
*
* @param content An input stream for the content we're examining.
*
* @exception IOException
*/
public static String getTextTransferEncoding(final InputStream content) throws IOException {
// for efficiency, we'll read in blocks.
final BufferedInputStream in = new BufferedInputStream(content, 4096);
int span = 0; // span of characters without a line break.
boolean containsLongLines = false;
int asciiChars = 0;
int nonAsciiChars = 0;
while (true) {
final int ch = in.read();
// if we hit an EOF here, go decide what type we've actually found.
if (ch == -1) {
break;
}
// we found a linebreak. Reset the line length counters on either one. We don't
// really need to validate here.
if (ch == '\n' || ch == '\r') {
// hit a line end, reset our line length counter
span = 0;
}
else {
span++;
// the text has long lines, we can't transfer this as unencoded text.
if (span > 998) {
containsLongLines = true;
}
// non-ascii character, we have to transfer this in binary.
if (!isAscii(ch)) {
nonAsciiChars++;
}
else {
asciiChars++;
}
}
}
// looking good so far, only valid chars here.
if (nonAsciiChars == 0) {
// does this contain long text lines? We need to use a Q-P encoding which will
// be only slightly longer, but handles folding the longer lines.
if (containsLongLines) {
return "quoted-printable";
}
else {
// ideal! Easiest one to handle.
return "7bit";
}
}
else {
// mostly characters requiring encoding? Base64 is our best bet.
if (nonAsciiChars > asciiChars) {
return "base64";
}
else {
// Q-P encoding will use fewer bytes than the full Base64.
return "quoted-printable";
}
}
}
/**
* Examine a stream of text and make a judgement on what encoding
* type should be used for the text. Ideally, we want to use 7bit
* encoding to determine this, but we may need to use either quoted-printable
* or base64. The choice is made on the ratio of 7-bit characters to non-7bit.
*
* @param content A string for the content we're examining.
*/
public static String getTextTransferEncoding(final String content) {
int asciiChars = 0;
int nonAsciiChars = 0;
for (int i = 0; i < content.length(); i++) {
final int ch = content.charAt(i);
// non-ascii character, we have to transfer this in binary.
if (!isAscii(ch)) {
nonAsciiChars++;
}
else {
asciiChars++;
}
}
// looking good so far, only valid chars here.
if (nonAsciiChars == 0) {
// ideal! Easiest one to handle.
return "7bit";
}
else {
// mostly characters requiring encoding? Base64 is our best bet.
if (nonAsciiChars > asciiChars) {
return "base64";
}
else {
// Q-P encoding will use fewer bytes than the full Base64.
return "quoted-printable";
}
}
}
/**
* Determine if the transfer encoding looks like it might be
* valid ascii text, and thus transferable as 7bit code. In
* order for this to be true, all characters must be valid
* 7-bit ASCII code AND all line breaks must be properly formed
* (JUST '\r\n' sequences). 7-bit transfers also
* typically have a line limit of 1000 bytes (998 + the CRLF), so any
* stretch of charactes longer than that will also force Base64 encoding.
*
* @param content An input stream for the content we're examining.
*
* @exception IOException
*/
public static String getBinaryTransferEncoding(final InputStream content) throws IOException {
// for efficiency, we'll read in blocks.
final BufferedInputStream in = new BufferedInputStream(content, 4096);
int previousChar = 0;
int span = 0; // span of characters without a line break.
while (true) {
final int ch = in.read();
// if we hit an EOF here, we've only found valid text so far, so we can transfer this as
// 7-bit ascii.
if (ch == -1) {
return "7bit";
}
// we found a newline, this is only valid if the previous char was the '\r'
if (ch == '\n') {
// malformed linebreak? force this to base64 encoding.
if (previousChar != '\r') {
return "base64";
}
// hit a line end, reset our line length counter
span = 0;
}
else {
span++;
// the text has long lines, we can't transfer this as unencoded text.
if (span > 998) {
return "base64";
}
// non-ascii character, we have to transfer this in binary.
if (!isAscii(ch)) {
return "base64";
}
}
previousChar = ch;
}
}
}
| 1,907 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/Base64DecoderStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An implementation of a FilterInputStream that decodes the
* stream data in BASE64 encoding format. This version does the
* decoding "on the fly" rather than decoding a single block of
* data. Since this version is intended for use by the MimeUtilty class,
* it also handles line breaks in the encoded data.
*/
public class Base64DecoderStream extends FilterInputStream {
static protected final String MAIL_BASE64_IGNOREERRORS = "mail.mime.base64.ignoreerrors";
// number of decodeable units we'll try to process at one time. We'll attempt to read that much
// data from the input stream and decode in blocks.
static protected final int BUFFERED_UNITS = 2000;
// our decoder for processing the data
protected Base64Encoder decoder = new Base64Encoder();
// can be overridden by a system property.
protected boolean ignoreErrors = false;
// buffer for reading in chars for decoding (which can support larger bulk reads)
protected byte[] encodedChars = new byte[BUFFERED_UNITS * 4];
// a buffer for one decoding unit's worth of data (3 bytes). This is the minimum amount we
// can read at one time.
protected byte[] decodedChars = new byte[BUFFERED_UNITS * 3];
// count of characters in the buffer
protected int decodedCount = 0;
// index of the next decoded character
protected int decodedIndex = 0;
public Base64DecoderStream(final InputStream in) {
super(in);
// make sure we get the ignore errors flag
ignoreErrors = SessionUtil.getBooleanProperty(MAIL_BASE64_IGNOREERRORS, false);
}
/**
* Test for the existance of decoded characters in our buffer
* of decoded data.
*
* @return True if we currently have buffered characters.
*/
private boolean dataAvailable() {
return decodedCount != 0;
}
/**
* Get the next buffered decoded character.
*
* @return The next decoded character in the buffer.
*/
private byte getBufferedChar() {
decodedCount--;
return decodedChars[decodedIndex++];
}
/**
* Decode a requested number of bytes of data into a buffer.
*
* @return true if we were able to obtain more data, false otherwise.
*/
private boolean decodeStreamData() throws IOException {
decodedIndex = 0;
// fill up a data buffer with input data
final int readCharacters = fillEncodedBuffer();
if (readCharacters > 0) {
decodedCount = decoder.decode(encodedChars, 0, readCharacters, decodedChars);
return true;
}
return false;
}
/**
* Retrieve a single byte from the decoded characters buffer.
*
* @return The decoded character or -1 if there was an EOF condition.
*/
private int getByte() throws IOException {
if (!dataAvailable()) {
if (!decodeStreamData()) {
return -1;
}
}
decodedCount--;
// we need to ensure this doesn't get sign extended
return decodedChars[decodedIndex++] & 0xff;
}
private int getBytes(final byte[] data, int offset, int length) throws IOException {
int readCharacters = 0;
while (length > 0) {
// need data? Try to get some
if (!dataAvailable()) {
// if we can't get this, return a count of how much we did get (which may be -1).
if (!decodeStreamData()) {
return readCharacters > 0 ? readCharacters : -1;
}
}
// now copy some of the data from the decoded buffer to the target buffer
final int copyCount = Math.min(decodedCount, length);
System.arraycopy(decodedChars, decodedIndex, data, offset, copyCount);
decodedIndex += copyCount;
decodedCount -= copyCount;
offset += copyCount;
length -= copyCount;
readCharacters += copyCount;
}
return readCharacters;
}
/**
* Fill our buffer of input characters for decoding from the
* stream. This will attempt read a full buffer, but will
* terminate on an EOF or read error. This will filter out
* non-Base64 encoding chars and will only return a valid
* multiple of 4 number of bytes.
*
* @return The count of characters read.
*/
private int fillEncodedBuffer() throws IOException
{
int readCharacters = 0;
while (true) {
// get the next character from the stream
final int ch = in.read();
// did we hit an EOF condition?
if (ch == -1) {
// now check to see if this is normal, or potentially an error
// if we didn't get characters as a multiple of 4, we may need to complain about this.
if ((readCharacters % 4) != 0) {
// the error checking can be turned off...normally it isn't
if (!ignoreErrors) {
throw new IOException("Base64 encoding error, data truncated");
}
// we're ignoring errors, so round down to a multiple and return that.
return (readCharacters / 4) * 4;
}
// return the count.
return readCharacters;
}
// if this character is valid in a Base64 stream, copy it to the buffer.
else if (decoder.isValidBase64(ch)) {
encodedChars[readCharacters++] = (byte)ch;
// if we've filled up the buffer, time to quit.
if (readCharacters >= encodedChars.length) {
return readCharacters;
}
}
// we're filtering out whitespace and CRLF characters, so just ignore these
}
}
// in order to function as a filter, these streams need to override the different
// read() signature.
@Override
public int read() throws IOException
{
return getByte();
}
@Override
public int read(final byte [] buffer, final int offset, final int length) throws IOException {
return getBytes(buffer, offset, length);
}
@Override
public boolean markSupported() {
return false;
}
@Override
public int available() throws IOException {
return ((in.available() / 4) * 3) + decodedCount;
}
}
| 1,908 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/Base64Encoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class Base64Encoder
implements Encoder
{
protected final byte[] encodingTable =
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v',
(byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6',
(byte)'7', (byte)'8', (byte)'9',
(byte)'+', (byte)'/'
};
protected byte padding = (byte)'=';
/*
* set up the decoding table.
*/
protected final byte[] decodingTable = new byte[256];
protected void initialiseDecodingTable()
{
for (int i = 0; i < encodingTable.length; i++)
{
decodingTable[encodingTable[i]] = (byte)i;
}
}
public Base64Encoder()
{
initialiseDecodingTable();
}
/**
* encode the input data producing a base 64 output stream.
*
* @return the number of bytes produced.
*/
public int encode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
final int modulus = length % 3;
final int dataLength = (length - modulus);
int a1, a2, a3;
for (int i = off; i < off + dataLength; i += 3)
{
a1 = data[i] & 0xff;
a2 = data[i + 1] & 0xff;
a3 = data[i + 2] & 0xff;
out.write(encodingTable[(a1 >>> 2) & 0x3f]);
out.write(encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
out.write(encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]);
out.write(encodingTable[a3 & 0x3f]);
}
/*
* process the tail end.
*/
int b1, b2, b3;
int d1, d2;
switch (modulus)
{
case 0: /* nothing left to do */
break;
case 1:
d1 = data[off + dataLength] & 0xff;
b1 = (d1 >>> 2) & 0x3f;
b2 = (d1 << 4) & 0x3f;
out.write(encodingTable[b1]);
out.write(encodingTable[b2]);
out.write(padding);
out.write(padding);
break;
case 2:
d1 = data[off + dataLength] & 0xff;
d2 = data[off + dataLength + 1] & 0xff;
b1 = (d1 >>> 2) & 0x3f;
b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
b3 = (d2 << 2) & 0x3f;
out.write(encodingTable[b1]);
out.write(encodingTable[b2]);
out.write(encodingTable[b3]);
out.write(padding);
break;
}
return (dataLength / 3) * 4 + ((modulus == 0) ? 0 : 4);
}
private boolean ignore(
final char c)
{
return (c == '\n' || c =='\r' || c == '\t' || c == ' ');
}
/**
* decode the base 64 encoded byte data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public int decode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
byte b1, b2, b3, b4;
int outLen = 0;
int end = off + length;
while (end > 0)
{
if (!ignore((char)data[end - 1]))
{
break;
}
end--;
}
int i = off;
final int finish = end - 4;
while (i < finish)
{
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
b1 = decodingTable[data[i++]];
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
b2 = decodingTable[data[i++]];
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
b3 = decodingTable[data[i++]];
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
b4 = decodingTable[data[i++]];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
outLen += 3;
}
if (data[end - 2] == padding)
{
b1 = decodingTable[data[end - 4]];
b2 = decodingTable[data[end - 3]];
out.write((b1 << 2) | (b2 >> 4));
outLen += 1;
}
else if (data[end - 1] == padding)
{
b1 = decodingTable[data[end - 4]];
b2 = decodingTable[data[end - 3]];
b3 = decodingTable[data[end - 2]];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
outLen += 2;
}
else
{
b1 = decodingTable[data[end - 4]];
b2 = decodingTable[data[end - 3]];
b3 = decodingTable[data[end - 2]];
b4 = decodingTable[data[end - 1]];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
outLen += 3;
}
return outLen;
}
/**
* decode the base 64 encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public int decode(
final String data,
final OutputStream out)
throws IOException
{
byte b1, b2, b3, b4;
int length = 0;
int end = data.length();
while (end > 0)
{
if (!ignore(data.charAt(end - 1)))
{
break;
}
end--;
}
int i = 0;
final int finish = end - 4;
while (i < finish)
{
while ((i < finish) && ignore(data.charAt(i)))
{
i++;
}
b1 = decodingTable[data.charAt(i++)];
while ((i < finish) && ignore(data.charAt(i)))
{
i++;
}
b2 = decodingTable[data.charAt(i++)];
while ((i < finish) && ignore(data.charAt(i)))
{
i++;
}
b3 = decodingTable[data.charAt(i++)];
while ((i < finish) && ignore(data.charAt(i)))
{
i++;
}
b4 = decodingTable[data.charAt(i++)];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
length += 3;
}
if (data.charAt(end - 2) == padding)
{
b1 = decodingTable[data.charAt(end - 4)];
b2 = decodingTable[data.charAt(end - 3)];
out.write((b1 << 2) | (b2 >> 4));
length += 1;
}
else if (data.charAt(end - 1) == padding)
{
b1 = decodingTable[data.charAt(end - 4)];
b2 = decodingTable[data.charAt(end - 3)];
b3 = decodingTable[data.charAt(end - 2)];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
length += 2;
}
else
{
b1 = decodingTable[data.charAt(end - 4)];
b2 = decodingTable[data.charAt(end - 3)];
b3 = decodingTable[data.charAt(end - 2)];
b4 = decodingTable[data.charAt(end - 1)];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
length += 3;
}
return length;
}
/**
* decode the base 64 encoded byte data writing it to the provided byte array buffer.
*
* @return the number of bytes produced.
*/
public int decode(final byte[] data, final int off, final int length, final byte[] out) throws IOException
{
byte b1, b2, b3, b4;
int outLen = 0;
int end = off + length;
while (end > 0)
{
if (!ignore((char)data[end - 1]))
{
break;
}
end--;
}
int i = off;
final int finish = end - 4;
while (i < finish)
{
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
b1 = decodingTable[data[i++]];
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
b2 = decodingTable[data[i++]];
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
b3 = decodingTable[data[i++]];
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
b4 = decodingTable[data[i++]];
out[outLen++] = (byte)((b1 << 2) | (b2 >> 4));
out[outLen++] = (byte)((b2 << 4) | (b3 >> 2));
out[outLen++] = (byte)((b3 << 6) | b4);
}
if (data[end - 2] == padding)
{
b1 = decodingTable[data[end - 4]];
b2 = decodingTable[data[end - 3]];
out[outLen++] = (byte)((b1 << 2) | (b2 >> 4));
}
else if (data[end - 1] == padding)
{
b1 = decodingTable[data[end - 4]];
b2 = decodingTable[data[end - 3]];
b3 = decodingTable[data[end - 2]];
out[outLen++] = (byte)((b1 << 2) | (b2 >> 4));
out[outLen++] = (byte)((b2 << 4) | (b3 >> 2));
}
else
{
b1 = decodingTable[data[end - 4]];
b2 = decodingTable[data[end - 3]];
b3 = decodingTable[data[end - 2]];
b4 = decodingTable[data[end - 1]];
out[outLen++] = (byte)((b1 << 2) | (b2 >> 4));
out[outLen++] = (byte)((b2 << 4) | (b3 >> 2));
out[outLen++] = (byte)((b3 << 6) | b4);
}
return outLen;
}
/**
* Test if a character is a valid Base64 encoding character. This
* must be either a valid digit or the padding character ("=").
*
* @param ch The test character.
*
* @return true if this is valid in Base64 encoded data, false otherwise.
*/
public boolean isValidBase64(final int ch) {
// 'A' has the value 0 in the decoding table, so we need a special one for that
return ch == padding || ch == 'A' || decodingTable[ch] != 0;
}
/**
* Perform RFC-2047 word encoding using Base64 data encoding.
*
* @param in The source for the encoded data.
* @param charset The charset tag to be added to each encoded data section.
* @param out The output stream where the encoded data is to be written.
* @param fold Controls whether separate sections of encoded data are separated by
* linebreaks or whitespace.
*
* @exception IOException
*/
public void encodeWord(final InputStream in, final String charset, final OutputStream out, final boolean fold) throws IOException
{
final PrintStream writer = new PrintStream(out);
// encoded words are restricted to 76 bytes, including the control adornments.
final int limit = 75 - 7 - charset.length();
boolean firstLine = true;
final StringBuffer encodedString = new StringBuffer(76);
while (true) {
// encode the next segment.
encode(in, encodedString, limit);
// if we're out of data, nothing will be encoded.
if (encodedString.length() == 0) {
break;
}
// if we have more than one segment, we need to insert separators. Depending on whether folding
// was requested, this is either a blank or a linebreak.
if (!firstLine) {
if (fold) {
writer.print("\r\n");
}
else {
writer.print(" ");
}
}
// add the encoded word header
writer.print("=?");
writer.print(charset);
writer.print("?B?");
// the data
writer.print(encodedString.toString());
// and the word terminator.
writer.print("?=");
writer.flush();
// reset our string buffer for the next segment.
encodedString.setLength(0);
// we need a delimiter after this
firstLine = false;
}
}
/**
* Perform RFC-2047 word encoding using Base64 data encoding.
*
* @param in The source for the encoded data.
* @param charset The charset tag to be added to each encoded data section.
* @param out The output stream where the encoded data is to be written.
* @param fold Controls whether separate sections of encoded data are separated by
* linebreaks or whitespace.
*
* @exception IOException
*/
public void encodeWord(final byte[] data, final StringBuffer out, final String charset) throws IOException
{
// append the word header
out.append("=?");
out.append(charset);
out.append("?B?");
// add on the encodeded data
encodeWordData(data, out);
// the end of the encoding marker
out.append("?=");
}
/**
* encode the input data producing a base 64 output stream.
*
* @return the number of bytes produced.
*/
public void encodeWordData(final byte[] data, final StringBuffer out)
{
final int modulus = data.length % 3;
final int dataLength = (data.length - modulus);
int a1, a2, a3;
for (int i = 0; i < dataLength; i += 3)
{
a1 = data[i] & 0xff;
a2 = data[i + 1] & 0xff;
a3 = data[i + 2] & 0xff;
out.append((char)encodingTable[(a1 >>> 2) & 0x3f]);
out.append((char)encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
out.append((char)encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]);
out.append((char)encodingTable[a3 & 0x3f]);
}
/*
* process the tail end.
*/
int b1, b2, b3;
int d1, d2;
switch (modulus)
{
case 0: /* nothing left to do */
break;
case 1:
d1 = data[dataLength] & 0xff;
b1 = (d1 >>> 2) & 0x3f;
b2 = (d1 << 4) & 0x3f;
out.append((char)encodingTable[b1]);
out.append((char)encodingTable[b2]);
out.append((char)padding);
out.append((char)padding);
break;
case 2:
d1 = data[dataLength] & 0xff;
d2 = data[dataLength + 1] & 0xff;
b1 = (d1 >>> 2) & 0x3f;
b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
b3 = (d2 << 2) & 0x3f;
out.append((char)encodingTable[b1]);
out.append((char)encodingTable[b2]);
out.append((char)encodingTable[b3]);
out.append((char)padding);
break;
}
}
/**
* encode the input data producing a base 64 output stream.
*
* @return the number of bytes produced.
*/
public void encode(final InputStream in, final StringBuffer out, final int limit) throws IOException
{
int count = limit / 4;
final byte [] inBuffer = new byte[3];
while (count-- > 0) {
final int readCount = in.read(inBuffer);
// did we get a full triplet? that's an easy encoding.
if (readCount == 3) {
final int a1 = inBuffer[0] & 0xff;
final int a2 = inBuffer[1] & 0xff;
final int a3 = inBuffer[2] & 0xff;
out.append((char)encodingTable[(a1 >>> 2) & 0x3f]);
out.append((char)encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
out.append((char)encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]);
out.append((char)encodingTable[a3 & 0x3f]);
}
else if (readCount <= 0) {
// eof condition, don'e entirely.
return;
}
else if (readCount == 1) {
final int a1 = inBuffer[0] & 0xff;
out.append((char)encodingTable[(a1 >>> 2) & 0x3f]);
out.append((char)encodingTable[(a1 << 4) & 0x3f]);
out.append((char)padding);
out.append((char)padding);
return;
}
else if (readCount == 2) {
final int a1 = inBuffer[0] & 0xff;
final int a2 = inBuffer[1] & 0xff;
out.append((char)encodingTable[(a1 >>> 2) & 0x3f]);
out.append((char)encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
out.append((char)encodingTable[(a2 << 2) & 0x3f]);
out.append((char)padding);
return;
}
}
}
/**
* Estimate the final encoded size of a segment of data.
* This is used to ensure that the encoded blocks do
* not get split across a unicode character boundary and
* that the encoding will fit within the bounds of
* a mail header line.
*
* @param data The data we're anticipating encoding.
*
* @return The size of the byte data in encoded form.
*/
public int estimateEncodedLength(final byte[] data)
{
return ((data.length + 2) / 3) * 4;
}
}
| 1,909 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/Base64.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Base64
{
private static final Encoder encoder = new Base64Encoder();
/**
* encode the input data producing a base 64 encoded byte array.
*
* @return a byte array containing the base 64 encoded data.
*/
public static byte[] encode(
final byte[] data)
{
// just forward to the general array encoder.
return encode(data, 0, data.length);
}
/**
* encode the input data producing a base 64 encoded byte array.
*
* @param data The data array to encode.
* @param offset The starting offset within the data array.
* @param length The length of the data to encode.
*
* @return a byte array containing the base 64 encoded data.
*/
public static byte[] encode(
final byte[] data,
final int offset,
final int length)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.encode(data, 0, data.length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception encoding base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* Encode the byte data to base 64 writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final OutputStream out)
throws IOException
{
return encoder.encode(data, 0, data.length, out);
}
/**
* Encode the byte data to base 64 writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
return encoder.encode(data, off, length, out);
}
/**
* decode the base 64 encoded input data. It is assumed the input data is valid.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final byte[] data)
{
// just decode the entire array of data.
return decode(data, 0, data.length);
}
/**
* decode the base 64 encoded input data. It is assumed the input data is valid.
*
* @param data The data array to decode.
* @param offset The offset of the data array.
* @param length The length of data to decode.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final byte[] data,
final int offset,
final int length)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, offset, length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the base 64 encoded String data - whitespace will be ignored.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final String data)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the base 64 encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public static int decode(
final String data,
final OutputStream out)
throws IOException
{
return encoder.decode(data, out);
}
/**
* decode the base 64 encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @param data The array data to decode.
* @param out The output stream for the data.
*
* @return the number of bytes produced.
* @exception IOException
*/
public static int decode(final byte [] data, final OutputStream out) throws IOException
{
return encoder.decode(data, 0, data.length, out);
}
}
| 1,910 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/UUEncode.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class UUEncode {
private static final Encoder encoder = new UUEncoder();
/**
* encode the input data producing a UUEncoded byte array.
*
* @return a byte array containing the UUEncoded data.
*/
public static byte[] encode(
final byte[] data)
{
return encode(data, 0, data.length);
}
/**
* encode the input data producing a UUEncoded byte array.
*
* @return a byte array containing the UUEncoded data.
*/
public static byte[] encode(
final byte[] data,
final int off,
final int length)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.encode(data, off, length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception encoding UUEncoded string: " + e);
}
return bOut.toByteArray();
}
/**
* UUEncode the byte data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final OutputStream out)
throws IOException
{
return encoder.encode(data, 0, data.length, out);
}
/**
* UUEncode the byte data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
return encoder.encode(data, 0, data.length, out);
}
/**
* decode the UUEncoded input data. It is assumed the input data is valid.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final byte[] data)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, 0, data.length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding UUEncoded string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the UUEncided String data.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final String data)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding UUEncoded string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the UUEncoded encoded String data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int decode(
final String data,
final OutputStream out)
throws IOException
{
return encoder.decode(data, out);
}
}
| 1,911 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/XTextEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.IOException;
import java.io.OutputStream;
public class XTextEncoder
implements Encoder
{
protected final byte[] encodingTable =
{
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
(byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F'
};
/*
* set up the decoding table.
*/
protected final byte[] decodingTable = new byte[128];
protected void initialiseDecodingTable()
{
for (int i = 0; i < encodingTable.length; i++)
{
decodingTable[encodingTable[i]] = (byte)i;
}
}
public XTextEncoder()
{
initialiseDecodingTable();
}
/**
* encode the input data producing an XText output stream.
*
* @return the number of bytes produced.
*/
public int encode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
int bytesWritten = 0;
for (int i = off; i < (off + length); i++)
{
final int v = data[i] & 0xff;
// character tha must be encoded? Prefix with a '+' and encode in hex.
if (v < 33 || v > 126 || v == '+' || v == '+') {
out.write((byte)'+');
out.write(encodingTable[(v >>> 4)]);
out.write(encodingTable[v & 0xf]);
bytesWritten += 3;
}
else {
// add unchanged.
out.write((byte)v);
bytesWritten++;
}
}
return bytesWritten;
}
/**
* decode the xtext encoded byte data writing it to the given output stream
*
* @return the number of bytes produced.
*/
public int decode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
byte b1, b2;
int outLen = 0;
final int end = off + length;
int i = off;
while (i < end)
{
final byte v = data[i++];
// a plus is a hex character marker, need to decode a hex value.
if (v == '+') {
b1 = decodingTable[data[i++]];
b2 = decodingTable[data[i++]];
out.write((b1 << 4) | b2);
}
else {
// copied over unchanged.
out.write(v);
}
// always just one byte added
outLen++;
}
return outLen;
}
/**
* decode the xtext encoded String data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public int decode(
final String data,
final OutputStream out)
throws IOException
{
byte b1, b2;
int length = 0;
final int end = data.length();
int i = 0;
while (i < end)
{
final char v = data.charAt(i++);
if (v == '+') {
b1 = decodingTable[data.charAt(i++)];
b2 = decodingTable[data.charAt(i++)];
out.write((b1 << 4) | b2);
}
else {
out.write((byte)v);
}
length++;
}
return length;
}
}
| 1,912 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.IOException;
import java.io.OutputStream;
/**
* An implementation of an OutputStream that writes the data directly
* out to a StringBuffer object. Useful for applications where an
* intermediate ByteArrayOutputStream is required to append generated
* characters to a StringBuffer;
*/
public class StringBufferOutputStream extends OutputStream {
// the target buffer
protected StringBuffer buffer;
/**
* Create an output stream that writes to the target StringBuffer
*
* @param out The wrapped output stream.
*/
public StringBufferOutputStream(final StringBuffer out) {
buffer = out;
}
// in order for this to work, we only need override the single character form, as the others
// funnel through this one by default.
@Override
public void write(final int ch) throws IOException {
// just append the character
buffer.append((char)ch);
}
}
| 1,913 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
/**
* An implementation of a FilterOutputStream that decodes the
* stream data in UU encoding format. This version does the
* decoding "on the fly" rather than decoding a single block of
* data. Since this version is intended for use by the MimeUtilty class,
* it also handles line breaks in the encoded data.
*/
public class UUDecoderStream extends FilterInputStream {
// maximum number of chars that can appear in a single line
protected static final int MAX_CHARS_PER_LINE = 45;
// our decoder for processing the data
protected UUEncoder decoder = new UUEncoder();
// a buffer for one decoding unit's worth of data (45 bytes).
protected byte[] decodedChars;
// count of characters in the buffer
protected int decodedCount = 0;
// index of the next decoded character
protected int decodedIndex = 0;
// indicates whether we've already processed the "begin" prefix.
protected boolean beginRead = false;
public UUDecoderStream(final InputStream in) {
super(in);
}
/**
* Test for the existance of decoded characters in our buffer
* of decoded data.
*
* @return True if we currently have buffered characters.
*/
private boolean dataAvailable() {
return decodedCount != 0;
}
/**
* Get the next buffered decoded character.
*
* @return The next decoded character in the buffer.
*/
private byte getBufferedChar() {
decodedCount--;
return decodedChars[decodedIndex++];
}
/**
* Decode a requested number of bytes of data into a buffer.
*
* @return true if we were able to obtain more data, false otherwise.
*/
private boolean decodeStreamData() throws IOException {
decodedIndex = 0;
// fill up a data buffer with input data
return fillEncodedBuffer() != -1;
}
/**
* Retrieve a single byte from the decoded characters buffer.
*
* @return The decoded character or -1 if there was an EOF condition.
*/
private int getByte() throws IOException {
if (!dataAvailable()) {
if (!decodeStreamData()) {
return -1;
}
}
decodedCount--;
return decodedChars[decodedIndex++];
}
private int getBytes(final byte[] data, int offset, int length) throws IOException {
int readCharacters = 0;
while (length > 0) {
// need data? Try to get some
if (!dataAvailable()) {
// if we can't get this, return a count of how much we did get (which may be -1).
if (!decodeStreamData()) {
return readCharacters > 0 ? readCharacters : -1;
}
}
// now copy some of the data from the decoded buffer to the target buffer
final int copyCount = Math.min(decodedCount, length);
System.arraycopy(decodedChars, decodedIndex, data, offset, copyCount);
decodedIndex += copyCount;
decodedCount -= copyCount;
offset += copyCount;
length -= copyCount;
readCharacters += copyCount;
}
return readCharacters;
}
/**
* Verify that the first line of the buffer is a valid begin
* marker.
*
* @exception IOException
*/
private void checkBegin() throws IOException {
// we only do this the first time we're requested to read from the stream.
if (beginRead) {
return;
}
// we might have to skip over lines to reach the marker. If we hit the EOF without finding
// the begin, that's an error.
while (true) {
final String line = readLine();
if (line == null) {
throw new IOException("Missing UUEncode begin command");
}
// is this our begin?
if (line.regionMatches(true, 0, "begin ", 0, 6)) {
// This is the droid we're looking for.....
beginRead = true;
return;
}
}
}
/**
* Read a line of data. Returns null if there is an EOF.
*
* @return The next line read from the stream. Returns null if we
* hit the end of the stream.
* @exception IOException
*/
protected String readLine() throws IOException {
decodedIndex = 0;
// get an accumulator for the data
final StringBuffer buffer = new StringBuffer();
// now process a character at a time.
int ch = in.read();
while (ch != -1) {
// a naked new line completes the line.
if (ch == '\n') {
break;
}
// a carriage return by itself is ignored...we're going to assume that this is followed
// by a new line because we really don't have the capability of pushing this back .
else if (ch == '\r') {
;
}
else {
// add this to our buffer
buffer.append((char)ch);
}
ch = in.read();
}
// if we didn't get any data at all, return nothing
if (ch == -1 && buffer.length() == 0) {
return null;
}
// convert this into a string.
return buffer.toString();
}
/**
* Fill our buffer of input characters for decoding from the
* stream. This will attempt read a full buffer, but will
* terminate on an EOF or read error. This will filter out
* non-Base64 encoding chars and will only return a valid
* multiple of 4 number of bytes.
*
* @return The count of characters read.
*/
private int fillEncodedBuffer() throws IOException
{
checkBegin();
// reset the buffer position
decodedIndex = 0;
while (true) {
// we read these as character lines. We need to be looking for the "end" marker for the
// end of the data.
final String line = readLine();
// this should NOT be happening....
if (line == null) {
throw new IOException("Missing end in UUEncoded data");
}
// Is this the end marker? EOF baby, EOF!
if (line.equalsIgnoreCase("end")) {
// this indicates we got nuttin' more to do.
return -1;
}
final ByteArrayOutputStream out = new ByteArrayOutputStream(MAX_CHARS_PER_LINE);
byte [] lineBytes;
try {
lineBytes = line.getBytes("US-ASCII");
} catch (final UnsupportedEncodingException e) {
throw new IOException("Invalid UUEncoding");
}
// decode this line
decodedCount = decoder.decode(lineBytes, 0, lineBytes.length, out);
// not just a zero-length line?
if (decodedCount != 0) {
// get the resulting byte array
decodedChars = out.toByteArray();
return decodedCount;
}
}
}
// in order to function as a filter, these streams need to override the different
// read() signature.
@Override
public int read() throws IOException
{
return getByte();
}
@Override
public int read(final byte [] buffer, final int offset, final int length) throws IOException {
return getBytes(buffer, offset, length);
}
@Override
public boolean markSupported() {
return false;
}
@Override
public int available() throws IOException {
return ((in.available() / 4) * 3) + decodedCount;
}
}
| 1,914 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/Hex.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Hex
{
private static final Encoder encoder = new HexEncoder();
/**
* encode the input data producing a Hex encoded byte array.
*
* @return a byte array containing the Hex encoded data.
*/
public static byte[] encode(
final byte[] data)
{
return encode(data, 0, data.length);
}
/**
* encode the input data producing a Hex encoded byte array.
*
* @return a byte array containing the Hex encoded data.
*/
public static byte[] encode(
final byte[] data,
final int off,
final int length)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.encode(data, off, length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception encoding Hex string: " + e);
}
return bOut.toByteArray();
}
/**
* Hex encode the byte data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final OutputStream out)
throws IOException
{
return encoder.encode(data, 0, data.length, out);
}
/**
* Hex encode the byte data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
return encoder.encode(data, 0, data.length, out);
}
/**
* decode the Hex encoded input data. It is assumed the input data is valid.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final byte[] data)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, 0, data.length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding Hex string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the Hex encoded String data - whitespace will be ignored.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final String data)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding Hex string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the Hex encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public static int decode(
final String data,
final OutputStream out)
throws IOException
{
return encoder.decode(data, out);
}
}
| 1,915 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableDecoderStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An implementation of a FilterOutputStream that decodes the
* stream data in Q-P encoding format. This version does the
* decoding "on the fly" rather than decoding a single block of
* data. Since this version is intended for use by the MimeUtilty class,
* it also handles line breaks in the encoded data.
*/
public class QuotedPrintableDecoderStream extends FilterInputStream {
// our decoder for processing the data
protected QuotedPrintableEncoder decoder;
/**
* Stream constructor.
*
* @param in The InputStream this stream is filtering.
*/
public QuotedPrintableDecoderStream(final InputStream in) {
super(in);
decoder = new QuotedPrintableEncoder();
}
// in order to function as a filter, these streams need to override the different
// read() signatures.
/**
* Read a single byte from the stream.
*
* @return The next byte of the stream. Returns -1 for an EOF condition.
* @exception IOException
*/
@Override
public int read() throws IOException
{
// just get a single byte from the decoder
return decoder.decode(in);
}
/**
* Read a buffer of data from the input stream.
*
* @param buffer The target byte array the data is placed into.
* @param offset The starting offset for the read data.
* @param length How much data is requested.
*
* @return The number of bytes of data read.
* @exception IOException
*/
@Override
public int read(final byte [] buffer, final int offset, final int length) throws IOException {
for (int i = 0; i < length; i++) {
final int ch = decoder.decode(in);
if (ch == -1) {
return i == 0 ? -1 : i;
}
buffer[offset + i] = (byte)ch;
}
return length;
}
/**
* Indicate whether this stream supports the mark() operation.
*
* @return Always returns false.
*/
@Override
public boolean markSupported() {
return false;
}
/**
* Give an estimate of how much additional data is available
* from this stream.
*
* @return Always returns -1.
* @exception IOException
*/
@Override
public int available() throws IOException {
// this is almost impossible to determine at this point
return -1;
}
}
| 1,916 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PushbackInputStream;
import java.io.UnsupportedEncodingException;
public class QuotedPrintableEncoder implements Encoder {
static protected final byte[] encodingTable =
{
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
(byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F'
};
/*
* set up the decoding table.
*/
static protected final byte[] decodingTable = new byte[128];
static {
// initialize the decoding table
for (int i = 0; i < encodingTable.length; i++)
{
decodingTable[encodingTable[i]] = (byte)i;
}
}
// default number of characters we will write per line.
static private final int DEFAULT_CHARS_PER_LINE = 76;
// the output stream we're wrapped around
protected OutputStream out;
// the number of bytes written;
protected int bytesWritten = 0;
// number of bytes written on the current line
protected int lineCount = 0;
// line length we're dealing with
protected int lineLength;
// number of deferred whitespace characters in decode mode.
protected int deferredWhitespace = 0;
protected int cachedCharacter = -1;
// indicates whether the last character was a '\r', potentially part of a CRLF sequence.
protected boolean lastCR = false;
// remember whether last character was a white space.
protected boolean lastWhitespace = false;
public QuotedPrintableEncoder() {
this(null, DEFAULT_CHARS_PER_LINE);
}
public QuotedPrintableEncoder(final OutputStream out) {
this(out, DEFAULT_CHARS_PER_LINE);
}
public QuotedPrintableEncoder(final OutputStream out, final int lineLength) {
this.out = out;
this.lineLength = lineLength;
}
private void checkDeferred(final int ch) throws IOException {
// was the last character we looked at a whitespace? Try to decide what to do with it now.
if (lastWhitespace) {
// if this whitespace is at the end of the line, write it out encoded
if (ch == '\r' || ch == '\n') {
writeEncodedCharacter(' ');
}
else {
// we can write this out without encoding.
writeCharacter(' ');
}
// we always turn this off.
lastWhitespace = false;
}
// deferred carriage return?
else if (lastCR) {
// if the char following the CR was not a new line, write an EOL now.
if (ch != '\n') {
writeEOL();
}
// we always turn this off too
lastCR = false;
}
}
/**
* encode the input data producing a UUEncoded output stream.
*
* @param data The array of byte data.
* @param off The starting offset within the data.
* @param length Length of the data to encode.
*
* @return the number of bytes produced.
*/
public int encode(final byte[] data, int off, final int length) throws IOException {
final int endOffset = off + length;
while (off < endOffset) {
// get the character
final byte ch = data[off++];
// handle the encoding of this character.
encode(ch);
}
return bytesWritten;
}
public void encode(int ch) throws IOException {
// make sure this is just a single byte value.
ch = ch &0xFF;
// see if we had to defer handling of a whitespace or '\r' character, and handle it if necessary.
checkDeferred(ch);
// different characters require special handling.
switch (ch) {
// spaces require special handling. If the next character is a line terminator, then
// the space needs to be encoded.
case ' ':
{
// at this point, we don't know whether this needs encoding or not. If the next
// character is a linend, it gets encoded. If anything else, we just write it as is.
lastWhitespace = true;
// turn off any CR flags.
lastCR = false;
break;
}
// carriage return, which may be part of a CRLF sequence.
case '\r':
{
// just flag this until we see the next character.
lastCR = true;
break;
}
// a new line character...we need to check to see if it was paired up with a '\r' char.
case '\n':
{
// we always write this out for a newline. We defer CRs until we see if the LF follows.
writeEOL();
break;
}
// an '=' is the escape character for an encoded character, so it must also
// be written encoded.
case '=':
{
writeEncodedCharacter(ch);
break;
}
// all other characters. If outside the printable character range, write it encoded.
default:
{
if (ch < 32 || ch >= 127) {
writeEncodedCharacter(ch);
}
else {
writeCharacter(ch);
}
break;
}
}
}
/**
* encode the input data producing a UUEncoded output stream.
*
* @param data The array of byte data.
* @param off The starting offset within the data.
* @param length Length of the data to encode.
*
* @return the number of bytes produced.
*/
public int encode(final byte[] data, int off, final int length, final String specials) throws IOException {
final int endOffset = off + length;
while (off < endOffset) {
// get the character
final byte ch = data[off++];
// handle the encoding of this character.
encode(ch, specials);
}
return bytesWritten;
}
/**
* encode the input data producing a UUEncoded output stream.
*
* @param data The array of byte data.
* @param off The starting offset within the data.
* @param length Length of the data to encode.
*
* @return the number of bytes produced.
*/
public int encode(final PushbackInputStream in, final StringBuffer out, final String specials, final int limit) throws IOException {
int count = 0;
while (count < limit) {
int ch = in.read();
if (ch == -1) {
return count;
}
// make sure this is just a single byte value.
ch = ch &0xFF;
// spaces require special handling. If the next character is a line terminator, then
// the space needs to be encoded.
if (ch == ' ') {
// blanks get translated into underscores, because the encoded tokens can't have embedded blanks.
out.append('_');
count++;
}
// non-ascii chars and the designated specials all get encoded.
else if (ch < 32 || ch >= 127 || specials.indexOf(ch) != -1) {
// we need at least 3 characters to write this out, so we need to
// forget we saw this one and try in the next segment.
if (count + 3 > limit) {
in.unread(ch);
return count;
}
out.append('=');
out.append((char)encodingTable[ch >> 4]);
out.append((char)encodingTable[ch & 0x0F]);
count += 3;
}
else {
// good character, just use unchanged.
out.append((char)ch);
count++;
}
}
return count;
}
/**
* Specialized version of the decoder that handles encoding of
* RFC 2047 encoded word values. This has special handling for
* certain characters, but less special handling for blanks and
* linebreaks.
*
* @param ch
* @param specials
*
* @exception IOException
*/
public void encode(int ch, final String specials) throws IOException {
// make sure this is just a single byte value.
ch = ch &0xFF;
// spaces require special handling. If the next character is a line terminator, then
// the space needs to be encoded.
if (ch == ' ') {
// blanks get translated into underscores, because the encoded tokens can't have embedded blanks.
writeCharacter('_');
}
// non-ascii chars and the designated specials all get encoded.
else if (ch < 32 || ch >= 127 || specials.indexOf(ch) != -1) {
writeEncodedCharacter(ch);
}
else {
// good character, just use unchanged.
writeCharacter(ch);
}
}
/**
* encode the input data producing a UUEncoded output stream.
*
* @param data The array of byte data.
* @param off The starting offset within the data.
* @param length Length of the data to encode.
* @param out The output stream the encoded data is written to.
*
* @return the number of bytes produced.
*/
public int encode(final byte[] data, final int off, final int length, final OutputStream out) throws IOException {
// make sure we're writing to the correct stream
this.out = out;
bytesWritten = 0;
// do the actual encoding
return encode(data, off, length);
}
/**
* decode the uuencoded byte data writing it to the given output stream
*
* @param data The array of byte data to decode.
* @param off Starting offset within the array.
* @param length The length of data to encode.
* @param out The output stream used to return the decoded data.
*
* @return the number of bytes produced.
* @exception IOException
*/
public int decode(final byte[] data, int off, final int length, final OutputStream out) throws IOException {
// make sure we're writing to the correct stream
this.out = out;
final int endOffset = off + length;
int bytesWritten = 0;
while (off < endOffset) {
final byte ch = data[off++];
// space characters are a pain. We need to scan ahead until we find a non-space character.
// if the character is a line terminator, we need to discard the blanks.
if (ch == ' ') {
int trailingSpaces = 1;
// scan forward, counting the characters.
while (off < endOffset && data[off] == ' ') {
// step forward and count this.
off++;
trailingSpaces++;
}
// is this a lineend at the current location?
if (off >= endOffset || data[off] == '\r' || data[off] == '\n') {
// go to the next one
continue;
}
else {
// make sure we account for the spaces in the output count.
bytesWritten += trailingSpaces;
// write out the blank characters we counted and continue with the non-blank.
while (trailingSpaces-- > 0) {
out.write(' ');
}
}
}
else if (ch == '=') {
// we found an encoded character. Reduce the 3 char sequence to one.
// but first, make sure we have two characters to work with.
if (off + 1 >= endOffset) {
throw new IOException("Invalid quoted printable encoding");
}
// convert the two bytes back from hex.
byte b1 = data[off++];
byte b2 = data[off++];
// we've found an encoded carriage return. The next char needs to be a newline
if (b1 == '\r') {
if (b2 != '\n') {
throw new IOException("Invalid quoted printable encoding");
}
// this was a soft linebreak inserted by the encoding. We just toss this away
// on decode.
}
else {
// this is a hex pair we need to convert back to a single byte.
b1 = decodingTable[b1];
b2 = decodingTable[b2];
out.write((b1 << 4) | b2);
// 3 bytes in, one byte out
bytesWritten++;
}
}
else {
// simple character, just write it out.
out.write(ch);
bytesWritten++;
}
}
return bytesWritten;
}
/**
* Decode a byte array of data.
*
* @param data The data array.
* @param out The output stream target for the decoded data.
*
* @return The number of bytes written to the stream.
* @exception IOException
*/
public int decodeWord(final byte[] data, final OutputStream out) throws IOException {
return decodeWord(data, 0, data.length, out);
}
/**
* decode the uuencoded byte data writing it to the given output stream
*
* @param data The array of byte data to decode.
* @param off Starting offset within the array.
* @param length The length of data to encode.
* @param out The output stream used to return the decoded data.
*
* @return the number of bytes produced.
* @exception IOException
*/
public int decodeWord(final byte[] data, int off, final int length, final OutputStream out) throws IOException {
// make sure we're writing to the correct stream
this.out = out;
final int endOffset = off + length;
int bytesWritten = 0;
while (off < endOffset) {
final byte ch = data[off++];
// space characters were translated to '_' on encode, so we need to translate them back.
if (ch == '_') {
out.write(' ');
}
else if (ch == '=') {
// we found an encoded character. Reduce the 3 char sequence to one.
// but first, make sure we have two characters to work with.
if (off + 1 >= endOffset) {
throw new IOException("Invalid quoted printable encoding");
}
// convert the two bytes back from hex.
final byte b1 = data[off++];
final byte b2 = data[off++];
// we've found an encoded carriage return. The next char needs to be a newline
if (b1 == '\r') {
if (b2 != '\n') {
throw new IOException("Invalid quoted printable encoding");
}
// this was a soft linebreak inserted by the encoding. We just toss this away
// on decode.
}
else {
// this is a hex pair we need to convert back to a single byte.
final byte c1 = decodingTable[b1];
final byte c2 = decodingTable[b2];
out.write((c1 << 4) | c2);
// 3 bytes in, one byte out
bytesWritten++;
}
}
else {
// simple character, just write it out.
out.write(ch);
bytesWritten++;
}
}
return bytesWritten;
}
/**
* decode the UUEncoded String data writing it to the given output stream.
*
* @param data The String data to decode.
* @param out The output stream to write the decoded data to.
*
* @return the number of bytes produced.
* @exception IOException
*/
public int decode(final String data, final OutputStream out) throws IOException {
try {
// just get the byte data and decode.
final byte[] bytes = data.getBytes("US-ASCII");
return decode(bytes, 0, bytes.length, out);
} catch (final UnsupportedEncodingException e) {
throw new IOException("Invalid UUEncoding");
}
}
private void checkLineLength(final int required) throws IOException {
// if we're at our line length limit, write out a soft line break and reset.
if ((lineCount + required) >= lineLength ) {
out.write('=');
out.write('\r');
out.write('\n');
bytesWritten += 3;
lineCount = 0;
}
}
public void writeEncodedCharacter(final int ch) throws IOException {
// we need 3 characters for an encoded value
checkLineLength(3);
out.write('=');
out.write(encodingTable[ch >> 4]);
out.write(encodingTable[ch & 0x0F]);
lineCount += 3;
bytesWritten += 3;
}
public void writeCharacter(final int ch) throws IOException {
// we need 3 characters for an encoded value
checkLineLength(1);
out.write(ch);
lineCount++;
bytesWritten++;
}
public void writeEOL() throws IOException {
out.write('\r');
out.write('\n');
lineCount = 0;
bytesWritten += 3;
}
public int decode(final InputStream in) throws IOException {
// we potentially need to scan over spans of whitespace characters to determine if they're real
// we just return blanks until the count goes to zero.
if (deferredWhitespace > 0) {
deferredWhitespace--;
return ' ';
}
// we may have needed to scan ahead to find the first non-blank character, which we would store here.
// hand that back once we're done with the blanks.
if (cachedCharacter != -1) {
final int result = cachedCharacter;
cachedCharacter = -1;
return result;
}
int ch = in.read();
// reflect back an EOF condition.
if (ch == -1) {
return -1;
}
// space characters are a pain. We need to scan ahead until we find a non-space character.
// if the character is a line terminator, we need to discard the blanks.
if (ch == ' ') {
// scan forward, counting the characters.
while ((ch = in.read()) == ' ') {
deferredWhitespace++;
}
// is this a lineend at the current location?
if (ch == -1 || ch == '\r' || ch == '\n') {
// those blanks we so zealously counted up don't really exist. Clear out the counter.
deferredWhitespace = 0;
// return the real significant character now.
return ch;
}
// remember this character for later, after we've used up the deferred blanks.
cachedCharacter = decodeNonspaceChar(in, ch);
// return this space. We did not include this one in the deferred count, so we're right in sync.
return ' ';
}
return decodeNonspaceChar(in, ch);
}
private int decodeNonspaceChar(final InputStream in, final int ch) throws IOException {
if (ch == '=') {
int b1 = in.read();
// we need to get two characters after the quotation marker
if (b1 == -1) {
throw new IOException("Truncated quoted printable data");
}
int b2 = in.read();
// we need to get two characters after the quotation marker
if (b2 == -1) {
throw new IOException("Truncated quoted printable data");
}
// we've found an encoded carriage return. The next char needs to be a newline
if (b1 == '\r') {
if (b2 != '\n') {
throw new IOException("Invalid quoted printable encoding");
}
// this was a soft linebreak inserted by the encoding. We just toss this away
// on decode. We need to return something, so recurse and decode the next.
return decode(in);
}
else {
// this is a hex pair we need to convert back to a single byte.
b1 = decodingTable[b1];
b2 = decodingTable[b2];
return (b1 << 4) | b2;
}
}
else {
return ch;
}
}
/**
* Perform RFC-2047 word encoding using Q-P data encoding.
*
* @param in The source for the encoded data.
* @param charset The charset tag to be added to each encoded data section.
* @param specials The set of special characters that we require to encoded.
* @param out The output stream where the encoded data is to be written.
* @param fold Controls whether separate sections of encoded data are separated by
* linebreaks or whitespace.
*
* @exception IOException
*/
public void encodeWord(final InputStream in, final String charset, final String specials, final OutputStream out, final boolean fold) throws IOException
{
// we need to scan ahead in a few places, which may require pushing characters back on to the stream.
// make sure we have a stream where this is possible.
final PushbackInputStream inStream = new PushbackInputStream(in);
final PrintStream writer = new PrintStream(out);
// segments of encoded data are limited to 75 byes, including the control sections.
final int limit = 75 - 7 - charset.length();
boolean firstLine = true;
final StringBuffer encodedString = new StringBuffer(76);
while (true) {
// encode another segment of data.
encode(inStream, encodedString, specials, limit);
// nothing encoded means we've hit the end of the data.
if (encodedString.length() == 0) {
break;
}
// if we have more than one segment, we need to insert separators. Depending on whether folding
// was requested, this is either a blank or a linebreak.
if (!firstLine) {
if (fold) {
writer.print("\r\n");
}
else {
writer.print(" ");
}
}
// add the encoded word header
writer.print("=?");
writer.print(charset);
writer.print("?Q?");
// the data
writer.print(encodedString.toString());
// and the terminator mark
writer.print("?=");
writer.flush();
// we reset the string buffer and reuse it.
encodedString.setLength(0);
// we need a delimiter between sections from this point on.
firstLine = false;
}
}
/**
* Perform RFC-2047 word encoding using Base64 data encoding.
*
* @param in The source for the encoded data.
* @param charset The charset tag to be added to each encoded data section.
* @param out The output stream where the encoded data is to be written.
* @param fold Controls whether separate sections of encoded data are separated by
* linebreaks or whitespace.
*
* @exception IOException
*/
public void encodeWord(final byte[] data, final StringBuffer out, final String charset, final String specials) throws IOException
{
// append the word header
out.append("=?");
out.append(charset);
out.append("?Q?");
// add on the encodeded data
encodeWordData(data, out, specials);
// the end of the encoding marker
out.append("?=");
}
/**
* Perform RFC-2047 word encoding using Q-P data encoding.
*
* @param in The source for the encoded data.
* @param charset The charset tag to be added to each encoded data section.
* @param specials The set of special characters that we require to encoded.
* @param out The output stream where the encoded data is to be written.
* @param fold Controls whether separate sections of encoded data are separated by
* linebreaks or whitespace.
*
* @exception IOException
*/
public void encodeWordData(final byte[] data, final StringBuffer out, final String specials) throws IOException {
for (int i = 0; i < data.length; i++) {
final int ch = data[i] & 0xff; ;
// spaces require special handling. If the next character is a line terminator, then
// the space needs to be encoded.
if (ch == ' ') {
// blanks get translated into underscores, because the encoded tokens can't have embedded blanks.
out.append('_');
}
// non-ascii chars and the designated specials all get encoded.
else if (ch < 32 || ch >= 127 || specials.indexOf(ch) != -1) {
out.append('=');
out.append((char)encodingTable[ch >> 4]);
out.append((char)encodingTable[ch & 0x0F]);
}
else {
// good character, just use unchanged.
out.append((char)ch);
}
}
}
/**
* Estimate the final encoded size of a segment of data.
* This is used to ensure that the encoded blocks do
* not get split across a unicode character boundary and
* that the encoding will fit within the bounds of
* a mail header line.
*
* @param data The data we're anticipating encoding.
*
* @return The size of the byte data in encoded form.
*/
public int estimateEncodedLength(final byte[] data, final String specials)
{
int count = 0;
for (int i = 0; i < data.length; i++) {
// make sure this is just a single byte value.
final int ch = data[i] & 0xff;
// non-ascii chars and the designated specials all get encoded.
if (ch < 32 || ch >= 127 || specials.indexOf(ch) != -1) {
// Q encoding translates a single char into 3 characters
count += 3;
}
else {
// non-encoded character
count++;
}
}
return count;
}
}
| 1,917 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/UUEncoderStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
/**
* An implementation of a FilterOutputStream that encodes the
* stream data in UUencoding format. This version does the
* encoding "on the fly" rather than encoding a single block of
* data. Since this version is intended for use by the MimeUtilty class,
* it also handles line breaks in the encoded data.
*/
public class UUEncoderStream extends FilterOutputStream {
// default values included on the "begin" prefix of the data stream.
protected static final int DEFAULT_MODE = 644;
protected static final String DEFAULT_NAME = "encoder.buf";
protected static final int MAX_CHARS_PER_LINE = 45;
// the configured name on the "begin" command.
protected String name;
// the configured mode for the "begin" command.
protected int mode;
// since this is a filtering stream, we need to wait until we have the first byte written for encoding
// to write out the "begin" marker. A real pain, but necessary.
protected boolean beginWritten = false;
// our encoder utility class.
protected UUEncoder encoder = new UUEncoder();
// Data is generally written out in 45 character lines, so we're going to buffer that amount before
// asking the encoder to process this.
// the buffered byte count
protected int bufferedBytes = 0;
// we'll encode this part once it is filled up.
protected byte[] buffer = new byte[45];
/**
* Create a Base64 encoder stream that wraps a specifed stream
* using the default line break size.
*
* @param out The wrapped output stream.
*/
public UUEncoderStream(final OutputStream out) {
this(out, DEFAULT_NAME, DEFAULT_MODE);
}
/**
* Create a Base64 encoder stream that wraps a specifed stream
* using the default line break size.
*
* @param out The wrapped output stream.
* @param name The filename placed on the "begin" command.
*/
public UUEncoderStream(final OutputStream out, final String name) {
this(out, name, DEFAULT_MODE);
}
public UUEncoderStream(final OutputStream out, final String name, final int mode) {
super(out);
// fill in the name and mode information.
this.name = name;
this.mode = mode;
}
private void checkBegin() throws IOException {
if (!beginWritten) {
// grumble...OutputStream doesn't directly support writing String data. We'll wrap this in
// a PrintStream() to accomplish the task of writing the begin command.
final PrintStream writer = new PrintStream(out);
// write out the stream with a CRLF marker
writer.print("begin " + mode + " " + name + "\r\n");
writer.flush();
beginWritten = true;
}
}
private void writeEnd() throws IOException {
final PrintStream writer = new PrintStream(out);
// write out the stream with a CRLF marker
writer.print("\nend\r\n");
writer.flush();
}
private void flushBuffer() throws IOException {
// make sure we've written the begin marker first
checkBegin();
// ask the encoder to encode and write this out.
if (bufferedBytes != 0) {
encoder.encode(buffer, 0, bufferedBytes, out);
// reset the buffer count
bufferedBytes = 0;
}
}
private int bufferSpace() {
return MAX_CHARS_PER_LINE - bufferedBytes;
}
private boolean isBufferFull() {
return bufferedBytes >= MAX_CHARS_PER_LINE;
}
// in order for this to work, we need to override the 3 different signatures for write
@Override
public void write(final int ch) throws IOException {
// store this in the buffer.
buffer[bufferedBytes++] = (byte)ch;
// if we filled this up, time to encode and write to the output stream.
if (isBufferFull()) {
flushBuffer();
}
}
@Override
public void write(final byte [] data) throws IOException {
write(data, 0, data.length);
}
@Override
public void write(final byte [] data, int offset, int length) throws IOException {
// first check to see how much space we have left in the buffer, and copy that over
final int copyBytes = Math.min(bufferSpace(), length);
System.arraycopy(buffer, bufferedBytes, data, offset, copyBytes);
bufferedBytes += copyBytes;
offset += copyBytes;
length -= copyBytes;
// if we filled this up, time to encode and write to the output stream.
if (isBufferFull()) {
flushBuffer();
}
// we've flushed the leading part up to the line break. Now if we have complete lines
// of data left, we can have the encoder process all of these lines directly.
if (length >= MAX_CHARS_PER_LINE) {
final int fullLinesLength = (length / MAX_CHARS_PER_LINE) * MAX_CHARS_PER_LINE;
// ask the encoder to encode and write this out.
encoder.encode(data, offset, fullLinesLength, out);
offset += fullLinesLength;
length -= fullLinesLength;
}
// ok, now we're down to a potential trailing bit we need to move into the
// buffer for later processing.
if (length > 0) {
System.arraycopy(buffer, 0, data, offset, length);
bufferedBytes += length;
offset += length;
length -= length;
}
}
@Override
public void flush() throws IOException {
// flush any unencoded characters we're holding.
flushBuffer();
// write out the data end marker
writeEnd();
// and flush the output stream too so that this data is available.
out.flush();
}
@Override
public void close() throws IOException {
// flush all of the streams and close the target output stream.
flush();
out.close();
}
}
| 1,918 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoderStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* An implementation of a FilterOutputStream that encodes the
* stream data in Q-P encoding format. This version does the
* encoding "on the fly" rather than encoding a single block of
* data. Since this version is intended for use by the MimeUtilty class,
* it also handles line breaks in the encoded data.
*/
public class QuotedPrintableEncoderStream extends FilterOutputStream {
// our hex encoder utility class.
protected QuotedPrintableEncoder encoder;
// our default for line breaks
protected static final int DEFAULT_LINEBREAK = 76;
// the instance line break value
protected int lineBreak;
/**
* Create a Base64 encoder stream that wraps a specifed stream
* using the default line break size.
*
* @param out The wrapped output stream.
*/
public QuotedPrintableEncoderStream(final OutputStream out) {
this(out, DEFAULT_LINEBREAK);
}
public QuotedPrintableEncoderStream(final OutputStream out, final int lineBreak) {
super(out);
// lines are processed only in multiple of 4, so round this down.
this.lineBreak = (lineBreak / 4) * 4 ;
// create an encoder configured to this amount
encoder = new QuotedPrintableEncoder(out, this.lineBreak);
}
@Override
public void write(final int ch) throws IOException {
// have the encoder do the heavy lifting here.
encoder.encode(ch);
}
@Override
public void write(final byte [] data) throws IOException {
write(data, 0, data.length);
}
@Override
public void write(final byte [] data, final int offset, final int length) throws IOException {
// the encoder does the heavy lifting here.
encoder.encode(data, offset, length);
}
@Override
public void close() throws IOException {
out.close();
}
@Override
public void flush() throws IOException {
out.flush();
}
}
| 1,919 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import javax.mail.Session;
/**
* Simple utility class for managing session properties.
*/
public class SessionUtil {
/**
* Get a property associated with this mail session. Returns
* the provided default if it doesn't exist.
*
* @param session The attached session.
* @param name The name of the property.
*
* @return The property value (returns null if the property has not been set).
*/
static public String getProperty(final Session session, final String name) {
// occasionally, we get called with a null session if an object is not attached to
// a session. In that case, treat this like an unknown parameter.
if (session == null) {
return null;
}
return session.getProperty(name);
}
/**
* Get a property associated with this mail session. Returns
* the provided default if it doesn't exist.
*
* @param session The attached session.
* @param name The name of the property.
* @param defaultValue
* The default value to return if the property doesn't exist.
*
* @return The property value (returns defaultValue if the property has not been set).
*/
static public String getProperty(final Session session, final String name, final String defaultValue) {
final String result = getProperty(session, name);
if (result == null) {
return defaultValue;
}
return result;
}
/**
* Process a session property as a boolean value, returning
* either true or false.
*
* @param session The source session.
* @param name
*
* @return True if the property value is "true". Returns false for any
* other value (including null).
*/
static public boolean isPropertyTrue(final Session session, final String name) {
final String property = getProperty(session, name);
if (property != null) {
return property.equals("true");
}
return false;
}
/**
* Process a session property as a boolean value, returning
* either true or false.
*
* @param session The source session.
* @param name
*
* @return True if the property value is "false". Returns false for
* other value (including null).
*/
static public boolean isPropertyFalse(final Session session, final String name) {
final String property = getProperty(session, name);
if (property != null) {
return property.equals("false");
}
return false;
}
/**
* Get a property associated with this mail session as an integer value. Returns
* the default value if the property doesn't exist or it doesn't have a valid int value.
*
* @param session The source session.
* @param name The name of the property.
* @param defaultValue
* The default value to return if the property doesn't exist.
*
* @return The property value converted to an int.
*/
static public int getIntProperty(final Session session, final String name, final int defaultValue) {
final String result = getProperty(session, name);
if (result != null) {
try {
// convert into an int value.
return Integer.parseInt(result);
} catch (final NumberFormatException e) {
}
}
// return default value if it doesn't exist is isn't convertable.
return defaultValue;
}
/**
* Get a property associated with this mail session as a boolean value. Returns
* the default value if the property doesn't exist or it doesn't have a valid boolean value.
*
* @param session The source session.
* @param name The name of the property.
* @param defaultValue
* The default value to return if the property doesn't exist.
*
* @return The property value converted to a boolean.
*/
static public boolean getBooleanProperty(final Session session, final String name, final boolean defaultValue) {
final String result = getProperty(session, name);
if (result != null) {
return Boolean.valueOf(result).booleanValue();
}
// return default value if it doesn't exist is isn't convertable.
return defaultValue;
}
/**
* Get a system property associated with this mail session as a boolean value. Returns
* the default value if the property doesn't exist or it doesn't have a valid boolean value.
*
* @param name The name of the property.
* @param defaultValue
* The default value to return if the property doesn't exist.
*
* @return The property value converted to a boolean.
*/
static public boolean getBooleanProperty(final String name, final boolean defaultValue) {
try {
final String result = System.getProperty(name);
if (result != null) {
return Boolean.valueOf(result).booleanValue();
}
} catch (final SecurityException e) {
// we can't access the property, so for all intents, it doesn't exist.
}
// return default value if it doesn't exist is isn't convertable.
return defaultValue;
}
/**
* Get a system property associated with this mail session as a boolean value. Returns
* the default value if the property doesn't exist.
*
* @param name The name of the property.
* @param defaultValue
* The default value to return if the property doesn't exist.
*
* @return The property value
*/
static public String getProperty(final String name, final String defaultValue) {
try {
final String result = System.getProperty(name);
if (result != null) {
return result;
}
} catch (final SecurityException e) {
// we can't access the property, so for all intents, it doesn't exist.
}
// return default value if it doesn't exist is isn't convertable.
return defaultValue;
}
/**
* Get a system property associated with this mail session as a boolean value. Returns
* the default value if the property doesn't exist.
*
* @param name The name of the property.
*
* @return The property value
*/
static public String getProperty(final String name) {
try {
return System.getProperty(name);
} catch (final SecurityException e) {
// we can't access the property, so for all intents, it doesn't exist.
}
// return null if we got an exception.
return null;
}
}
| 1,920 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import javax.mail.internet.MimeUtility;
/**
* Encoder for RFC2231 encoded parameters
*
* RFC2231 string are encoded as
*
* charset'language'encoded-text
*
* and
*
* encoded-text = *(char / hexchar)
*
* where
*
* char is any ASCII character in the range 33-126, EXCEPT
* the characters "%" and " ".
*
* hexchar is an ASCII "%" followed by two upper case
* hexadecimal digits.
*/
public class RFC2231Encoder implements Encoder
{
protected final byte[] encodingTable =
{
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
(byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F'
};
protected String DEFAULT_SPECIALS = " *'%";
protected String specials = DEFAULT_SPECIALS;
/*
* set up the decoding table.
*/
protected final byte[] decodingTable = new byte[128];
protected void initialiseDecodingTable()
{
for (int i = 0; i < encodingTable.length; i++)
{
decodingTable[encodingTable[i]] = (byte)i;
}
}
public RFC2231Encoder()
{
this(null);
}
public RFC2231Encoder(final String specials)
{
if (specials != null) {
this.specials = DEFAULT_SPECIALS + specials;
}
initialiseDecodingTable();
}
/**
* encode the input data producing an RFC2231 output stream.
*
* @return the number of bytes produced.
*/
public int encode(final byte[] data, final int off, final int length, final OutputStream out) throws IOException {
int bytesWritten = 0;
for (int i = off; i < (off + length); i++)
{
final int ch = data[i] & 0xff;
// character tha must be encoded? Prefix with a '%' and encode in hex.
if (ch <= 32 || ch >= 127 || specials.indexOf(ch) != -1) {
out.write((byte)'%');
out.write(encodingTable[ch >> 4]);
out.write(encodingTable[ch & 0xf]);
bytesWritten += 3;
}
else {
// add unchanged.
out.write((byte)ch);
bytesWritten++;
}
}
return bytesWritten;
}
/**
* decode the RFC2231 encoded byte data writing it to the given output stream
*
* @return the number of bytes produced.
*/
public int decode(final byte[] data, final int off, final int length, final OutputStream out) throws IOException {
int outLen = 0;
final int end = off + length;
int i = off;
while (i < end)
{
final byte v = data[i++];
// a percent is a hex character marker, need to decode a hex value.
if (v == '%') {
final byte b1 = decodingTable[data[i++]];
final byte b2 = decodingTable[data[i++]];
out.write((b1 << 4) | b2);
}
else {
// copied over unchanged.
out.write(v);
}
// always just one byte added
outLen++;
}
return outLen;
}
/**
* decode the RFC2231 encoded String data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public int decode(final String data, final OutputStream out) throws IOException
{
int length = 0;
final int end = data.length();
int i = 0;
while (i < end)
{
final char v = data.charAt(i++);
if (v == '%') {
final byte b1 = decodingTable[data.charAt(i++)];
final byte b2 = decodingTable[data.charAt(i++)];
out.write((b1 << 4) | b2);
}
else {
out.write((byte)v);
}
length++;
}
return length;
}
/**
* Encode a string as an RFC2231 encoded parameter, using the
* given character set and language.
*
* @param charset The source character set (the MIME version).
* @param language The encoding language.
* @param data The data to encode.
*
* @return The encoded string.
*/
public String encode(final String charset, final String language, final String data) throws IOException {
byte[] bytes = null;
try {
// the charset we're adding is the MIME-defined name. We need the java version
// in order to extract the bytes.
bytes = data.getBytes(MimeUtility.javaCharset(charset));
} catch (final UnsupportedEncodingException e) {
// we have a translation problem here.
return null;
}
final StringBuffer result = new StringBuffer();
// append the character set, if we have it.
if (charset != null) {
result.append(charset);
}
// the field marker is required.
result.append("'");
// and the same for the language.
if (language != null) {
result.append(language);
}
// the field marker is required.
result.append("'");
// wrap an output stream around our buffer for the decoding
final OutputStream out = new StringBufferOutputStream(result);
// encode the data stream
encode(bytes, 0, bytes.length, out);
// finis!
return result.toString();
}
/**
* Decode an RFC2231 encoded string.
*
* @param data The data to decode.
*
* @return The decoded string.
* @exception IOException
* @exception UnsupportedEncodingException
*/
public String decode(final String data) throws IOException, UnsupportedEncodingException {
// get the end of the language field
final int charsetEnd = data.indexOf('\'');
// uh oh, might not be there
if (charsetEnd == -1) {
throw new IOException("Missing charset in RFC2231 encoded value");
}
final String charset = data.substring(0, charsetEnd);
// now pull out the language the same way
final int languageEnd = data.indexOf('\'', charsetEnd + 1);
if (languageEnd == -1) {
throw new IOException("Missing language in RFC2231 encoded value");
}
//final String language = data.substring(charsetEnd + 1, languageEnd);
final ByteArrayOutputStream out = new ByteArrayOutputStream(data.length());
// decode the data
decode(data.substring(languageEnd + 1), out);
final byte[] bytes = out.toByteArray();
// build a new string from this using the java version of the encoded charset.
return new String(bytes, 0, bytes.length, MimeUtility.javaCharset(charset));
}
}
| 1,921 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/QuotedPrintable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class QuotedPrintable {
// NOTE: the QuotedPrintableEncoder class needs to keep some active state about what's going on with
// respect to line breaks and significant white spaces. This makes it difficult to keep one static
// instance of the decode around for reuse.
/**
* encode the input data producing a Q-P encoded byte array.
*
* @return a byte array containing the Q-P encoded data.
*/
public static byte[] encode(
final byte[] data)
{
return encode(data, 0, data.length);
}
/**
* encode the input data producing a Q-P encoded byte array.
*
* @return a byte array containing the Q-P encoded data.
*/
public static byte[] encode(
final byte[] data,
final int off,
final int length)
{
final QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.encode(data, off, length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception encoding Q-P encoded string: " + e);
}
return bOut.toByteArray();
}
/**
* Q-P encode the byte data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final OutputStream out)
throws IOException
{
final QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
return encoder.encode(data, 0, data.length, out);
}
/**
* Q-P encode the byte data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
final QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
return encoder.encode(data, 0, data.length, out);
}
/**
* decode the Q-P encoded input data. It is assumed the input data is valid.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final byte[] data)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
final QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
try
{
encoder.decode(data, 0, data.length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding Q-P encoded string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the UUEncided String data.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final String data)
{
final QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding Q-P encoded string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the Q-P encoded encoded String data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int decode(
final String data,
final OutputStream out)
throws IOException
{
final QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
return encoder.decode(data, out);
}
/**
* decode the base Q-P encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @param data The array data to decode.
* @param out The output stream for the data.
*
* @return the number of bytes produced.
* @exception IOException
*/
public static int decode(final byte [] data, final OutputStream out) throws IOException
{
final QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
return encoder.decode(data, 0, data.length, out);
}
}
| 1,922 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/HexEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.IOException;
import java.io.OutputStream;
public class HexEncoder
implements Encoder
{
protected final byte[] encodingTable =
{
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
(byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'
};
/*
* set up the decoding table.
*/
protected final byte[] decodingTable = new byte[128];
protected void initialiseDecodingTable()
{
for (int i = 0; i < encodingTable.length; i++)
{
decodingTable[encodingTable[i]] = (byte)i;
}
decodingTable['A'] = decodingTable['a'];
decodingTable['B'] = decodingTable['b'];
decodingTable['C'] = decodingTable['c'];
decodingTable['D'] = decodingTable['d'];
decodingTable['E'] = decodingTable['e'];
decodingTable['F'] = decodingTable['f'];
}
public HexEncoder()
{
initialiseDecodingTable();
}
/**
* encode the input data producing a Hex output stream.
*
* @return the number of bytes produced.
*/
public int encode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
for (int i = off; i < (off + length); i++)
{
final int v = data[i] & 0xff;
out.write(encodingTable[(v >>> 4)]);
out.write(encodingTable[v & 0xf]);
}
return length * 2;
}
private boolean ignore(
final char c)
{
return (c == '\n' || c =='\r' || c == '\t' || c == ' ');
}
/**
* decode the Hex encoded byte data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public int decode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
byte b1, b2;
int outLen = 0;
int end = off + length;
while (end > 0)
{
if (!ignore((char)data[end - 1]))
{
break;
}
end--;
}
int i = off;
while (i < end)
{
while (i < end && ignore((char)data[i]))
{
i++;
}
b1 = decodingTable[data[i++]];
while (i < end && ignore((char)data[i]))
{
i++;
}
b2 = decodingTable[data[i++]];
out.write((b1 << 4) | b2);
outLen++;
}
return outLen;
}
/**
* decode the Hex encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public int decode(
final String data,
final OutputStream out)
throws IOException
{
byte b1, b2;
int length = 0;
int end = data.length();
while (end > 0)
{
if (!ignore(data.charAt(end - 1)))
{
break;
}
end--;
}
int i = 0;
while (i < end)
{
while (i < end && ignore(data.charAt(i)))
{
i++;
}
b1 = decodingTable[data.charAt(i++)];
while (i < end && ignore(data.charAt(i)))
{
i++;
}
b2 = decodingTable[data.charAt(i++)];
out.write((b1 << 4) | b2);
length++;
}
return length;
}
}
| 1,923 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/XText.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Encoder for RFC1891 xtext.
*
* xtext strings are defined as
*
* xtext = *( xchar / hexchar )
*
* where
*
* xchar is any ASCII character in the range 33-126, EXCEPT
* the characters "+" and "=".
*
* hexchar is an ASCII "+" followed by two upper case
* hexadecimal digits.
*/
public class XText
{
private static final Encoder encoder = new XTextEncoder();
/**
* encode the input data producing an xtext encoded byte array.
*
* @return a byte array containing the xtext encoded data.
*/
public static byte[] encode(
final byte[] data)
{
return encode(data, 0, data.length);
}
/**
* encode the input data producing an xtext encoded byte array.
*
* @return a byte array containing the xtext encoded data.
*/
public static byte[] encode(
final byte[] data,
final int off,
final int length)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.encode(data, off, length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception encoding xtext string: " + e);
}
return bOut.toByteArray();
}
/**
* xtext encode the byte data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final OutputStream out)
throws IOException
{
return encoder.encode(data, 0, data.length, out);
}
/**
* extext encode the byte data writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
final byte[] data,
final int off,
final int length,
final OutputStream out)
throws IOException
{
return encoder.encode(data, 0, data.length, out);
}
/**
* decode the xtext encoded input data. It is assumed the input data is valid.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final byte[] data)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, 0, data.length, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding xtext string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the xtext encoded String data - whitespace will be ignored.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
final String data)
{
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, bOut);
}
catch (final IOException e)
{
throw new RuntimeException("exception decoding xtext string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the xtext encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public static int decode(
final String data,
final OutputStream out)
throws IOException
{
return encoder.decode(data, out);
}
}
| 1,924 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* An implementation of a FilterOutputStream that encodes the
* stream data in BASE64 encoding format. This version does the
* encoding "on the fly" rather than encoding a single block of
* data. Since this version is intended for use by the MimeUtilty class,
* it also handles line breaks in the encoded data.
*/
public class Base64EncoderStream extends FilterOutputStream {
// our Filtered stream writes everything out as byte data. This allows the CRLF sequence to
// be written with a single call.
protected static final byte[] CRLF = { '\r', '\n' };
// our hex encoder utility class.
protected Base64Encoder encoder = new Base64Encoder();
// our default for line breaks
protected static final int DEFAULT_LINEBREAK = 76;
// Data can only be written out in complete units of 3 bytes encoded as 4. Therefore, we need to buffer
// as many as 2 bytes to fill out an encoding unit.
// the buffered byte count
protected int bufferedBytes = 0;
// we'll encode this part once it is filled up.
protected byte[] buffer = new byte[3];
// the size we process line breaks at. If this is Integer.MAX_VALUE, no line breaks are handled.
protected int lineBreak;
// the number of encoded characters we've written to the stream, which determines where we
// insert line breaks.
protected int outputCount;
/**
* Create a Base64 encoder stream that wraps a specifed stream
* using the default line break size.
*
* @param out The wrapped output stream.
*/
public Base64EncoderStream(final OutputStream out) {
this(out, DEFAULT_LINEBREAK);
}
public Base64EncoderStream(final OutputStream out, final int lineBreak) {
super(out);
// lines are processed only in multiple of 4, so round this down.
this.lineBreak = (lineBreak / 4) * 4 ;
}
// in order for this to work, we need to override the 3 different signatures for write
@Override
public void write(final int ch) throws IOException {
// store this in the buffer.
buffer[bufferedBytes++] = (byte)ch;
// if the buffer is filled, encode these bytes
if (bufferedBytes == 3) {
// check for room in the current line for this character
checkEOL(4);
// write these directly to the stream.
encoder.encode(buffer, 0, 3, out);
bufferedBytes = 0;
// and update the line length checkers
updateLineCount(4);
}
}
@Override
public void write(final byte [] data) throws IOException {
write(data, 0, data.length);
}
@Override
public void write(final byte [] data, int offset, int length) throws IOException {
// if we have something in the buffer, we need to write enough bytes out to flush
// those into the output stream AND continue on to finish off a line. Once we're done there
// we can write additional data out in complete blocks.
while ((bufferedBytes > 0 || outputCount > 0) && length > 0) {
write(data[offset++]);
length--;
}
if (length > 0) {
// no linebreaks requested? YES!!!!!, we can just dispose of the lot with one call.
if (lineBreak == Integer.MAX_VALUE) {
encoder.encode(data, offset, length, out);
}
else {
// calculate the size of a segment we can encode directly as a line.
final int segmentSize = (lineBreak / 4) * 3;
// write this out a block at a time, with separators between.
while (length > segmentSize) {
// encode a segment
encoder.encode(data, offset, segmentSize, out);
// write an EOL marker
out.write(CRLF);
offset += segmentSize;
length -= segmentSize;
}
// any remainder we write out a byte at a time to manage the groupings and
// the line count appropriately.
if (length > 0) {
while (length > 0) {
write(data[offset++]);
length--;
}
}
}
}
}
@Override
public void close() throws IOException {
flush();
out.close();
}
@Override
public void flush() throws IOException {
if (bufferedBytes > 0) {
encoder.encode(buffer, 0, bufferedBytes, out);
bufferedBytes = 0;
}
}
/**
* Check for whether we're about the reach the end of our
* line limit for an update that's about to occur. If we will
* overflow, then a line break is inserted.
*
* @param required The space required for this pending write.
*
* @exception IOException
*/
private void checkEOL(final int required) throws IOException {
if (lineBreak != Integer.MAX_VALUE) {
// if this write would exceed the line maximum, add a linebreak to the stream.
if (outputCount + required > lineBreak) {
out.write(CRLF);
outputCount = 0;
}
}
}
/**
* Update the counter of characters on the current working line.
* This is conditional if we're not working with a line limit.
*
* @param added The number of characters just added.
*/
private void updateLineCount(final int added) {
if (lineBreak != Integer.MAX_VALUE) {
outputCount += added;
}
}
}
| 1,925 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/Encoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.IOException;
import java.io.OutputStream;
/**
* Encode and decode byte arrays (typically from binary to 7-bit ASCII
* encodings).
*/
public interface Encoder
{
int encode(byte[] data, int off, int length, OutputStream out) throws IOException;
int decode(byte[] data, int off, int length, OutputStream out) throws IOException;
int decode(String data, OutputStream out) throws IOException;
}
| 1,926 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/util/UUEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.util;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
public class UUEncoder implements Encoder {
// this is the maximum number of chars allowed per line, since we have to include a uuencoded length at
// the start of each line.
static private final int MAX_CHARS_PER_LINE = 45;
public UUEncoder()
{
}
/**
* encode the input data producing a UUEncoded output stream.
*
* @param data The array of byte data.
* @param off The starting offset within the data.
* @param length Length of the data to encode.
* @param out The output stream the encoded data is written to.
*
* @return the number of bytes produced.
*/
public int encode(final byte[] data, int off, int length, final OutputStream out) throws IOException
{
int byteCount = 0;
while (true) {
// keep writing complete lines until we've exhausted the data.
if (length > MAX_CHARS_PER_LINE) {
// encode another line and adjust the length and position
byteCount += encodeLine(data, off, MAX_CHARS_PER_LINE, out);
length -= MAX_CHARS_PER_LINE;
off += MAX_CHARS_PER_LINE;
}
else {
// last line. Encode the partial and quit
byteCount += encodeLine(data, off, MAX_CHARS_PER_LINE, out);
break;
}
}
return byteCount;
}
/**
* Encode a single line of data (less than or equal to 45 characters).
*
* @param data The array of byte data.
* @param off The starting offset within the data.
* @param length Length of the data to encode.
* @param out The output stream the encoded data is written to.
*
* @return The number of bytes written to the output stream.
* @exception IOException
*/
private int encodeLine(final byte[] data, final int offset, final int length, final OutputStream out) throws IOException {
// write out the number of characters encoded in this line.
out.write((byte)((length & 0x3F) + ' '));
byte a;
byte b;
byte c;
// count the bytes written...we add 2, one for the length and 1 for the linend terminator.
int bytesWritten = 2;
for (int i = 0; i < length;) {
// set the padding defauls
b = 1;
c = 1;
// get the next 3 bytes (if we have them)
a = data[offset + i++];
if (i < length) {
b = data[offset + i++];
if (i < length) {
c = data[offset + i++];
}
}
final byte d1 = (byte)(((a >>> 2) & 0x3F) + ' ');
final byte d2 = (byte)(((( a << 4) & 0x30) | ((b >>> 4) & 0x0F)) + ' ');
final byte d3 = (byte)((((b << 2) & 0x3C) | ((c >>> 6) & 0x3)) + ' ');
final byte d4 = (byte)((c & 0x3F) + ' ');
out.write(d1);
out.write(d2);
out.write(d3);
out.write(d4);
bytesWritten += 4;
}
// terminate with a linefeed alone
out.write('\n');
return bytesWritten;
}
/**
* decode the uuencoded byte data writing it to the given output stream
*
* @param data The array of byte data to decode.
* @param off Starting offset within the array.
* @param length The length of data to encode.
* @param out The output stream used to return the decoded data.
*
* @return the number of bytes produced.
* @exception IOException
*/
public int decode(final byte[] data, int off, int length, final OutputStream out) throws IOException
{
int bytesWritten = 0;
while (length > 0) {
final int lineOffset = off;
// scan forward looking for a EOL terminator for the next line of data.
while (length > 0 && data[off] != '\n') {
off++;
length--;
}
// go decode this line of data
bytesWritten += decodeLine(data, lineOffset, off - lineOffset, out);
// the offset was left pointing at the EOL character, so step over that one before
// scanning again.
off++;
length--;
}
return bytesWritten;
}
/**
* decode a single line of uuencoded byte data writing it to the given output stream
*
* @param data The array of byte data to decode.
* @param off Starting offset within the array.
* @param length The length of data to decode (length does NOT include the terminating new line).
* @param out The output stream used to return the decoded data.
*
* @return the number of bytes produced.
* @exception IOException
*/
private int decodeLine(final byte[] data, int off, final int length, final OutputStream out) throws IOException {
int count = data[off++];
// obtain and validate the count
if (count < ' ') {
throw new IOException("Invalid UUEncode line length");
}
count = (count - ' ') & 0x3F;
// get the rounded count of characters that should have been used to encode this. The + 1 is for the
// length encoded at the beginning
final int requiredLength = (((count * 8) + 5) / 6) + 1;
if (length < requiredLength) {
throw new IOException("UUEncoded data and length do not match");
}
int bytesWritten = 0;
// now decode the bytes.
while (bytesWritten < count) {
// even one byte of data requires two bytes to encode, so we should have that.
final byte a = (byte)((data[off++] - ' ') & 0x3F);
final byte b = (byte)((data[off++] - ' ') & 0x3F);
byte c = 0;
byte d = 0;
// do the first byte
final byte first = (byte)(((a << 2) & 0xFC) | ((b >>> 4) & 3));
out.write(first);
bytesWritten++;
// still have more bytes to decode? do the second byte of the second. That requires
// a third byte from the data.
if (bytesWritten < count) {
c = (byte)((data[off++] - ' ') & 0x3F);
final byte second = (byte)(((b << 4) & 0xF0) | ((c >>> 2) & 0x0F));
out.write(second);
bytesWritten++;
// need the third one?
if (bytesWritten < count) {
d = (byte)((data[off++] - ' ') & 0x3F);
final byte third = (byte)(((c << 6) & 0xC0) | (d & 0x3F));
out.write(third);
bytesWritten++;
}
}
}
return bytesWritten;
}
/**
* decode the UUEncoded String data writing it to the given output stream.
*
* @param data The String data to decode.
* @param out The output stream to write the decoded data to.
*
* @return the number of bytes produced.
* @exception IOException
*/
public int decode(final String data, final OutputStream out) throws IOException
{
try {
// just get the byte data and decode.
final byte[] bytes = data.getBytes("US-ASCII");
return decode(bytes, 0, bytes.length, out);
} catch (final UnsupportedEncodingException e) {
throw new IOException("Invalid UUEncoding");
}
}
}
| 1,927 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/handlers/MultipartHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.handlers;
import java.awt.datatransfer.DataFlavor;
import java.io.IOException;
import java.io.OutputStream;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataContentHandler;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMultipart;
public class MultipartHandler implements DataContentHandler {
/**
* Field dataFlavor
*/
ActivationDataFlavor dataFlavor;
public MultipartHandler(){
dataFlavor = new ActivationDataFlavor(javax.mail.internet.MimeMultipart.class, "multipart/mixed", "Multipart");
}
/**
* Constructor TextHandler
*
* @param dataFlavor
*/
public MultipartHandler(final ActivationDataFlavor dataFlavor) {
this.dataFlavor = dataFlavor;
}
/**
* Method getDF
*
* @return dataflavor
*/
protected ActivationDataFlavor getDF() {
return dataFlavor;
}
/**
* Method getTransferDataFlavors
*
* @return dataflavors
*/
public DataFlavor[] getTransferDataFlavors() {
return (new DataFlavor[]{dataFlavor});
}
/**
* Method getTransferData
*
* @param dataflavor
* @param datasource
* @return
* @throws IOException
*/
public Object getTransferData(final DataFlavor dataflavor, final DataSource datasource)
throws IOException {
if (getDF().equals(dataflavor)) {
return getContent(datasource);
}
return null;
}
/**
* Method getContent
*
* @param datasource
* @return
* @throws IOException
*/
public Object getContent(final DataSource datasource) throws IOException {
try {
return new MimeMultipart(datasource);
} catch (final MessagingException e) {
// if there is a syntax error from the datasource parsing, the content is
// just null.
return null;
}
}
/**
* Method writeTo
*
* @param object
* @param s
* @param outputstream
* @throws IOException
*/
public void writeTo(final Object object, final String s, final OutputStream outputstream) throws IOException {
// if this object is a MimeMultipart, then delegate to the part.
if (object instanceof MimeMultipart) {
try {
((MimeMultipart)object).writeTo(outputstream);
} catch (final MessagingException e) {
// we need to transform any exceptions into an IOException.
throw new IOException("Exception writing MimeMultipart: " + e.toString());
}
}
}
}
| 1,928 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/handlers/TextHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.handlers;
import java.awt.datatransfer.DataFlavor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataContentHandler;
import javax.activation.DataSource;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.ParseException;
public class TextHandler implements DataContentHandler {
/**
* Field dataFlavor
*/
ActivationDataFlavor dataFlavor;
public TextHandler(){
dataFlavor = new ActivationDataFlavor(java.lang.String.class, "text/plain", "Text String");
}
/**
* Constructor TextHandler
*
* @param dataFlavor
*/
public TextHandler(final ActivationDataFlavor dataFlavor) {
this.dataFlavor = dataFlavor;
}
/**
* Method getDF
*
* @return dataflavor
*/
protected ActivationDataFlavor getDF() {
return dataFlavor;
}
/**
* Method getTransferDataFlavors
*
* @return dataflavors
*/
public DataFlavor[] getTransferDataFlavors() {
return (new DataFlavor[]{dataFlavor});
}
/**
* Method getTransferData
*
* @param dataflavor
* @param datasource
* @return
* @throws IOException
*/
public Object getTransferData(final DataFlavor dataflavor, final DataSource datasource)
throws IOException {
if (getDF().equals(dataflavor)) {
return getContent(datasource);
}
return null;
}
/**
* Method getContent
*
* @param datasource
* @return
* @throws IOException
*/
public Object getContent(final DataSource datasource) throws IOException {
final InputStream is = datasource.getInputStream();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
int count;
final byte[] buffer = new byte[1000];
try {
while ((count = is.read(buffer, 0, buffer.length)) > 0) {
os.write(buffer, 0, count);
}
} finally {
is.close();
}
try {
return os.toString(getCharSet(datasource.getContentType()));
} catch (final ParseException e) {
throw new UnsupportedEncodingException(e.getMessage());
}
}
/**
* Write an object of "our" type out to the provided
* output stream. The content type might modify the
* result based on the content type parameters.
*
* @param object The object to write.
* @param contentType
* The content mime type, including parameters.
* @param outputstream
* The target output stream.
*
* @throws IOException
*/
public void writeTo(final Object object, final String contentType, final OutputStream outputstream)
throws IOException {
OutputStreamWriter os;
try {
final String charset = getCharSet(contentType);
os = new OutputStreamWriter(outputstream, charset);
} catch (final Exception ex) {
throw new UnsupportedEncodingException(ex.toString());
}
final String content = (String) object;
os.write(content, 0, content.length());
os.flush();
}
/**
* get the character set from content type
* @param contentType
* @return
* @throws ParseException
*/
protected String getCharSet(final String contentType) throws ParseException {
final ContentType type = new ContentType(contentType);
String charset = type.getParameter("charset");
if (charset == null) {
charset = "us-ascii";
}
return MimeUtility.javaCharset(charset);
}
}
| 1,929 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/handlers/MessageHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.handlers;
import java.awt.datatransfer.DataFlavor;
import java.io.IOException;
import java.io.OutputStream;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataContentHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.MessageAware;
import javax.mail.MessageContext;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
public class MessageHandler implements DataContentHandler {
/**
* Field dataFlavor
*/
ActivationDataFlavor dataFlavor;
public MessageHandler(){
dataFlavor = new ActivationDataFlavor(java.lang.String.class, "message/rfc822", "Text");
}
/**
* Method getDF
*
* @return dataflavor
*/
protected ActivationDataFlavor getDF() {
return dataFlavor;
}
/**
* Method getTransferDataFlavors
*
* @return dataflavors
*/
public DataFlavor[] getTransferDataFlavors() {
return (new DataFlavor[]{dataFlavor});
}
/**
* Method getTransferData
*
* @param dataflavor
* @param datasource
* @return
* @throws IOException
*/
public Object getTransferData(final DataFlavor dataflavor, final DataSource datasource)
throws IOException {
if (getDF().equals(dataflavor)) {
return getContent(datasource);
}
return null;
}
/**
* Method getContent
*
* @param datasource
* @return
* @throws IOException
*/
public Object getContent(final DataSource datasource) throws IOException {
try {
// if this is a proper message, it implements the MessageAware interface. We need this to
// get the associated session.
if (datasource instanceof MessageAware) {
final MessageContext context = ((MessageAware)datasource).getMessageContext();
// construct a mime message instance from the stream, associating it with the
// data source session.
return new MimeMessage(context.getSession(), datasource.getInputStream());
}
} catch (final MessagingException e) {
// we need to transform any exceptions into an IOException.
throw new IOException("Exception writing MimeMultipart: " + e.toString());
}
return null;
}
/**
* Method writeTo
*
* @param object
* @param s
* @param outputstream
* @throws IOException
*/
public void writeTo(final Object object, final String s, final OutputStream outputstream) throws IOException {
// proper message type?
if (object instanceof Message) {
try {
((Message)object).writeTo(outputstream);
} catch (final MessagingException e) {
throw new IOException("Error parsing message: " + e.toString());
}
}
}
}
| 1,930 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/handlers/HtmlHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.handlers;
import javax.activation.ActivationDataFlavor;
public class HtmlHandler extends TextHandler {
public HtmlHandler() {
super(new ActivationDataFlavor(java.lang.String.class, "text/html", "HTML String"));
}
}
| 1,931 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/org/apache/geronimo/mail/handlers/XMLHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.mail.handlers;
import javax.activation.ActivationDataFlavor;
public class XMLHandler extends TextHandler {
public XMLHandler() {
super(new ActivationDataFlavor(java.lang.String.class, "text/xml", "XML String"));
}
}
| 1,932 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/StoreClosedException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class StoreClosedException extends MessagingException {
private static final long serialVersionUID = -3145392336120082655L;
private transient Store _store;
public StoreClosedException(final Store store) {
super();
_store = store;
}
public StoreClosedException(final Store store, final String message) {
super(message);
_store = store;
}
/**
* Constructs a StoreClosedException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param store The dead Store object
* @param message The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public StoreClosedException(final Store store, final String message, final Exception e) {
super(message, e);
_store = store;
}
public Store getStore() {
return _store;
}
}
| 1,933 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/BodyPart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public abstract class BodyPart implements Part {
protected Multipart parent;
public Multipart getParent() {
return parent;
}
// Can't be public. Not strictly required for spec, but mirrors Sun's javamail api impl.
void setParent(final Multipart parent)
{
this.parent = parent;
}
}
| 1,934 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Message.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.Date;
import javax.mail.search.SearchTerm;
/**
* @version $Rev$ $Date$
*/
public abstract class Message implements Part {
/**
* Enumeration of types of recipients allowed by the Message class.
*/
public static class RecipientType implements Serializable {
/**
* A "To" or primary recipient.
*/
public static final RecipientType TO = new RecipientType("To");
/**
* A "Cc" or carbon-copy recipient.
*/
public static final RecipientType CC = new RecipientType("Cc");
/**
* A "Bcc" or blind carbon-copy recipient.
*/
public static final RecipientType BCC = new RecipientType("Bcc");
protected String type;
protected RecipientType(final String type) {
this.type = type;
}
protected Object readResolve() throws ObjectStreamException {
if (type.equals("To")) {
return TO;
} else if (type.equals("Cc")) {
return CC;
} else if (type.equals("Bcc")) {
return BCC;
} else {
throw new InvalidObjectException("Invalid RecipientType: " + type);
}
}
@Override
public String toString() {
return type;
}
}
/**
* The index of a message within its folder, or zero if the message was not retrieved from a folder.
*/
protected int msgnum;
/**
* True if this message has been expunged from the Store.
*/
protected boolean expunged;
/**
* The {@link Folder} that contains this message, or null if it was not obtained from a folder.
*/
protected Folder folder;
/**
* The {@link Session} associated with this message.
*/
protected Session session;
/**
* Default constructor.
*/
protected Message() {
}
/**
* Constructor initializing folder and message msgnum; intended to be used by implementations of Folder.
*
* @param folder the folder that contains the message
* @param msgnum the message index within the folder
*/
protected Message(final Folder folder, final int msgnum) {
this.folder = folder;
this.msgnum = msgnum;
// make sure we copy the session information from the folder.
this.session = folder.getStore().getSession();
}
/**
* Constructor initializing the session; intended to by used by client created instances.
*
* @param session the session associated with this message
*/
protected Message(final Session session) {
this.session = session;
}
/**
* Return the "From" header indicating the identity of the person the message is from;
* in some circumstances this may be different than the actual sender.
*
* @return a list of addresses this message is from; may be empty if the header is present but empty, or null
* if the header is not present
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract Address[] getFrom() throws MessagingException;
/**
* Set the "From" header for this message to the value of the "mail.user" property,
* or if that property is not set, to the value of the system property "user.name"
*
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void setFrom() throws MessagingException;
/**
* Set the "From" header to the supplied address.
*
* @param address the address of the person the message is from
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void setFrom(Address address) throws MessagingException;
/**
* Add multiple addresses to the "From" header.
*
* @param addresses the addresses to add
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void addFrom(Address[] addresses) throws MessagingException;
/**
* Get all recipients of the given type.
*
* @param type the type of recipient to get
* @return a list of addresses; may be empty if the header is present but empty,
* or null if the header is not present
* @throws MessagingException if there was a problem accessing the Store
* @see RecipientType
*/
public abstract Address[] getRecipients(RecipientType type) throws MessagingException;
/**
* Get all recipients of this message.
* The default implementation extracts the To, Cc, and Bcc recipients using {@link #getRecipients(javax.mail.Message.RecipientType)}
* and then concatentates the results into a single array; it returns null if no headers are defined.
*
* @return an array containing all recipients
* @throws MessagingException if there was a problem accessing the Store
*/
public Address[] getAllRecipients() throws MessagingException {
final Address[] to = getRecipients(RecipientType.TO);
final Address[] cc = getRecipients(RecipientType.CC);
final Address[] bcc = getRecipients(RecipientType.BCC);
if (to == null && cc == null && bcc == null) {
return null;
}
final int length = (to != null ? to.length : 0) + (cc != null ? cc.length : 0) + (bcc != null ? bcc.length : 0);
final Address[] result = new Address[length];
int j = 0;
if (to != null) {
for (int i = 0; i < to.length; i++) {
result[j++] = to[i];
}
}
if (cc != null) {
for (int i = 0; i < cc.length; i++) {
result[j++] = cc[i];
}
}
if (bcc != null) {
for (int i = 0; i < bcc.length; i++) {
result[j++] = bcc[i];
}
}
return result;
}
/**
* Set the list of recipients for the specified type.
*
* @param type the type of recipient
* @param addresses the new addresses
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException;
/**
* Set the list of recipients for the specified type to a single address.
*
* @param type the type of recipient
* @param address the new address
* @throws MessagingException if there was a problem accessing the Store
*/
public void setRecipient(final RecipientType type, final Address address) throws MessagingException {
setRecipients(type, new Address[]{address});
}
/**
* Add recipents of a specified type.
*
* @param type the type of recipient
* @param addresses the addresses to add
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void addRecipients(RecipientType type, Address[] addresses) throws MessagingException;
/**
* Add a recipent of a specified type.
*
* @param type the type of recipient
* @param address the address to add
* @throws MessagingException if there was a problem accessing the Store
*/
public void addRecipient(final RecipientType type, final Address address) throws MessagingException {
addRecipients(type, new Address[]{address});
}
/**
* Get the addresses to which replies should be directed.
* <p/>
* As the most common behavior is to return to sender, the default implementation
* simply calls {@link #getFrom()}.
*
* @return a list of addresses to which replies should be directed
* @throws MessagingException if there was a problem accessing the Store
*/
public Address[] getReplyTo() throws MessagingException {
return getFrom();
}
/**
* Set the addresses to which replies should be directed.
* <p/>
* The default implementation throws a MethodNotSupportedException.
*
* @param addresses to which replies should be directed
* @throws MessagingException if there was a problem accessing the Store
*/
public void setReplyTo(final Address[] addresses) throws MessagingException {
throw new MethodNotSupportedException("setReplyTo not supported");
}
/**
* Get the subject for this message.
*
* @return the subject
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract String getSubject() throws MessagingException;
/**
* Set the subject of this message
*
* @param subject the subject
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void setSubject(String subject) throws MessagingException;
/**
* Return the date that this message was sent.
*
* @return the date this message was sent
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract Date getSentDate() throws MessagingException;
/**
* Set the date this message was sent.
*
* @param sent the date when this message was sent
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void setSentDate(Date sent) throws MessagingException;
/**
* Return the Session used when this message was created.
*
* @return the message's Session
* @since JavaMail 1.5
*/
public Session getSession() {
return this.session;
}
/**
* Return the date this message was received.
*
* @return the date this message was received
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract Date getReceivedDate() throws MessagingException;
/**
* Return a copy the flags associated with this message.
*
* @return a copy of the flags for this message
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract Flags getFlags() throws MessagingException;
/**
* Check whether the supplied flag is set.
* The default implementation checks the flags returned by {@link #getFlags()}.
*
* @param flag the flags to check for
* @return true if the flags is set
* @throws MessagingException if there was a problem accessing the Store
*/
public boolean isSet(final Flags.Flag flag) throws MessagingException {
return getFlags().contains(flag);
}
/**
* Set the flags specified to the supplied value; flags not included in the
* supplied {@link Flags} parameter are not affected.
*
* @param flags the flags to modify
* @param set the new value of those flags
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void setFlags(Flags flags, boolean set) throws MessagingException;
/**
* Set a flag to the supplied value.
* The default implmentation uses {@link #setFlags(Flags, boolean)}.
*
* @param flag the flag to set
* @param set the value for that flag
* @throws MessagingException if there was a problem accessing the Store
*/
public void setFlag(final Flags.Flag flag, final boolean set) throws MessagingException {
setFlags(new Flags(flag), set);
}
/**
* Return the message number for this Message.
* This number refers to the relative position of this message in a Folder; the message
* number for any given message can change during a session if the Folder is expunged.
* Message numbers for messages in a folder start at one; the value zero indicates that
* this message does not belong to a folder.
*
* @return the message number
*/
public int getMessageNumber() {
return msgnum;
}
/**
* Set the message number for this Message.
* This must be invoked by implementation classes when the message number changes.
*
* @param number the new message number
*/
protected void setMessageNumber(final int number) {
msgnum = number;
}
/**
* Return the folder containing this message. If this is a new or nested message
* then this method returns null.
*
* @return the folder containing this message
*/
public Folder getFolder() {
return folder;
}
/**
* Checks to see if this message has been expunged. If true, all methods other than
* {@link #getMessageNumber()} are invalid.
*
* @return true if this method has been expunged
*/
public boolean isExpunged() {
return expunged;
}
/**
* Set the expunged flag for this message.
*
* @param expunged true if this message has been expunged
*/
protected void setExpunged(final boolean expunged) {
this.expunged = expunged;
}
/**
* Create a new message suitable as a reply to this message with all headers set
* up appropriately. The message body will be empty.
* <p/>
* if replyToAll is set then the new message will be addressed to all recipients
* of this message; otherwise the reply will be addressed only to the sender as
* returned by {@link #getReplyTo()}.
* <p/>
* The subject field will be initialized with the subject field from the orginal
* message; the text "Re:" will be prepended unless it is already present.
*
* @param replyToAll if true, indciates the message should be addressed to all recipients not just the sender
* @return a new message suitable as a reply to this message
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract Message reply(boolean replyToAll) throws MessagingException;
/**
* To ensure changes are saved to the Store, this message should be invoked
* before its containing Folder is closed. Implementations may save modifications
* immediately but are free to defer such updates to they may be sent to the server
* in one batch; if saveChanges is not called then such changes may not be made
* permanent.
*
* @throws MessagingException if there was a problem accessing the Store
*/
public abstract void saveChanges() throws MessagingException;
/**
* Apply the specified search criteria to this message
*
* @param term the search criteria
* @return true if this message matches the search criteria.
* @throws MessagingException if there was a problem accessing the Store
*/
public boolean match(final SearchTerm term) throws MessagingException {
return term.match(this);
}
}
| 1,935 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Flags.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.io.Serializable;
import java.util.Hashtable;
/**
* Representation of flags that may be associated with a message.
* Flags can either be system flags, defined by the {@link Flags.Flag Flag} inner class,
* or user-defined flags defined by a String. The system flags represent those expected
* to be provided by most folder systems; user-defined flags allow for additional flags
* on a per-provider basis.
* <p/>
* This class is Serializable but compatibility is not guaranteed across releases.
*
* @version $Rev$ $Date$
*/
public class Flags implements Cloneable, Serializable {
private static final long serialVersionUID = 6243590407214169028L;
public static final class Flag {
/**
* Flag that indicates that the message has been replied to; has a bit value of 1.
*/
public static final Flag ANSWERED = new Flag(1);
/**
* Flag that indicates that the message has been marked for deletion and
* should be removed on a subsequent expunge operation; has a bit value of 2.
*/
public static final Flag DELETED = new Flag(2);
/**
* Flag that indicates that the message is a draft; has a bit value of 4.
*/
public static final Flag DRAFT = new Flag(4);
/**
* Flag that indicates that the message has been flagged; has a bit value of 8.
*/
public static final Flag FLAGGED = new Flag(8);
/**
* Flag that indicates that the message has been delivered since the last time
* this folder was opened; has a bit value of 16.
*/
public static final Flag RECENT = new Flag(16);
/**
* Flag that indicates that the message has been viewed; has a bit value of 32.
* This flag is set by the {@link Message#getInputStream()} and {@link Message#getContent()}
* methods.
*/
public static final Flag SEEN = new Flag(32);
/**
* Flags that indicates if this folder supports user-defined flags; has a bit value of 0x80000000.
*/
public static final Flag USER = new Flag(0x80000000);
private final int mask;
private Flag(final int mask) {
this.mask = mask;
}
}
// the Serialized form of this class required the following two fields to be persisted
// this leads to a specific type of implementation
private int system_flags;
private final Hashtable user_flags;
/**
* Construct a Flags instance with no flags set.
*/
public Flags() {
user_flags = new Hashtable();
}
/**
* Construct a Flags instance with a supplied system flag set.
* @param flag the system flag to set
*/
public Flags(final Flag flag) {
system_flags = flag.mask;
user_flags = new Hashtable();
}
/**
* Construct a Flags instance with a same flags set.
* @param flags the instance to copy
*/
public Flags(final Flags flags) {
system_flags = flags.system_flags;
user_flags = new Hashtable(flags.user_flags);
}
/**
* Construct a Flags instance with the supplied user flags set.
* Question: should this automatically set the USER system flag?
* @param name the user flag to set
*/
public Flags(final String name) {
user_flags = new Hashtable();
user_flags.put(name.toLowerCase(), name);
}
/**
* Set a system flag.
* @param flag the system flag to set
*/
public void add(final Flag flag) {
system_flags |= flag.mask;
}
/**
* Set all system and user flags from the supplied Flags.
* Question: do we need to check compatibility of USER flags?
* @param flags the Flags to add
*/
public void add(final Flags flags) {
system_flags |= flags.system_flags;
user_flags.putAll(flags.user_flags);
}
/**
* Set a user flag.
* Question: should this fail if the USER system flag is not set?
* @param name the user flag to set
*/
public void add(final String name) {
user_flags.put(name.toLowerCase(), name);
}
/**
* Return a copy of this instance.
* @return a copy of this instance
*/
@Override
public Object clone() {
return new Flags(this);
}
/**
* See if the supplied system flags are set
* @param flag the system flags to check for
* @return true if the flags are set
*/
public boolean contains(final Flag flag) {
return (system_flags & flag.mask) != 0;
}
/**
* See if all of the supplied Flags are set
* @param flags the flags to check for
* @return true if all the supplied system and user flags are set
*/
public boolean contains(final Flags flags) {
return ((system_flags & flags.system_flags) == flags.system_flags)
&& user_flags.keySet().containsAll(flags.user_flags.keySet());
}
/**
* See if the supplied user flag is set
* @param name the user flag to check for
* @return true if the flag is set
*/
public boolean contains(final String name) {
return user_flags.containsKey(name.toLowerCase());
}
/**
* Equality is defined as true if the other object is a instanceof Flags with the
* same system and user flags set (using a case-insensitive name comparison for user flags).
* @param other the instance to compare against
* @return true if the two instance are the same
*/
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof Flags == false) {
return false;
}
final Flags flags = (Flags) other;
return system_flags == flags.system_flags && user_flags.keySet().equals(flags.user_flags.keySet());
}
/**
* Calculate a hashCode for this instance
* @return a hashCode for this instance
*/
@Override
public int hashCode() {
return system_flags ^ user_flags.keySet().hashCode();
}
/**
* Return a list of {@link Flags.Flag Flags} containing the system flags that have been set
* @return the system flags that have been set
*/
public Flag[] getSystemFlags() {
// assumption: it is quicker to calculate the size than it is to reallocate the array
int size = 0;
if ((system_flags & Flag.ANSWERED.mask) != 0) {
size += 1;
}
if ((system_flags & Flag.DELETED.mask) != 0) {
size += 1;
}
if ((system_flags & Flag.DRAFT.mask) != 0) {
size += 1;
}
if ((system_flags & Flag.FLAGGED.mask) != 0) {
size += 1;
}
if ((system_flags & Flag.RECENT.mask) != 0) {
size += 1;
}
if ((system_flags & Flag.SEEN.mask) != 0) {
size += 1;
}
if ((system_flags & Flag.USER.mask) != 0) {
size += 1;
}
final Flag[] result = new Flag[size];
if ((system_flags & Flag.USER.mask) != 0) {
result[--size] = Flag.USER;
}
if ((system_flags & Flag.SEEN.mask) != 0) {
result[--size] = Flag.SEEN;
}
if ((system_flags & Flag.RECENT.mask) != 0) {
result[--size] = Flag.RECENT;
}
if ((system_flags & Flag.FLAGGED.mask) != 0) {
result[--size] = Flag.FLAGGED;
}
if ((system_flags & Flag.DRAFT.mask) != 0) {
result[--size] = Flag.DRAFT;
}
if ((system_flags & Flag.DELETED.mask) != 0) {
result[--size] = Flag.DELETED;
}
if ((system_flags & Flag.ANSWERED.mask) != 0) {
result[--size] = Flag.ANSWERED;
}
return result;
}
/**
* Return a list of user flags that have been set
* @return a list of user flags
*/
public String[] getUserFlags() {
return (String[]) user_flags.values().toArray(new String[user_flags.values().size()]);
}
/**
* Unset the supplied system flag.
* Question: what happens if we unset the USER flags and user flags are set?
* @param flag the flag to clear
*/
public void remove(final Flag flag) {
system_flags &= ~flag.mask;
}
/**
* Unset all flags from the supplied instance.
* @param flags the flags to clear
*/
public void remove(final Flags flags) {
system_flags &= ~flags.system_flags;
user_flags.keySet().removeAll(flags.user_flags.keySet());
}
/**
* Unset the supplied user flag.
* @param name the flag to clear
*/
public void remove(final String name) {
user_flags.remove(name.toLowerCase());
}
}
| 1,936 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/MessagingException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class MessagingException extends Exception {
private static final long serialVersionUID = -7569192289819959253L;
// Required because serialization expects it to be here
private Exception next;
public MessagingException() {
super();
}
public MessagingException(final String message) {
super(message);
}
public MessagingException(final String message, final Exception cause) {
super(message, cause);
next = cause;
}
public synchronized Exception getNextException() {
return next;
}
public synchronized boolean setNextException(final Exception cause) {
if (next == null) {
next = cause;
return true;
} else if (next instanceof MessagingException) {
return ((MessagingException) next).setNextException(cause);
} else {
return false;
}
}
@Override
public String getMessage() {
final Exception next = getNextException();
if (next == null) {
return super.getMessage();
} else {
return super.getMessage()
+ " ("
+ next.getClass().getName()
+ ": "
+ next.getMessage()
+ ")";
}
}
/**
* MessagingException uses the nextException to provide a legacy chained throwable.
* override the getCause method to return the nextException.
*/
@Override
public synchronized Throwable getCause() {
return next;
}
}
| 1,937 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/MessageAware.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public interface MessageAware {
public abstract MessageContext getMessageContext();
}
| 1,938 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/NoSuchProviderException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class NoSuchProviderException extends MessagingException {
private static final long serialVersionUID = 8058319293154708827L;
public NoSuchProviderException() {
super();
}
public NoSuchProviderException(final String message) {
super(message);
}
/**
* Constructs a NoSuchProviderException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param message The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public NoSuchProviderException(final String message, final Exception e) {
super(message, e);
}
}
| 1,939 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/MailSessionDefinition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used by Java EE applications to define a MailSession
* to be registered within JNDI.
* The annotation is used to configure the commonly used Session
* properties.
* Additional standard and vendor-specific properties may be
* specified using the properties element.
*
* The session will be registered under the JNDI name specified in the
* name element. It may be defined to be in any valid
* Java EE namespace, and will determine the accessibility of
* the session from other components.
*
* @since JavaMail 1.5
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MailSessionDefinition {
/**
* Description of this mail session.
*/
String description() default "";
/**
* JNDI name by which the mail session will be registered.
*/
String name();
/**
* Store protocol name.
*/
String storeProtocol() default "";
/**
* Transport protocol name.
*/
String transportProtocol() default "";
/**
* Host name for the mail server.
*/
String host() default "";
/**
* User name to use for authentication.
*/
String user() default "";
/**
* Password to use for authentication.
*/
String password() default "";
/**
* From address for the user.
*/
String from() default "";
/**
* Properties to include in the Session.
* Properties are specified using the format:
* propertyName=propertyValue with one property per array element.
*/
String[] properties() default {};
}
| 1,940 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/MessageContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* The context in which a piece of message content is contained.
*
* @version $Rev$ $Date$
*/
public class MessageContext {
private final Part part;
/**
* Create a MessageContext object describing the context of the supplied Part.
*
* @param part the containing part
*/
public MessageContext(final Part part) {
this.part = part;
}
/**
* Return the {@link Part} that contains the content.
*
* @return the part
*/
public Part getPart() {
return part;
}
/**
* Return the message that contains the content; if the Part is a {@link Multipart}
* then recurse up the chain until a {@link Message} is found.
*
* @return
*/
public Message getMessage() {
return getMessageFrom(part);
}
/**
* Return the session associated with the Message containing this Part.
*
* @return the session associated with this context's root message
*/
public Session getSession() {
final Message message = getMessage();
if (message == null) {
return null;
} else {
return message.session;
}
}
/**
* recurse up the chain of MultiPart/BodyPart parts until we hit a message
*
* @param p The starting part.
*
* @return The encountered Message or null if no Message parts
* are found.
*/
private Message getMessageFrom(Part p) {
while (p != null) {
if (p instanceof Message) {
return (Message) p;
}
final Multipart mp = ((BodyPart) p).getParent();
if (mp == null) {
return null;
}
p = mp.getParent();
}
return null;
}
}
| 1,941 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/FetchProfile.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.util.ArrayList;
import java.util.List;
/**
* A FetchProfile defines a list of message attributes that a client wishes to prefetch
* from the server during a fetch operation.
*
* Clients can either specify individual headers, or can reference common profiles
* as defined by {@link FetchProfile.Item FetchProfile.Item}.
*
* @version $Rev$ $Date$
*/
public class FetchProfile {
/**
* Inner class that defines sets of headers that are commonly bundled together
* in a FetchProfile.
*/
public static class Item {
/**
* Item for fetching information about the content of the message.
*
* This includes all the headers about the content including but not limited to:
* Content-Type, Content-Disposition, Content-Description, Size and Line-Count
*/
public static final Item CONTENT_INFO = new Item("CONTENT_INFO");
/**
* Item for fetching information about the envelope of the message.
*
* This includes all the headers comprising the envelope including but not limited to:
* From, To, Cc, Bcc, Reply-To, Subject and Date
*
* For IMAP4, this should also include the ENVELOPE data item.
*
*/
public static final Item ENVELOPE = new Item("ENVELOPE");
/**
* Item for fetching information about message flags.
* General corresponds to the X-Flags header.
*/
public static final Item FLAGS = new Item("FLAGS");
/**
* SIZE is a fetch profile item that can be included in a
* FetchProfile during a fetch request to a Folder.
* This item indicates that the sizes of the messages in the specified
* range should be prefetched.
*
* @since JavaMail 1.5
*/
public static final Item SIZE = new Item("SIZE");
protected Item(final String name) {
// hmmm, name is passed in but we are not allowed to provide accessors
// or to override equals/hashCode so what use is it?
}
}
// use Lists as we don't expect contains to be called often and the number of elements should be small
private final List items = new ArrayList();
private final List headers = new ArrayList();
/**
* Add a predefined profile of headers.
*
* @param item the profile to add
*/
public void add(final Item item) {
items.add(item);
}
/**
* Add a specific header.
* @param header the header whose value should be prefetched
*/
public void add(final String header) {
headers.add(header);
}
/**
* Determine if the given profile item is already included.
* @param item the profile to check for
* @return true if the profile item is already included
*/
public boolean contains(final Item item) {
return items.contains(item);
}
/**
* Determine if the specified header is already included.
* @param header the header to check for
* @return true if the header is already included
*/
public boolean contains(final String header) {
return headers.contains(header);
}
/**
* Get the profile items already included.
* @return the items already added to this profile
*/
public Item[] getItems() {
return (Item[]) items.toArray(new Item[items.size()]);
}
/** Get the headers that have already been included.
* @return the headers already added to this profile
*/
public String[] getHeaderNames() {
return (String[]) headers.toArray(new String[headers.size()]);
}
}
| 1,942 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/MultipartDataSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import javax.activation.DataSource;
/**
* @version $Rev$ $Date$
*/
public interface MultipartDataSource extends DataSource {
public abstract BodyPart getBodyPart(int index) throws MessagingException;
public abstract int getCount();
}
| 1,943 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Provider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class Provider {
/**
* A enumeration inner class that defines Provider types.
*/
public static class Type {
/**
* A message store provider such as POP3 or IMAP4.
*/
public static final Type STORE = new Type();
/**
* A message transport provider such as SMTP.
*/
public static final Type TRANSPORT = new Type();
private Type() {
}
}
private final String className;
private final String protocol;
private final Type type;
private final String vendor;
private final String version;
public Provider(final Type type, final String protocol, final String className, final String vendor, final String version) {
this.protocol = protocol;
this.className = className;
this.type = type;
this.vendor = vendor;
this.version = version;
}
public String getClassName() {
return className;
}
public String getProtocol() {
return protocol;
}
public Type getType() {
return type;
}
public String getVendor() {
return vendor;
}
public String getVersion() {
return version;
}
@Override
public String toString() {
return "protocol="
+ protocol
+ "; type="
+ type
+ "; class="
+ className
+ (vendor == null ? "" : "; vendor=" + vendor)
+ (version == null ? "" : ";version=" + version);
}
}
| 1,944 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/FolderClosedException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class FolderClosedException extends MessagingException {
private static final long serialVersionUID = 1687879213433302315L;
private transient Folder _folder;
public FolderClosedException(final Folder folder) {
this(folder, "Folder Closed: " + folder.getName());
}
public FolderClosedException(final Folder folder, final String message) {
super(message);
_folder = folder;
}
/**
* Constructs a FolderClosedException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param folder The Folder
* @param message The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public FolderClosedException(final Folder folder, final String message, final Exception e) {
super(message, e);
_folder = folder;
}
public Folder getFolder() {
return _folder;
}
}
| 1,945 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Part.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.activation.DataHandler;
/**
* Note: Parts are used in Collections so implementing classes must provide
* a suitable implementation of equals and hashCode.
*
* @version $Rev$ $Date$
*/
public interface Part {
/**
* This part should be presented as an attachment.
*/
public static final String ATTACHMENT = "attachment";
/**
* This part should be presented or rendered inline.
*/
public static final String INLINE = "inline";
/**
* Add this value to the existing headers with the given name. This method
* does not replace any headers that may already exist.
*
* @param name The name of the target header.
* @param value The value to be added to the header set.
*
* @exception MessagingException
*/
public abstract void addHeader(String name, String value) throws MessagingException;
/**
* Return all headers as an Enumeration of Header objects.
*
* @return An Enumeration containing all of the current Header objects.
* @exception MessagingException
*/
public abstract Enumeration getAllHeaders() throws MessagingException;
/**
* Return a content object for this Part. The
* content object type is dependent upon the
* DataHandler for the Part.
*
* @return A content object for this Part.
* @exception IOException
* @exception MessagingException
*/
public abstract Object getContent() throws IOException, MessagingException;
/**
* Get the ContentType for this part, or null if the
* ContentType has not been set. The ContentType
* is expressed using the MIME typing system.
*
* @return The ContentType for this part.
* @exception MessagingException
*/
public abstract String getContentType() throws MessagingException;
/**
* Returns a DataHandler instance for the content
* with in the Part.
*
* @return A DataHandler appropriate for the Part content.
* @exception MessagingException
*/
public abstract DataHandler getDataHandler() throws MessagingException;
/**
* Returns a description string for this Part. Returns
* null if a description has not been set.
*
* @return The description string.
* @exception MessagingException
*/
public abstract String getDescription() throws MessagingException;
/**
* Return the disposition of the part. The disposition
* determines how the part should be presented to the
* user. Two common disposition values are ATTACHMENT
* and INLINE.
*
* @return The current disposition value.
* @exception MessagingException
*/
public abstract String getDisposition() throws MessagingException;
/**
* Get a file name associated with this part. The
* file name is useful for presenting attachment
* parts as their original source. The file names
* are generally simple names without containing
* any directory information. Returns null if the
* filename has not been set.
*
* @return The string filename, if any.
* @exception MessagingException
*/
public abstract String getFileName() throws MessagingException;
/**
* Get all Headers for this header name. Returns null if no headers with
* the given name exist.
*
* @param name The target header name.
*
* @return An array of all matching header values, or null if the given header
* does not exist.
* @exception MessagingException
*/
public abstract String[] getHeader(String name) throws MessagingException;
/**
* Return an InputStream for accessing the Part
* content. Any mail-related transfer encodings
* will be removed, so the data presented with
* be the actual part content.
*
* @return An InputStream for accessing the part content.
* @exception IOException
* @exception MessagingException
*/
public abstract InputStream getInputStream() throws IOException, MessagingException;
/**
* Return the number of lines in the content, or
* -1 if the line count cannot be determined.
*
* @return The estimated number of lines in the content.
* @exception MessagingException
*/
public abstract int getLineCount() throws MessagingException;
/**
* Return all headers that match the list of names as an Enumeration of
* Header objects.
*
* @param names An array of names of the desired headers.
*
* @return An Enumeration of Header objects containing the matching headers.
* @exception MessagingException
*/
public abstract Enumeration getMatchingHeaders(String[] names) throws MessagingException;
/**
* Return an Enumeration of all Headers except those that match the names
* given in the exclusion list.
*
* @param names An array of String header names that will be excluded from the return
* Enumeration set.
*
* @return An Enumeration of Headers containing all headers except for those named
* in the exclusion list.
* @exception MessagingException
*/
public abstract Enumeration getNonMatchingHeaders(String[] names) throws MessagingException;
/**
* Return the size of this part, or -1 if the size
* cannot be reliably determined.
*
* Note: the returned size does not take into account
* internal encodings, nor is it an estimate of
* how many bytes are required to transfer this
* part across a network. This value is intended
* to give email clients a rough idea of the amount
* of space that might be required to present the
* item.
*
* @return The estimated part size, or -1 if the size
* information cannot be determined.
* @exception MessagingException
*/
public abstract int getSize() throws MessagingException;
/**
* Tests if the part is of the specified MIME type.
* Only the primaryPart and subPart of the MIME
* type are used for the comparison; arguments are
* ignored. The wildcard value of "*" may be used
* to match all subTypes.
*
* @param mimeType The target MIME type.
*
* @return true if the part matches the input MIME type,
* false if it is not of the requested type.
* @exception MessagingException
*/
public abstract boolean isMimeType(String mimeType) throws MessagingException;
/**
* Remove all headers with the given name from the Part.
*
* @param name The target header name used for removal.
*
* @exception MessagingException
*/
public abstract void removeHeader(String name) throws MessagingException;
public abstract void setContent(Multipart content) throws MessagingException;
/**
* Set a content object for this part. Internally,
* the Part will use the MIME type encoded in the
* type argument to wrap the provided content object.
* In order for this to work properly, an appropriate
* DataHandler must be installed in the Java Activation
* Framework.
*
* @param content The content object.
* @param type The MIME type for the inserted content Object.
*
* @exception MessagingException
*/
public abstract void setContent(Object content, String type) throws MessagingException;
/**
* Set a DataHandler for this part that defines the
* Part content. The DataHandler is used to access
* all Part content.
*
* @param handler The DataHandler instance.
*
* @exception MessagingException
*/
public abstract void setDataHandler(DataHandler handler) throws MessagingException;
/**
* Set a descriptive string for this part.
*
* @param description
* The new description.
*
* @exception MessagingException
*/
public abstract void setDescription(String description) throws MessagingException;
/**
* Set the disposition for this Part.
*
* @param disposition
* The disposition string.
*
* @exception MessagingException
*/
public abstract void setDisposition(String disposition) throws MessagingException;
/**
* Set a descriptive file name for this part. The
* name should be a simple name that does not include
* directory information.
*
* @param name The new name value.
*
* @exception MessagingException
*/
public abstract void setFileName(String name) throws MessagingException;
/**
* Sets a value for the given header. This operation will replace all
* existing headers with the given name.
*
* @param name The name of the target header.
* @param value The new value for the indicated header.
*
* @exception MessagingException
*/
public abstract void setHeader(String name, String value) throws MessagingException;
/**
* Set the Part content as text. This is a convenience method that sets
* the content to a MIME type of "text/plain".
*
* @param content The new text content, as a String object.
*
* @exception MessagingException
*/
public abstract void setText(String content) throws MessagingException;
/**
* Write the Part content out to the provided OutputStream as a byte
* stream using an encoding appropriate to the Part content.
*
* @param out The target OutputStream.
*
* @exception IOException
* @exception MessagingException
*/
public abstract void writeTo(OutputStream out) throws IOException, MessagingException;
}
| 1,946 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Transport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;
/**
* Abstract class modeling a message transport.
*
* @version $Rev$ $Date$
*/
public abstract class Transport extends Service {
/**
* Send a message to all recipient addresses the message contains (as returned by {@link Message#getAllRecipients()})
* using message transports appropriate for each address. Message addresses are checked during submission,
* but there is no guarantee that the ultimate address is valid or that the message will ever be delivered.
* <p/>
* {@link Message#saveChanges()} will be called before the message is actually sent.
*
* @param message the message to send
* @throws MessagingException if there was a problem sending the message
*/
public static void send(final Message message) throws MessagingException {
send(message, message.getAllRecipients());
}
/**
* Send a message to all addresses provided irrespective of any recipients contained in the message,
* using message transports appropriate for each address. Message addresses are checked during submission,
* but there is no guarantee that the ultimate address is valid or that the message will ever be delivered.
* <p/>
* {@link Message#saveChanges()} will be called before the message is actually sent.
*
* @param message the message to send
* @param addresses the addesses to send to
* @throws MessagingException if there was a problem sending the message
*/
public static void send(final Message message, final Address[] addresses) throws MessagingException {
sendInternal(message, addresses, null, null);
}
private static void sendInternal(final Message message, final Address[] addresses, final String user, final String password) throws MessagingException {
if (addresses == null || addresses.length == 0) {
throw new SendFailedException("No recipient addresses");
}
final Session session = message.session;
final Map<Transport, List<Address>> msgsByTransport = new HashMap<Transport, List<Address>>();
for (int i = 0; i < addresses.length; i++) {
final Address address = addresses[i];
final Transport transport = session.getTransport(address);
List<Address> addrs = msgsByTransport.get(transport);
if (addrs == null) {
addrs = new ArrayList<Address>();
msgsByTransport.put(transport, addrs);
}
addrs.add(address);
}
message.saveChanges();
// Since we might be sending to multiple protocols, we need to catch and process each exception
// when we send and then throw a new SendFailedException when everything is done. Unfortunately, this
// also means unwrapping the information in any SendFailedExceptions we receive and building
// composite failed list.
MessagingException chainedException = null;
final List<Address> sentAddresses = new ArrayList<Address>();
final List<Address> unsentAddresses = new ArrayList<Address>();
final List<Address> invalidAddresses = new ArrayList<Address>();
for (final Iterator<Entry<Transport, List<Address>>> i = msgsByTransport.entrySet().iterator(); i.hasNext();) {
final Entry<Transport, List<Address>> entry = i.next();
final Transport transport = entry.getKey();
final List<Address> addrs = entry.getValue();
try {
// we MUST connect to the transport before attempting to send.
if(user != null) {
transport.connect(user, password);
} else {
transport.connect();
}
transport.sendMessage(message, addrs.toArray(new Address[addrs.size()]));
// if we have to throw an exception because of another failure, these addresses need to
// be in the valid list. Since we succeeded here, we can add these now.
sentAddresses.addAll(addrs);
} catch (final SendFailedException e) {
// a true send failure. The exception contains a wealth of information about
// the failures, including a potential chain of exceptions explaining what went wrong. We're
// going to send a new one of these, so we need to merge the information.
// add this to our exception chain
if (chainedException == null) {
chainedException = e;
}
else {
chainedException.setNextException(e);
}
// now extract each of the address categories from
Address[] exAddrs = e.getValidSentAddresses();
if (exAddrs != null) {
for (int j = 0; j < exAddrs.length; j++) {
sentAddresses.add(exAddrs[j]);
}
}
exAddrs = e.getValidUnsentAddresses();
if (exAddrs != null) {
for (int j = 0; j < exAddrs.length; j++) {
unsentAddresses.add(exAddrs[j]);
}
}
exAddrs = e.getInvalidAddresses();
if (exAddrs != null) {
for (int j = 0; j < exAddrs.length; j++) {
invalidAddresses.add(exAddrs[j]);
}
}
} catch (final MessagingException e) {
// add this to our exception chain
if (chainedException == null) {
chainedException = e;
}
else {
chainedException.setNextException(e);
}
}
finally {
transport.close();
}
}
// if we have an exception chain then we need to throw a new exception giving the failure
// information.
if (chainedException != null) {
// if we're only sending to a single transport (common), and we received a SendFailedException
// as a result, then we have a fully formed exception already. Rather than wrap this in another
// exception, we can just rethrow the one we have.
if (msgsByTransport.size() == 1 && chainedException instanceof SendFailedException) {
throw chainedException;
}
// create our lists for notification and exception reporting from this point on.
final Address[] sent = sentAddresses.toArray(new Address[0]);
final Address[] unsent = unsentAddresses.toArray(new Address[0]);
final Address[] invalid = invalidAddresses.toArray(new Address[0]);
throw new SendFailedException("Send failure", chainedException, sent, unsent, invalid);
}
}
/**
* Send a message. The message will be sent to all recipient
* addresses specified in the message (as returned from the
* Message method getAllRecipients).
* The send method calls the saveChanges
* method on the message before sending it.
*
* Use the specified user name and password to authenticate to
* the mail server.
*
* @param msg the message to send
* @param user the user name
* @param password this user's password
* @exception SendFailedException if the message could not
* be sent to some or any of the recipients.
* @exception MessagingException
* @see Message#saveChanges
* @see #send(Message)
* @see javax.mail.SendFailedException
* @since JavaMail 1.5
*/
public static void send(final Message msg,
final String user, final String password) throws MessagingException {
send(msg, msg.getAllRecipients(), user, password);
}
/**
* Send the message to the specified addresses, ignoring any
* recipients specified in the message itself. The
* send method calls the saveChanges
* method on the message before sending it.
*
* Use the specified user name and password to authenticate to
* the mail server.
*
* @param msg the message to send
* @param addresses the addresses to which to send the message
* @param user the user name
* @param password this user's password
* @exception SendFailedException if the message could not
* be sent to some or any of the recipients.
* @exception MessagingException
* @see Message#saveChanges
* @see #send(Message)
* @see javax.mail.SendFailedException
* @since JavaMail 1.5
*/
public static void send(final Message msg, final Address[] addresses,
final String user, final String password) throws MessagingException {
sendInternal(msg, addresses, user, password);
}
/**
* Constructor taking Session and URLName parameters required for {@link Service#Service(Session, URLName)}.
*
* @param session the Session this transport is for
* @param name the location this transport is for
*/
public Transport(final Session session, final URLName name) {
super(session, name);
}
/**
* Send a message to the supplied addresses using this transport; if any of the addresses are
* invalid then a {@link SendFailedException} is thrown. Whether the message is actually sent
* to any of the addresses is undefined.
* <p/>
* Unlike the static {@link #send(Message, Address[])} method, {@link Message#saveChanges()} is
* not called. A {@link TransportEvent} will be sent to registered listeners once the delivery
* attempt has been made.
*
* @param message the message to send
* @param addresses list of addresses to send it to
* @throws SendFailedException if the send failed
* @throws MessagingException if there was a problem sending the message
*/
public abstract void sendMessage(Message message, Address[] addresses) throws MessagingException;
private final Vector<TransportListener> transportListeners = new Vector<TransportListener>();
public void addTransportListener(final TransportListener listener) {
transportListeners.add(listener);
}
public void removeTransportListener(final TransportListener listener) {
transportListeners.remove(listener);
}
protected void notifyTransportListeners(final int type, final Address[] validSent, final Address[] validUnsent, final Address[] invalid, final Message message) {
queueEvent(new TransportEvent(this, type, validSent, validUnsent, invalid, message), transportListeners);
}
}
| 1,947 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/SendFailedException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class SendFailedException extends MessagingException {
private static final long serialVersionUID = -6457531621682372913L;
protected transient Address invalid[];
protected transient Address validSent[];
protected transient Address validUnsent[];
public SendFailedException() {
super();
}
public SendFailedException(final String message) {
super(message);
}
public SendFailedException(final String message, final Exception cause) {
super(message, cause);
}
public SendFailedException(final String message,
final Exception cause,
final Address[] validSent,
final Address[] validUnsent,
final Address[] invalid) {
this(message, cause);
this.invalid = invalid;
this.validSent = validSent;
this.validUnsent = validUnsent;
}
public Address[] getValidSentAddresses() {
return validSent;
}
public Address[] getValidUnsentAddresses() {
return validUnsent;
}
public Address[] getInvalidAddresses() {
return invalid;
}
}
| 1,948 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/EncodingAware.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* A class that implements EncodingAware may specify the Content-Transfer-Encoding
* to use for its data. Valid Content-Transfer-Encoding values specified
* by RFC 2045 are "7bit", "8bit", "quoted-printable", "base64", and "binary".
* This is mainly used for {@link javax.activation.DataSource DataSource}s.
*
* @since JavaMail 1.5
*/
public interface EncodingAware {
/**
* @return the MIME Content-Transfer-Encoding to use for this data,
* or null to indicate that an appropriate value should be chosen
* by the caller.
*/
public String getEncoding();
}
| 1,949 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/EventQueue.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//
package javax.mail;
import java.util.LinkedList;
import java.util.List;
import javax.mail.event.MailEvent;
/**
* This is an event queue to dispatch javamail events on separate threads
* from the main thread. EventQueues are created by javamail Services
* (Transport and Store instances), as well as Folders created from Store
* instances. Each entity will have its own private EventQueue instance, but
* will delay creating it until it has an event to dispatch to a real listener.
*
* NOTE: It would be nice to use the concurrency support in Java 5 to
* manage the queue, but this code needs to run on Java 1.4 still. We also
* don't want to have dependencies on other packages with this, so no
* outside concurrency packages can be used either.
* @version $Rev$ $Date$
*/
class EventQueue implements Runnable {
/**
* The dispatch thread that handles notification events.
*/
protected Thread dispatchThread;
/**
* The dispatching queue for events.
*/
protected List eventQueue = new LinkedList();
/**
* Create a new EventQueue, including starting the new thread.
*/
public EventQueue() {
dispatchThread = new Thread(this, "JavaMail-EventQueue");
dispatchThread.setDaemon(true); // this is a background server thread.
// start the thread up
dispatchThread.start();
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public void run() {
try {
while (true) {
// get the next event
final PendingEvent p = dequeueEvent();
// an empty event on the queue means time to shut things down.
if (p.event == null) {
return;
}
// and tap the listeners on the shoulder.
dispatchEvent(p.event, p.listeners);
}
} catch (final InterruptedException e) {
// been told to stop, so we stop
}
}
/**
* Stop the EventQueue. This will terminate the dispatcher thread as soon
* as it can, so there may be undispatched events in the queue that will
* not get dispatched.
*/
public synchronized void stop() {
// if the thread has not been stopped yet, interrupt it
// and clear the reference.
if (dispatchThread != null) {
// push a dummy marker on to the event queue
// to force the dispatch thread to wake up.
queueEvent(null, null);
dispatchThread = null;
}
}
/**
* Add a new event to the queue.
*
* @param event The event to dispatch.
* @param listeners The List of listeners to dispatch this to. This is assumed to be a
* static snapshot of the listeners that will not change between the time
* the event is queued and the dispatcher thread makes the calls to the
* handlers.
*/
public synchronized void queueEvent(final MailEvent event, final List listeners) {
// add an element to the list, then notify the processing thread.
// Note that we make a copy of the listeners list. This ensures
// we're going to dispatch this to the snapshot of the listeners
final PendingEvent p = new PendingEvent(event, listeners);
eventQueue.add(p);
// wake up the dispatch thread
notify();
}
/**
* Remove the next event from the message queue.
*
* @return The PendingEvent item from the queue.
*/
protected synchronized PendingEvent dequeueEvent() throws InterruptedException {
// a little spin loop to wait for an event
while (eventQueue.isEmpty()) {
wait();
}
// just remove the first element of this
return (PendingEvent)eventQueue.remove(0);
}
/**
* Dispatch an event to a list of listeners. Any exceptions thrown by
* the listeners will be swallowed.
*
* @param event The event to dispatch.
* @param listeners The list of listeners this gets dispatched to.
*/
protected void dispatchEvent(final MailEvent event, final List listeners) {
// iterate through the listeners list calling the handlers.
for (int i = 0; i < listeners.size(); i++) {
try {
event.dispatch(listeners.get(i));
} catch (final Throwable e) {
// just eat these
}
}
}
/**
* Small helper class to give a single reference handle for a pending event.
*/
class PendingEvent {
// the event we're broadcasting
MailEvent event;
// the list of listeners we send this to.
List listeners;
PendingEvent(final MailEvent event, final List listeners) {
this.event = event;
this.listeners = listeners;
}
}
}
| 1,950 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Address.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.io.Serializable;
/**
* This abstract class models the addresses in a message.
* Addresses are Serializable so that they may be serialized along with other search terms.
*
* @version $Rev$ $Date$
*/
public abstract class Address implements Serializable {
private static final long serialVersionUID = -5822459626751992278L;
/**
* Subclasses must provide a suitable implementation of equals().
*
* @param object the object to compare t
* @return true if the subclass determines the other object is equal to this Address
*/
@Override
public abstract boolean equals(Object object);
/**
* Return a String that identifies this address type.
* @return the type of this address
*/
public abstract String getType();
/**
* Subclasses must provide a suitable representation of their address.
* @return a representation of an Address as a String
*/
@Override
public abstract String toString();
}
| 1,951 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/URLName.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
* @version $Rev$ $Date$
*/
public class URLName {
private static final String nonEncodedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-.*";
private String file;
private String host;
private String password;
private int port;
private String protocol;
private String ref;
private String username;
protected String fullURL;
private int hashCode;
public URLName(final String url) {
parseString(url);
}
protected void parseString(final String url) {
URI uri;
try {
if (url == null) {
uri = null;
} else {
uri = new URI(url);
}
} catch (final URISyntaxException e) {
uri = null;
}
if (uri == null) {
protocol = null;
host = null;
port = -1;
file = null;
ref = null;
username = null;
password = null;
return;
}
protocol = checkBlank(uri.getScheme());
host = checkBlank(uri.getHost());
port = uri.getPort();
file = checkBlank(uri.getPath());
// if the file starts with "/", we need to strip that off.
// URL and URLName do not have the same behavior when it comes
// to keeping that there.
if (file != null && file.length() > 1 && file.startsWith("/")) {
file = checkBlank(file.substring(1));
}
ref = checkBlank(uri.getFragment());
final String userInfo = checkBlank(uri.getUserInfo());
if (userInfo == null) {
username = null;
password = null;
} else {
final int pos = userInfo.indexOf(':');
if (pos == -1) {
username = userInfo;
password = null;
} else {
username = userInfo.substring(0, pos);
password = userInfo.substring(pos + 1);
}
}
updateFullURL();
}
public URLName(final String protocol, final String host, final int port, final String file, String username, String password) {
this.protocol = checkBlank(protocol);
this.host = checkBlank(host);
this.port = port;
if (file == null || file.length() == 0) {
this.file = null;
ref = null;
} else {
final int pos = file.indexOf('#');
if (pos == -1) {
this.file = file;
ref = null;
} else {
this.file = file.substring(0, pos);
ref = file.substring(pos + 1);
}
}
this.username = checkBlank(username);
if (this.username != null) {
this.password = checkBlank(password);
} else {
this.password = null;
}
username = encode(username);
password = encode(password);
updateFullURL();
}
public URLName(final URL url) {
protocol = checkBlank(url.getProtocol());
host = checkBlank(url.getHost());
port = url.getPort();
file = checkBlank(url.getFile());
ref = checkBlank(url.getRef());
final String userInfo = checkBlank(url.getUserInfo());
if (userInfo == null) {
username = null;
password = null;
} else {
final int pos = userInfo.indexOf(':');
if (pos == -1) {
username = userInfo;
password = null;
} else {
username = userInfo.substring(0, pos);
password = userInfo.substring(pos + 1);
}
}
updateFullURL();
}
private static String checkBlank(final String target) {
if (target == null || target.length() == 0) {
return null;
} else {
return target;
}
}
private void updateFullURL() {
hashCode = 0;
final StringBuffer buf = new StringBuffer(100);
if (protocol != null) {
buf.append(protocol).append(':');
if (host != null) {
buf.append("//");
if (username != null) {
buf.append(encode(username));
if (password != null) {
buf.append(':').append(encode(password));
}
buf.append('@');
}
buf.append(host);
if (port != -1) {
buf.append(':').append(port);
}
if (file != null) {
buf.append('/').append(file);
}
hashCode = buf.toString().hashCode();
if (ref != null) {
buf.append('#').append(ref);
}
}
}
fullURL = buf.toString();
}
@Override
public boolean equals(final Object o) {
if(this == o) {
return true;
}
if (o instanceof URLName == false) {
return false;
}
final URLName other = (URLName) o;
// check same protocol - false if either is null
if (protocol == null || other.protocol == null || !protocol.equals(other.protocol)) {
return false;
}
if (port != other.port) {
return false;
}
// check host - false if not (both null or both equal)
return areSame(host, other.host) && areSame(file, other.file) && areSame(username, other.username) && areSame(password, other.password);
}
private static boolean areSame(final String s1, final String s2) {
if (s1 == null) {
return s2 == null;
} else {
return s1.equals(s2);
}
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return fullURL;
}
public String getFile() {
return file;
}
public String getHost() {
return host;
}
public String getPassword() {
return password;
}
public int getPort() {
return port;
}
public String getProtocol() {
return protocol;
}
public String getRef() {
return ref;
}
public URL getURL() throws MalformedURLException {
return new URL(fullURL);
}
public String getUsername() {
return username;
}
/**
* Perform an HTTP encoding to the username and
* password elements of the URLName.
*
* @param v The input (uncoded) string.
*
* @return The HTTP encoded version of the string.
*/
private static String encode(final String v) {
// make sure we don't operate on a null string
if (v == null) {
return null;
}
boolean needsEncoding = false;
for (int i = 0; i < v.length(); i++) {
// not in the list of things that don't need encoding?
if (nonEncodedChars.indexOf(v.charAt(i)) == -1) {
// got to do this the hard way
needsEncoding = true;
break;
}
}
// just fine the way it is.
if (!needsEncoding) {
return v;
}
// we know we're going to be larger, but not sure by how much.
// just give a little extra
final StringBuffer encoded = new StringBuffer(v.length() + 10);
// we get the bytes so that we can have the default encoding applied to
// this string. This will flag the ones we need to give special processing to.
final byte[] data = v.getBytes();
for (int i = 0; i < data.length; i++) {
// pick this up as a one-byte character The 7-bit ascii ones will be fine
// here.
final char ch = (char)(data[i] & 0xff);
// blanks get special treatment
if (ch == ' ') {
encoded.append('+');
}
// not in the list of things that don't need encoding?
else if (nonEncodedChars.indexOf(ch) == -1) {
// forDigit() uses the lowercase letters for the radix. The HTML specifications
// require the uppercase letters.
final char firstChar = Character.toUpperCase(Character.forDigit((ch >> 4) & 0xf, 16));
final char secondChar = Character.toUpperCase(Character.forDigit(ch & 0xf, 16));
// now append the encoded triplet.
encoded.append('%');
encoded.append(firstChar);
encoded.append(secondChar);
}
else {
// just add this one to the buffer
encoded.append(ch);
}
}
// convert to string form.
return encoded.toString();
}
}
| 1,952 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/MethodNotSupportedException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class MethodNotSupportedException extends MessagingException {
private static final long serialVersionUID = -3757386618726131322L;
public MethodNotSupportedException() {
super();
}
public MethodNotSupportedException(final String message) {
super(message);
}
/**
* Constructs a MethodNotSupportedException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param s The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public MethodNotSupportedException(final String s, final Exception e) {
super(s, e);
}
}
| 1,953 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/MailSessionDefinitions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Declares MailSessionDefinition annotations.
*
* @see MailSessionDefinition
* @since JavaMail 1.5
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MailSessionDefinitions {
MailSessionDefinition[] value();
} | 1,954 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Service.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Vector;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.ConnectionListener;
import javax.mail.event.MailEvent;
/**
* @version $Rev$ $Date$
*/
public abstract class Service {
/**
* The session from which this service was created.
*/
protected Session session;
/**
* The URLName of this service
*/
protected URLName url;
/**
* Debug flag for this service, set from the Session's debug flag.
*/
protected boolean debug;
private boolean connected;
private final Vector connectionListeners = new Vector(2);
// the EventQueue spins off a new thread, so we only create this
// if we have actual listeners to dispatch an event to.
private EventQueue queue = null;
// when returning the URL, we need to ensure that the password and file information is
// stripped out.
private URLName exposedUrl;
/**
* Construct a new Service.
* @param session the session from which this service was created
* @param url the URLName of this service
*/
protected Service(final Session session, final URLName url) {
this.session = session;
this.url = url;
this.debug = session.getDebug();
}
/**
* A generic connect method that takes no parameters allowing subclasses
* to implement an appropriate authentication scheme.
* The default implementation calls <code>connect(null, null, null)</code>
* @throws AuthenticationFailedException if authentication fails
* @throws MessagingException for other failures
*/
public void connect() throws MessagingException {
connect(null, null, null);
}
/**
* Connect to the specified host using a simple username/password authenticaion scheme
* and the default port.
* The default implementation calls <code>connect(host, -1, user, password)</code>
*
* @param host the host to connect to
* @param user the user name
* @param password the user's password
* @throws AuthenticationFailedException if authentication fails
* @throws MessagingException for other failures
*/
public void connect(final String host, final String user, final String password) throws MessagingException {
connect(host, -1, user, password);
}
/**
* Connect to the specified host using a simple username/password authenticaion scheme
* and the default host and port.
* The default implementation calls <code>connect(host, -1, user, password)</code>
*
* @param user the user name
* @param password the user's password
* @throws AuthenticationFailedException if authentication fails
* @throws MessagingException for other failures
*/
public void connect(final String user, final String password) throws MessagingException {
connect(null, -1, user, password);
}
/**
* Connect to the specified host at the specified port using a simple username/password authenticaion scheme.
*
* If this Service is already connected, an IllegalStateException is thrown.
*
* @param host the host to connect to
* @param port the port to connect to; pass -1 to use the default for the protocol
* @param user the user name
* @param password the user's password
* @throws AuthenticationFailedException if authentication fails
* @throws MessagingException for other failures
* @throws IllegalStateException if this service is already connected
*/
public void connect(String host, int port, String user, String password) throws MessagingException {
if (isConnected()) {
throw new IllegalStateException("Already connected");
}
// before we try to connect, we need to derive values for some parameters that may not have
// been explicitly specified. For example, the normal connect() method leaves us to derive all
// of these from other sources. Some of the values are derived from our URLName value, others
// from session parameters. We need to go through all of these to develop a set of values we
// can connect with.
// this is the protocol we're connecting with. We use this largely to derive configured values from
// session properties.
String protocol = null;
// if we're working with the URL form, then we can retrieve the protocol from the URL.
if (url != null) {
protocol = url.getProtocol();
}
// if the port is -1, see if we have an override from url.
if (port == -1) {
if (protocol != null) {
port = url.getPort();
}
}
// now try to derive values for any of the arguments we've been given as defaults
if (host == null) {
// first choice is from the url, if we have
if (url != null) {
host = url.getHost();
// it is possible that this could return null (rare). If it does, try to get a
// value from a protocol specific session variable.
if (host == null) {
if (protocol != null) {
host = session.getProperty("mail." + protocol + ".host");
}
}
}
// this may still be null...get the global mail property
if (host == null) {
host = session.getProperty("mail.host");
}
}
// ok, go after userid information next.
if (user == null) {
// first choice is from the url, if we have
if (url != null) {
user = url.getUsername();
// make sure we get the password from the url, if we can.
if (password == null) {
password = url.getPassword();
}
}
// user still null? We have several levels of properties to try yet
if (user == null) {
if (protocol != null) {
user = session.getProperty("mail." + protocol + ".user");
}
// this may still be null...get the global mail property
if (user == null) {
user = session.getProperty("mail.user");
// still null, try using the user.name system property
if (user == null) {
// finally, we try getting the system defined user name
try {
user = System.getProperty("user.name");
} catch (final SecurityException e) {
// we ignore this, and just us a null username.
}
}
}
}
}
// if we have an explicitly given user name, we need to see if this matches the url one and
// grab the password from there.
else {
if (url != null && user.equals(url.getUsername())) {
password = url.getPassword();
}
}
// we need to update the URLName associated with this connection once we have all of the information,
// which means we also need to propogate the file portion of the URLName if we have this form when
// we start.
String file = null;
if (url != null) {
file = url.getFile();
}
// see if we have cached security information to use. If this is not cached, we'll save it
// after we successfully connect.
boolean cachePassword = false;
// still have a null password to this point, and using a url form?
if (password == null && url != null) {
// construct a new URL, filling in any pieces that may have been explicitly specified.
setURLName(new URLName(protocol, host, port, file, user, password));
// now see if we have a saved password from a previous request.
final PasswordAuthentication cachedPassword = session.getPasswordAuthentication(getURLName());
// if we found a saved one, see if we need to get any the pieces from here.
if (cachedPassword != null) {
// not even a resolved userid? Then use both bits.
if (user == null) {
user = cachedPassword.getUserName();
password = cachedPassword.getPassword();
}
// our user name must match the cached name to be valid.
else if (user.equals(cachedPassword.getUserName())) {
password = cachedPassword.getPassword();
}
}
else
{
// nothing found in the cache, so we need to save this if we can connect successfully.
cachePassword = true;
}
}
// we've done our best up to this point to obtain all of the information needed to make the
// connection. Now we pass this off to the protocol handler to see if it works. If we get a
// connection failure, we may need to prompt for a password before continuing.
try {
connected = protocolConnect(host, port, user, password);
}
catch (final AuthenticationFailedException e) {
}
if (!connected) {
InetAddress ipAddress = null;
try {
ipAddress = InetAddress.getByName(host);
} catch (final UnknownHostException e) {
}
// now ask the session to try prompting for a password.
final PasswordAuthentication promptPassword = session.requestPasswordAuthentication(ipAddress, port, protocol, null, user);
// if we were able to obtain new information from the session, then try again using the
// provided information .
if (promptPassword != null) {
user = promptPassword.getUserName();
password = promptPassword.getPassword();
}
connected = protocolConnect(host, port, user, password);
}
// if we're still not connected, then this is an exception.
if (!connected) {
throw new AuthenticationFailedException();
}
// the URL name needs to reflect the most recent information.
setURLName(new URLName(protocol, host, port, file, user, password));
// we need to update the global password cache with this information.
if (cachePassword) {
session.setPasswordAuthentication(getURLName(), new PasswordAuthentication(user, password));
}
// we're now connected....broadcast this to any interested parties.
setConnected(connected);
notifyConnectionListeners(ConnectionEvent.OPENED);
}
/**
* Attempt the protocol-specific connection; subclasses should override this to establish
* a connection in the appropriate manner.
*
* This method should return true if the connection was established.
* It may return false to cause the {@link #connect(String, int, String, String)} method to
* reattempt the connection after trying to obtain user and password information from the user.
* Alternatively it may throw a AuthenticatedFailedException to abandon the conection attempt.
*
* @param host The target host name of the service.
* @param port The connection port for the service.
* @param user The user name used for the connection.
* @param password The password used for the connection.
*
* @return true if a connection was established, false if there was authentication
* error with the connection.
* @throws AuthenticationFailedException
* if authentication fails
* @throws MessagingException
* for other failures
*/
protected boolean protocolConnect(final String host, final int port, final String user, final String password) throws MessagingException {
return false;
}
/**
* Check if this service is currently connected.
* The default implementation simply returns the value of a private boolean field;
* subclasses may wish to override this method to verify the physical connection.
*
* @return true if this service is connected
*/
public boolean isConnected() {
return connected;
}
/**
* Notification to subclasses that the connection state has changed.
* This method is called by the connect() and close() methods to indicate state change;
* subclasses should also call this method if the connection is automatically closed
* for some reason.
*
* @param connected the connection state
*/
protected void setConnected(final boolean connected) {
this.connected = connected;
}
/**
* Close this service and terminate its physical connection.
* The default implementation simply calls setConnected(false) and then
* sends a CLOSED event to all registered ConnectionListeners.
* Subclasses overriding this method should still ensure it is closed; they should
* also ensure that it is called if the connection is closed automatically, for
* for example in a finalizer.
*
*@throws MessagingException if there were errors closing; the connection is still closed
*/
public void close() throws MessagingException {
setConnected(false);
notifyConnectionListeners(ConnectionEvent.CLOSED);
}
/**
* Return a copy of the URLName representing this service with the password and file information removed.
*
* @return the URLName for this service
*/
public URLName getURLName() {
// if we haven't composed the URL version we hand out, create it now. But only if we really
// have a URL.
if (exposedUrl == null) {
if (url != null) {
exposedUrl = new URLName(url.getProtocol(), url.getHost(), url.getPort(), null, url.getUsername(), null);
}
}
return exposedUrl;
}
/**
* Set the url field.
* @param url the new value
*/
protected void setURLName(final URLName url) {
this.url = url;
}
public void addConnectionListener(final ConnectionListener listener) {
connectionListeners.add(listener);
}
public void removeConnectionListener(final ConnectionListener listener) {
connectionListeners.remove(listener);
}
protected void notifyConnectionListeners(final int type) {
queueEvent(new ConnectionEvent(this, type), connectionListeners);
}
@Override
public String toString() {
// NOTE: We call getURLName() rather than use the URL directly
// because the get method strips out the password information.
final URLName url = getURLName();
return url == null ? super.toString() : url.toString();
}
protected void queueEvent(final MailEvent event, final Vector listeners) {
// if there are no listeners to dispatch this to, don't put it on the queue.
// This allows us to delay creating the queue (and its new thread) until
// we
if (listeners.isEmpty()) {
return;
}
// first real event? Time to get the queue kicked off.
if (queue == null) {
queue = new EventQueue();
}
// tee it up and let it rip.
queue.queueEvent(event, (List)listeners.clone());
}
@Override
protected void finalize() throws Throwable {
// stop our event queue if we had to create one
if (queue != null) {
queue.stop();
}
connectionListeners.clear();
super.finalize();
}
/**
* Package scope utility method to allow Message instances
* access to the Service's session.
*
* @return The Session the service is associated with.
*/
Session getSession() {
return session;
}
}
| 1,955 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Authenticator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.net.InetAddress;
/**
* @version $Rev$ $Date$
*/
public abstract class Authenticator {
private InetAddress host;
private int port;
private String prompt;
private String protocol;
private String username;
synchronized PasswordAuthentication authenticate(final InetAddress host, final int port, final String protocol, final String prompt, final String username) {
this.host = host;
this.port = port;
this.protocol = protocol;
this.prompt = prompt;
this.username = username;
return getPasswordAuthentication();
}
protected final String getDefaultUserName() {
return username;
}
protected PasswordAuthentication getPasswordAuthentication() {
return null;
}
protected final int getRequestingPort() {
return port;
}
protected final String getRequestingPrompt() {
return prompt;
}
protected final String getRequestingProtocol() {
return protocol;
}
protected final InetAddress getRequestingSite() {
return host;
}
}
| 1,956 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/QuotaAwareStore.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* An interface for Store implementations to support the IMAP RFC 2087 Quota extension.
*
* @version $Rev$ $Date$
*/
public interface QuotaAwareStore {
/**
* Get the quotas for the specified root element.
*
* @param root The root name for the quota information.
*
* @return An array of Quota objects defined for the root.
* @throws MessagingException if the quotas cannot be retrieved
*/
public Quota[] getQuota(String root) throws javax.mail.MessagingException;
/**
* Set a quota item. The root contained in the Quota item identifies
* the quota target.
*
* @param quota The source quota item.
* @throws MessagingException if the quota cannot be set
*/
public void setQuota(Quota quota) throws javax.mail.MessagingException;
}
| 1,957 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/IllegalWriteException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class IllegalWriteException extends MessagingException {
private static final long serialVersionUID = 3974370223328268013L;
public IllegalWriteException() {
super();
}
public IllegalWriteException(final String message) {
super(message);
}
/**
* Constructs an IllegalWriteException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param s The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public IllegalWriteException(final String s, final Exception e) {
super(s, e);
}
}
| 1,958 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/FolderNotFoundException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class FolderNotFoundException extends MessagingException {
private static final long serialVersionUID = 472612108891249403L;
private transient Folder _folder;
public FolderNotFoundException() {
super();
}
public FolderNotFoundException(final Folder folder) {
this(folder, "Folder not found: " + folder.getName());
}
public FolderNotFoundException(final Folder folder, final String message) {
super(message);
_folder = folder;
}
public FolderNotFoundException(final String message, final Folder folder) {
this(folder, message);
}
/**
* Constructs a FolderNotFoundException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param folder The Folder
* @param s The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public FolderNotFoundException(final Folder folder, final String s, final Exception e) {
super(s, e);
_folder = folder;
}
public Folder getFolder() {
return _folder;
}
}
| 1,959 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/AuthenticationFailedException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class AuthenticationFailedException extends MessagingException {
private static final long serialVersionUID = 492080754054436511L;
public AuthenticationFailedException() {
super();
}
public AuthenticationFailedException(final String message) {
super(message);
}
/**
* Constructs an AuthenticationFailedException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param message The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public AuthenticationFailedException(final String message, final Exception e) {
super(message, e);
}
}
| 1,960 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Store.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.util.Vector;
import javax.mail.event.FolderEvent;
import javax.mail.event.FolderListener;
import javax.mail.event.StoreEvent;
import javax.mail.event.StoreListener;
/**
* Abstract class that represents a message store.
*
* @version $Rev$ $Date$
*/
public abstract class Store extends Service {
private static final Folder[] FOLDER_ARRAY = new Folder[0];
private final Vector folderListeners = new Vector(2);
private final Vector storeListeners = new Vector(2);
/**
* Constructor specifying session and url of this store.
* Subclasses MUST provide a constructor with this signature.
*
* @param session the session associated with this store
* @param name the URL of the store
*/
protected Store(final Session session, final URLName name) {
super(session, name);
}
/**
* Return a Folder object that represents the root of the namespace for the current user.
*
* Note that in some store configurations (such as IMAP4) the root folder might
* not be the INBOX folder.
*
* @return the root Folder
* @throws MessagingException if there was a problem accessing the store
*/
public abstract Folder getDefaultFolder() throws MessagingException;
/**
* Return the Folder corresponding to the given name.
* The folder might not physically exist; the {@link Folder#exists()} method can be used
* to determine if it is real.
* @param name the name of the Folder to return
* @return the corresponding folder
* @throws MessagingException if there was a problem accessing the store
*/
public abstract Folder getFolder(String name) throws MessagingException;
/**
* Return the folder identified by the URLName; the URLName must refer to this Store.
* Implementations may use the {@link URLName#getFile()} method to determined the folder name.
*
* @param name the folder to return
* @return the corresponding folder
* @throws MessagingException if there was a problem accessing the store
*/
public abstract Folder getFolder(URLName name) throws MessagingException;
/**
* Return the root folders of the personal namespace belonging to the current user.
*
* The default implementation simply returns an array containing the folder returned by {@link #getDefaultFolder()}.
* @return the root folders of the user's peronal namespaces
* @throws MessagingException if there was a problem accessing the store
*/
public Folder[] getPersonalNamespaces() throws MessagingException {
return new Folder[]{getDefaultFolder()};
}
/**
* Return the root folders of the personal namespaces belonging to the supplied user.
*
* The default implementation simply returns an empty array.
*
* @param user the user whose namespaces should be returned
* @return the root folders of the given user's peronal namespaces
* @throws MessagingException if there was a problem accessing the store
*/
public Folder[] getUserNamespaces(final String user) throws MessagingException {
return FOLDER_ARRAY;
}
/**
* Return the root folders of namespaces that are intended to be shared between users.
*
* The default implementation simply returns an empty array.
* @return the root folders of all shared namespaces
* @throws MessagingException if there was a problem accessing the store
*/
public Folder[] getSharedNamespaces() throws MessagingException {
return FOLDER_ARRAY;
}
public void addStoreListener(final StoreListener listener) {
storeListeners.add(listener);
}
public void removeStoreListener(final StoreListener listener) {
storeListeners.remove(listener);
}
protected void notifyStoreListeners(final int type, final String message) {
queueEvent(new StoreEvent(this, type, message), storeListeners);
}
public void addFolderListener(final FolderListener listener) {
folderListeners.add(listener);
}
public void removeFolderListener(final FolderListener listener) {
folderListeners.remove(listener);
}
protected void notifyFolderListeners(final int type, final Folder folder) {
queueEvent(new FolderEvent(this, folder, type), folderListeners);
}
protected void notifyFolderRenamedListeners(final Folder oldFolder, final Folder newFolder) {
queueEvent(new FolderEvent(this, oldFolder, newFolder, FolderEvent.RENAMED), folderListeners);
}
}
| 1,961 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Session.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import org.apache.geronimo.mail.MailProviderRegistry;
import org.apache.geronimo.osgi.locator.ProviderLocator;
/**
* OK, so we have a final class in the API with a heck of a lot of implementation required...
* let's try and figure out what it is meant to do.
* <p/>
* It is supposed to collect together properties and defaults so that they can be
* shared by multiple applications on a desktop; with process isolation and no
* real concept of shared memory, this seems challenging. These properties and
* defaults rely on system properties, making management in a app server harder,
* and on resources loaded from "mail.jar" which may lead to skew between
* differnet independent implementations of this API.
*
* @version $Rev$ $Date$
*/
public final class Session {
private static final Class[] PARAM_TYPES = {Session.class, URLName.class};
private static final WeakHashMap addressMapsByClassLoader = new WeakHashMap();
private static Session DEFAULT_SESSION;
private final Map passwordAuthentications = new HashMap();
private final Properties properties;
private final Authenticator authenticator;
private boolean debug;
private PrintStream debugOut = System.out;
private static final WeakHashMap providersByClassLoader = new WeakHashMap();
/**
* No public constrcutor allowed.
*/
private Session(final Properties properties, final Authenticator authenticator) {
this.properties = properties;
this.authenticator = authenticator;
debug = Boolean.valueOf(properties.getProperty("mail.debug")).booleanValue();
}
/**
* Create a new session initialized with the supplied properties which uses the supplied authenticator.
* Clients should ensure the properties listed in Appendix A of the JavaMail specification are
* set as the defaults are unlikey to work in most scenarios; particular attention should be given
* to:
* <ul>
* <li>mail.store.protocol</li>
* <li>mail.transport.protocol</li>
* <li>mail.host</li>
* <li>mail.user</li>
* <li>mail.from</li>
* </ul>
*
* @param properties the session properties
* @param authenticator an authenticator for callbacks to the user
* @return a new session
*/
public static Session getInstance(Properties properties, final Authenticator authenticator) {
// if we have a properties bundle, we need a copy of the provided one
if (properties != null) {
properties = (Properties)properties.clone();
}
return new Session(properties, authenticator);
}
/**
* Create a new session initialized with the supplied properties with no authenticator.
*
* @param properties the session properties
* @return a new session
* @see #getInstance(java.util.Properties, Authenticator)
*/
public static Session getInstance(final Properties properties) {
return getInstance(properties, null);
}
/**
* Get the "default" instance assuming no authenticator is required.
*
* @param properties the session properties
* @return if "default" session
* @throws SecurityException if the does not have permission to access the default session
*/
public synchronized static Session getDefaultInstance(final Properties properties) {
return getDefaultInstance(properties, null);
}
/**
* Get the "default" session.
* If there is not current "default", a new Session is created and installed as the default.
*
* @param properties
* @param authenticator
* @return if "default" session
* @throws SecurityException if the does not have permission to access the default session
*/
public synchronized static Session getDefaultInstance(final Properties properties, final Authenticator authenticator) {
if (DEFAULT_SESSION == null) {
DEFAULT_SESSION = getInstance(properties, authenticator);
} else {
if (authenticator != DEFAULT_SESSION.authenticator) {
if (authenticator == null || DEFAULT_SESSION.authenticator == null || authenticator.getClass().getClassLoader() != DEFAULT_SESSION.authenticator.getClass().getClassLoader()) {
throw new SecurityException();
}
}
// todo we should check with the SecurityManager here as well
}
return DEFAULT_SESSION;
}
/**
* Enable debugging for this session.
* Debugging can also be enabled by setting the "mail.debug" property to true when
* the session is being created.
*
* @param debug the debug setting
*/
public void setDebug(final boolean debug) {
this.debug = debug;
}
/**
* Get the debug setting for this session.
*
* @return the debug setting
*/
public boolean getDebug() {
return debug;
}
/**
* Set the output stream where debug information should be sent.
* If set to null, System.out will be used.
*
* @param out the stream to write debug information to
*/
public void setDebugOut(final PrintStream out) {
debugOut = out == null ? System.out : out;
}
/**
* Return the debug output stream.
*
* @return the debug output stream
*/
public PrintStream getDebugOut() {
return debugOut;
}
/**
* Return the list of providers available to this application.
* This method searches for providers that are defined in the javamail.providers
* and javamail.default.providers resources available through the current context
* classloader, or if that is not available, the classloader that loaded this class.
* <p/>
* As searching for providers is potentially expensive, this implementation maintains
* a WeakHashMap of providers indexed by ClassLoader.
*
* @return an array of providers
*/
public Provider[] getProviders() {
final ProviderInfo info = getProviderInfo();
return (Provider[]) info.all.toArray(new Provider[info.all.size()]);
}
/**
* Return the provider for a specific protocol.
* This implementation initially looks in the Session properties for an property with the name
* "mail.<protocol>.class"; if found it attempts to create an instance of the class named in that
* property throwing a NoSuchProviderException if the class cannot be loaded.
* If this property is not found, it searches the providers returned by {@link #getProviders()}
* for a entry for the specified protocol.
*
* @param protocol the protocol to get a provider for
* @return a provider for that protocol
* @throws NoSuchProviderException
*/
public Provider getProvider(final String protocol) throws NoSuchProviderException {
final ProviderInfo info = getProviderInfo();
Provider provider = null;
final String providerName = properties.getProperty("mail." + protocol + ".class");
if (providerName != null) {
provider = (Provider) info.byClassName.get(providerName);
if (debug) {
writeDebug("DEBUG: new provider loaded: " + provider.toString());
}
}
// if not able to locate this by class name, just grab a registered protocol.
if (provider == null) {
provider = (Provider) info.byProtocol.get(protocol);
}
if (provider == null) {
throw new NoSuchProviderException("Unable to locate provider for protocol: " + protocol);
}
if (debug) {
writeDebug("DEBUG: getProvider() returning provider " + provider.toString());
}
return provider;
}
/**
* Make the supplied Provider the default for its protocol.
*
* @param provider the new default Provider
* @throws NoSuchProviderException
*/
public void setProvider(final Provider provider) throws NoSuchProviderException {
final ProviderInfo info = getProviderInfo();
info.byProtocol.put(provider.getProtocol(), provider);
}
/**
* Return a Store for the default protocol defined by the mail.store.protocol property.
*
* @return the store for the default protocol
* @throws NoSuchProviderException
*/
public Store getStore() throws NoSuchProviderException {
final String protocol = properties.getProperty("mail.store.protocol");
if (protocol == null) {
throw new NoSuchProviderException("mail.store.protocol property is not set");
}
return getStore(protocol);
}
/**
* Return a Store for the specified protocol.
*
* @param protocol the protocol to get a Store for
* @return a Store
* @throws NoSuchProviderException if no provider is defined for the specified protocol
*/
public Store getStore(final String protocol) throws NoSuchProviderException {
final Provider provider = getProvider(protocol);
return getStore(provider);
}
/**
* Return a Store for the protocol specified in the given URL
*
* @param url the URL of the Store
* @return a Store
* @throws NoSuchProviderException if no provider is defined for the specified protocol
*/
public Store getStore(final URLName url) throws NoSuchProviderException {
return (Store) getService(getProvider(url.getProtocol()), url);
}
/**
* Return the Store specified by the given provider.
*
* @param provider the provider to create from
* @return a Store
* @throws NoSuchProviderException if there was a problem creating the Store
*/
public Store getStore(final Provider provider) throws NoSuchProviderException {
if (Provider.Type.STORE != provider.getType()) {
throw new NoSuchProviderException("Not a Store Provider: " + provider);
}
return (Store) getService(provider, null);
}
/**
* Return a closed folder for the supplied URLName, or null if it cannot be obtained.
* <p/>
* The scheme portion of the URL is used to locate the Provider and create the Store;
* the returned Store is then used to obtain the folder.
*
* @param name the location of the folder
* @return the requested folder, or null if it is unavailable
* @throws NoSuchProviderException if there is no provider
* @throws MessagingException if there was a problem accessing the Store
*/
public Folder getFolder(final URLName name) throws MessagingException {
final Store store = getStore(name);
return store.getFolder(name);
}
/**
* Return a Transport for the default protocol specified by the
* <code>mail.transport.protocol</code> property.
*
* @return a Transport
* @throws NoSuchProviderException
*/
public Transport getTransport() throws NoSuchProviderException {
final String protocol = properties.getProperty("mail.transport.protocol");
if (protocol == null) {
throw new NoSuchProviderException("mail.transport.protocol property is not set");
}
return getTransport(protocol);
}
/**
* Return a Transport for the specified protocol.
*
* @param protocol the protocol to use
* @return a Transport
* @throws NoSuchProviderException
*/
public Transport getTransport(final String protocol) throws NoSuchProviderException {
final Provider provider = getProvider(protocol);
return getTransport(provider);
}
/**
* Return a transport for the protocol specified in the URL.
*
* @param name the URL whose scheme specifies the protocol
* @return a Transport
* @throws NoSuchProviderException
*/
public Transport getTransport(final URLName name) throws NoSuchProviderException {
return (Transport) getService(getProvider(name.getProtocol()), name);
}
/**
* Return a transport for the protocol associated with the type of this address.
*
* @param address the address we are trying to deliver to
* @return a Transport
* @throws NoSuchProviderException
*/
public Transport getTransport(final Address address) throws NoSuchProviderException {
final String type = address.getType();
// load the address map from the resource files.
final Map addressMap = getAddressMap();
final String protocolName = (String)addressMap.get(type);
if (protocolName == null) {
throw new NoSuchProviderException("No provider for address type " + type);
}
return getTransport(protocolName);
}
/**
* Return the Transport specified by a Provider
*
* @param provider the defining Provider
* @return a Transport
* @throws NoSuchProviderException
*/
public Transport getTransport(final Provider provider) throws NoSuchProviderException {
return (Transport) getService(provider, null);
}
/**
* Set the password authentication associated with a URL.
*
* @param name the url
* @param authenticator the authenticator
*/
public void setPasswordAuthentication(final URLName name, final PasswordAuthentication authenticator) {
if (authenticator == null) {
passwordAuthentications.remove(name);
} else {
passwordAuthentications.put(name, authenticator);
}
}
/**
* Get the password authentication associated with a URL
*
* @param name the URL
* @return any authenticator for that url, or null if none
*/
public PasswordAuthentication getPasswordAuthentication(final URLName name) {
return (PasswordAuthentication) passwordAuthentications.get(name);
}
/**
* Call back to the application supplied authenticator to get the needed username add password.
*
* @param host the host we are trying to connect to, may be null
* @param port the port on that host
* @param protocol the protocol trying to be used
* @param prompt a String to show as part of the prompt, may be null
* @param defaultUserName the default username, may be null
* @return the authentication information collected by the authenticator; may be null
*/
public PasswordAuthentication requestPasswordAuthentication(final InetAddress host, final int port, final String protocol, final String prompt, final String defaultUserName) {
if (authenticator == null) {
return null;
}
return authenticator.authenticate(host, port, protocol, prompt, defaultUserName);
}
/**
* Return the properties object for this Session; this is a live collection.
*
* @return the properties for the Session
*/
public Properties getProperties() {
return properties;
}
/**
* Return the specified property.
*
* @param property the property to get
* @return its value, or null if not present
*/
public String getProperty(final String property) {
return getProperties().getProperty(property);
}
/**
* Add a provider to the Session managed provider list.
*
* @param provider The new provider to add.
*/
public synchronized void addProvider(final Provider provider) {
final ProviderInfo info = getProviderInfo();
info.addProvider(provider);
}
/**
* Add a mapping between an address type and a protocol used
* to process that address type.
*
* @param addressType
* The address type identifier.
* @param protocol The protocol name mapping.
*/
public void setProtocolForAddress(final String addressType, final String protocol) {
final Map addressMap = getAddressMap();
// no protocol specified is a removal
if (protocol == null) {
addressMap.remove(addressType);
}
else {
addressMap.put(addressType, protocol);
}
}
private Service getService(final Provider provider, URLName name) throws NoSuchProviderException {
try {
if (name == null) {
name = new URLName(provider.getProtocol(), null, -1, null, null, null);
}
final ClassLoader cl = getClassLoader();
Class clazz = null;
try {
clazz = ProviderLocator.loadClass(provider.getClassName(), this.getClass(), cl);
} catch (final ClassNotFoundException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Unable to load class for provider: " + provider).initCause(e);
}
final Constructor ctr = clazz.getConstructor(PARAM_TYPES);
return(Service) ctr.newInstance(new Object[]{this, name});
} catch (final NoSuchMethodException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Provider class does not have a constructor(Session, URLName): " + provider).initCause(e);
} catch (final InstantiationException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Unable to instantiate provider class: " + provider).initCause(e);
} catch (final IllegalAccessException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Unable to instantiate provider class: " + provider).initCause(e);
} catch (final InvocationTargetException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Exception from constructor of provider class: " + provider).initCause(e.getCause());
}
}
private ProviderInfo getProviderInfo() {
final ClassLoader cl = getClassLoader();
synchronized (providersByClassLoader) {
ProviderInfo info = (ProviderInfo) providersByClassLoader.get(cl);
if (info == null) {
info = loadProviders(cl);
}
return info;
}
}
private Map getAddressMap() {
final ClassLoader cl = getClassLoader();
Map addressMap = (Map)addressMapsByClassLoader.get(cl);
if (addressMap == null) {
addressMap = loadAddressMap(cl);
}
return addressMap;
}
/**
* Resolve a class loader used to resolve context resources. The
* class loader used is either a current thread context class
* loader (if set), the class loader used to load an authenticator
* we've been initialized with, or the class loader used to load
* this class instance (which may be a subclass of Session).
*
* @return The class loader used to load resources.
*/
private ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
if (authenticator != null) {
cl = authenticator.getClass().getClassLoader();
}
else {
cl = this.getClass().getClassLoader();
}
}
return cl;
}
private ProviderInfo loadProviders(final ClassLoader cl) {
// we create a merged map from reading all of the potential address map entries. The locations
// searched are:
// 1. java.home/lib/javamail.address.map
// 2. META-INF/javamail.address.map
// 3. META-INF/javamail.default.address.map
//
final ProviderInfo info = new ProviderInfo();
// NOTE: Unlike the addressMap, we process these in the defined order. The loading routine
// will not overwrite entries if they already exist in the map.
try {
final File file = new File(System.getProperty("java.home"), "lib/javamail.providers");
final InputStream is = new FileInputStream(file);
try {
loadProviders(info, is);
if (debug) {
writeDebug("Loaded lib/javamail.providers from " + file.toString());
}
} finally{
is.close();
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
try {
final Enumeration e = cl.getResources("META-INF/javamail.providers");
while (e.hasMoreElements()) {
final URL url = (URL) e.nextElement();
if (debug) {
writeDebug("Loading META-INF/javamail.providers from " + url.toString());
}
final InputStream is = url.openStream();
try {
loadProviders(info, is);
} finally{
is.close();
}
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
// we could be running in an OSGi environment, so there might be some globally defined
// providers
try {
final Collection<URL> l = MailProviderRegistry.getProviders();
for (final URL url : l) {
if (debug) {
writeDebug("Loading META-INF/javamail.providers from " + url.toString());
}
final InputStream is = url.openStream();
try {
loadProviders(info, is);
} finally{
is.close();
}
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
try {
final Enumeration e = cl.getResources("META-INF/javamail.default.providers");
while (e.hasMoreElements()) {
final URL url = (URL) e.nextElement();
if (debug) {
writeDebug("Loading javamail.default.providers from " + url.toString());
}
final InputStream is = url.openStream();
try {
loadProviders(info, is);
} finally{
is.close();
}
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
// we could be running in an OSGi environment, so there might be some globally defined
// providers
try {
final Collection<URL> l = MailProviderRegistry.getDefaultProviders();
for (final URL url : l) {
if (debug) {
writeDebug("Loading META-INF/javamail.providers from " + url.toString());
}
final InputStream is = url.openStream();
try {
loadProviders(info, is);
} finally{
is.close();
}
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
// make sure this is added to the global map.
providersByClassLoader.put(cl, info);
return info;
}
private void loadProviders(final ProviderInfo info, final InputStream is) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
// Lines beginning with "#" are just comments.
if (line.startsWith("#")) {
continue;
}
final StringTokenizer tok = new StringTokenizer(line, ";");
String protocol = null;
Provider.Type type = null;
String className = null;
String vendor = null;
String version = null;
while (tok.hasMoreTokens()) {
final String property = tok.nextToken();
final int index = property.indexOf('=');
if (index == -1) {
continue;
}
final String key = property.substring(0, index).trim().toLowerCase();
final String value = property.substring(index+1).trim();
if (protocol == null && "protocol".equals(key)) {
protocol = value;
} else if (type == null && "type".equals(key)) {
if ("store".equals(value)) {
type = Provider.Type.STORE;
} else if ("transport".equals(value)) {
type = Provider.Type.TRANSPORT;
}
} else if (className == null && "class".equals(key)) {
className = value;
} else if ("vendor".equals(key)) {
vendor = value;
} else if ("version".equals(key)) {
version = value;
}
}
if (protocol == null || type == null || className == null) {
//todo should we log a warning?
continue;
}
if (debug) {
writeDebug("DEBUG: loading new provider protocol=" + protocol + ", className=" + className + ", vendor=" + vendor + ", version=" + version);
}
final Provider provider = new Provider(type, protocol, className, vendor, version);
// add to the info list.
info.addProvider(provider);
}
}
/**
* Load up an address map associated with a using class loader
* instance.
*
* @param cl The class loader used to resolve the address map.
*
* @return A map containing the entries associated with this classloader
* instance.
*/
private static Map loadAddressMap(final ClassLoader cl) {
// we create a merged map from reading all of the potential address map entries. The locations
// searched are:
// 1. java.home/lib/javamail.address.map
// 2. META-INF/javamail.address.map
// 3. META-INF/javamail.default.address.map
//
// if all of the above searches fail, we just set up some "default" defaults.
// the format of the address.map file is defined as a property file. We can cheat and
// just use Properties.load() to read in the files.
final Properties addressMap = new Properties();
// add this to the tracking map.
addressMapsByClassLoader.put(cl, addressMap);
// NOTE: We are reading these resources in reverse order of what's cited above. This allows
// user defined entries to overwrite default entries if there are similarly named items.
try {
final Enumeration e = cl.getResources("META-INF/javamail.default.address.map");
while (e.hasMoreElements()) {
final URL url = (URL) e.nextElement();
final InputStream is = url.openStream();
try {
// load as a property file
addressMap.load(is);
} finally{
is.close();
}
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
try {
final Enumeration e = cl.getResources("META-INF/javamail.address.map");
while (e.hasMoreElements()) {
final URL url = (URL) e.nextElement();
final InputStream is = url.openStream();
try {
// load as a property file
addressMap.load(is);
} finally{
is.close();
}
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
try {
final File file = new File(System.getProperty("java.home"), "lib/javamail.address.map");
final InputStream is = new FileInputStream(file);
try {
// load as a property file
addressMap.load(is);
} finally{
is.close();
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
try {
final Enumeration e = cl.getResources("META-INF/javamail.address.map");
while (e.hasMoreElements()) {
final URL url = (URL) e.nextElement();
final InputStream is = url.openStream();
try {
// load as a property file
addressMap.load(is);
} finally{
is.close();
}
}
} catch (final SecurityException e) {
// ignore
} catch (final IOException e) {
// ignore
}
// if unable to load anything, at least create the MimeMessage-smtp protocol mapping.
if (addressMap.isEmpty()) {
addressMap.put("rfc822", "smtp");
}
return addressMap;
}
/**
* Private convenience routine for debug output.
*
* @param msg The message to write out to the debug stream.
*/
private void writeDebug(final String msg) {
debugOut.println(msg);
}
private static class ProviderInfo {
private final Map byClassName = new HashMap();
private final Map byProtocol = new HashMap();
private final List all = new ArrayList();
public void addProvider(final Provider provider) {
final String className = provider.getClassName();
if (!byClassName.containsKey(className)) {
byClassName.put(className, provider);
}
final String protocol = provider.getProtocol();
if (!byProtocol.containsKey(protocol)) {
byProtocol.put(protocol, provider);
}
all.add(provider);
}
}
}
| 1,962 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/MessageRemovedException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class MessageRemovedException extends MessagingException {
private static final long serialVersionUID = 1951292550679528690L;
public MessageRemovedException() {
super();
}
public MessageRemovedException(final String message) {
super(message);
}
/**
* Constructs a MessageRemovedException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param s The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public MessageRemovedException(final String s, final Exception e) {
super(s, e);
}
}
| 1,963 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/PasswordAuthentication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* A data holder used by Authenticator to contain a username and password.
*
* @version $Rev$ $Date$
*/
public final class PasswordAuthentication {
private final String user;
private final String password;
public PasswordAuthentication(final String user, final String password) {
this.user = user;
this.password = password;
}
public String getUserName() {
return user;
}
public String getPassword() {
return password;
}
}
| 1,964 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/ReadOnlyFolderException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public class ReadOnlyFolderException extends MessagingException {
private static final long serialVersionUID = 5711829372799039325L;
private transient Folder _folder;
public ReadOnlyFolderException(final Folder folder) {
this(folder, "Folder not found: " + folder.getName());
}
public ReadOnlyFolderException(final Folder folder, final String message) {
super(message);
_folder = folder;
}
/**
* Constructs a ReadOnlyFolderException with the specified
* detail message and embedded exception. The exception is chained
* to this exception.
*
* @param folder The Folder
* @param message The detailed error message
* @param e The embedded exception
* @since JavaMail 1.5
*/
public ReadOnlyFolderException(final Folder folder, final String message, final Exception e) {
super(message, e);
_folder = folder;
}
public Folder getFolder() {
return _folder;
}
}
| 1,965 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Header.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* Class representing a header field.
*
* @version $Rev$ $Date$
*/
public class Header {
/**
* The name of the header.
*/
protected String name;
/**
* The header value (can be null).
*/
protected String value;
/**
* Constructor initializing all immutable fields.
*
* @param name the name of this header
* @param value the value of this header
*/
public Header(final String name, final String value) {
this.name = name;
this.value = value;
}
/**
* Return the name of this header.
*
* @return the name of this header
*/
public String getName() {
return name;
}
/**
* Return the value of this header.
*
* @return the value of this header
*/
public String getValue() {
return value;
}
}
| 1,966 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Folder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.util.ArrayList;
import java.util.List;
import javax.mail.Flags.Flag;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.ConnectionListener;
import javax.mail.event.FolderEvent;
import javax.mail.event.FolderListener;
import javax.mail.event.MailEvent;
import javax.mail.event.MessageChangedEvent;
import javax.mail.event.MessageChangedListener;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import javax.mail.search.SearchTerm;
/**
* An abstract representation of a folder in a mail system; subclasses would
* implement Folders for each supported protocol.
* <p/>
* Depending on protocol and implementation, folders may contain other folders, messages,
* or both as indicated by the {@link Folder#HOLDS_FOLDERS} and {@link Folder#HOLDS_MESSAGES} flags.
* If the immplementation supports hierarchical folders, the format of folder names is
* implementation dependent; however, components of the name are separated by the
* delimiter character returned by {@link Folder#getSeparator()}.
* <p/>
* The case-insensitive folder name "INBOX" is reserved to refer to the primary folder
* for the current user on the current server; not all stores will provide an INBOX
* and it may not be available at all times.
*
* @version $Rev$ $Date$
*/
public abstract class Folder {
/**
* Flag that indicates that a folder can contain messages.
*/
public static final int HOLDS_MESSAGES = 1;
/**
* Flag that indicates that a folder can contain other folders.
*/
public static final int HOLDS_FOLDERS = 2;
/**
* Flag indicating that this folder cannot be modified.
*/
public static final int READ_ONLY = 1;
/**
* Flag indictaing that this folder can be modified.
* Question: what does it mean if both are set?
*/
public static final int READ_WRITE = 2;
/**
* The store that this folder is part of.
*/
protected Store store;
/**
* The current mode of this folder.
* When open, this can be {@link #READ_ONLY} or {@link #READ_WRITE};
* otherwise is set to -1.
*/
protected int mode = -1;
private final ArrayList connectionListeners = new ArrayList(2);
private final ArrayList folderListeners = new ArrayList(2);
private final ArrayList messageChangedListeners = new ArrayList(2);
private final ArrayList messageCountListeners = new ArrayList(2);
// the EventQueue spins off a new thread, so we only create this
// if we have actual listeners to dispatch an event to.
private EventQueue queue = null;
/**
* Constructor that initializes the Store.
*
* @param store the store that this folder is part of
*/
protected Folder(final Store store) {
this.store = store;
}
/**
* Return the name of this folder.
* This can be invoked when the folder is closed.
*
* @return this folder's name
*/
public abstract String getName();
/**
* Return the full absolute name of this folder.
* This can be invoked when the folder is closed.
*
* @return the full name of this folder
*/
public abstract String getFullName();
/**
* Return the URLName for this folder, which includes the location of the store.
*
* @return the URLName for this folder
* @throws MessagingException
*/
public URLName getURLName() throws MessagingException {
final URLName baseURL = store.getURLName();
return new URLName(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
getFullName(), baseURL.getUsername(), null);
}
/**
* Return the store that this folder is part of.
*
* @return the store this folder is part of
*/
public Store getStore() {
return store;
}
/**
* Return the parent for this folder; if the folder is at the root of a heirarchy
* this returns null.
* This can be invoked when the folder is closed.
*
* @return this folder's parent
* @throws MessagingException
*/
public abstract Folder getParent() throws MessagingException;
/**
* Check to see if this folder physically exists in the store.
* This can be invoked when the folder is closed.
*
* @return true if the folder really exists
* @throws MessagingException if there was a problem accessing the store
*/
public abstract boolean exists() throws MessagingException;
/**
* Return a list of folders from this Folder's namespace that match the supplied pattern.
* Patterns may contain the following wildcards:
* <ul><li>'%' which matches any characater except hierarchy delimiters</li>
* <li>'*' which matches any character including hierarchy delimiters</li>
* </ul>
* This can be invoked when the folder is closed.
*
* @param pattern the pattern to search for
* @return a, possibly empty, array containing Folders that matched the pattern
* @throws MessagingException if there was a problem accessing the store
*/
public abstract Folder[] list(String pattern) throws MessagingException;
/**
* Return a list of folders to which the user is subscribed and which match the supplied pattern.
* If the store does not support the concept of subscription then this should match against
* all folders; the default implementation of this method achieves this by defaulting to the
* {@link #list(String)} method.
*
* @param pattern the pattern to search for
* @return a, possibly empty, array containing subscribed Folders that matched the pattern
* @throws MessagingException if there was a problem accessing the store
*/
public Folder[] listSubscribed(final String pattern) throws MessagingException {
return list(pattern);
}
/**
* Convenience method that invokes {@link #list(String)} with the pattern "%".
*
* @return a, possibly empty, array of subfolders
* @throws MessagingException if there was a problem accessing the store
*/
public Folder[] list() throws MessagingException {
return list("%");
}
/**
* Convenience method that invokes {@link #listSubscribed(String)} with the pattern "%".
*
* @return a, possibly empty, array of subscribed subfolders
* @throws MessagingException if there was a problem accessing the store
*/
public Folder[] listSubscribed() throws MessagingException {
return listSubscribed("%");
}
/**
* Return the character used by this folder's Store to separate path components.
*
* @return the name separater character
* @throws MessagingException if there was a problem accessing the store
*/
public abstract char getSeparator() throws MessagingException;
/**
* Return the type of this folder, indicating whether it can contain subfolders,
* messages, or both. The value returned is a bitmask with the appropriate bits set.
*
* @return the type of this folder
* @throws MessagingException if there was a problem accessing the store
* @see #HOLDS_FOLDERS
* @see #HOLDS_MESSAGES
*/
public abstract int getType() throws MessagingException;
/**
* Create a new folder capable of containing subfoldera and/or messages as
* determined by the type parameter. Any hierarchy defined by the folder
* name will be recursively created.
* If the folder was sucessfully created, a {@link FolderEvent#CREATED CREATED FolderEvent}
* is sent to all FolderListeners registered with this Folder or with the Store.
*
* @param type the type, indicating if this folder should contain subfolders, messages or both
* @return true if the folder was sucessfully created
* @throws MessagingException if there was a problem accessing the store
*/
public abstract boolean create(int type) throws MessagingException;
/**
* Determine if the user is subscribed to this Folder. The default implementation in
* this class always returns true.
*
* @return true is the user is subscribed to this Folder
*/
public boolean isSubscribed() {
return true;
}
/**
* Set the user's subscription to this folder.
* Not all Stores support subscription; the default implementation in this class
* always throws a MethodNotSupportedException
*
* @param subscribed whether to subscribe to this Folder
* @throws MessagingException if there was a problem accessing the store
* @throws MethodNotSupportedException if the Store does not support subscription
*/
public void setSubscribed(final boolean subscribed) throws MessagingException {
throw new MethodNotSupportedException();
}
/**
* Check to see if this Folder conatins messages with the {@link Flag.RECENT} flag set.
* This can be used when the folder is closed to perform a light-weight check for new mail;
* to perform an incremental check for new mail the folder must be opened.
*
* @return true if the Store has recent messages
* @throws MessagingException if there was a problem accessing the store
*/
public abstract boolean hasNewMessages() throws MessagingException;
/**
* Get the Folder determined by the supplied name; if the name is relative
* then it is interpreted relative to this folder. This does not check that
* the named folder actually exists.
*
* @param name the name of the folder to return
* @return the named folder
* @throws MessagingException if there was a problem accessing the store
*/
public abstract Folder getFolder(String name) throws MessagingException;
/**
* Delete this folder and possibly any subfolders. This operation can only be
* performed on a closed folder.
* If recurse is true, then all subfolders are deleted first, then any messages in
* this folder are removed and it is finally deleted; {@link FolderEvent#DELETED}
* events are sent as appropriate.
* If recurse is false, then the behaviour depends on the folder type and store
* implementation as followd:
* <ul>
* <li>If the folder can only conrain messages, then all messages are removed and
* then the folder is deleted; a {@link FolderEvent#DELETED} event is sent.</li>
* <li>If the folder can onlu contain subfolders, then if it is empty it will be
* deleted and a {@link FolderEvent#DELETED} event is sent; if the folder is not
* empty then the delete fails and this method returns false.</li>
* <li>If the folder can contain both subfolders and messages, then if the folder
* does not contain any subfolders, any messages are deleted, the folder itself
* is deleted and a {@link FolderEvent#DELETED} event is sent; if the folder does
* contain subfolders then the implementation may choose from the following three
* behaviors:
* <ol>
* <li>it may return false indicting the operation failed</li>
* <li>it may remove all messages within the folder, send a {@link FolderEvent#DELETED}
* event, and then return true to indicate the delete was performed. Note this does
* not delete the folder itself and the {@link #exists()} operation for this folder
* will return true</li>
* <li>it may remove all messages within the folder as per the previous option; in
* addition it may change the type of the Folder to only HOLDS_FOLDERS indictaing
* that messages may no longer be added</li>
* </li>
* </ul>
* FolderEvents are sent to all listeners registered with this folder or
* with the Store.
*
* @param recurse whether subfolders should be recursively deleted as well
* @return true if the delete operation succeeds
* @throws MessagingException if there was a problem accessing the store
*/
public abstract boolean delete(boolean recurse) throws MessagingException;
/**
* Rename this folder; the folder must be closed.
* If the rename is successfull, a {@link FolderEvent#RENAMED} event is sent to
* all listeners registered with this folder or with the store.
*
* @param newName the new name for this folder
* @return true if the rename succeeded
* @throws MessagingException if there was a problem accessing the store
*/
public abstract boolean renameTo(Folder newName) throws MessagingException;
/**
* Open this folder; the folder must be able to contain messages and
* must currently be closed. If the folder is opened successfully then
* a {@link ConnectionEvent#OPENED} event is sent to listeners registered
* with this Folder.
* <p/>
* Whether the Store allows multiple connections or if it allows multiple
* writers is implementation defined.
*
* @param mode READ_ONLY or READ_WRITE
* @throws MessagingException if there was a problem accessing the store
*/
public abstract void open(int mode) throws MessagingException;
/**
* Close this folder; it must already be open.
* A {@link ConnectionEvent#CLOSED} event is sent to all listeners registered
* with this folder.
*
* @param expunge whether to expunge all deleted messages
* @throws MessagingException if there was a problem accessing the store; the folder is still closed
*/
public abstract void close(boolean expunge) throws MessagingException;
/**
* Indicates that the folder has been opened.
*
* @return true if the folder is open
*/
public abstract boolean isOpen();
/**
* Return the mode of this folder ass passed to {@link #open(int)}, or -1 if
* the folder is closed.
*
* @return the mode this folder was opened with
*/
public int getMode() {
return mode;
}
/**
* Get the flags supported by this folder.
*
* @return the flags supported by this folder, or null if unknown
* @see Flags
*/
public abstract Flags getPermanentFlags();
/**
* Return the number of messages this folder contains.
* If this operation is invoked on a closed folder, the implementation
* may choose to return -1 to avoid the expense of opening the folder.
*
* @return the number of messages, or -1 if unknown
* @throws MessagingException if there was a problem accessing the store
*/
public abstract int getMessageCount() throws MessagingException;
/**
* Return the numbew of messages in this folder that have the {@link Flag.RECENT} flag set.
* If this operation is invoked on a closed folder, the implementation
* may choose to return -1 to avoid the expense of opening the folder.
* The default implmentation of this method iterates over all messages
* in the folder; subclasses should override if possible to provide a more
* efficient implementation.
*
* @return the number of new messages, or -1 if unknown
* @throws MessagingException if there was a problem accessing the store
*/
public int getNewMessageCount() throws MessagingException {
return getCount(Flags.Flag.RECENT, true);
}
/**
* Return the numbew of messages in this folder that do not have the {@link Flag.SEEN} flag set.
* If this operation is invoked on a closed folder, the implementation
* may choose to return -1 to avoid the expense of opening the folder.
* The default implmentation of this method iterates over all messages
* in the folder; subclasses should override if possible to provide a more
* efficient implementation.
*
* @return the number of new messages, or -1 if unknown
* @throws MessagingException if there was a problem accessing the store
*/
public int getUnreadMessageCount() throws MessagingException {
return getCount(Flags.Flag.SEEN, false);
}
/**
* Return the numbew of messages in this folder that have the {@link Flag.DELETED} flag set.
* If this operation is invoked on a closed folder, the implementation
* may choose to return -1 to avoid the expense of opening the folder.
* The default implmentation of this method iterates over all messages
* in the folder; subclasses should override if possible to provide a more
* efficient implementation.
*
* @return the number of new messages, or -1 if unknown
* @throws MessagingException if there was a problem accessing the store
*/
public int getDeletedMessageCount() throws MessagingException {
return getCount(Flags.Flag.DELETED, true);
}
private int getCount(final Flag flag, final boolean value) throws MessagingException {
if (!isOpen()) {
return -1;
}
final Message[] messages = getMessages();
int total = 0;
for (int i = 0; i < messages.length; i++) {
if (messages[i].getFlags().contains(flag) == value) {
total++;
}
}
return total;
}
/**
* Retrieve the message with the specified index in this Folder;
* messages indices start at 1 not zero.
* Clients should note that the index for a specific message may change
* if the folder is expunged; {@link Message} objects should be used as
* references instead.
*
* @param index the index of the message to fetch
* @return the message
* @throws MessagingException if there was a problem accessing the store
*/
public abstract Message getMessage(int index) throws MessagingException;
/**
* Retrieve messages with index between start and end inclusive
*
* @param start index of first message
* @param end index of last message
* @return an array of messages from start to end inclusive
* @throws MessagingException if there was a problem accessing the store
*/
public Message[] getMessages(int start, final int end) throws MessagingException {
final Message[] result = new Message[end - start + 1];
for (int i = 0; i < result.length; i++) {
result[i] = getMessage(start++);
}
return result;
}
/**
* Retrieve messages with the specified indices.
*
* @param ids the indices of the messages to fetch
* @return the specified messages
* @throws MessagingException if there was a problem accessing the store
*/
public Message[] getMessages(final int ids[]) throws MessagingException {
final Message[] result = new Message[ids.length];
for (int i = 0; i < ids.length; i++) {
result[i] = getMessage(ids[i]);
}
return result;
}
/**
* Retrieve all messages.
*
* @return all messages in this folder
* @throws MessagingException if there was a problem accessing the store
*/
public Message[] getMessages() throws MessagingException {
return getMessages(1, getMessageCount());
}
/**
* Append the supplied messages to this folder. A {@link MessageCountEvent} is sent
* to all listeners registered with this folder when all messages have been appended.
* If the array contains a previously expunged message, it must be re-appended to the Store
* and implementations must not abort this operation.
*
* @param messages the messages to append
* @throws MessagingException if there was a problem accessing the store
*/
public abstract void appendMessages(Message[] messages) throws MessagingException;
/**
* Hint to the store to prefetch information on the supplied messaged.
* Subclasses should override this method to provide an efficient implementation;
* the default implementation in this class simply returns.
*
* @param messages messages for which information should be fetched
* @param profile the information to fetch
* @throws MessagingException if there was a problem accessing the store
* @see FetchProfile
*/
public void fetch(final Message[] messages, final FetchProfile profile) throws MessagingException {
return;
}
/**
* Set flags on the messages to the supplied value; all messages must belong to this folder.
* This method may be overridden by subclasses that can optimize the setting
* of flags on multiple messages at once; the default implementation simply calls
* {@link Message#setFlags(Flags, boolean)} for each supplied messages.
*
* @param messages whose flags should be set
* @param flags the set of flags to modify
* @param value the value the flags should be set to
* @throws MessagingException if there was a problem accessing the store
*/
public void setFlags(final Message[] messages, final Flags flags, final boolean value) throws MessagingException {
for (int i = 0; i < messages.length; i++) {
final Message message = messages[i];
message.setFlags(flags, value);
}
}
/**
* Set flags on a range of messages to the supplied value.
* This method may be overridden by subclasses that can optimize the setting
* of flags on multiple messages at once; the default implementation simply
* gets each message and then calls {@link Message#setFlags(Flags, boolean)}.
*
* @param start first message end set
* @param end last message end set
* @param flags the set of flags end modify
* @param value the value the flags should be set end
* @throws MessagingException if there was a problem accessing the store
*/
public void setFlags(final int start, final int end, final Flags flags, final boolean value) throws MessagingException {
for (int i = start; i <= end; i++) {
final Message message = getMessage(i);
message.setFlags(flags, value);
}
}
/**
* Set flags on a set of messages to the supplied value.
* This method may be overridden by subclasses that can optimize the setting
* of flags on multiple messages at once; the default implementation simply
* gets each message and then calls {@link Message#setFlags(Flags, boolean)}.
*
* @param ids the indexes of the messages to set
* @param flags the set of flags end modify
* @param value the value the flags should be set end
* @throws MessagingException if there was a problem accessing the store
*/
public void setFlags(final int ids[], final Flags flags, final boolean value) throws MessagingException {
for (int i = 0; i < ids.length; i++) {
final Message message = getMessage(ids[i]);
message.setFlags(flags, value);
}
}
/**
* Copy the specified messages to another folder.
* The default implementation simply appends the supplied messages to the
* target folder using {@link #appendMessages(Message[])}.
* @param messages the messages to copy
* @param folder the folder to copy to
* @throws MessagingException if there was a problem accessing the store
*/
public void copyMessages(final Message[] messages, final Folder folder) throws MessagingException {
folder.appendMessages(messages);
}
/**
* Permanently delete all supplied messages that have the DELETED flag set from the Store.
* The original message indices of all messages actually deleted are returned and a
* {@link MessageCountEvent} event is sent to all listeners with this folder. The expunge
* may cause the indices of all messaged that remain in the folder to change.
*
* @return the original indices of messages that were actually deleted
* @throws MessagingException if there was a problem accessing the store
*/
public abstract Message[] expunge() throws MessagingException;
/**
* Search this folder for messages matching the supplied search criteria.
* The default implementation simply invoke <code>search(term, getMessages())
* applying the search over all messages in the folder; subclasses may provide
* a more efficient mechanism.
*
* @param term the search criteria
* @return an array containing messages that match the criteria
* @throws MessagingException if there was a problem accessing the store
*/
public Message[] search(final SearchTerm term) throws MessagingException {
return search(term, getMessages());
}
/**
* Search the supplied messages for those that match the supplied criteria;
* messages must belong to this folder.
* The default implementation iterates through the messages, returning those
* whose {@link Message#match(javax.mail.search.SearchTerm)} method returns true;
* subclasses may provide a more efficient implementation.
*
* @param term the search criteria
* @param messages the messages to search
* @return an array containing messages that match the criteria
* @throws MessagingException if there was a problem accessing the store
*/
public Message[] search(final SearchTerm term, final Message[] messages) throws MessagingException {
final List result = new ArrayList(messages.length);
for (int i = 0; i < messages.length; i++) {
final Message message = messages[i];
if (message.match(term)) {
result.add(message);
}
}
return (Message[]) result.toArray(new Message[result.size()]);
}
public void addConnectionListener(final ConnectionListener listener) {
connectionListeners.add(listener);
}
public void removeConnectionListener(final ConnectionListener listener) {
connectionListeners.remove(listener);
}
protected void notifyConnectionListeners(final int type) {
queueEvent(new ConnectionEvent(this, type), connectionListeners);
}
public void addFolderListener(final FolderListener listener) {
folderListeners.add(listener);
}
public void removeFolderListener(final FolderListener listener) {
folderListeners.remove(listener);
}
protected void notifyFolderListeners(final int type) {
queueEvent(new FolderEvent(this, this, type), folderListeners);
}
protected void notifyFolderRenamedListeners(final Folder newFolder) {
queueEvent(new FolderEvent(this, this, newFolder, FolderEvent.RENAMED), folderListeners);
}
public void addMessageCountListener(final MessageCountListener listener) {
messageCountListeners.add(listener);
}
public void removeMessageCountListener(final MessageCountListener listener) {
messageCountListeners.remove(listener);
}
protected void notifyMessageAddedListeners(final Message[] messages) {
queueEvent(new MessageCountEvent(this, MessageCountEvent.ADDED, false, messages), messageChangedListeners);
}
protected void notifyMessageRemovedListeners(final boolean removed, final Message[] messages) {
queueEvent(new MessageCountEvent(this, MessageCountEvent.REMOVED, removed, messages), messageChangedListeners);
}
public void addMessageChangedListener(final MessageChangedListener listener) {
messageChangedListeners.add(listener);
}
public void removeMessageChangedListener(final MessageChangedListener listener) {
messageChangedListeners.remove(listener);
}
protected void notifyMessageChangedListeners(final int type, final Message message) {
queueEvent(new MessageChangedEvent(this, type, message), messageChangedListeners);
}
/**
* Unregisters all listeners.
*/
@Override
protected void finalize() throws Throwable {
// shut our queue down, if needed.
if (queue != null) {
queue.stop();
queue = null;
}
connectionListeners.clear();
folderListeners.clear();
messageChangedListeners.clear();
messageCountListeners.clear();
store = null;
super.finalize();
}
/**
* Returns the full name of this folder; if null, returns the value from the superclass.
* @return a string form of this folder
*/
@Override
public String toString() {
final String name = getFullName();
return name == null ? super.toString() : name;
}
/**
* Add an event on the event queue, creating the queue if this is the
* first event with actual listeners.
*
* @param event The event to dispatch.
* @param listeners The listener list.
*/
private synchronized void queueEvent(final MailEvent event, final ArrayList listeners) {
// if there are no listeners to dispatch this to, don't put it on the queue.
// This allows us to delay creating the queue (and its new thread) until
// we
if (listeners.isEmpty()) {
return;
}
// first real event? Time to get the queue kicked off.
if (queue == null) {
queue = new EventQueue();
}
// tee it up and let it rip.
queue.queueEvent(event, (List)listeners.clone());
}
}
| 1,967 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Quota.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* A representation of a Quota item for a given quota root.
*
* @version $Rev$ $Date$
*/
public class Quota {
/**
* The name of the quota root.
*/
public String quotaRoot;
/**
* The resources associated with this quota root.
*/
public Resource[] resources;
/**
* Create a Quota with the given name and no resources.
*
* @param quotaRoot The quota root name.
*/
public Quota(final String quotaRoot) {
this.quotaRoot = quotaRoot;
}
/**
* Set a limit value for a resource. If the resource is not
* currently associated with this Quota, a new Resource item is
* added to the resources list.
*
* @param name The target resource name.
* @param limit The new limit value for the resource.
*/
public void setResourceLimit(final String name, final long limit) {
final Resource target = findResource(name);
target.limit = limit;
}
/**
* Locate a particular named resource, adding one to the list
* if it does not exist.
*
* @param name The target resource name.
*
* @return A Resource item for this named resource (either existing or new).
*/
private Resource findResource(final String name) {
// no resources yet? Make it so.
if (resources == null) {
final Resource target = new Resource(name, 0, 0);
resources = new Resource[] { target };
return target;
}
// see if this one exists and return it.
for (int i = 0; i < resources.length; i++) {
final Resource current = resources[i];
if (current.name.equalsIgnoreCase(name)) {
return current;
}
}
// have to extend the array...this is a pain.
final Resource[] newResources = new Resource[resources.length + 1];
System.arraycopy(resources, 0, newResources, 0, resources.length);
final Resource target = new Resource(name, 0, 0);
newResources[resources.length] = target;
resources = newResources;
return target;
}
/**
* A representation of a given resource definition.
*/
public static class Resource {
/**
* The resource name.
*/
public String name;
/**
* The current resource usage.
*/
public long usage;
/**
* The limit value for this resource.
*/
public long limit;
/**
* Construct a Resource object from the given name and usage/limit
* information.
*
* @param name The Resource name.
* @param usage The current resource usage.
* @param limit The Resource limit value.
*/
public Resource(final String name, final long usage, final long limit) {
this.name = name;
this.usage = usage;
this.limit = limit;
}
}
}
| 1,968 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/Multipart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
/**
* A container for multiple {@link BodyPart BodyParts}.
*
* @version $Rev$ $Date$
*/
public abstract class Multipart {
/**
* Vector of sub-parts.
*/
protected Vector parts = new Vector();
/**
* The content type of this multipart object; defaults to "multipart/mixed"
*/
protected String contentType = "multipart/mixed";
/**
* The Part that contains this multipart.
*/
protected Part parent;
protected Multipart() {
}
/**
* Initialize this multipart object from the supplied data source.
* This adds any {@link BodyPart BodyParts} into this object and initializes the content type.
*
* @param mds the data source
* @throws MessagingException
*/
protected void setMultipartDataSource(final MultipartDataSource mds) throws MessagingException {
parts.clear();
contentType = mds.getContentType();
final int size = mds.getCount();
for (int i = 0; i < size; i++) {
parts.add(mds.getBodyPart(i));
}
}
/**
* Return the content type.
*
* @return the content type
*/
public String getContentType() {
return contentType;
}
/**
* Return the number of enclosed parts
*
* @return the number of parts
* @throws MessagingException
*/
public int getCount() throws MessagingException {
return parts.size();
}
/**
* Get the specified part; numbering starts at zero.
*
* @param index the part to get
* @return the part
* @throws MessagingException
*/
public BodyPart getBodyPart(final int index) throws MessagingException {
return (BodyPart) parts.get(index);
}
/**
* Remove the supplied part from the list.
*
* @param part the part to remove
* @return true if the part was removed
* @throws MessagingException
*/
public boolean removeBodyPart(final BodyPart part) throws MessagingException {
return parts.remove(part);
}
/**
* Remove the specified part; all others move down one
*
* @param index the part to remove
* @throws MessagingException
*/
public void removeBodyPart(final int index) throws MessagingException {
parts.remove(index);
}
/**
* Add a part to the end of the list.
*
* @param part the part to add
* @throws MessagingException
*/
public void addBodyPart(final BodyPart part) throws MessagingException {
parts.add(part);
}
/**
* Insert a part into the list at a designated point; all subsequent parts move down
*
* @param part the part to add
* @param pos the index of the new part
* @throws MessagingException
*/
public void addBodyPart(final BodyPart part, final int pos) throws MessagingException {
parts.add(pos, part);
}
/**
* Encode and write this multipart to the supplied OutputStream; the encoding
* used is determined by the implementation.
*
* @param out the stream to write to
* @throws IOException
* @throws MessagingException
*/
public abstract void writeTo(OutputStream out) throws IOException, MessagingException;
/**
* Return the Part containing this Multipart object or null if unknown.
*
* @return this Multipart's parent
*/
public Part getParent() {
return parent;
}
/**
* Set the parent of this Multipart object
*
* @param part this object's parent
*/
public void setParent(final Part part) {
parent = part;
}
}
| 1,969 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/UIDFolder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public interface UIDFolder {
/**
* A special value than can be passed as the <code>end</code> parameter to
* {@link Folder#getMessages(int, int)} to indicate the last message in this folder.
*/
public static final long LASTUID = -1;
/**
* Get the UID validity value for this Folder.
*
* @return The current UID validity value, as a long.
* @exception MessagingException
*/
public abstract long getUIDValidity() throws MessagingException;
/**
* Retrieve a message using the UID rather than the
* message sequence number. Returns null if the message
* doesn't exist.
*
* @param uid The target UID.
*
* @return the Message object. Returns null if the message does
* not exist.
* @exception MessagingException
*/
public abstract Message getMessageByUID(long uid)
throws MessagingException;
/**
* Get a series of messages using a UID range. The
* special value LASTUID can be used to mark the
* last available message.
*
* @param start The start of the UID range.
* @param end The end of the UID range. The special value
* LASTUID can be used to request all messages up
* to the last UID.
*
* @return An array containing all of the messages in the
* range.
* @exception MessagingException
*/
public abstract Message[] getMessagesByUID(long start, long end)
throws MessagingException;
/**
* Retrieve a set of messages by explicit UIDs. If
* any message in the list does not exist, null
* will be returned for the corresponding item.
*
* @param ids An array of UID values to be retrieved.
*
* @return An array of Message items the same size as the ids
* argument array. This array will contain null
* entries for any UIDs that do not exist.
* @exception MessagingException
*/
public abstract Message[] getMessagesByUID(long[] ids)
throws MessagingException;
/**
* Retrieve the UID for a message from this Folder.
* The argument Message MUST belong to this Folder
* instance, otherwise a NoSuchElementException will
* be thrown.
*
* @param message The target message.
*
* @return The UID associated with this message.
* @exception MessagingException
*/
public abstract long getUID(Message message) throws MessagingException;
/**
* Special profile item used for fetching UID information.
*/
public static class FetchProfileItem extends FetchProfile.Item {
public static final FetchProfileItem UID = new FetchProfileItem("UID");
protected FetchProfileItem(final String name) {
super(name);
}
}
}
| 1,970 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/util/ByteArrayDataSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataSource;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.ParseException;
/**
* An activation DataSource object that sources the data from
* a byte[] array.
* @version $Rev$ $Date$
*/
public class ByteArrayDataSource implements DataSource {
// the data source
private final byte[] source;
// the content MIME type
private final String contentType;
// the name information (defaults to a null string)
private String name = "";
/**
* Create a ByteArrayDataSource from an input stream.
*
* @param in The source input stream.
* @param type The MIME-type of the data.
*
* @exception IOException
*/
public ByteArrayDataSource(final InputStream in, final String type) throws IOException {
final ByteArrayOutputStream sink = new ByteArrayOutputStream();
// ok, how I wish you could just pipe an input stream into an output stream :-)
final byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) > 0) {
sink.write(buffer, 0, bytesRead);
}
source = sink.toByteArray();
contentType = type;
}
/**
* Create a ByteArrayDataSource directly from a byte array.
*
* @param data The source byte array (not copied).
* @param type The content MIME-type.
*/
public ByteArrayDataSource(final byte[] data, final String type) {
source = data;
contentType = type;
}
/**
* Create a ByteArrayDataSource from a string value. If the
* type information includes a charset parameter, that charset
* is used to extract the bytes. Otherwise, the default Java
* char set is used.
*
* @param data The source data string.
* @param type The MIME type information.
*
* @exception IOException
*/
public ByteArrayDataSource(final String data, final String type) throws IOException {
String charset = null;
try {
// the charset can be encoded in the content type, which we parse using
// the ContentType class.
final ContentType content = new ContentType(type);
charset = content.getParameter("charset");
} catch (final ParseException e) {
// ignored...just use the default if this fails
}
if (charset == null) {
charset = MimeUtility.getDefaultJavaCharset();
}
else {
// the type information encodes a MIME charset, which may need mapping to a Java one.
charset = MimeUtility.javaCharset(charset);
}
// get the source using the specified charset
source = data.getBytes(charset);
contentType = type;
}
/**
* Create an input stream for this data. A new input stream
* is created each time.
*
* @return An InputStream for reading the encapsulated data.
* @exception IOException
*/
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(source);
}
/**
* Open an output stream for the DataSource. This is not
* supported by this DataSource, so an IOException is always
* throws.
*
* @return Nothing...an IOException is always thrown.
* @exception IOException
*/
public OutputStream getOutputStream() throws IOException {
throw new IOException("Writing to a ByteArrayDataSource is not supported");
}
/**
* Get the MIME content type information for this DataSource.
*
* @return The MIME content type string.
*/
public String getContentType() {
return contentType;
}
/**
* Retrieve the DataSource name. If not explicitly set, this
* returns "".
*
* @return The currently set DataSource name.
*/
public String getName() {
return name;
}
/**
* Set a new DataSource name.
*
* @param name The new name.
*/
public void setName(final String name) {
this.name = name;
}
}
| 1,971 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/util/SharedFileInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import javax.mail.internet.SharedInputStream;
public class SharedFileInputStream extends BufferedInputStream implements SharedInputStream {
// This initial size isn't documented, but bufsize is 2048 after initialization for the
// Sun implementation.
private static final int DEFAULT_BUFFER_SIZE = 2048;
// the shared file information, used to synchronize opens/closes of the base file.
private SharedFileSource source;
/**
* The file offset that is the first byte in the read buffer.
*/
protected long bufpos;
/**
* The normal size of the read buffer.
*/
protected int bufsize;
/**
* The size of the file subset represented by this stream instance.
*/
protected long datalen;
/**
* The source of the file data. This is shared across multiple
* instances.
*/
protected RandomAccessFile in;
/**
* The starting position of data represented by this stream relative
* to the start of the file data. This stream instance represents
* data in the range start to (start + datalen - 1).
*/
protected long start;
/**
* Construct a SharedFileInputStream from a file name, using the default buffer size.
*
* @param file The name of the file.
*
* @exception IOException
*/
public SharedFileInputStream(final String file) throws IOException {
this(file, DEFAULT_BUFFER_SIZE);
}
/**
* Construct a SharedFileInputStream from a File object, using the default buffer size.
*
* @param file The name of the file.
*
* @exception IOException
*/
public SharedFileInputStream(final File file) throws IOException {
this(file, DEFAULT_BUFFER_SIZE);
}
/**
* Construct a SharedFileInputStream from a file name, with a given initial buffer size.
*
* @param file The name of the file.
* @param bufferSize The initial buffer size.
*
* @exception IOException
*/
public SharedFileInputStream(final String file, final int bufferSize) throws IOException {
// I'm not sure this is correct or not. The SharedFileInputStream spec requires this
// be a subclass of BufferedInputStream. The BufferedInputStream constructor takes a stream,
// which we're not really working from at this point. Using null seems to work so far.
super(null);
init(new File(file), bufferSize);
}
/**
* Construct a SharedFileInputStream from a File object, with a given initial buffer size.
*
* @param file The name of the file.
* @param bufferSize The initial buffer size.
*
* @exception IOException
*/
public SharedFileInputStream(final File file, final int bufferSize) throws IOException {
// I'm not sure this is correct or not. The SharedFileInputStream spec requires this
// be a subclass of BufferedInputStream. The BufferedInputStream constructor takes a stream,
// which we're not really working from at this point. Using null seems to work so far.
super(null);
init(file, bufferSize);
}
/**
* Private constructor used to spawn off a shared instance
* of this stream.
*
* @param source The internal class object that manages the shared resources of
* the stream.
* @param start The starting offset relative to the beginning of the file.
* @param len The length of file data in this shared instance.
* @param bufsize The initial buffer size (same as the spawning parent.
*/
private SharedFileInputStream(final SharedFileSource source, final long start, final long len, final int bufsize) {
super(null);
this.source = source;
in = source.open();
this.start = start;
bufpos = start;
datalen = len;
this.bufsize = bufsize;
buf = new byte[bufsize];
// other fields such as pos and count initialized by the super class constructor.
}
/**
* Shared initializtion routine for the constructors.
*
* @param file The file we're accessing.
* @param bufferSize The initial buffer size to use.
*
* @exception IOException
*/
private void init(final File file, final int bufferSize) throws IOException {
if (bufferSize <= 0) {
throw new IllegalArgumentException("Buffer size must be positive");
}
// create a random access file for accessing the data, then create an object that's used to share
// instances of the same stream.
source = new SharedFileSource(file);
// we're opening the first one.
in = source.open();
// this represents the entire file, for now.
start = 0;
// use the current file length for the bounds
datalen = in.length();
// now create our buffer version
bufsize = bufferSize;
bufpos = 0;
// NB: this is using the super class protected variable.
buf = new byte[bufferSize];
}
/**
* Check to see if we need to read more data into our buffer.
*
* @return False if there's not valid data in the buffer (generally means
* an EOF condition).
* @exception IOException
*/
private boolean checkFill() throws IOException {
// if we have data in the buffer currently, just return
if (pos < count) {
return true;
}
// ugh, extending BufferedInputStream also means supporting mark positions. That complicates everything.
// life is so much easier if marks are not used....
if (markpos < 0) {
// reset back to the buffer position
pos = 0;
// this will be the new position within the file once we're read some data.
bufpos += count;
}
else {
// we have marks to worry about....damn.
// if we have room in the buffer to read more data, then we will. Otherwise, we need to see
// if it's possible to shift the data in the buffer or extend the buffer (up to the mark limit).
if (pos >= buf.length) {
// the mark position is not at the beginning of the buffer, so just shuffle the bytes, leaving
// us room to read more data.
if (markpos > 0) {
// this is the size of the data we need to keep.
final int validSize = pos - markpos;
// perform the shift operation.
System.arraycopy(buf, markpos, buf, 0, validSize);
// now adjust the positional markers for this shift.
pos = validSize;
bufpos += markpos;
markpos = 0;
}
// the mark is at the beginning, and we've used up the buffer. See if we're allowed to
// extend this.
else if (buf.length < marklimit) {
// try to double this, but throttle to the mark limit
final int newSize = Math.min(buf.length * 2, marklimit);
final byte[] newBuffer = new byte[newSize];
System.arraycopy(buf, 0, newBuffer, 0, buf.length);
// replace the old buffer. Note that all other positional markers remain the same here.
buf = newBuffer;
}
// we've got further than allowed, so invalidate the mark, and just reset the buffer
else {
markpos = -1;
pos = 0;
bufpos += count;
}
}
}
// if we're past our designated end, force an eof.
if (bufpos + pos >= start + datalen) {
// make sure we zero the count out, otherwise we'll reuse this data
// if called again.
count = pos;
return false;
}
// seek to the read location start. Note this is a shared file, so this assumes all of the methods
// doing buffer fills will be synchronized.
int fillLength = buf.length - pos;
// we might be working with a subset of the file data, so normal eof processing might not apply.
// we need to limit how much we read to the data length.
if (bufpos - start + pos + fillLength > datalen) {
fillLength = (int)(datalen - (bufpos - start + pos));
}
// finally, try to read more data into the buffer.
fillLength = source.read(bufpos + pos, buf, pos, fillLength);
// we weren't able to read anything, count this as an eof failure.
if (fillLength <= 0) {
// make sure we zero the count out, otherwise we'll reuse this data
// if called again.
count = pos;
return false;
}
// set the new buffer count
count = fillLength + pos;
// we have data in the buffer.
return true;
}
/**
* Return the number of bytes available for reading without
* blocking for a long period.
*
* @return For this stream, this is the number of bytes between the
* current read position and the indicated end of the file.
* @exception IOException
*/
@Override
public synchronized int available() throws IOException {
checkOpen();
// this is backed by a file, which doesn't really block. We can return all the way to the
// marked data end, if necessary
final long endMarker = start + datalen;
return (int)(endMarker - (bufpos + pos));
}
/**
* Return the current read position of the stream.
*
* @return The current position relative to the beginning of the stream.
* This is not the position relative to the start of the file, since
* the stream starting position may be other than the beginning.
*/
public long getPosition() {
checkOpenRuntime();
return bufpos + pos - start;
}
/**
* Mark the current position for retracing.
*
* @param readlimit The limit for the distance the read position can move from
* the mark position before the mark is reset.
*/
@Override
public synchronized void mark(final int readlimit) {
checkOpenRuntime();
marklimit = readlimit;
markpos = pos;
}
/**
* Read a single byte of data from the input stream.
*
* @return The read byte. Returns -1 if an eof condition has been hit.
* @exception IOException
*/
@Override
public synchronized int read() throws IOException {
checkOpen();
// check to see if we can fill more data
if (!checkFill()) {
return -1;
}
// return the current byte...anded to prevent sign extension.
return buf[pos++] & 0xff;
}
/**
* Read multiple bytes of data and place them directly into
* a byte-array buffer.
*
* @param buffer The target buffer.
* @param offset The offset within the buffer to place the data.
* @param length The length to attempt to read.
*
* @return The number of bytes actually read. Returns -1 for an EOF
* condition.
* @exception IOException
*/
@Override
public synchronized int read(final byte buffer[], int offset, int length) throws IOException {
checkOpen();
// asked to read nothing? That's what we'll do.
if (length == 0) {
return 0;
}
int returnCount = 0;
while (length > 0) {
// check to see if we can/must fill more data
if (!checkFill()) {
// we've hit the end, but if we've read data, then return that.
if (returnCount > 0) {
return returnCount;
}
// trun eof.
return -1;
}
final int available = count - pos;
final int given = Math.min(available, length);
System.arraycopy(buf, pos, buffer, offset, given);
// now adjust all of our positions and counters
pos += given;
length -= given;
returnCount += given;
offset += given;
}
// return the accumulated count.
return returnCount;
}
/**
* Skip the read pointer ahead a given number of bytes.
*
* @param n The number of bytes to skip.
*
* @return The number of bytes actually skipped.
* @exception IOException
*/
@Override
public synchronized long skip(final long n) throws IOException {
checkOpen();
// nothing to skip, so don't skip
if (n <= 0) {
return 0;
}
// see if we need to fill more data, and potentially shift the mark positions
if (!checkFill()) {
return 0;
}
final long available = count - pos;
// the skipped contract allows skipping within the current buffer bounds, so cap it there.
final long skipped = available < n ? available : n;
pos += skipped;
return skipped;
}
/**
* Reset the mark position.
*
* @exception IOException
*/
@Override
public synchronized void reset() throws IOException {
checkOpen();
if (markpos < 0) {
throw new IOException("Resetting to invalid mark position");
}
// if we have a markpos, it will still be in the buffer bounds.
pos = markpos;
}
/**
* Indicates the mark() operation is supported.
*
* @return Always returns true.
*/
@Override
public boolean markSupported() {
return true;
}
/**
* Close the stream. This does not close the source file until
* the last shared instance is closed.
*
* @exception IOException
*/
@Override
public void close() throws IOException {
// already closed? This is not an error
if (in == null) {
return;
}
try {
// perform a close on the source version.
source.close();
} finally {
in = null;
}
}
/**
* Create a new stream from this stream, using the given
* start offset and length.
*
* @param offset The offset relative to the start of this stream instance.
* @param end The end offset of the substream. If -1, the end of the parent stream is used.
*
* @return A new SharedFileInputStream object sharing the same source
* input file.
*/
public InputStream newStream(final long offset, long end) {
checkOpenRuntime();
if (offset < 0) {
throw new IllegalArgumentException("Start position is less than 0");
}
// the default end position is the datalen of the one we're spawning from.
if (end == -1) {
end = datalen;
}
// create a new one using the private constructor
return new SharedFileInputStream(source, start + (int)offset, (int)(end - offset), bufsize);
}
/**
* Check if the file is open and throw an IOException if not.
*
* @exception IOException
*/
private void checkOpen() throws IOException {
if (in == null) {
throw new IOException("Stream has been closed");
}
}
/**
* Check if the file is open and throw an IOException if not. This version is
* used because several API methods are not defined as throwing IOException, so
* checkOpen() can't be used. The Sun implementation just throws RuntimeExceptions
* in those methods, hence 2 versions.
*
* @exception RuntimeException
*/
private void checkOpenRuntime() {
if (in == null) {
throw new RuntimeException("Stream has been closed");
}
}
/**
* Internal class used to manage resources shared between the
* ShareFileInputStream instances.
*/
class SharedFileSource {
// the file source
public RandomAccessFile source;
// the shared instance count for this file (open instances)
public int instanceCount = 0;
public SharedFileSource(final File file) throws IOException {
source = new RandomAccessFile(file, "r");
}
/**
* Open the shared stream to keep track of open instances.
*/
public synchronized RandomAccessFile open() {
instanceCount++;
return source;
}
/**
* Process a close request for this stream. If there are multiple
* instances using this underlying stream, the stream will not
* be closed.
*
* @exception IOException
*/
public synchronized void close() throws IOException {
if (instanceCount > 0) {
instanceCount--;
// if the last open instance, close the real source file.
if (instanceCount == 0) {
source.close();
}
}
}
/**
* Read a buffer of data from the shared file.
*
* @param position The position to read from.
* @param buf The target buffer for storing the read data.
* @param offset The starting offset within the buffer.
* @param length The length to attempt to read.
*
* @return The number of bytes actually read.
* @exception IOException
*/
public synchronized int read(final long position, final byte[] buf, final int offset, final int length) throws IOException {
// seek to the read location start. Note this is a shared file, so this assumes all of the methods
// doing buffer fills will be synchronized.
source.seek(position);
return source.read(buf, offset, length);
}
/**
* Ensure the stream is closed when this shared object is finalized.
*
* @exception Throwable
*/
@Override
protected void finalize() throws Throwable {
super.finalize();
if (instanceCount > 0) {
source.close();
}
}
}
}
| 1,972 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/util/SharedByteArrayInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.util;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.mail.internet.SharedInputStream;
public class SharedByteArrayInputStream extends ByteArrayInputStream implements SharedInputStream {
/**
* Position within shared buffer that this stream starts at.
*/
protected int start;
/**
* Create a SharedByteArrayInputStream that shares the entire
* buffer.
*
* @param buf The input data.
*/
public SharedByteArrayInputStream(final byte[] buf) {
this(buf, 0, buf.length);
}
/**
* Create a SharedByteArrayInputStream using a subset of the
* array data.
*
* @param buf The source data array.
* @param offset The starting offset within the array.
* @param length The length of data to use.
*/
public SharedByteArrayInputStream(final byte[] buf, final int offset, final int length) {
super(buf, offset, length);
start = offset;
}
/**
* Get the position within the output stream, adjusted by the
* starting offset.
*
* @return The adjusted position within the stream.
*/
public long getPosition() {
return pos - start;
}
/**
* Create a new input stream from this input stream, accessing
* a subset of the data. Think of it as a substring operation
* for a stream.
*
* The starting offset must be non-negative. The end offset can
* by -1, which means use the remainder of the stream.
*
* @param offset The starting offset.
* @param end The end offset (which can be -1).
*
* @return An InputStream configured to access the indicated data subrange.
*/
public InputStream newStream(final long offset, long end) {
if (offset < 0) {
throw new IllegalArgumentException("Starting position must be non-negative");
}
if (end == -1) {
end = count - start;
}
return new SharedByteArrayInputStream(buf, start + (int)offset, (int)(end - offset));
}
}
| 1,973 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/FlagTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* Term for matching message {@link Flags}.
*
* @version $Rev$ $Date$
*/
public final class FlagTerm extends SearchTerm {
private static final long serialVersionUID = -142991500302030647L;
/**
* If true, test that all flags are set; if false, test that all flags are clear.
*/
private final boolean set;
/**
* The flags to test.
*/
private final Flags flags;
/**
* @param flags the flags to test
* @param set test for set or clear; {@link #set}
*/
public FlagTerm(final Flags flags, final boolean set) {
this.set = set;
this.flags = flags;
}
public Flags getFlags() {
return flags;
}
public boolean getTestSet() {
return set;
}
@Override
public boolean match(final Message message) {
try {
final Flags msgFlags = message.getFlags();
if (set) {
return msgFlags.contains(flags);
} else {
// yuk - I wish we could get at the internal state of the Flags
final Flags.Flag[] system = flags.getSystemFlags();
for (int i = 0; i < system.length; i++) {
final Flags.Flag flag = system[i];
if (msgFlags.contains(flag)) {
return false;
}
}
final String[] user = flags.getUserFlags();
for (int i = 0; i < user.length; i++) {
final String flag = user[i];
if (msgFlags.contains(flag)) {
return false;
}
}
return true;
}
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof FlagTerm == false) {
return false;
}
final FlagTerm otherFlags = (FlagTerm) other;
return otherFlags.set == this.set && otherFlags.flags.equals(flags);
}
@Override
public int hashCode() {
return set ? flags.hashCode() : ~flags.hashCode();
}
}
| 1,974 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/SearchException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public class SearchException extends MessagingException {
private static final long serialVersionUID = -7092886778226268686L;
public SearchException() {
super();
}
public SearchException(final String message) {
super(message);
}
}
| 1,975 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/MessageNumberTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Message;
/**
* @version $Rev$ $Date$
*/
public final class MessageNumberTerm extends IntegerComparisonTerm {
private static final long serialVersionUID = -5379625829658623812L;
public MessageNumberTerm(final int number) {
super(EQ, number);
}
@Override
public boolean match(final Message message) {
return match(message.getMessageNumber());
}
@Override
public boolean equals(final Object other) {
if (!(other instanceof MessageNumberTerm)) {
return false;
}
return super.equals(other);
}
}
| 1,976 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/SentDateTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import java.util.Date;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class SentDateTerm extends DateTerm {
private static final long serialVersionUID = 5647755030530907263L;
public SentDateTerm(final int comparison, final Date date) {
super(comparison, date);
}
@Override
public boolean match(final Message message) {
try {
final Date date = message.getSentDate();
if (date == null) {
return false;
}
return match(message.getSentDate());
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof SentDateTerm == false) {
return false;
}
return super.equals(other);
}
}
| 1,977 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/FromStringTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class FromStringTerm extends AddressStringTerm {
private static final long serialVersionUID = 5801127523826772788L;
public FromStringTerm(final String string) {
super(string);
}
@Override
public boolean match(final Message message) {
try {
final Address from[] = message.getFrom();
if (from == null) {
return false;
}
for (int i = 0; i < from.length; i++) {
if (match(from[i])){
return true;
}
}
return false;
} catch (final MessagingException e) {
return false;
}
}
}
| 1,978 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/SizeTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class SizeTerm extends IntegerComparisonTerm {
private static final long serialVersionUID = -2556219451005103709L;
public SizeTerm(final int comparison, final int size) {
super(comparison, size);
}
@Override
public boolean match(final Message message) {
try {
return match(message.getSize());
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof SizeTerm == false) {
return false;
}
return super.equals(other);
}
}
| 1,979 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/OrTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import java.util.Arrays;
import javax.mail.Message;
/**
* @version $Rev$ $Date$
*/
public final class OrTerm extends SearchTerm {
private static final long serialVersionUID = 5380534067523646936L;
private final SearchTerm[] terms;
public OrTerm(final SearchTerm a, final SearchTerm b) {
terms = new SearchTerm[]{a, b};
}
public OrTerm(final SearchTerm[] terms) {
this.terms = terms;
}
public SearchTerm[] getTerms() {
return terms;
}
@Override
public boolean match(final Message message) {
for (int i = 0; i < terms.length; i++) {
final SearchTerm term = terms[i];
if (term.match(message)) {
return true;
}
}
return false;
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof OrTerm == false) {
return false;
}
return Arrays.equals(terms, ((OrTerm) other).terms);
}
@Override
public int hashCode() {
int hash = 0;
for (int i = 0; i < terms.length; i++) {
hash = hash * 37 + terms[i].hashCode();
}
return hash;
}
}
| 1,980 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/HeaderTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class HeaderTerm extends StringTerm {
private static final long serialVersionUID = 8342514650333389122L;
private final String headerName;
public HeaderTerm(final String header, final String pattern) {
super(pattern);
this.headerName = header;
}
public String getHeaderName() {
return headerName;
}
@Override
public boolean match(final Message message) {
try {
final String values[] = message.getHeader(headerName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
final String value = values[i];
if (match(value)) {
return true;
}
}
}
return false;
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof HeaderTerm == false) {
return false;
}
// we need to compare with more than just the header name.
return headerName.equalsIgnoreCase(((HeaderTerm) other).headerName) && super.equals(other);
}
@Override
public int hashCode() {
return headerName.toLowerCase().hashCode() + super.hashCode();
}
}
| 1,981 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/RecipientStringTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class RecipientStringTerm extends AddressStringTerm {
private static final long serialVersionUID = -8293562089611618849L;
private final Message.RecipientType type;
public RecipientStringTerm(final Message.RecipientType type, final String pattern) {
super(pattern);
this.type = type;
}
public Message.RecipientType getRecipientType() {
return type;
}
@Override
public boolean match(final Message message) {
try {
final Address from[] = message.getRecipients(type);
if (from == null) {
return false;
}
for (int i = 0; i < from.length; i++) {
final Address address = from[i];
if (match(address)) {
return true;
}
}
return false;
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof RecipientStringTerm == false) {
return false;
}
final RecipientStringTerm otherTerm = (RecipientStringTerm) other;
return this.pattern.equals(otherTerm.pattern) && this.type == otherTerm.type;
}
@Override
public int hashCode() {
return pattern.hashCode() + type.hashCode();
}
}
| 1,982 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/AddressStringTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Address;
/**
* A Term that compares two Addresses as Strings.
*
* @version $Rev$ $Date$
*/
public abstract class AddressStringTerm extends StringTerm {
private static final long serialVersionUID = 3086821234204980368L;
/**
* Constructor.
* @param pattern the pattern to be compared
*/
protected AddressStringTerm(final String pattern) {
super(pattern);
}
/**
* Tests if the patterm associated with this Term is a substring of
* the address in the supplied object.
*
* @param address
* @return
*/
protected boolean match(final Address address) {
return match(address.toString());
}
}
| 1,983 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/RecipientTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class RecipientTerm extends AddressTerm {
private static final long serialVersionUID = 6548700653122680468L;
private final Message.RecipientType type;
public RecipientTerm(final Message.RecipientType type, final Address address) {
super(address);
this.type = type;
}
public Message.RecipientType getRecipientType() {
return type;
}
@Override
public boolean match(final Message message) {
try {
final Address from[] = message.getRecipients(type);
if (from == null) {
return false;
}
for (int i = 0; i < from.length; i++) {
final Address address = from[i];
if (match(address)) {
return true;
}
}
return false;
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof RecipientTerm == false) {
return false;
}
final RecipientTerm recipientTerm = (RecipientTerm) other;
return address.equals(recipientTerm.address) && type == recipientTerm.type;
}
@Override
public int hashCode() {
return address.hashCode() + type.hashCode();
}
}
| 1,984 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/DateTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import java.util.Date;
/**
* @version $Rev$ $Date$
*/
public abstract class DateTerm extends ComparisonTerm {
private static final long serialVersionUID = 4818873430063720043L;
protected Date date;
protected DateTerm(final int comparison, final Date date) {
super();
this.comparison = comparison;
this.date = date;
}
public Date getDate() {
return date;
}
public int getComparison() {
return comparison;
}
protected boolean match(final Date match) {
final long matchTime = match.getTime();
final long mytime = date.getTime();
switch (comparison) {
case EQ:
return matchTime == mytime;
case NE:
return matchTime != mytime;
case LE:
return matchTime <= mytime;
case LT:
return matchTime < mytime;
case GT:
return matchTime > mytime;
case GE:
return matchTime >= mytime;
default:
return false;
}
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof DateTerm == false) {
return false;
}
final DateTerm term = (DateTerm) other;
return this.comparison == term.comparison && this.date.equals(term.date);
}
@Override
public int hashCode() {
return date.hashCode() + super.hashCode();
}
}
| 1,985 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/NotTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Message;
/**
* Term that implements a logical negation.
*
* @version $Rev$ $Date$
*/
public final class NotTerm extends SearchTerm {
private static final long serialVersionUID = 7152293214217310216L;
private final SearchTerm term;
public NotTerm(final SearchTerm term) {
this.term = term;
}
public SearchTerm getTerm() {
return term;
}
@Override
public boolean match(final Message message) {
return !term.match(message);
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof NotTerm == false) {
return false;
}
return term.equals(((NotTerm) other).term);
}
@Override
public int hashCode() {
return term.hashCode();
}
}
| 1,986 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/ComparisonTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
/**
* Base for comparison terms.
*
* @version $Rev$ $Date$
*/
public abstract class ComparisonTerm extends SearchTerm {
private static final long serialVersionUID = 1456646953666474308L;
public static final int LE = 1;
public static final int LT = 2;
public static final int EQ = 3;
public static final int NE = 4;
public static final int GT = 5;
public static final int GE = 6;
protected int comparison;
public ComparisonTerm() {
}
@Override
public boolean equals(final Object other) {
if (!(other instanceof ComparisonTerm)) {
return false;
}
return comparison == ((ComparisonTerm)other).comparison;
}
@Override
public int hashCode() {
return comparison;
}
}
| 1,987 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/SubjectTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class SubjectTerm extends StringTerm {
private static final long serialVersionUID = 7481568618055573432L;
public SubjectTerm(final String subject) {
super(subject);
}
@Override
public boolean match(final Message message) {
try {
final String subject = message.getSubject();
if (subject == null) {
return false;
}
return match(subject);
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof SubjectTerm == false) {
return false;
}
return super.equals(other);
}
}
| 1,988 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/AndTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import java.util.Arrays;
import javax.mail.Message;
/**
* Term that implements a logical AND across terms.
*
* @version $Rev$ $Date$
*/
public final class AndTerm extends SearchTerm {
private static final long serialVersionUID = -3583274505380989582L;
/**
* Terms to which the AND operator should be applied.
*/
private final SearchTerm[] terms;
/**
* Constructor for performing a binary AND.
*
* @param a the first term
* @param b the second ter,
*/
public AndTerm(final SearchTerm a, final SearchTerm b) {
terms = new SearchTerm[]{a, b};
}
/**
* Constructor for performing and AND across an arbitraty number of terms.
* @param terms the terms to AND together
*/
public AndTerm(final SearchTerm[] terms) {
this.terms = terms;
}
/**
* Return the terms.
* @return the terms
*/
public SearchTerm[] getTerms() {
return terms;
}
/**
* Match by applying the terms, in order, to the Message and performing an AND operation
* to the result. Comparision will stop immediately if one of the terms returns false.
*
* @param message the Message to apply the terms to
* @return true if all terms match
*/
@Override
public boolean match(final Message message) {
for (int i = 0; i < terms.length; i++) {
final SearchTerm term = terms[i];
if (!term.match(message)) {
return false;
}
}
return true;
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof AndTerm == false) {
return false;
}
return Arrays.equals(terms, ((AndTerm) other).terms);
}
@Override
public int hashCode() {
int hash = 0;
for (int i = 0; i < terms.length; i++) {
hash = hash * 37 + terms[i].hashCode();
}
return hash;
}
}
| 1,989 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/StringTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
/**
* A Term that provides matching criteria for Strings.
*
* @version $Rev$ $Date$
*/
public abstract class StringTerm extends SearchTerm {
private static final long serialVersionUID = 1274042129007696269L;
/**
* If true, case should be ignored during matching.
*/
protected boolean ignoreCase;
/**
* The pattern associated with this term.
*/
protected String pattern;
/**
* Constructor specifying a pattern.
* Defaults to case insensitive matching.
* @param pattern the pattern for this term
*/
protected StringTerm(final String pattern) {
this(pattern, true);
}
/**
* Constructor specifying pattern and case sensitivity.
* @param pattern the pattern for this term
* @param ignoreCase if true, case should be ignored during matching
*/
protected StringTerm(final String pattern, final boolean ignoreCase) {
this.pattern = pattern;
this.ignoreCase = ignoreCase;
}
/**
* Return the pattern associated with this term.
* @return the pattern associated with this term
*/
public String getPattern() {
return pattern;
}
/**
* Indicate if case should be ignored when matching.
* @return if true, case should be ignored during matching
*/
public boolean getIgnoreCase() {
return ignoreCase;
}
/**
* Determine if the pattern associated with this term is a substring of the
* supplied String. If ignoreCase is true then case will be ignored.
*
* @param match the String to compare to
* @return true if this patter is a substring of the supplied String
*/
protected boolean match(final String match) {
final int matchLength = pattern.length();
final int length = match.length() - matchLength;
for (int i = 0; i <= length; i++) {
if (match.regionMatches(ignoreCase, i, pattern, 0, matchLength)) {
return true;
}
}
return false;
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof StringTerm == false) {
return false;
}
final StringTerm term = (StringTerm)other;
if (ignoreCase) {
return term.pattern.equalsIgnoreCase(pattern) && term.ignoreCase == ignoreCase;
}
else {
return term.pattern.equals(pattern) && term.ignoreCase == ignoreCase;
}
}
@Override
public int hashCode() {
return pattern.hashCode() + (ignoreCase ? 32 : 79);
}
}
| 1,990 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/MessageIDTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class MessageIDTerm extends StringTerm {
private static final long serialVersionUID = -2121096296454691963L;
public MessageIDTerm(final String id) {
super(id);
}
@Override
public boolean match(final Message message) {
try {
final String values[] = message.getHeader("Message-ID");
if (values != null) {
for (int i = 0; i < values.length; i++) {
final String value = values[i];
if (match(value)) {
return true;
}
}
}
return false;
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (!(other instanceof MessageIDTerm)) {
return false;
}
return super.equals(other);
}
}
| 1,991 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/BodyTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import java.io.IOException;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
/**
* Term that matches on a message body. All {@link javax.mail.BodyPart parts} that have
* a MIME type of "text/*" are searched.
*
* @version $Rev$ $Date$
*/
public final class BodyTerm extends StringTerm {
private static final long serialVersionUID = -4888862527916911385L;
public BodyTerm(final String pattern) {
super(pattern);
}
@Override
public boolean match(final Message message) {
try {
return matchPart(message);
} catch (final IOException e) {
return false;
} catch (final MessagingException e) {
return false;
}
}
private boolean matchPart(final Part part) throws MessagingException, IOException {
if (part.isMimeType("multipart/*")) {
final Multipart mp = (Multipart) part.getContent();
final int count = mp.getCount();
for (int i=0; i < count; i++) {
final BodyPart bp = mp.getBodyPart(i);
if (matchPart(bp)) {
return true;
}
}
return false;
} else if (part.isMimeType("text/*")) {
final String content = (String) part.getContent();
return super.match(content);
} else if (part.isMimeType("message/rfc822")) {
// nested messages need recursion
return matchPart((Part)part.getContent());
} else {
return false;
}
}
}
| 1,992 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/SearchTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import java.io.Serializable;
import javax.mail.Message;
/**
* Base class for Terms in a parse tree used to represent a search condition.
*
* This class is Serializable to allow for the short term persistence of
* searches between Sessions; this is not intended for long-term persistence.
*
* @version $Rev$ $Date$
*/
public abstract class SearchTerm implements Serializable {
private static final long serialVersionUID = -6652358452205992789L;
/**
* Checks a matching criteria defined by the concrete subclass of this Term.
*
* @param message the message to apply the matching criteria to
* @return true if the matching criteria is met
*/
public abstract boolean match(Message message);
}
| 1,993 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/FromTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class FromTerm extends AddressTerm {
private static final long serialVersionUID = 5214730291502658665L;
public FromTerm(final Address match) {
super(match);
}
@Override
public boolean match(final Message message) {
try {
final Address from[] = message.getFrom();
if (from == null) {
return false;
}
for (int i = 0; i < from.length; i++) {
if (match(from[i])) {
return true;
}
}
return false;
} catch (final MessagingException e) {
return false;
}
}
}
| 1,994 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/AddressTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Address;
/**
* Term that compares two addresses.
*
* @version $Rev$ $Date$
*/
public abstract class AddressTerm extends SearchTerm {
private static final long serialVersionUID = 2005405551929769980L;
/**
* The address.
*/
protected Address address;
/**
* Constructor taking the address for this term.
* @param address the address
*/
protected AddressTerm(final Address address) {
this.address = address;
}
/**
* Return the address of this term.
*
* @return the addre4ss
*/
public Address getAddress() {
return address;
}
/**
* Match to the supplied address.
*
* @param address the address to match with
* @return true if the addresses match
*/
protected boolean match(final Address address) {
return this.address.equals(address);
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof AddressTerm == false) {
return false;
}
return address.equals(((AddressTerm) other).address);
}
@Override
public int hashCode() {
return address.hashCode();
}
}
| 1,995 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/ReceivedDateTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import java.util.Date;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public final class ReceivedDateTerm extends DateTerm {
private static final long serialVersionUID = -2756695246195503170L;
public ReceivedDateTerm(final int comparison, final Date date) {
super(comparison, date);
}
@Override
public boolean match(final Message message) {
try {
final Date date = message.getReceivedDate();
if (date == null) {
return false;
}
return match(date);
} catch (final MessagingException e) {
return false;
}
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof ReceivedDateTerm == false) {
return false;
}
return super.equals(other);
}
}
| 1,996 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/search/IntegerComparisonTerm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
/**
* A Term that provides comparisons for integers.
*
* @version $Rev$ $Date$
*/
public abstract class IntegerComparisonTerm extends ComparisonTerm {
private static final long serialVersionUID = -6963571240154302484L;
protected int number;
protected IntegerComparisonTerm(final int comparison, final int number) {
super();
this.comparison = comparison;
this.number = number;
}
public int getNumber() {
return number;
}
public int getComparison() {
return comparison;
}
protected boolean match(final int match) {
switch (comparison) {
case EQ:
return match == number;
case NE:
return match != number;
case GT:
return match > number;
case GE:
return match >= number;
case LT:
return match < number;
case LE:
return match <= number;
default:
return false;
}
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other instanceof IntegerComparisonTerm == false) {
return false;
}
final IntegerComparisonTerm term = (IntegerComparisonTerm) other;
return this.comparison == term.comparison && this.number == term.number;
}
@Override
public int hashCode() {
return number + super.hashCode();
}
}
| 1,997 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/SharedInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.InputStream;
/**
* @version $Rev$ $Date$
*/
public interface SharedInputStream {
public abstract long getPosition();
public abstract InputStream newStream(long start, long end);
}
| 1,998 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/MimeBodyPart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.EncodingAware;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.HeaderTokenizer.Token;
import org.apache.geronimo.mail.util.ASCIIUtil;
import org.apache.geronimo.mail.util.SessionUtil;
/**
* @version $Rev$ $Date$
*/
public class MimeBodyPart extends BodyPart implements MimePart {
// constants for accessed properties
private static final String MIME_DECODEFILENAME = "mail.mime.decodefilename";
private static final String MIME_ENCODEFILENAME = "mail.mime.encodefilename";
private static final String MIME_SETDEFAULTTEXTCHARSET = "mail.mime.setdefaulttextcharset";
private static final String MIME_SETCONTENTTYPEFILENAME = "mail.mime.setcontenttypefilename";
static final boolean cacheMultipart = SessionUtil.getBooleanProperty("mail.mime.cachemultipart", true);
/**
* The {@link DataHandler} for this Message's content.
*/
protected DataHandler dh;
/**
* This message's content (unless sourced from a SharedInputStream).
*/
/**
* If our content is a Multipart or Message object, we save it
* the first time it's created by parsing a stream so that changes
* to the contained objects will not be lost.
*
* If this field is not null, it's return by the {@link #getContent}
* method. The {@link #getContent} method sets this field if it
* would return a Multipart or MimeMessage object. This field is
* is cleared by the {@link #setDataHandler} method.
*
* @since JavaMail 1.5
*/
protected Object cachedContent;
protected byte content[];
/**
* If the data for this message was supplied by a {@link SharedInputStream}
* then this is another such stream representing the content of this message;
* if this field is non-null, then {@link #content} will be null.
*/
protected InputStream contentStream;
/**
* This message's headers.
*/
protected InternetHeaders headers;
public MimeBodyPart() {
headers = new InternetHeaders();
}
public MimeBodyPart(final InputStream in) throws MessagingException {
headers = new InternetHeaders(in);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final byte[] buffer = new byte[1024];
int count;
try {
while((count = in.read(buffer, 0, 1024)) > 0) {
baos.write(buffer, 0, count);
}
} catch (final IOException e) {
throw new MessagingException(e.toString(),e);
}
content = baos.toByteArray();
}
public MimeBodyPart(final InternetHeaders headers, final byte[] content) throws MessagingException {
this.headers = headers;
this.content = content;
}
/**
* Return the content size of this message. This is obtained
* either from the size of the content field (if available) or
* from the contentStream, IFF the contentStream returns a positive
* size. Returns -1 if the size is not available.
*
* @return Size of the content in bytes.
* @exception MessagingException
*/
public int getSize() throws MessagingException {
if (content != null) {
return content.length;
}
if (contentStream != null) {
try {
final int size = contentStream.available();
if (size > 0) {
return size;
}
} catch (final IOException e) {
}
}
return -1;
}
public int getLineCount() throws MessagingException {
return -1;
}
public String getContentType() throws MessagingException {
String value = getSingleHeader("Content-Type");
if (value == null) {
value = "text/plain";
}
return value;
}
/**
* Tests to see if this message has a mime-type match with the
* given type name.
*
* @param type The tested type name.
*
* @return If this is a type match on the primary and secondare portion of the types.
* @exception MessagingException
*/
public boolean isMimeType(final String type) throws MessagingException {
return new ContentType(getContentType()).match(type);
}
/**
* Retrieve the message "Content-Disposition" header field.
* This value represents how the part should be represented to
* the user.
*
* @return The string value of the Content-Disposition field.
* @exception MessagingException
*/
public String getDisposition() throws MessagingException {
final String disp = getSingleHeader("Content-Disposition");
if (disp != null) {
return new ContentDisposition(disp).getDisposition();
}
return null;
}
/**
* Set a new dispostion value for the "Content-Disposition" field.
* If the new value is null, the header is removed.
*
* @param disposition
* The new disposition value.
*
* @exception MessagingException
*/
public void setDisposition(final String disposition) throws MessagingException {
if (disposition == null) {
removeHeader("Content-Disposition");
}
else {
// the disposition has parameters, which we'll attempt to preserve in any existing header.
final String currentHeader = getSingleHeader("Content-Disposition");
if (currentHeader != null) {
final ContentDisposition content = new ContentDisposition(currentHeader);
content.setDisposition(disposition);
setHeader("Content-Disposition", content.toString());
}
else {
// set using the raw string.
setHeader("Content-Disposition", disposition);
}
}
}
/**
* Retrieves the current value of the "Content-Transfer-Encoding"
* header. Returns null if the header does not exist.
*
* @return The current header value or null.
* @exception MessagingException
*/
public String getEncoding() throws MessagingException {
// this might require some parsing to sort out.
final String encoding = getSingleHeader("Content-Transfer-Encoding");
if (encoding != null) {
// we need to parse this into ATOMs and other constituent parts. We want the first
// ATOM token on the string.
final HeaderTokenizer tokenizer = new HeaderTokenizer(encoding, HeaderTokenizer.MIME);
final Token token = tokenizer.next();
while (token.getType() != Token.EOF) {
// if this is an ATOM type, return it.
if (token.getType() == Token.ATOM) {
return token.getValue();
}
}
// not ATOMs found, just return the entire header value....somebody might be able to make sense of
// this.
return encoding;
}
// no header, nothing to return.
return null;
}
/**
* Retrieve the value of the "Content-ID" header. Returns null
* if the header does not exist.
*
* @return The current header value or null.
* @exception MessagingException
*/
public String getContentID() throws MessagingException {
return getSingleHeader("Content-ID");
}
public void setContentID(final String cid) throws MessagingException {
setOrRemoveHeader("Content-ID", cid);
}
public String getContentMD5() throws MessagingException {
return getSingleHeader("Content-MD5");
}
public void setContentMD5(final String md5) throws MessagingException {
setHeader("Content-MD5", md5);
}
public String[] getContentLanguage() throws MessagingException {
return getHeader("Content-Language");
}
public void setContentLanguage(final String[] languages) throws MessagingException {
if (languages == null) {
removeHeader("Content-Language");
} else if (languages.length == 1) {
setHeader("Content-Language", languages[0]);
} else {
final StringBuffer buf = new StringBuffer(languages.length * 20);
buf.append(languages[0]);
for (int i = 1; i < languages.length; i++) {
buf.append(',').append(languages[i]);
}
setHeader("Content-Language", buf.toString());
}
}
public String getDescription() throws MessagingException {
final String description = getSingleHeader("Content-Description");
if (description != null) {
try {
// this could be both folded and encoded. Return this to usable form.
return MimeUtility.decodeText(MimeUtility.unfold(description));
} catch (final UnsupportedEncodingException e) {
// ignore
}
}
// return the raw version for any errors.
return description;
}
public void setDescription(final String description) throws MessagingException {
setDescription(description, null);
}
public void setDescription(final String description, final String charset) throws MessagingException {
if (description == null) {
removeHeader("Content-Description");
}
else {
try {
setHeader("Content-Description", MimeUtility.fold(21, MimeUtility.encodeText(description, charset, null)));
} catch (final UnsupportedEncodingException e) {
throw new MessagingException(e.getMessage(), e);
}
}
}
public String getFileName() throws MessagingException {
// see if there is a disposition. If there is, parse off the filename parameter.
final String disposition = getSingleHeader("Content-Disposition");
String filename = null;
if (disposition != null) {
filename = new ContentDisposition(disposition).getParameter("filename");
}
// if there's no filename on the disposition, there might be a name parameter on a
// Content-Type header.
if (filename == null) {
final String type = getSingleHeader("Content-Type");
if (type != null) {
try {
filename = new ContentType(type).getParameter("name");
} catch (final ParseException e) {
}
}
}
// if we have a name, we might need to decode this if an additional property is set.
if (filename != null && SessionUtil.getBooleanProperty(MIME_DECODEFILENAME, false)) {
try {
filename = MimeUtility.decodeText(filename);
} catch (final UnsupportedEncodingException e) {
throw new MessagingException("Unable to decode filename", e);
}
}
return filename;
}
public void setFileName(String name) throws MessagingException {
// there's an optional session property that requests file name encoding...we need to process this before
// setting the value.
if (name != null && SessionUtil.getBooleanProperty(MIME_ENCODEFILENAME, false)) {
try {
name = MimeUtility.encodeText(name);
} catch (final UnsupportedEncodingException e) {
throw new MessagingException("Unable to encode filename", e);
}
}
// get the disposition string.
String disposition = getDisposition();
// if not there, then this is an attachment.
if (disposition == null) {
disposition = Part.ATTACHMENT;
}
// now create a disposition object and set the parameter.
final ContentDisposition contentDisposition = new ContentDisposition(disposition);
contentDisposition.setParameter("filename", name);
// serialize this back out and reset.
setHeader("Content-Disposition", contentDisposition.toString());
// The Sun implementation appears to update the Content-type name parameter too, based on
// another system property
if (SessionUtil.getBooleanProperty(MIME_SETCONTENTTYPEFILENAME, true)) {
final ContentType type = new ContentType(getContentType());
type.setParameter("name", name);
setHeader("Content-Type", type.toString());
}
}
public InputStream getInputStream() throws MessagingException, IOException {
return getDataHandler().getInputStream();
}
protected InputStream getContentStream() throws MessagingException {
if (contentStream != null) {
return contentStream;
}
if (content != null) {
return new ByteArrayInputStream(content);
} else {
throw new MessagingException("No content");
}
}
public InputStream getRawInputStream() throws MessagingException {
return getContentStream();
}
public synchronized DataHandler getDataHandler() throws MessagingException {
if (dh == null) {
dh = new DataHandler(new MimePartDataSource(this));
}
return dh;
}
public Object getContent() throws MessagingException, IOException {
if (cachedContent != null) {
return cachedContent;
}
final Object c = getDataHandler().getContent();
if (MimeBodyPart.cacheMultipart && (c instanceof Multipart || c instanceof Message) && (content != null || contentStream != null)) {
cachedContent = c;
if (c instanceof MimeMultipart) {
((MimeMultipart) c).parse();
}
}
return c;
}
public void setDataHandler(final DataHandler handler) throws MessagingException {
dh = handler;
// if we have a handler override, then we need to invalidate any content
// headers that define the types. This information will be derived from the
// data heander unless subsequently overridden.
removeHeader("Content-Type");
removeHeader("Content-Transfer-Encoding");
cachedContent = null;
}
public void setContent(final Object content, final String type) throws MessagingException {
// Multipart content needs to be handled separately.
if (content instanceof Multipart) {
setContent((Multipart)content);
}
else {
setDataHandler(new DataHandler(content, type));
}
}
public void setText(final String text) throws MessagingException {
setText(text, null);
}
public void setText(final String text, final String charset) throws MessagingException {
// the default subtype is plain text.
setText(text, charset, "plain");
}
public void setText(final String text, String charset, final String subtype) throws MessagingException {
// we need to sort out the character set if one is not provided.
if (charset == null) {
// if we have non us-ascii characters here, we need to adjust this.
if (!ASCIIUtil.isAscii(text)) {
charset = MimeUtility.getDefaultMIMECharset();
}
else {
charset = "us-ascii";
}
}
setContent(text, "text/plain; charset=" + MimeUtility.quote(charset, HeaderTokenizer.MIME));
}
public void setContent(final Multipart part) throws MessagingException {
setDataHandler(new DataHandler(part, part.getContentType()));
part.setParent(this);
}
public void writeTo(final OutputStream out) throws IOException, MessagingException {
headers.writeTo(out, null);
// add the separater between the headers and the data portion.
out.write('\r');
out.write('\n');
// we need to process this using the transfer encoding type
final OutputStream encodingStream = MimeUtility.encode(out, getEncoding());
getDataHandler().writeTo(encodingStream);
encodingStream.flush();
}
public String[] getHeader(final String name) throws MessagingException {
return headers.getHeader(name);
}
public String getHeader(final String name, final String delimiter) throws MessagingException {
return headers.getHeader(name, delimiter);
}
public void setHeader(final String name, final String value) throws MessagingException {
headers.setHeader(name, value);
}
/**
* Conditionally set or remove a named header. If the new value
* is null, the header is removed.
*
* @param name The header name.
* @param value The new header value. A null value causes the header to be
* removed.
*
* @exception MessagingException
*/
private void setOrRemoveHeader(final String name, final String value) throws MessagingException {
if (value == null) {
headers.removeHeader(name);
}
else {
headers.setHeader(name, value);
}
}
public void addHeader(final String name, final String value) throws MessagingException {
headers.addHeader(name, value);
}
public void removeHeader(final String name) throws MessagingException {
headers.removeHeader(name);
}
public Enumeration getAllHeaders() throws MessagingException {
return headers.getAllHeaders();
}
public Enumeration getMatchingHeaders(final String[] name) throws MessagingException {
return headers.getMatchingHeaders(name);
}
public Enumeration getNonMatchingHeaders(final String[] name) throws MessagingException {
return headers.getNonMatchingHeaders(name);
}
public void addHeaderLine(final String line) throws MessagingException {
headers.addHeaderLine(line);
}
public Enumeration getAllHeaderLines() throws MessagingException {
return headers.getAllHeaderLines();
}
public Enumeration getMatchingHeaderLines(final String[] names) throws MessagingException {
return headers.getMatchingHeaderLines(names);
}
public Enumeration getNonMatchingHeaderLines(final String[] names) throws MessagingException {
return headers.getNonMatchingHeaderLines(names);
}
protected void updateHeaders() throws MessagingException {
final DataHandler handler = getDataHandler();
try {
// figure out the content type. If not set, we'll need to figure this out.
String type = dh.getContentType();
// parse this content type out so we can do matches/compares.
final ContentType contentType = new ContentType(type);
// we might need to reconcile the content type and our explicitly set type
final String explicitType = getSingleHeader("Content-Type");
// is this a multipart content?
if (contentType.match("multipart/*")) {
// the content is suppose to be a MimeMultipart. Ping it to update it's headers as well.
try {
final MimeMultipart part = (MimeMultipart)handler.getContent();
part.updateHeaders();
} catch (final ClassCastException e) {
throw new MessagingException("Message content is not MimeMultipart", e);
}
}
else if (!contentType.match("message/rfc822")) {
// simple part, we need to update the header type information
// if no encoding is set yet, figure this out from the data handler.
if (getSingleHeader("Content-Transfer-Encoding") == null) {
setHeader("Content-Transfer-Encoding", MimeUtility.getEncoding(handler));
}
// is a content type header set? Check the property to see if we need to set this.
if (explicitType == null) {
if (SessionUtil.getBooleanProperty(MIME_SETDEFAULTTEXTCHARSET, true)) {
// is this a text type? Figure out the encoding and make sure it is set.
if (contentType.match("text/*")) {
// the charset should be specified as a parameter on the MIME type. If not there,
// try to figure one out.
if (contentType.getParameter("charset") == null) {
final String encoding = getEncoding();
// if we're sending this as 7-bit ASCII, our character set need to be
// compatible.
if (encoding != null && encoding.equalsIgnoreCase("7bit")) {
contentType.setParameter("charset", "us-ascii");
}
else {
// get the global default.
contentType.setParameter("charset", MimeUtility.getDefaultMIMECharset());
}
// replace the datasource provided type
type = contentType.toString();
}
}
}
}
}
// if we don't have a content type header, then create one.
if (explicitType == null) {
// get the disposition header, and if it is there, copy the filename parameter into the
// name parameter of the type.
final String disp = getHeader("Content-Disposition", null);
if (disp != null) {
// parse up the string value of the disposition
final ContentDisposition disposition = new ContentDisposition(disp);
// now check for a filename value
final String filename = disposition.getParameter("filename");
// copy and rename the parameter, if it exists.
if (filename != null) {
contentType.setParameter("name", filename);
// and update the string version
type = contentType.toString();
}
}
// set the header with the updated content type information.
setHeader("Content-Type", type);
}
if (cachedContent != null) {
dh = new DataHandler(cachedContent, getContentType());
cachedContent = null;
content = null;
if (contentStream != null) {
try {
contentStream.close();
} catch (final IOException ioex) {
//np-op
}
}
contentStream = null;
}
} catch (final IOException e) {
throw new MessagingException("Error updating message headers", e);
}
}
private String getSingleHeader(final String name) throws MessagingException {
final String[] values = getHeader(name);
if (values == null || values.length == 0) {
return null;
} else {
return values[0];
}
}
/**
* Use the specified file to provide the data for this part.
* The simple file name is used as the file name for this
* part and the data in the file is used as the data for this
* part. The encoding will be chosen appropriately for the
* file data. The disposition of this part is set to
* {@link Part#ATTACHMENT Part.ATTACHMENT}.
*
* @param file the File object to attach
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.4
*/
public void attachFile(final File file) throws IOException, MessagingException {
final FileDataSource dataSource = new FileDataSource(file);
setDataHandler(new DataHandler(dataSource));
setFileName(dataSource.getName());
/* Since JavaMail 1.5:
An oversight when these methods were originally added.
Clearly attachments should set the disposition to ATTACHMENT.
*/
setDisposition(ATTACHMENT);
}
/**
* Use the specified file to provide the data for this part.
* The simple file name is used as the file name for this
* part and the data in the file is used as the data for this
* part. The encoding will be chosen appropriately for the
* file data.
*
* @param file the name of the file to attach
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.4
*/
public void attachFile(final String file) throws IOException, MessagingException {
attachFile(new File(file));
}
/**
* Use the specified file with the specified Content-Type and
* Content-Transfer-Encoding to provide the data for this part.
* If contentType or encoding are null, appropriate values will
* be chosen.
* The simple file name is used as the file name for this
* part and the data in the file is used as the data for this
* part. The disposition of this part is set to
* {@link Part#ATTACHMENT Part.ATTACHMENT}.
*
* @param file the File object to attach
* @param contentType the Content-Type, or null
* @param encoding the Content-Transfer-Encoding, or null
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.5
*/
public void attachFile(final File file, final String contentType, final String encoding)
throws IOException, MessagingException {
final FileDataSource dataSource = new EncodingAwareFileDataSource(file, contentType, encoding);
setDataHandler(new DataHandler(dataSource));
setFileName(dataSource.getName());
/* Since JavaMail 1.5:
An oversight when these methods were originally added.
Clearly attachments should set the disposition to ATTACHMENT.
*/
setDisposition(ATTACHMENT);
}
/**
* Use the specified file with the specified Content-Type and
* Content-Transfer-Encoding to provide the data for this part.
* If contentType or encoding are null, appropriate values will
* be chosen.
* The simple file name is used as the file name for this
* part and the data in the file is used as the data for this
* part. The disposition of this part is set to
* {@link Part#ATTACHMENT Part.ATTACHMENT}.
*
* @param file the name of the file
* @param contentType the Content-Type, or null
* @param encoding the Content-Transfer-Encoding, or null
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.5
*/
public void attachFile(final String file, final String contentType, final String encoding)
throws IOException, MessagingException {
attachFile(new File(file), contentType, encoding);
}
/**
* Save the body part content to a given target file.
*
* @param file The File object used to store the information.
*
* @exception IOException
* @exception MessagingException
*/
public void saveFile(final File file) throws IOException, MessagingException {
final OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
// we need to read the data in to write it out (sigh).
final InputStream in = getInputStream();
try {
final byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
finally {
// make sure all of the streams are closed before we return
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
/**
* Save the body part content to a given target file.
*
* @param file The file name used to store the information.
*
* @exception IOException
* @exception MessagingException
*/
public void saveFile(final String file) throws IOException, MessagingException {
saveFile(new File(file));
}
private static class EncodingAwareFileDataSource extends FileDataSource implements EncodingAware {
private final String contentType;
private final String encoding;
public EncodingAwareFileDataSource(final File file, final String contentType, final String encoding) {
super(file);
this.contentType = contentType;
this.encoding = encoding;
}
@Override
public String getContentType() {
return contentType == null ? super.getContentType() : contentType;
}
//this will be evaluated in MimeUtility.getEncoding(DataSource)
public String getEncoding() {
return encoding;
}
}
}
| 1,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.