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.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String message) {
super(message);
}
}
| 1,000 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(Session session, 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(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(StoreListener listener) {
storeListeners.add(listener);
}
public void removeStoreListener(StoreListener listener) {
storeListeners.remove(listener);
}
protected void notifyStoreListeners(int type, String message) {
queueEvent(new StoreEvent(this, type, message), storeListeners);
}
public void addFolderListener(FolderListener listener) {
folderListeners.add(listener);
}
public void removeFolderListener(FolderListener listener) {
folderListeners.remove(listener);
}
protected void notifyFolderListeners(int type, Folder folder) {
queueEvent(new FolderEvent(this, folder, type), folderListeners);
}
protected void notifyFolderRenamedListeners(Folder oldFolder, Folder newFolder) {
queueEvent(new FolderEvent(this, oldFolder, newFolder, FolderEvent.RENAMED), folderListeners);
}
}
| 1,001 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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.osgi.locator.ProviderLocator;
import org.apache.geronimo.mail.MailProviderRegistry;
/**
* 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 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(Properties properties, 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, 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(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(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(Properties properties, 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(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(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() {
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(String protocol) throws NoSuchProviderException {
ProviderInfo info = getProviderInfo();
Provider provider = null;
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(Provider provider) throws NoSuchProviderException {
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 {
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(String protocol) throws NoSuchProviderException {
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(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(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(URLName name) throws MessagingException {
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 {
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(String protocol) throws NoSuchProviderException {
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(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(Address address) throws NoSuchProviderException {
String type = address.getType();
// load the address map from the resource files.
Map addressMap = getAddressMap();
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(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(URLName name, 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(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(InetAddress host, int port, String protocol, String prompt, 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(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(Provider provider) {
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(String addressType, String protocol) {
Map addressMap = getAddressMap();
// no protocol specified is a removal
if (protocol == null) {
addressMap.remove(addressType);
}
else {
addressMap.put(addressType, protocol);
}
}
private Service getService(Provider provider, URLName name) throws NoSuchProviderException {
try {
if (name == null) {
name = new URLName(provider.getProtocol(), null, -1, null, null, null);
}
ClassLoader cl = getClassLoader();
Class clazz = null;
try {
clazz = ProviderLocator.loadClass(provider.getClassName(), this.getClass(), cl);
} catch (ClassNotFoundException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Unable to load class for provider: " + provider).initCause(e);
}
Constructor ctr = clazz.getConstructor(PARAM_TYPES);
return(Service) ctr.newInstance(new Object[]{this, name});
} catch (NoSuchMethodException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Provider class does not have a constructor(Session, URLName): " + provider).initCause(e);
} catch (InstantiationException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Unable to instantiate provider class: " + provider).initCause(e);
} catch (IllegalAccessException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Unable to instantiate provider class: " + provider).initCause(e);
} catch (InvocationTargetException e) {
throw (NoSuchProviderException) new NoSuchProviderException("Exception from constructor of provider class: " + provider).initCause(e.getCause());
}
}
private ProviderInfo getProviderInfo() {
ClassLoader cl = getClassLoader();
synchronized (providersByClassLoader) {
ProviderInfo info = (ProviderInfo) providersByClassLoader.get(cl);
if (info == null) {
info = loadProviders(cl);
}
return info;
}
}
private Map getAddressMap() {
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(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
//
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 {
File file = new File(System.getProperty("java.home"), "lib/javamail.providers");
InputStream is = new FileInputStream(file);
try {
loadProviders(info, is);
if (debug) {
writeDebug("Loaded lib/javamail.providers from " + file.toString());
}
} finally{
is.close();
}
} catch (SecurityException e) {
// ignore
} catch (IOException e) {
// ignore
}
try {
Enumeration e = cl.getResources("META-INF/javamail.providers");
while (e.hasMoreElements()) {
URL url = (URL) e.nextElement();
if (debug) {
writeDebug("Loading META-INF/javamail.providers from " + url.toString());
}
InputStream is = url.openStream();
try {
loadProviders(info, is);
} finally{
is.close();
}
}
} catch (SecurityException e) {
// ignore
} catch (IOException e) {
// ignore
}
// we could be running in an OSGi environment, so there might be some globally defined
// providers
try {
Collection<URL> l = MailProviderRegistry.getProviders();
for (URL url : l) {
if (debug) {
writeDebug("Loading META-INF/javamail.providers from " + url.toString());
}
InputStream is = url.openStream();
try {
loadProviders(info, is);
} finally{
is.close();
}
}
} catch (SecurityException e) {
// ignore
} catch (IOException e) {
// ignore
}
try {
Enumeration e = cl.getResources("META-INF/javamail.default.providers");
while (e.hasMoreElements()) {
URL url = (URL) e.nextElement();
if (debug) {
writeDebug("Loading javamail.default.providers from " + url.toString());
}
InputStream is = url.openStream();
try {
loadProviders(info, is);
} finally{
is.close();
}
}
} catch (SecurityException e) {
// ignore
} catch (IOException e) {
// ignore
}
// we could be running in an OSGi environment, so there might be some globally defined
// providers
try {
Collection<URL> l = MailProviderRegistry.getDefaultProviders();
for (URL url : l) {
if (debug) {
writeDebug("Loading META-INF/javamail.providers from " + url.toString());
}
InputStream is = url.openStream();
try {
loadProviders(info, is);
} finally{
is.close();
}
}
} catch (SecurityException e) {
// ignore
} catch (IOException e) {
// ignore
}
// make sure this is added to the global map.
providersByClassLoader.put(cl, info);
return info;
}
private void loadProviders(ProviderInfo info, InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
// Lines beginning with "#" are just comments.
if (line.startsWith("#")) {
continue;
}
StringTokenizer tok = new StringTokenizer(line, ";");
String protocol = null;
Provider.Type type = null;
String className = null;
String vendor = null;
String version = null;
while (tok.hasMoreTokens()) {
String property = tok.nextToken();
int index = property.indexOf('=');
if (index == -1) {
continue;
}
String key = property.substring(0, index).trim().toLowerCase();
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);
}
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(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.
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 {
Enumeration e = cl.getResources("META-INF/javamail.default.address.map");
while (e.hasMoreElements()) {
URL url = (URL) e.nextElement();
InputStream is = url.openStream();
try {
// load as a property file
addressMap.load(is);
} finally{
is.close();
}
}
} catch (SecurityException e) {
// ignore
} catch (IOException e) {
// ignore
}
try {
Enumeration e = cl.getResources("META-INF/javamail.address.map");
while (e.hasMoreElements()) {
URL url = (URL) e.nextElement();
InputStream is = url.openStream();
try {
// load as a property file
addressMap.load(is);
} finally{
is.close();
}
}
} catch (SecurityException e) {
// ignore
} catch (IOException e) {
// ignore
}
try {
File file = new File(System.getProperty("java.home"), "lib/javamail.address.map");
InputStream is = new FileInputStream(file);
try {
// load as a property file
addressMap.load(is);
} finally{
is.close();
}
} catch (SecurityException e) {
// ignore
} catch (IOException e) {
// ignore
}
try {
Enumeration e = cl.getResources("META-INF/javamail.address.map");
while (e.hasMoreElements()) {
URL url = (URL) e.nextElement();
InputStream is = url.openStream();
try {
// load as a property file
addressMap.load(is);
} finally{
is.close();
}
}
} catch (SecurityException e) {
// ignore
} catch (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(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(Provider provider) {
String className = provider.getClassName();
if (!byClassName.containsKey(className)) {
byClassName.put(className, provider);
}
String protocol = provider.getProtocol();
if (!byProtocol.containsKey(protocol)) {
byProtocol.put(protocol, provider);
}
all.add(provider);
}
}
}
| 1,002 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String message) {
super(message);
}
}
| 1,003 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String user, String password) {
this.user = user;
this.password = password;
}
public String getUserName() {
return user;
}
public String getPassword() {
return password;
}
}
| 1,004 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(Folder folder) {
this(folder, "Folder not found: " + folder.getName());
}
public ReadOnlyFolderException(Folder folder, String message) {
super(message);
_folder = folder;
}
public Folder getFolder() {
return _folder;
}
}
| 1,005 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String name, 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,006 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(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 {
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(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(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(Flag flag, boolean value) throws MessagingException {
if (!isOpen()) {
return -1;
}
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, int end) throws MessagingException {
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(int ids[]) throws MessagingException {
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(Message[] messages, 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(Message[] messages, Flags flags, boolean value) throws MessagingException {
for (int i = 0; i < messages.length; i++) {
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(int start, int end, Flags flags, boolean value) throws MessagingException {
for (int i = start; i <= end; i++) {
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(int ids[], Flags flags, boolean value) throws MessagingException {
for (int i = 0; i < ids.length; i++) {
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(Message[] messages, 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(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(SearchTerm term, Message[] messages) throws MessagingException {
List result = new ArrayList(messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
if (message.match(term)) {
result.add(message);
}
}
return (Message[]) result.toArray(new Message[result.size()]);
}
public void addConnectionListener(ConnectionListener listener) {
connectionListeners.add(listener);
}
public void removeConnectionListener(ConnectionListener listener) {
connectionListeners.remove(listener);
}
protected void notifyConnectionListeners(int type) {
queueEvent(new ConnectionEvent(this, type), connectionListeners);
}
public void addFolderListener(FolderListener listener) {
folderListeners.add(listener);
}
public void removeFolderListener(FolderListener listener) {
folderListeners.remove(listener);
}
protected void notifyFolderListeners(int type) {
queueEvent(new FolderEvent(this, this, type), folderListeners);
}
protected void notifyFolderRenamedListeners(Folder newFolder) {
queueEvent(new FolderEvent(this, this, newFolder, FolderEvent.RENAMED), folderListeners);
}
public void addMessageCountListener(MessageCountListener listener) {
messageCountListeners.add(listener);
}
public void removeMessageCountListener(MessageCountListener listener) {
messageCountListeners.remove(listener);
}
protected void notifyMessageAddedListeners(Message[] messages) {
queueEvent(new MessageCountEvent(this, MessageCountEvent.ADDED, false, messages), messageChangedListeners);
}
protected void notifyMessageRemovedListeners(boolean removed, Message[] messages) {
queueEvent(new MessageCountEvent(this, MessageCountEvent.REMOVED, removed, messages), messageChangedListeners);
}
public void addMessageChangedListener(MessageChangedListener listener) {
messageChangedListeners.add(listener);
}
public void removeMessageChangedListener(MessageChangedListener listener) {
messageChangedListeners.remove(listener);
}
protected void notifyMessageChangedListeners(int type, Message message) {
queueEvent(new MessageChangedEvent(this, type, message), messageChangedListeners);
}
/**
* Unregisters all listeners.
*/
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
*/
public String toString() {
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(MailEvent event, 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,007 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(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(String name, long limit) {
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(String name) {
// no resources yet? Make it so.
if (resources == null) {
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++) {
Resource current = resources[i];
if (current.name.equalsIgnoreCase(name)) {
return current;
}
}
// have to extend the array...this is a pain.
Resource[] newResources = new Resource[resources.length + 1];
System.arraycopy(resources, 0, newResources, 0, resources.length);
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(String name, long usage, long limit) {
this.name = name;
this.usage = usage;
this.limit = limit;
}
}
}
| 1,008 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(MultipartDataSource mds) throws MessagingException {
parts.clear();
contentType = mds.getContentType();
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(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(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(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(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(BodyPart part, 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(Part part) {
parent = part;
}
}
| 1,009 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String name) {
super(name);
}
}
}
| 1,010 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
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.ParseException;
import javax.mail.internet.MimeUtility;
/**
* An activation DataSource object that sources the data from
* a byte[] array.
* @version $Rev$ $Date$
*/
public class ByteArrayDataSource implements DataSource {
// the data source
private byte[] source;
// the content MIME type
private 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(InputStream in, String type) throws IOException {
ByteArrayOutputStream sink = new ByteArrayOutputStream();
// ok, how I wish you could just pipe an input stream into an output stream :-)
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(byte[] data, 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(String data, String type) throws IOException {
String charset = null;
try {
// the charset can be encoded in the content type, which we parse using
// the ContentType class.
ContentType content = new ContentType(type);
charset = content.getParameter("charset");
} catch (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(String name) {
this.name = name;
}
}
| 1,011 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(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(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(String file, 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(File file, 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(SharedFileSource source, long start, long len, 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(File file, 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.
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
int newSize = Math.min(buf.length * 2, marklimit);
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
*/
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
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.
*/
public synchronized void mark(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
*/
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
*/
public synchronized int read(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;
}
int available = count - pos;
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
*/
public synchronized long skip(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;
}
long available = count - pos;
// the skipped contract allows skipping within the current buffer bounds, so cap it there.
long skipped = available < n ? available : n;
pos += skipped;
return skipped;
}
/**
* Reset the mark position.
*
* @exception IOException
*/
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.
*/
public boolean markSupported() {
return true;
}
/**
* Close the stream. This does not close the source file until
* the last shared instance is closed.
*
* @exception IOException
*/
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(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(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(long position, byte[] buf, int offset, 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
*/
protected void finalize() throws Throwable {
super.finalize();
if (instanceCount > 0) {
source.close();
}
}
}
}
| 1,012 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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.IOException;
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(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(byte[] buf, int offset, 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(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,013 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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.
*/
protected boolean set;
/**
* The flags to test.
*/
protected Flags flags;
/**
* @param flags the flags to test
* @param set test for set or clear; {@link #set}
*/
public FlagTerm(Flags flags, boolean set) {
this.set = set;
this.flags = flags;
}
public Flags getFlags() {
return flags;
}
public boolean getTestSet() {
return set;
}
public boolean match(Message message) {
try {
Flags msgFlags = message.getFlags();
if (set) {
return msgFlags.contains(flags);
} else {
// yuk - I wish we could get at the internal state of the Flags
Flags.Flag[] system = flags.getSystemFlags();
for (int i = 0; i < system.length; i++) {
Flags.Flag flag = system[i];
if (msgFlags.contains(flag)) {
return false;
}
}
String[] user = flags.getUserFlags();
for (int i = 0; i < user.length; i++) {
String flag = user[i];
if (msgFlags.contains(flag)) {
return false;
}
}
return true;
}
} catch (MessagingException e) {
return false;
}
}
public boolean equals(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);
}
public int hashCode() {
return set ? flags.hashCode() : ~flags.hashCode();
}
}
| 1,014 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String message) {
super(message);
}
}
| 1,015 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(int number) {
super(EQ, number);
}
public boolean match(Message message) {
return match(message.getMessageNumber());
}
public boolean equals(Object other) {
if (!(other instanceof MessageNumberTerm)) {
return false;
}
return super.equals(other);
}
}
| 1,016 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(int comparison, Date date) {
super(comparison, date);
}
public boolean match(Message message) {
try {
Date date = message.getSentDate();
if (date == null) {
return false;
}
return match(message.getSentDate());
} catch (MessagingException e) {
return false;
}
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof SentDateTerm == false) return false;
return super.equals(other);
}
}
| 1,017 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String string) {
super(string);
}
public boolean match(Message message) {
try {
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 (MessagingException e) {
return false;
}
}
}
| 1,018 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(int comparison, int size) {
super(comparison, size);
}
public boolean match(Message message) {
try {
return match(message.getSize());
} catch (MessagingException e) {
return false;
}
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof SizeTerm == false) return false;
return super.equals(other);
}
}
| 1,019 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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;
protected SearchTerm[] terms;
public OrTerm(SearchTerm a, SearchTerm b) {
terms = new SearchTerm[]{a, b};
}
public OrTerm(SearchTerm[] terms) {
this.terms = terms;
}
public SearchTerm[] getTerms() {
return terms;
}
public boolean match(Message message) {
for (int i = 0; i < terms.length; i++) {
SearchTerm term = terms[i];
if (term.match(message)) {
return true;
}
}
return false;
}
public boolean equals(Object other) {
if (other == this) return true;
if (other instanceof OrTerm == false) return false;
return Arrays.equals(terms, ((OrTerm) other).terms);
}
public int hashCode() {
int hash = 0;
for (int i = 0; i < terms.length; i++) {
hash = hash * 37 + terms[i].hashCode();
}
return hash;
}
}
| 1,020 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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;
protected String headerName;
public HeaderTerm(String header, String pattern) {
super(pattern);
this.headerName = header;
}
public String getHeaderName() {
return headerName;
}
public boolean match(Message message) {
try {
String values[] = message.getHeader(headerName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (match(value)) {
return true;
}
}
}
return false;
} catch (MessagingException e) {
return false;
}
}
public boolean equals(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);
}
public int hashCode() {
return headerName.toLowerCase().hashCode() + super.hashCode();
}
}
| 1,021 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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 Message.RecipientType type;
public RecipientStringTerm(Message.RecipientType type, String pattern) {
super(pattern);
this.type = type;
}
public Message.RecipientType getRecipientType() {
return type;
}
public boolean match(Message message) {
try {
Address from[] = message.getRecipients(type);
if (from == null) {
return false;
}
for (int i = 0; i < from.length; i++) {
Address address = from[i];
if (match(address)) {
return true;
}
}
return false;
} catch (MessagingException e) {
return false;
}
}
public boolean equals(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;
}
public int hashCode() {
return pattern.hashCode() + type.hashCode();
}
}
| 1,022 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(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(Address address) {
return match(address.toString());
}
}
| 1,023 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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;
protected Message.RecipientType type;
public RecipientTerm(Message.RecipientType type, Address address) {
super(address);
this.type = type;
}
public Message.RecipientType getRecipientType() {
return type;
}
public boolean match(Message message) {
try {
Address from[] = message.getRecipients(type);
if (from == null) {
return false;
}
for (int i = 0; i < from.length; i++) {
Address address = from[i];
if (match(address)) {
return true;
}
}
return false;
} catch (MessagingException e) {
return false;
}
}
public boolean equals(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;
}
public int hashCode() {
return address.hashCode() + type.hashCode();
}
}
| 1,024 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(int comparison, Date date) {
super();
this.comparison = comparison;
this.date = date;
}
public Date getDate() {
return date;
}
public int getComparison() {
return comparison;
}
protected boolean match(Date match) {
long matchTime = match.getTime();
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;
}
}
public boolean equals(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);
}
public int hashCode() {
return date.hashCode() + super.hashCode();
}
}
| 1,025 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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;
protected SearchTerm term;
public NotTerm(SearchTerm term) {
this.term = term;
}
public SearchTerm getTerm() {
return term;
}
public boolean match(Message message) {
return !term.match(message);
}
public boolean equals(Object other) {
if (other == this) return true;
if (other instanceof NotTerm == false) return false;
return term.equals(((NotTerm) other).term);
}
public int hashCode() {
return term.hashCode();
}
}
| 1,026 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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() {
}
public boolean equals(Object other) {
if (!(other instanceof ComparisonTerm)) {
return false;
}
return comparison == ((ComparisonTerm)other).comparison;
}
public int hashCode() {
return comparison;
}
}
| 1,027 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String subject) {
super(subject);
}
public boolean match(Message message) {
try {
String subject = message.getSubject();
if (subject == null) {
return false;
}
return match(subject);
} catch (MessagingException e) {
return false;
}
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof SubjectTerm == false) return false;
return super.equals(other);
}
}
| 1,028 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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.
*/
protected SearchTerm[] terms;
/**
* Constructor for performing a binary AND.
*
* @param a the first term
* @param b the second ter,
*/
public AndTerm(SearchTerm a, 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(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
*/
public boolean match(Message message) {
for (int i = 0; i < terms.length; i++) {
SearchTerm term = terms[i];
if (!term.match(message)) {
return false;
}
}
return true;
}
public boolean equals(Object other) {
if (other == this) return true;
if (other instanceof AndTerm == false) return false;
return Arrays.equals(terms, ((AndTerm) other).terms);
}
public int hashCode() {
int hash = 0;
for (int i = 0; i < terms.length; i++) {
hash = hash * 37 + terms[i].hashCode();
}
return hash;
}
}
| 1,029 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(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(String pattern, 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(String match) {
int matchLength = pattern.length();
int length = match.length() - matchLength;
for (int i = 0; i <= length; i++) {
if (match.regionMatches(ignoreCase, i, pattern, 0, matchLength)) {
return true;
}
}
return false;
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof StringTerm == false) return false;
StringTerm term = (StringTerm)other;
if (ignoreCase) {
return term.pattern.equalsIgnoreCase(pattern) && term.ignoreCase == ignoreCase;
}
else {
return term.pattern.equals(pattern) && term.ignoreCase == ignoreCase;
}
}
public int hashCode() {
return pattern.hashCode() + (ignoreCase ? 32 : 79);
}
}
| 1,030 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(String id) {
super(id);
}
public boolean match(Message message) {
try {
String values[] = message.getHeader("Message-ID");
if (values != null) {
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (match(value)) {
return true;
}
}
}
return false;
} catch (MessagingException e) {
return false;
}
}
public boolean equals(Object other) {
if (!(other instanceof MessageIDTerm)) {
return false;
}
return super.equals(other);
}
}
| 1,031 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Multipart;
import javax.mail.BodyPart;
/**
* 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(String pattern) {
super(pattern);
}
public boolean match(Message message) {
try {
return matchPart(message);
} catch (IOException e) {
return false;
} catch (MessagingException e) {
return false;
}
}
private boolean matchPart(Part part) throws MessagingException, IOException {
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
int count = mp.getCount();
for (int i=0; i < count; i++) {
BodyPart bp = mp.getBodyPart(i);
if (matchPart(bp)) {
return true;
}
}
return false;
} else if (part.isMimeType("text/*")) {
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,032 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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,033 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(Address match) {
super(match);
}
public boolean match(Message message) {
try {
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 (MessagingException e) {
return false;
}
}
}
| 1,034 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(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(Address address) {
return this.address.equals(address);
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof AddressTerm == false) return false;
return address.equals(((AddressTerm) other).address);
}
public int hashCode() {
return address.hashCode();
}
}
| 1,035 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(int comparison, Date date) {
super(comparison, date);
}
public boolean match(Message message) {
try {
Date date = message.getReceivedDate();
if (date == null) {
return false;
}
return match(date);
} catch (MessagingException e) {
return false;
}
}
public boolean equals(Object other) {
if (other == this) return true;
if (other instanceof ReceivedDateTerm == false) return false;
return super.equals(other);
}
}
| 1,036 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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(int comparison, int number) {
super();
this.comparison = comparison;
this.number = number;
}
public int getNumber() {
return number;
}
public int getComparison() {
return comparison;
}
protected boolean match(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;
}
}
public boolean equals(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;
}
public int hashCode() {
return number + super.hashCode();
}
}
| 1,037 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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,038 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_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.FileOutputStream;
import java.io.File;
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.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
protected 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";
/**
* The {@link DataHandler} for this Message's content.
*/
protected DataHandler dh;
/**
* This message's content (unless sourced from a SharedInputStream).
*/
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(InputStream in) throws MessagingException {
headers = new InternetHeaders(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
try {
while((count = in.read(buffer, 0, 1024)) > 0) {
baos.write(buffer, 0, count);
}
} catch (IOException e) {
throw new MessagingException(e.toString(),e);
}
content = baos.toByteArray();
}
public MimeBodyPart(InternetHeaders headers, 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 {
int size = contentStream.available();
if (size > 0) {
return size;
}
} catch (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(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 {
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(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.
String currentHeader = getSingleHeader("Content-Disposition");
if (currentHeader != null) {
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.
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.
HeaderTokenizer tokenizer = new HeaderTokenizer(encoding, HeaderTokenizer.MIME);
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(String cid) throws MessagingException {
setOrRemoveHeader("Content-ID", cid);
}
public String getContentMD5() throws MessagingException {
return getSingleHeader("Content-MD5");
}
public void setContentMD5(String md5) throws MessagingException {
setHeader("Content-MD5", md5);
}
public String[] getContentLanguage() throws MessagingException {
return getHeader("Content-Language");
}
public void setContentLanguage(String[] languages) throws MessagingException {
if (languages == null) {
removeHeader("Content-Language");
} else if (languages.length == 1) {
setHeader("Content-Language", languages[0]);
} else {
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 {
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 (UnsupportedEncodingException e) {
// ignore
}
}
// return the raw version for any errors.
return description;
}
public void setDescription(String description) throws MessagingException {
setDescription(description, null);
}
public void setDescription(String description, String charset) throws MessagingException {
if (description == null) {
removeHeader("Content-Description");
}
else {
try {
setHeader("Content-Description", MimeUtility.fold(21, MimeUtility.encodeText(description, charset, null)));
} catch (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.
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) {
String type = getSingleHeader("Content-Type");
if (type != null) {
try {
filename = new ContentType(type).getParameter("name");
} catch (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 (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 (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.
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)) {
String currentContentType = getSingleHeader("Content-Type");
if(currentContentType !=null) { //GERONIMO-6480
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 {
return getDataHandler().getContent();
}
public void setDataHandler(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");
}
public void setContent(Object content, 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(String text) throws MessagingException {
setText(text, null);
}
public void setText(String text, String charset) throws MessagingException {
// the default subtype is plain text.
setText(text, charset, "plain");
}
public void setText(String text, String charset, 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/"+((subtype==null || subtype.isEmpty())?"plain":subtype)+"; charset=" + MimeUtility.quote(charset, HeaderTokenizer.MIME));
}
public void setContent(Multipart part) throws MessagingException {
setDataHandler(new DataHandler(part, part.getContentType()));
part.setParent(this);
}
public void writeTo(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
OutputStream encodingStream = MimeUtility.encode(out, getEncoding());
getDataHandler().writeTo(encodingStream);
encodingStream.flush();
}
public String[] getHeader(String name) throws MessagingException {
return headers.getHeader(name);
}
public String getHeader(String name, String delimiter) throws MessagingException {
return headers.getHeader(name, delimiter);
}
public void setHeader(String name, 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(String name, String value) throws MessagingException {
if (value == null) {
headers.removeHeader(name);
}
else {
headers.setHeader(name, value);
}
}
public void addHeader(String name, String value) throws MessagingException {
headers.addHeader(name, value);
}
public void removeHeader(String name) throws MessagingException {
headers.removeHeader(name);
}
public Enumeration getAllHeaders() throws MessagingException {
return headers.getAllHeaders();
}
public Enumeration getMatchingHeaders(String[] name) throws MessagingException {
return headers.getMatchingHeaders(name);
}
public Enumeration getNonMatchingHeaders(String[] name) throws MessagingException {
return headers.getNonMatchingHeaders(name);
}
public void addHeaderLine(String line) throws MessagingException {
headers.addHeaderLine(line);
}
public Enumeration getAllHeaderLines() throws MessagingException {
return headers.getAllHeaderLines();
}
public Enumeration getMatchingHeaderLines(String[] names) throws MessagingException {
return headers.getMatchingHeaderLines(names);
}
public Enumeration getNonMatchingHeaderLines(String[] names) throws MessagingException {
return headers.getNonMatchingHeaderLines(names);
}
protected void updateHeaders() throws MessagingException {
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.
ContentType content = new ContentType(type);
// we might need to reconcile the content type and our explicitly set type
String explicitType = getSingleHeader("Content-Type");
// is this a multipart content?
if (content.match("multipart/*")) {
// the content is suppose to be a MimeMultipart. Ping it to update it's headers as well.
try {
MimeMultipart part = (MimeMultipart)handler.getContent();
part.updateHeaders();
} catch (ClassCastException e) {
throw new MessagingException("Message content is not MimeMultipart", e);
}
}
else if (!content.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 (content.match("text/*")) {
// the charset should be specified as a parameter on the MIME type. If not there,
// try to figure one out.
if (content.getParameter("charset") == null) {
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")) {
content.setParameter("charset", "us-ascii");
}
else {
// get the global default.
content.setParameter("charset", MimeUtility.getDefaultMIMECharset());
}
// replace the datasource provided type
type = content.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.
String disp = getHeader("Content-Disposition", null);
if (disp != null) {
// parse up the string value of the disposition
ContentDisposition disposition = new ContentDisposition(disp);
// now check for a filename value
String filename = disposition.getParameter("filename");
// copy and rename the parameter, if it exists.
if (filename != null) {
content.setParameter("name", filename);
// and update the string version
type = content.toString();
}
}
// set the header with the updated content type information.
setHeader("Content-Type", type);
}
} catch (IOException e) {
throw new MessagingException("Error updating message headers", e);
}
}
private String getSingleHeader(String name) throws MessagingException {
String[] values = getHeader(name);
if (values == null || values.length == 0) {
return null;
} else {
return values[0];
}
}
/**
* Attach a file to this body part from a File object.
*
* @param file The source File object.
*
* @exception IOException
* @exception MessagingException
*/
public void attachFile(File file) throws IOException, MessagingException {
FileDataSource dataSource = new FileDataSource(file);
setDataHandler(new DataHandler(dataSource));
setFileName(dataSource.getName());
}
/**
* Attach a file to this body part from a file name.
*
* @param file The source file name.
*
* @exception IOException
* @exception MessagingException
*/
public void attachFile(String file) throws IOException, MessagingException {
// just create a File object and attach.
attachFile(new File(file));
}
/**
* 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(File file) throws IOException, MessagingException {
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
// we need to read the data in to write it out (sigh).
InputStream in = getInputStream();
try {
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(String file) throws IOException, MessagingException {
saveFile(new File(file));
}
}
| 1,039 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/InternetAddress.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.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.mail.Address;
import javax.mail.Session;
import org.apache.geronimo.mail.util.SessionUtil;
/**
* A representation of an Internet email address as specified by RFC822 in
* conjunction with a human-readable personal name that can be encoded as
* specified by RFC2047.
* A typical address is "user@host.domain" and personal name "Joe User"
*
* @version $Rev$ $Date$
*/
public class InternetAddress extends Address implements Cloneable {
private static final long serialVersionUID = -7507595530758302903L;
/**
* The address in RFC822 format.
*/
protected String address;
/**
* The personal name in RFC2047 format.
* Subclasses must ensure that this field is updated if the personal field
* is updated; alternatively, it can be invalidated by setting to null
* which will cause it to be recomputed.
*/
protected String encodedPersonal;
/**
* The personal name as a Java String.
* Subclasses must ensure that this field is updated if the encodedPersonal field
* is updated; alternatively, it can be invalidated by setting to null
* which will cause it to be recomputed.
*/
protected String personal;
public InternetAddress() {
}
public InternetAddress(String address) throws AddressException {
this(address, true);
}
public InternetAddress(String address, boolean strict) throws AddressException {
// use the parse method to process the address. This has the wierd side effect of creating a new
// InternetAddress instance to create an InternetAddress, but these are lightweight objects and
// we need access to multiple pieces of data from the parsing process.
AddressParser parser = new AddressParser(address, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
InternetAddress parsedAddress = parser.parseAddress();
// copy the important information, which right now is just the address and
// personal info.
this.address = parsedAddress.address;
this.personal = parsedAddress.personal;
this.encodedPersonal = parsedAddress.encodedPersonal;
}
public InternetAddress(String address, String personal) throws UnsupportedEncodingException {
this(address, personal, null);
}
public InternetAddress(String address, String personal, String charset) throws UnsupportedEncodingException {
this.address = address;
setPersonal(personal, charset);
}
/**
* Clone this object.
*
* @return a copy of this object as created by Object.clone()
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new Error();
}
}
/**
* Return the type of this address.
*
* @return the type of this address; always "rfc822"
*/
public String getType() {
return "rfc822";
}
/**
* Set the address.
* No validation is performed; validate() can be used to check if it is valid.
*
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* Set the personal name.
* The name is first checked to see if it can be encoded; if this fails then an
* UnsupportedEncodingException is thrown and no fields are modified.
*
* @param name the new personal name
* @param charset the charset to use; see {@link MimeUtility#encodeWord(String, String, String) MimeUtilityencodeWord}
* @throws UnsupportedEncodingException if the name cannot be encoded
*/
public void setPersonal(String name, String charset) throws UnsupportedEncodingException {
personal = name;
if (name != null) {
encodedPersonal = MimeUtility.encodeWord(name, charset, null);
}
else {
encodedPersonal = null;
}
}
/**
* Set the personal name.
* The name is first checked to see if it can be encoded using {@link MimeUtility#encodeWord(String)}; if this fails then an
* UnsupportedEncodingException is thrown and no fields are modified.
*
* @param name the new personal name
* @throws UnsupportedEncodingException if the name cannot be encoded
*/
public void setPersonal(String name) throws UnsupportedEncodingException {
personal = name;
if (name != null) {
encodedPersonal = MimeUtility.encodeWord(name);
}
else {
encodedPersonal = null;
}
}
/**
* Return the address.
*
* @return the address
*/
public String getAddress() {
return address;
}
/**
* Return the personal name.
* If the personal field is null, then an attempt is made to decode the encodedPersonal
* field using {@link MimeUtility#decodeWord(String)}; if this is sucessful, then
* the personal field is updated with that value and returned; if there is a problem
* decoding the text then the raw value from encodedPersonal is returned.
*
* @return the personal name
*/
public String getPersonal() {
if (personal == null && encodedPersonal != null) {
try {
personal = MimeUtility.decodeWord(encodedPersonal);
} catch (ParseException e) {
return encodedPersonal;
} catch (UnsupportedEncodingException e) {
return encodedPersonal;
}
}
return personal;
}
/**
* Return the encoded form of the personal name.
* If the encodedPersonal field is null, then an attempt is made to encode the
* personal field using {@link MimeUtility#encodeWord(String)}; if this is
* successful then the encodedPersonal field is updated with that value and returned;
* if there is a problem encoding the text then null is returned.
*
* @return the encoded form of the personal name
*/
private String getEncodedPersonal() {
if (encodedPersonal == null && personal != null) {
try {
encodedPersonal = MimeUtility.encodeWord(personal);
} catch (UnsupportedEncodingException e) {
// as we could not encode this, return null
return null;
}
}
return encodedPersonal;
}
/**
* Return a string representation of this address using only US-ASCII characters.
*
* @return a string representation of this address
*/
public String toString() {
// group addresses are always returned without modification.
if (isGroup()) {
return address;
}
// if we have personal information, then we need to return this in the route-addr form:
// "personal <address>". If there is no personal information, then we typically return
// the address without the angle brackets. However, if the address contains anything other
// than atoms, '@', and '.' (e.g., uses domain literals, has specified routes, or uses
// quoted strings in the local-part), we bracket the address.
String p = getEncodedPersonal();
if (p == null) {
return formatAddress(address);
}
else {
StringBuffer buf = new StringBuffer(p.length() + 8 + address.length() + 3);
buf.append(AddressParser.quoteString(p));
buf.append(" <").append(address).append(">");
return buf.toString();
}
}
/**
* Check the form of an address, and enclose it within brackets
* if they are required for this address form.
*
* @param a The source address.
*
* @return A formatted address, which can be the original address string.
*/
private String formatAddress(String a)
{
// this could be a group address....we don't muck with those.
if (address.endsWith(";") && address.indexOf(":") > 0) {
return address;
}
if (AddressParser.containsCharacters(a, "()<>,;:\"[]")) {
StringBuffer buf = new StringBuffer(address.length() + 3);
buf.append("<").append(address).append(">");
return buf.toString();
}
return address;
}
/**
* Return a string representation of this address using Unicode characters.
*
* @return a string representation of this address
*/
public String toUnicodeString() {
// group addresses are always returned without modification.
if (isGroup()) {
return address;
}
// if we have personal information, then we need to return this in the route-addr form:
// "personal <address>". If there is no personal information, then we typically return
// the address without the angle brackets. However, if the address contains anything other
// than atoms, '@', and '.' (e.g., uses domain literals, has specified routes, or uses
// quoted strings in the local-part), we bracket the address.
// NB: The difference between toString() and toUnicodeString() is the use of getPersonal()
// vs. getEncodedPersonal() for the personal portion. If the personal information contains only
// ASCII-7 characters, these are the same.
String p = getPersonal();
if (p == null) {
return formatAddress(address);
}
else {
StringBuffer buf = new StringBuffer(p.length() + 8 + address.length() + 3);
buf.append(AddressParser.quoteString(p));
buf.append(" <").append(address).append(">");
return buf.toString();
}
}
/**
* Compares two addresses for equality.
* We define this as true if the other object is an InternetAddress
* and the two values returned by getAddress() are equal in a
* case-insensitive comparison.
*
* @param o the other object
* @return true if the addresses are the same
*/
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof InternetAddress)) return false;
InternetAddress other = (InternetAddress) o;
String myAddress = getAddress();
return myAddress == null ? (other.getAddress() == null) : myAddress.equalsIgnoreCase(other.getAddress());
}
/**
* Return the hashCode for this address.
* We define this to be the hashCode of the address after conversion to lowercase.
*
* @return a hashCode for this address
*/
public int hashCode() {
return (address == null) ? 0 : address.toLowerCase().hashCode();
}
/**
* Return true is this address is an RFC822 group address in the format
* <code>phrase ":" [#mailbox] ";"</code>.
* We check this by using the presense of a ':' character in the address, and a
* ';' as the very last character.
*
* @return true is this address represents a group
*/
public boolean isGroup() {
if (address == null) {
return false;
}
return address.endsWith(";") && address.indexOf(":") > 0;
}
/**
* Return the members of a group address.
*
* If strict is true and the address does not contain an initial phrase then an AddressException is thrown.
* Otherwise the phrase is skipped and the remainder of the address is checked to see if it is a group.
* If it is, the content and strict flag are passed to parseHeader to extract the list of addresses;
* if it is not a group then null is returned.
*
* @param strict whether strict RFC822 checking should be performed
* @return an array of InternetAddress objects for the group members, or null if this address is not a group
* @throws AddressException if there was a problem parsing the header
*/
public InternetAddress[] getGroup(boolean strict) throws AddressException {
if (address == null) {
return null;
}
// create an address parser and use it to extract the group information.
AddressParser parser = new AddressParser(address, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
return parser.extractGroupList();
}
/**
* Return an InternetAddress representing the current user.
* <P/>
* If session is not null, we first look for an address specified in its
* "mail.from" property; if this is not set, we look at its "mail.user"
* and "mail.host" properties and if both are not null then an address of
* the form "${mail.user}@${mail.host}" is created.
* If this fails to give an address, then an attempt is made to create
* an address by combining the value of the "user.name" System property
* with the value returned from InetAddress.getLocalHost().getHostName().
* Any SecurityException raised accessing the system property or any
* UnknownHostException raised getting the hostname are ignored.
* <P/>
* Finally, an attempt is made to convert the value obtained above to
* an InternetAddress. If this fails, then null is returned.
*
* @param session used to obtain mail properties
* @return an InternetAddress for the current user, or null if it cannot be determined
*/
public static InternetAddress getLocalAddress(Session session) {
String host = null;
String user = null;
// ok, we have several steps for resolving this. To start with, we could have a from address
// configured already, which will be a full InternetAddress string. If we don't have that, then
// we need to resolve a user and host to compose an address from.
if (session != null) {
String address = session.getProperty("mail.from");
// if we got this, we can skip out now
if (address != null) {
try {
return new InternetAddress(address);
} catch (AddressException e) {
// invalid address on the from...treat this as an error and return null.
return null;
}
}
// now try for user and host information. We have both session and system properties to check here.
// we'll just handle the session ones here, and check the system ones below if we're missing information.
user = session.getProperty("mail.user");
host = session.getProperty("mail.host");
}
try {
// if either user or host is null, then we check non-session sources for the information.
if (user == null) {
user = System.getProperty("user.name");
}
if (host == null) {
host = InetAddress.getLocalHost().getHostName();
}
if (user != null && host != null) {
// if we have both a user and host, we can create a local address
return new InternetAddress(user + '@' + host);
}
} catch (AddressException e) {
// ignore
} catch (UnknownHostException e) {
// ignore
} catch (SecurityException e) {
// ignore
}
return null;
}
/**
* Convert the supplied addresses into a single String of comma-separated text as
* produced by {@link InternetAddress#toString() toString()}.
* No line-break detection is performed.
*
* @param addresses the array of addresses to convert
* @return a one-line String of comma-separated addresses
*/
public static String toString(Address[] addresses) {
if (addresses == null || addresses.length == 0) {
return null;
}
if (addresses.length == 1) {
return addresses[0].toString();
} else {
StringBuffer buf = new StringBuffer(addresses.length * 32);
buf.append(addresses[0].toString());
for (int i = 1; i < addresses.length; i++) {
buf.append(", ");
buf.append(addresses[i].toString());
}
return buf.toString();
}
}
/**
* Convert the supplies addresses into a String of comma-separated text,
* inserting line-breaks between addresses as needed to restrict the line
* length to 72 characters. Splits will only be introduced between addresses
* so an address longer than 71 characters will still be placed on a single
* line.
*
* @param addresses the array of addresses to convert
* @param used the starting column
* @return a String of comma-separated addresses with optional line breaks
*/
public static String toString(Address[] addresses, int used) {
if (addresses == null || addresses.length == 0) {
return null;
}
if (addresses.length == 1) {
String s = addresses[0].toString();
if (used + s.length() > 72) {
s = "\r\n " + s;
}
return s;
} else {
StringBuffer buf = new StringBuffer(addresses.length * 32);
for (int i = 0; i < addresses.length; i++) {
String s = addresses[1].toString();
if (i == 0) {
if (used + s.length() + 1 > 72) {
buf.append("\r\n ");
used = 2;
}
} else {
if (used + s.length() + 1 > 72) {
buf.append(",\r\n ");
used = 2;
} else {
buf.append(", ");
used += 2;
}
}
buf.append(s);
used += s.length();
}
return buf.toString();
}
}
/**
* Parse addresses out of the string with basic checking.
*
* @param addresses the addresses to parse
* @return an array of InternetAddresses parsed from the string
* @throws AddressException if addresses checking fails
*/
public static InternetAddress[] parse(String addresses) throws AddressException {
return parse(addresses, true);
}
/**
* Parse addresses out of the string.
*
* @param addresses the addresses to parse
* @param strict if true perform detailed checking, if false just perform basic checking
* @return an array of InternetAddresses parsed from the string
* @throws AddressException if address checking fails
*/
public static InternetAddress[] parse(String addresses, boolean strict) throws AddressException {
return parse(addresses, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
}
/**
* Parse addresses out of the string.
*
* @param addresses the addresses to parse
* @param strict if true perform detailed checking, if false perform little checking
* @return an array of InternetAddresses parsed from the string
* @throws AddressException if address checking fails
*/
public static InternetAddress[] parseHeader(String addresses, boolean strict) throws AddressException {
return parse(addresses, strict ? AddressParser.STRICT : AddressParser.PARSE_HEADER);
}
/**
* Parse addresses with increasing degrees of RFC822 compliance checking.
*
* @param addresses the string to parse
* @param level The required strictness level.
*
* @return an array of InternetAddresses parsed from the string
* @throws AddressException
* if address checking fails
*/
private static InternetAddress[] parse(String addresses, int level) throws AddressException {
// create a parser and have it extract the list using the requested strictness leve.
AddressParser parser = new AddressParser(addresses, level);
return parser.parseAddressList();
}
/**
* Validate the address portion of an internet address to ensure
* validity. Throws an AddressException if any validity
* problems are encountered.
*
* @exception AddressException
*/
public void validate() throws AddressException {
// create a parser using the strictest validation level.
AddressParser parser = new AddressParser(formatAddress(address), AddressParser.STRICT);
parser.validateAddress();
}
}
| 1,040 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/ParameterList.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.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;// Represents lists in things like
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.geronimo.mail.util.ASCIIUtil;
import org.apache.geronimo.mail.util.RFC2231Encoder;
import org.apache.geronimo.mail.util.SessionUtil;
// Content-Type: text/plain;charset=klingon
//
// The ;charset=klingon is the parameter list, may have more of them with ';'
/**
* @version $Rev$ $Date$
*/
public class ParameterList {
private static final String MIME_ENCODEPARAMETERS = "mail.mime.encodeparameters";
private static final String MIME_DECODEPARAMETERS = "mail.mime.decodeparameters";
private static final String MIME_DECODEPARAMETERS_STRICT = "mail.mime.decodeparameters.strict";
private static final int HEADER_SIZE_LIMIT = 76;
private final Map _parameters = new LinkedHashMap(); //predictable iteration order, see toString()
private boolean encodeParameters = false;
private boolean decodeParameters = false;
private boolean decodeParametersStrict = false;
public ParameterList() {
// figure out how parameter handling is to be performed.
getInitialProperties();
}
public ParameterList(String list) throws ParseException {
// figure out how parameter handling is to be performed.
getInitialProperties();
// get a token parser for the type information
HeaderTokenizer tokenizer = new HeaderTokenizer(list, HeaderTokenizer.MIME);
while (true) {
HeaderTokenizer.Token token = tokenizer.next();
switch (token.getType()) {
// the EOF token terminates parsing.
case HeaderTokenizer.Token.EOF:
return;
// each new parameter is separated by a semicolon, including the first, which separates
// the parameters from the main part of the header.
case ';':
// the next token needs to be a parameter name
token = tokenizer.next();
// allow a trailing semicolon on the parameters.
if (token.getType() == HeaderTokenizer.Token.EOF) {
return;
}
if (token.getType() != HeaderTokenizer.Token.ATOM) {
throw new ParseException("Invalid parameter name: " + token.getValue());
}
// get the parameter name as a lower case version for better mapping.
String name = token.getValue().toLowerCase();
token = tokenizer.next();
// parameters are name=value, so we must have the "=" here.
if (token.getType() != '=') {
throw new ParseException("Missing '='");
}
// now the value, which may be an atom or a literal
token = tokenizer.next();
if (token.getType() != HeaderTokenizer.Token.ATOM && token.getType() != HeaderTokenizer.Token.QUOTEDSTRING) {
throw new ParseException("Invalid parameter value: " + token.getValue());
}
String value = token.getValue();
String decodedValue = null;
// we might have to do some additional decoding. A name that ends with "*"
// is marked as being encoded, so if requested, we decode the value.
if (decodeParameters && name.endsWith("*")) {
// the name needs to be pruned of the marker, and we need to decode the value.
name = name.substring(0, name.length() - 1);
// get a new decoder
RFC2231Encoder decoder = new RFC2231Encoder(HeaderTokenizer.MIME);
try {
// decode the value
decodedValue = decoder.decode(value);
} catch (Exception e) {
// if we're doing things strictly, then raise a parsing exception for errors.
// otherwise, leave the value in its current state.
if (decodeParametersStrict) {
throw new ParseException("Invalid RFC2231 encoded parameter");
}
}
_parameters.put(name, new ParameterValue(name, decodedValue, value));
}
else {
_parameters.put(name, new ParameterValue(name, value));
}
break;
default:
throw new ParseException("Missing ';'");
}
}
}
/**
* Get the initial parameters that control parsing and values.
* These parameters are controlled by System properties.
*/
private void getInitialProperties() {
decodeParameters = SessionUtil.getBooleanProperty(MIME_DECODEPARAMETERS, false);
decodeParametersStrict = SessionUtil.getBooleanProperty(MIME_DECODEPARAMETERS_STRICT, false);
encodeParameters = SessionUtil.getBooleanProperty(MIME_ENCODEPARAMETERS, true);
}
public int size() {
return _parameters.size();
}
public String get(String name) {
ParameterValue value = (ParameterValue)_parameters.get(name.toLowerCase());
if (value != null) {
return value.value;
}
return null;
}
public void set(String name, String value) {
name = name.toLowerCase();
_parameters.put(name, new ParameterValue(name, value));
}
public void set(String name, String value, String charset) {
name = name.toLowerCase();
// only encode if told to and this contains non-ASCII charactes.
if (encodeParameters && !ASCIIUtil.isAscii(value)) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
RFC2231Encoder encoder = new RFC2231Encoder(HeaderTokenizer.MIME);
// extract the bytes using the given character set and encode
byte[] valueBytes = value.getBytes(MimeUtility.javaCharset(charset));
// the string format is charset''data
out.write(charset.getBytes("ISO8859-1"));
out.write('\'');
out.write('\'');
encoder.encode(valueBytes, 0, valueBytes.length, out);
// default in case there is an exception
_parameters.put(name, new ParameterValue(name, value, new String(out.toByteArray(), "ISO8859-1")));
return;
} catch (Exception e) {
// just fall through and set the value directly if there is an error
}
}
// default in case there is an exception
_parameters.put(name, new ParameterValue(name, value));
}
public void remove(String name) {
_parameters.remove(name);
}
public Enumeration getNames() {
return Collections.enumeration(_parameters.keySet());
}
public String toString() {
// we need to perform folding, but out starting point is 0.
return toString(0);
}
public String toString(int used) {
StringBuffer stringValue = new StringBuffer();
Iterator entries = _parameters.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
ParameterValue parm = (ParameterValue) entry.getValue();
// get the values we're going to encode in here.
String name = parm.getEncodedName();
String value = parm.toString();
// add the semicolon separator. We also add a blank so that folding/unfolding rules can be used.
stringValue.append("; ");
used += 2;
// too big for the current header line?
if ((used + name.length() + value.length() + 1) > HEADER_SIZE_LIMIT) {
// and a CRLF-combo combo.
stringValue.append("\r\n\t");
// reset the counter for a fresh line
// note we use use 8 because we're using a rather than a blank
used = 8;
}
// now add the keyword/value pair.
stringValue.append(name);
stringValue.append("=");
used += name.length() + 1;
// we're not out of the woods yet. It is possible that the keyword/value pair by itself might
// be too long for a single line. If that's the case, the we need to fold the value, if possible
if (used + value.length() > HEADER_SIZE_LIMIT) {
String foldedValue = MimeUtility.fold(used, value);
stringValue.append(foldedValue);
// now we need to sort out how much of the current line is in use.
int lastLineBreak = foldedValue.lastIndexOf('\n');
if (lastLineBreak != -1) {
used = foldedValue.length() - lastLineBreak + 1;
}
else {
used += foldedValue.length();
}
}
else {
// no folding required, just append.
stringValue.append(value);
used += value.length();
}
}
return stringValue.toString();
}
/**
* Utility class for representing parameter values in the list.
*/
class ParameterValue {
public String name; // the name of the parameter
public String value; // the original set value
public String encodedValue; // an encoded value, if encoding is requested.
public ParameterValue(String name, String value) {
this.name = name;
this.value = value;
this.encodedValue = null;
}
public ParameterValue(String name, String value, String encodedValue) {
this.name = name;
this.value = value;
this.encodedValue = encodedValue;
}
public String toString() {
if (encodedValue != null) {
return MimeUtility.quote(encodedValue, HeaderTokenizer.MIME);
}
return MimeUtility.quote(value, HeaderTokenizer.MIME);
}
public String getEncodedName() {
if (encodedValue != null) {
return name + "*";
}
return name;
}
}
}
| 1,041 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/InternetHeaders.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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.mail.Address;
import javax.mail.Header;
import javax.mail.MessagingException;
/**
* Class that represents the RFC822 headers associated with a message.
*
* @version $Rev$ $Date$
*/
public class InternetHeaders {
// the list of headers (to preserve order);
protected List headers = new ArrayList();
private transient String lastHeaderName;
/**
* Create an empty InternetHeaders
*/
public InternetHeaders() {
// these are created in the preferred order of the headers.
addHeader("Return-Path", null);
addHeader("Received", null);
addHeader("Resent-Date", null);
addHeader("Resent-From", null);
addHeader("Resent-Sender", null);
addHeader("Resent-To", null);
addHeader("Resent-Cc", null);
addHeader("Resent-Bcc", null);
addHeader("Resent-Message-Id", null);
addHeader("Date", null);
addHeader("From", null);
addHeader("Sender", null);
addHeader("Reply-To", null);
addHeader("To", null);
addHeader("Cc", null);
addHeader("Bcc", null);
addHeader("Message-Id", null);
addHeader("In-Reply-To", null);
addHeader("References", null);
addHeader("Subject", null);
addHeader("Comments", null);
addHeader("Keywords", null);
addHeader("Errors-To", null);
addHeader("MIME-Version", null);
addHeader("Content-Type", null);
addHeader("Content-Transfer-Encoding", null);
addHeader("Content-MD5", null);
// the following is a special marker used to identify new header insertion points.
addHeader(":", null);
addHeader("Content-Length", null);
addHeader("Status", null);
}
/**
* Create a new InternetHeaders initialized by reading headers from the
* stream.
*
* @param in
* the RFC822 input stream to load from
* @throws MessagingException
* if there is a problem pasring the stream
*/
public InternetHeaders(InputStream in) throws MessagingException {
load(in);
}
/**
* Read and parse the supplied stream and add all headers to the current
* set.
*
* @param in
* the RFC822 input stream to load from
* @throws MessagingException
* if there is a problem pasring the stream
*/
public void load(InputStream in) throws MessagingException {
try {
StringBuffer buffer = new StringBuffer(128);
String line;
// loop until we hit the end or a null line
while ((line = readLine(in)) != null) {
// lines beginning with white space get special handling
if (line.startsWith(" ") || line.startsWith("\t")) {
// this gets handled using the logic defined by
// the addHeaderLine method. If this line is a continuation, but
// there's nothing before it, just call addHeaderLine to add it
// to the last header in the headers list
if (buffer.length() == 0) {
addHeaderLine(line);
}
else {
// preserve the line break and append the continuation
buffer.append("\r\n");
buffer.append(line);
}
}
else {
// if we have a line pending in the buffer, flush it
if (buffer.length() > 0) {
addHeaderLine(buffer.toString());
buffer.setLength(0);
}
// add this to the accumulator
buffer.append(line);
}
}
// if we have a line pending in the buffer, flush it
if (buffer.length() > 0) {
addHeaderLine(buffer.toString());
}
} catch (IOException e) {
throw new MessagingException("Error loading headers", e);
}
}
/**
* Read a single line from the input stream
*
* @param in The source stream for the line
*
* @return The string value of the line (without line separators)
*/
private String readLine(InputStream in) throws IOException {
StringBuffer buffer = new StringBuffer(128);
int c;
while ((c = in.read()) != -1) {
// a linefeed is a terminator, always.
if (c == '\n') {
break;
}
// just ignore the CR. The next character SHOULD be an NL. If not, we're
// just going to discard this
else if (c == '\r') {
continue;
}
else {
// just add to the buffer
buffer.append((char)c);
}
}
// no characters found...this was either an eof or a null line.
if (buffer.length() == 0) {
return null;
}
return buffer.toString();
}
/**
* Return all the values for the specified header.
*
* @param name
* the header to return
* @return the values for that header, or null if the header is not present
*/
public String[] getHeader(String name) {
List accumulator = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
if (header.getName().equalsIgnoreCase(name) && header.getValue() != null) {
accumulator.add(header.getValue());
}
}
// this is defined as returning null of nothing is found.
if (accumulator.isEmpty()) {
return null;
}
// convert this to an array.
return (String[])accumulator.toArray(new String[accumulator.size()]);
}
/**
* Return the values for the specified header as a single String. If the
* header has more than one value then all values are concatenated together
* separated by the supplied delimiter.
*
* @param name
* the header to return
* @param delimiter
* the delimiter used in concatenation
* @return the header as a single String
*/
public String getHeader(String name, String delimiter) {
// get all of the headers with this name
String[] matches = getHeader(name);
// no match? return a null.
if (matches == null) {
return null;
}
// a null delimiter means just return the first one. If there's only one item, this is easy too.
if (matches.length == 1 || delimiter == null) {
return matches[0];
}
// perform the concatenation
StringBuffer result = new StringBuffer(matches[0]);
for (int i = 1; i < matches.length; i++) {
result.append(delimiter);
result.append(matches[i]);
}
return result.toString();
}
/**
* Set the value of the header to the supplied value; any existing headers
* are removed.
*
* @param name
* the name of the header
* @param value
* the new value
*/
public void setHeader(String name, String value) {
// look for a header match
for (int i = 0; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
// found a matching header
if (name.equalsIgnoreCase(header.getName())) {
// we update both the name and the value for a set so that
// the header ends up with the same case as what is getting set
header.setValue(value);
header.setName(name);
// remove all of the headers from this point
removeHeaders(name, i + 1);
return;
}
}
// doesn't exist, so process as an add.
addHeader(name, value);
}
/**
* Remove all headers with the given name, starting with the
* specified start position.
*
* @param name The target header name.
* @param pos The position of the first header to examine.
*/
private void removeHeaders(String name, int pos) {
// now go remove all other instances of this header
for (int i = pos; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
// found a matching header
if (name.equalsIgnoreCase(header.getName())) {
// remove this item, and back up
headers.remove(i);
i--;
}
}
}
/**
* Find a header in the current list by name, returning the index.
*
* @param name The target name.
*
* @return The index of the header in the list. Returns -1 for a not found
* condition.
*/
private int findHeader(String name) {
return findHeader(name, 0);
}
/**
* Find a header in the current list, beginning with the specified
* start index.
*
* @param name The target header name.
* @param start The search start index.
*
* @return The index of the first matching header. Returns -1 if the
* header is not located.
*/
private int findHeader(String name, int start) {
for (int i = start; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
// found a matching header
if (name.equalsIgnoreCase(header.getName())) {
return i;
}
}
return -1;
}
/**
* Add a new value to the header with the supplied name.
*
* @param name
* the name of the header to add a new value for
* @param value
* another value
*/
public void addHeader(String name, String value) {
InternetHeader newHeader = new InternetHeader(name, value);
// The javamail spec states that "Recieved" headers need to be added in reverse order.
// Return-Path is permitted before Received, so handle it the same way.
if (name.equalsIgnoreCase("Received") || name.equalsIgnoreCase("Return-Path")) {
// see if we have one of these already
int pos = findHeader(name);
// either insert before an existing header, or insert at the very beginning
if (pos != -1) {
// this could be a placeholder header with a null value. If it is, just update
// the value. Otherwise, insert in front of the existing header.
InternetHeader oldHeader = (InternetHeader)headers.get(pos);
if (oldHeader.getValue() == null) {
oldHeader.setValue(value);
}
else {
headers.add(pos, newHeader);
}
}
else {
// doesn't exist, so insert at the beginning
headers.add(0, newHeader);
}
}
// normal insertion
else {
// see if we have one of these already
int pos = findHeader(name);
// either insert before an existing header, or insert at the very beginning
if (pos != -1) {
InternetHeader oldHeader = (InternetHeader)headers.get(pos);
// if the existing header is a place holder, we can just update the value
if (oldHeader.getValue() == null) {
oldHeader.setValue(value);
}
else {
// we have at least one existing header with this name. We need to find the last occurrance,
// and insert after that spot.
int lastPos = findHeader(name, pos + 1);
while (lastPos != -1) {
pos = lastPos;
lastPos = findHeader(name, pos + 1);
}
// ok, we have the insertion position
headers.add(pos + 1, newHeader);
}
}
else {
// find the insertion marker. If that is missing somehow, insert at the end.
pos = findHeader(":");
if (pos == -1) {
pos = headers.size();
}
headers.add(pos, newHeader);
}
}
}
/**
* Remove all header entries with the supplied name
*
* @param name
* the header to remove
*/
public void removeHeader(String name) {
// the first occurrance of a header is just zeroed out.
int pos = findHeader(name);
if (pos != -1) {
InternetHeader oldHeader = (InternetHeader)headers.get(pos);
// keep the header in the list, but with a null value
oldHeader.setValue(null);
// now remove all other headers with this name
removeHeaders(name, pos + 1);
}
}
/**
* Return all headers.
*
* @return an Enumeration<Header> containing all headers
*/
public Enumeration getAllHeaders() {
List result = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
result.add(header);
}
}
// just return a list enumerator for the header list.
return Collections.enumeration(result);
}
/**
* Test if a given header name is a match for any header in the
* given list.
*
* @param name The name of the current tested header.
* @param names The list of names to match against.
*
* @return True if this is a match for any name in the list, false
* for a complete mismatch.
*/
private boolean matchHeader(String name, String[] names) {
// the list of names is not required, so treat this as if it
// was an empty list and we didn't get a match.
if (names == null) {
return false;
}
for (int i = 0; i < names.length; i++) {
if (name.equalsIgnoreCase(names[i])) {
return true;
}
}
return false;
}
/**
* Return all matching Header objects.
*/
public Enumeration getMatchingHeaders(String[] names) {
List result = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
// only add the matching ones
if (matchHeader(header.getName(), names)) {
result.add(header);
}
}
}
return Collections.enumeration(result);
}
/**
* Return all non matching Header objects.
*/
public Enumeration getNonMatchingHeaders(String[] names) {
List result = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
// only add the non-matching ones
if (!matchHeader(header.getName(), names)) {
result.add(header);
}
}
}
return Collections.enumeration(result);
}
/**
* Add an RFC822 header line to the header store. If the line starts with a
* space or tab (a continuation line), add it to the last header line in the
* list. Otherwise, append the new header line to the list.
*
* Note that RFC822 headers can only contain US-ASCII characters
*
* @param line
* raw RFC822 header line
*/
public void addHeaderLine(String line) {
// null lines are a nop
if (line.length() == 0) {
return;
}
// we need to test the first character to see if this is a continuation whitespace
char ch = line.charAt(0);
// tabs and spaces are special. This is a continuation of the last header in the list.
if (ch == ' ' || ch == '\t') {
int size = headers.size();
// it's possible that we have a leading blank line.
if (size > 0) {
InternetHeader header = (InternetHeader)headers.get(size - 1);
header.appendValue(line);
}
}
else {
// this just gets appended to the end, preserving the addition order.
headers.add(new InternetHeader(line));
}
}
/**
* Return all the header lines as an Enumeration of Strings.
*/
public Enumeration getAllHeaderLines() {
return new HeaderLineEnumeration(getAllHeaders());
}
/**
* Return all matching header lines as an Enumeration of Strings.
*/
public Enumeration getMatchingHeaderLines(String[] names) {
return new HeaderLineEnumeration(getMatchingHeaders(names));
}
/**
* Return all non-matching header lines.
*/
public Enumeration getNonMatchingHeaderLines(String[] names) {
return new HeaderLineEnumeration(getNonMatchingHeaders(names));
}
/**
* Set an internet header from a list of addresses. The
* first address item is set, followed by a series of addHeaders().
*
* @param name The name to set.
* @param addresses The list of addresses to set.
*/
void setHeader(String name, Address[] addresses) {
// if this is empty, then we need to replace this
if (addresses.length == 0) {
removeHeader(name);
} else {
// replace the first header
setHeader(name, addresses[0].toString());
// now add the rest as extra headers.
for (int i = 1; i < addresses.length; i++) {
Address address = addresses[i];
addHeader(name, address.toString());
}
}
}
/**
* Write out the set of headers, except for any
* headers specified in the optional ignore list.
*
* @param out The output stream.
* @param ignore The optional ignore list.
*
* @exception IOException
*/
void writeTo(OutputStream out, String[] ignore) throws IOException {
if (ignore == null) {
// write out all header lines with non-null values
for (int i = 0; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
header.writeTo(out);
}
}
}
else {
// write out all matching header lines with non-null values
for (int i = 0; i < headers.size(); i++) {
InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
if (!matchHeader(header.getName(), ignore)) {
header.writeTo(out);
}
}
}
}
}
protected static final class InternetHeader extends Header {
public InternetHeader(String h) {
// initialize with null values, which we'll update once we parse the string
super("", "");
int separator = h.indexOf(':');
// no separator, then we take this as a name with a null string value.
if (separator == -1) {
name = h.trim();
}
else {
name = h.substring(0, separator);
// step past the separator. Now we need to remove any leading white space characters.
separator++;
while (separator < h.length()) {
char ch = h.charAt(separator);
if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') {
break;
}
separator++;
}
value = h.substring(separator);
}
}
public InternetHeader(String name, String value) {
super(name, value);
}
/**
* Package scope method for setting the header value.
*
* @param value The new header value.
*/
void setValue(String value) {
this.value = value;
}
/**
* Package scope method for setting the name value.
*
* @param name The new header name
*/
void setName(String name) {
this.name = name;
}
/**
* Package scope method for extending a header value.
*
* @param value The appended header value.
*/
void appendValue(String value) {
if (this.value == null) {
this.value = value;
}
else {
this.value = this.value + "\r\n" + value;
}
}
void writeTo(OutputStream out) throws IOException {
out.write(name.getBytes("ISO8859-1"));
out.write(':');
out.write(' ');
out.write(value.getBytes("ISO8859-1"));
out.write('\r');
out.write('\n');
}
}
private static class HeaderLineEnumeration implements Enumeration {
private Enumeration headers;
public HeaderLineEnumeration(Enumeration headers) {
this.headers = headers;
}
public boolean hasMoreElements() {
return headers.hasMoreElements();
}
public Object nextElement() {
Header h = (Header) headers.nextElement();
return h.getName() + ": " + h.getValue();
}
}
}
| 1,042 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/ContentDisposition.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;
// http://www.faqs.org/rfcs/rfc2183.html
/**
* @version $Rev$ $Date$
*/
public class ContentDisposition {
private String _disposition;
private ParameterList _list;
public ContentDisposition() {
setDisposition(null);
setParameterList(null);
}
public ContentDisposition(String disposition) throws ParseException {
// get a token parser for the type information
HeaderTokenizer tokenizer = new HeaderTokenizer(disposition, HeaderTokenizer.MIME);
// get the first token, which must be an ATOM
HeaderTokenizer.Token token = tokenizer.next();
if (token.getType() != HeaderTokenizer.Token.ATOM) {
throw new ParseException("Invalid content disposition");
}
_disposition = token.getValue();
// the remainder is parameters, which ParameterList will take care of parsing.
String remainder = tokenizer.getRemainder();
if (remainder != null) {
_list = new ParameterList(remainder);
}
}
public ContentDisposition(String disposition, ParameterList list) {
setDisposition(disposition);
setParameterList(list);
}
public String getDisposition() {
return _disposition;
}
public String getParameter(String name) {
if (_list == null) {
return null;
} else {
return _list.get(name);
}
}
public ParameterList getParameterList() {
return _list;
}
public void setDisposition(String string) {
_disposition = string;
}
public void setParameter(String name, String value) {
if (_list == null) {
_list = new ParameterList();
}
_list.set(name, value);
}
public void setParameterList(ParameterList list) {
if (list == null) {
_list = new ParameterList();
} else {
_list = list;
}
}
public String toString() {
// it is possible we might have a parameter list, but this is meaningless if
// there is no disposition string. Return a failure.
if (_disposition == null) {
return null;
}
// no parameter list? Just return the disposition string
if (_list == null) {
return _disposition;
}
// format this for use on a Content-Disposition header, which means we need to
// account for the length of the header part too.
return _disposition + _list.toString("Content-Disposition".length() + _disposition.length());
}
}
| 1,043 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/AddressException.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;
/**
* @version $Rev$ $Date$
*/
public class AddressException extends ParseException {
private static final long serialVersionUID = 9134583443539323120L;
protected int pos;
protected String ref;
public AddressException() {
this(null);
}
public AddressException(String message) {
this(message, null);
}
public AddressException(String message, String ref) {
this(message, null, -1);
}
public AddressException(String message, String ref, int pos) {
super(message);
this.ref = ref;
this.pos = pos;
}
public String getRef() {
return ref;
}
public int getPos() {
return pos;
}
public String toString() {
return super.toString() + " (" + ref + "," + pos + ")";
}
}
| 1,044 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/MailDateFormat.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.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* Formats ths date as specified by
* draft-ietf-drums-msg-fmt-08 dated January 26, 2000
* which supercedes RFC822.
* <p/>
* <p/>
* The format used is <code>EEE, d MMM yyyy HH:mm:ss Z</code> and
* locale is always US-ASCII.
*
* @version $Rev$ $Date$
*/
public class MailDateFormat extends SimpleDateFormat {
private static final long serialVersionUID = -8148227605210628779L;
public MailDateFormat() {
super("EEE, d MMM yyyy HH:mm:ss Z (z)", Locale.US);
}
public StringBuffer format(Date date, StringBuffer buffer, FieldPosition position) {
return super.format(date, buffer, position);
}
/**
* Parse a Mail date into a Date object. This uses fairly
* lenient rules for the format because the Mail standards
* for dates accept multiple formats.
*
* @param string The input string.
* @param position The position argument.
*
* @return The Date object with the information inside.
*/
public Date parse(String string, ParsePosition position) {
MailDateParser parser = new MailDateParser(string, position);
try {
return parser.parse(isLenient());
} catch (ParseException e) {
e.printStackTrace();
// just return a null for any parsing errors
return null;
}
}
/**
* The calendar cannot be set
* @param calendar
* @throws UnsupportedOperationException
*/
public void setCalendar(Calendar calendar) {
throw new UnsupportedOperationException();
}
/**
* The format cannot be set
* @param format
* @throws UnsupportedOperationException
*/
public void setNumberFormat(NumberFormat format) {
throw new UnsupportedOperationException();
}
// utility class for handling date parsing issues
class MailDateParser {
// our list of defined whitespace characters
static final String whitespace = " \t\r\n";
// current parsing position
int current;
// our end parsing position
int endOffset;
// the date source string
String source;
// The parsing position. We update this as we move along and
// also for any parsing errors
ParsePosition pos;
public MailDateParser(String source, ParsePosition pos)
{
this.source = source;
this.pos = pos;
// we start using the providing parsing index.
this.current = pos.getIndex();
this.endOffset = source.length();
}
/**
* Parse the timestamp, returning a date object.
*
* @param lenient The lenient setting from the Formatter object.
*
* @return A Date object based off of parsing the date string.
* @exception ParseException
*/
public Date parse(boolean lenient) throws ParseException {
// we just skip over any next date format, which means scanning ahead until we
// find the first numeric character
locateNumeric();
// the day can be either 1 or two digits
int day = parseNumber(1, 2);
// step over the delimiter
skipDateDelimiter();
// parse off the month (which is in character format)
int month = parseMonth();
// step over the delimiter
skipDateDelimiter();
// now pull of the year, which can be either 2-digit or 4-digit
int year = parseYear();
// white space is required here
skipRequiredWhiteSpace();
// accept a 1 or 2 digit hour
int hour = parseNumber(1, 2);
skipRequiredChar(':');
// the minutes must be two digit
int minutes = parseNumber(2, 2);
// the seconds are optional, but the ":" tells us if they are to
// be expected.
int seconds = 0;
if (skipOptionalChar(':')) {
seconds = parseNumber(2, 2);
}
// skip over the white space
skipWhiteSpace();
// and finally the timezone information
int offset = parseTimeZone();
// set the index of how far we've parsed this
pos.setIndex(current);
// create a calendar for creating the date
Calendar greg = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
// we inherit the leniency rules
greg.setLenient(lenient);
greg.set(year, month, day, hour, minutes, seconds);
// now adjust by the offset. This seems a little strange, but we
// need to negate the offset because this is a UTC calendar, so we need to
// apply the reverse adjustment. for example, for the EST timezone, the offset
// value will be -300 (5 hours). If the time was 15:00:00, the UTC adjusted time
// needs to be 20:00:00, so we subract -300 minutes.
greg.add(Calendar.MINUTE, -offset);
// now return this timestamp.
return greg.getTime();
}
/**
* Skip over a position where there's a required value
* expected.
*
* @param ch The required character.
*
* @exception ParseException
*/
private void skipRequiredChar(char ch) throws ParseException {
if (current >= endOffset) {
parseError("Delimiter '" + ch + "' expected");
}
if (source.charAt(current) != ch) {
parseError("Delimiter '" + ch + "' expected");
}
current++;
}
/**
* Skip over a position where iff the position matches the
* character
*
* @param ch The required character.
*
* @return true if the character was there, false otherwise.
* @exception ParseException
*/
private boolean skipOptionalChar(char ch) {
if (current >= endOffset) {
return false;
}
if (source.charAt(current) != ch) {
return false;
}
current++;
return true;
}
/**
* Skip over any white space characters until we find
* the next real bit of information. Will scan completely to the
* end, if necessary.
*/
private void skipWhiteSpace() {
while (current < endOffset) {
// if this is not in the white space list, then success.
if (whitespace.indexOf(source.charAt(current)) < 0) {
return;
}
current++;
}
// everything used up, just return
}
/**
* Skip over any non-white space characters until we find
* either a whitespace char or the end of the data.
*/
private void skipNonWhiteSpace() {
while (current < endOffset) {
// if this is not in the white space list, then success.
if (whitespace.indexOf(source.charAt(current)) >= 0) {
return;
}
current++;
}
// everything used up, just return
}
/**
* Skip over any white space characters until we find
* the next real bit of information. Will scan completely to the
* end, if necessary.
*/
private void skipRequiredWhiteSpace() throws ParseException {
int start = current;
while (current < endOffset) {
// if this is not in the white space list, then success.
if (whitespace.indexOf(source.charAt(current)) < 0) {
// we must have at least one white space character
if (start == current) {
parseError("White space character expected");
}
return;
}
current++;
}
// everything used up, just return, but make sure we had at least one
// white space
if (start == current) {
parseError("White space character expected");
}
}
private void parseError(String message) throws ParseException {
// we've got an error, set the index to the end.
pos.setErrorIndex(current);
throw new ParseException(message, current);
}
/**
* Locate an expected numeric field.
*
* @exception ParseException
*/
private void locateNumeric() throws ParseException {
while (current < endOffset) {
// found a digit? we're done
if (Character.isDigit(source.charAt(current))) {
return;
}
current++;
}
// we've got an error, set the index to the end.
parseError("Number field expected");
}
/**
* Parse out an expected numeric field.
*
* @param minDigits The minimum number of digits we expect in this filed.
* @param maxDigits The maximum number of digits expected. Parsing will
* stop at the first non-digit character. An exception will
* be thrown if the field contained more than maxDigits
* in it.
*
* @return The parsed numeric value.
* @exception ParseException
*/
private int parseNumber(int minDigits, int maxDigits) throws ParseException {
int start = current;
int accumulator = 0;
while (current < endOffset) {
char ch = source.charAt(current);
// if this is not a digit character, then quit
if (!Character.isDigit(ch)) {
break;
}
// add the digit value into the accumulator
accumulator = accumulator * 10 + Character.digit(ch, 10);
current++;
}
int fieldLength = current - start;
if (fieldLength < minDigits || fieldLength > maxDigits) {
parseError("Invalid number field");
}
return accumulator;
}
/**
* Skip a delimiter between the date portions of the
* string. The IMAP internal date format uses "-", so
* we either accept a single "-" or any number of white
* space characters (at least one required).
*
* @exception ParseException
*/
private void skipDateDelimiter() throws ParseException {
if (current >= endOffset) {
parseError("Invalid date field delimiter");
}
if (source.charAt(current) == '-') {
current++;
}
else {
// must be at least a single whitespace character
skipRequiredWhiteSpace();
}
}
/**
* Parse a character month name into the date month
* offset.
*
* @return
* @exception ParseException
*/
private int parseMonth() throws ParseException {
if ((endOffset - current) < 3) {
parseError("Invalid month");
}
int monthOffset = 0;
String month = source.substring(current, current + 3).toLowerCase();
if (month.equals("jan")) {
monthOffset = 0;
}
else if (month.equals("feb")) {
monthOffset = 1;
}
else if (month.equals("mar")) {
monthOffset = 2;
}
else if (month.equals("apr")) {
monthOffset = 3;
}
else if (month.equals("may")) {
monthOffset = 4;
}
else if (month.equals("jun")) {
monthOffset = 5;
}
else if (month.equals("jul")) {
monthOffset = 6;
}
else if (month.equals("aug")) {
monthOffset = 7;
}
else if (month.equals("sep")) {
monthOffset = 8;
}
else if (month.equals("oct")) {
monthOffset = 9;
}
else if (month.equals("nov")) {
monthOffset = 10;
}
else if (month.equals("dec")) {
monthOffset = 11;
}
else {
parseError("Invalid month");
}
// ok, this is valid. Update the position and return it
current += 3;
return monthOffset;
}
/**
* Parse off a year field that might be expressed as
* either 2 or 4 digits.
*
* @return The numeric value of the year.
* @exception ParseException
*/
private int parseYear() throws ParseException {
// the year is between 2 to 4 digits
int year = parseNumber(2, 4);
// the two digit years get some sort of adjustment attempted.
if (year < 50) {
year += 2000;
}
else if (year < 100) {
year += 1990;
}
return year;
}
/**
* Parse all of the different timezone options.
*
* @return The timezone offset.
* @exception ParseException
*/
private int parseTimeZone() throws ParseException {
if (current >= endOffset) {
parseError("Missing time zone");
}
// get the first non-blank. If this is a sign character, this
// is a zone offset.
char sign = source.charAt(current);
if (sign == '-' || sign == '+') {
// need to step over the sign character
current++;
// a numeric timezone is always a 4 digit number, but
// expressed as minutes/seconds. I'm too lazy to write a
// different parser that will bound on just a couple of characters, so
// we'll grab this as a single value and adjust
int zoneInfo = parseNumber(4, 4);
int offset = (zoneInfo / 100) * 60 + (zoneInfo % 100);
// negate this, if we have a negativeo offset
if (sign == '-') {
offset = -offset;
}
return offset;
}
else {
// need to parse this out using the obsolete zone names. This will be
// either a 3-character code (defined set), or a single character military
// zone designation.
int start = current;
skipNonWhiteSpace();
String name = source.substring(start, current).toUpperCase();
if (name.length() == 1) {
return militaryZoneOffset(name);
}
else if (name.length() <= 3) {
return namedZoneOffset(name);
}
else {
parseError("Invalid time zone");
}
return 0;
}
}
/**
* Parse the obsolete mail timezone specifiers. The
* allowed set of timezones are terribly US centric.
* That's the spec. The preferred timezone form is
* the +/-mmss form.
*
* @param name The input name.
*
* @return The standard timezone offset for the specifier.
* @exception ParseException
*/
private int namedZoneOffset(String name) throws ParseException {
// NOTE: This is "UT", NOT "UTC"
if (name.equals("UT")) {
return 0;
}
else if (name.equals("GMT")) {
return 0;
}
else if (name.equals("EST")) {
return -300;
}
else if (name.equals("EDT")) {
return -240;
}
else if (name.equals("CST")) {
return -360;
}
else if (name.equals("CDT")) {
return -300;
}
else if (name.equals("MST")) {
return -420;
}
else if (name.equals("MDT")) {
return -360;
}
else if (name.equals("PST")) {
return -480;
}
else if (name.equals("PDT")) {
return -420;
}
else {
parseError("Invalid time zone");
return 0;
}
}
/**
* Parse a single-character military timezone.
*
* @param name The one-character name.
*
* @return The offset corresponding to the military designation.
*/
private int militaryZoneOffset(String name) throws ParseException {
switch (Character.toUpperCase(name.charAt(0))) {
case 'A':
return 60;
case 'B':
return 120;
case 'C':
return 180;
case 'D':
return 240;
case 'E':
return 300;
case 'F':
return 360;
case 'G':
return 420;
case 'H':
return 480;
case 'I':
return 540;
case 'K':
return 600;
case 'L':
return 660;
case 'M':
return 720;
case 'N':
return -60;
case 'O':
return -120;
case 'P':
return -180;
case 'Q':
return -240;
case 'R':
return -300;
case 'S':
return -360;
case 'T':
return -420;
case 'U':
return -480;
case 'V':
return -540;
case 'W':
return -600;
case 'X':
return -660;
case 'Y':
return -720;
case 'Z':
return 0;
default:
parseError("Invalid time zone");
return 0;
}
}
}
}
| 1,045 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/MimeUtility.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.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import org.apache.geronimo.mail.util.ASCIIUtil;
import org.apache.geronimo.mail.util.Base64;
import org.apache.geronimo.mail.util.Base64DecoderStream;
import org.apache.geronimo.mail.util.Base64Encoder;
import org.apache.geronimo.mail.util.Base64EncoderStream;
import org.apache.geronimo.mail.util.SessionUtil;
import org.apache.geronimo.mail.util.UUDecoderStream;
import org.apache.geronimo.mail.util.UUEncoderStream;
import org.apache.james.mime4j.codec.DecodeMonitor;
import org.apache.james.mime4j.codec.DecoderUtil;
import org.apache.james.mime4j.codec.EncoderUtil;
import org.apache.james.mime4j.codec.EncoderUtil.Encoding;
import org.apache.james.mime4j.codec.EncoderUtil.Usage;
import org.apache.james.mime4j.codec.QuotedPrintableInputStream;
import org.apache.james.mime4j.codec.QuotedPrintableOutputStream;
// encodings include "base64", "quoted-printable", "7bit", "8bit" and "binary".
// In addition, "uuencode" is also supported. The
/**
* @version $Rev$ $Date$
*/
public class MimeUtility {
private static final String MIME_FOLDENCODEDWORDS = "mail.mime.foldencodedwords";
private static final String MIME_DECODE_TEXT_STRICT = "mail.mime.decodetext.strict";
private static final String MIME_FOLDTEXT = "mail.mime.foldtext";
private static final int FOLD_THRESHOLD = 76;
private MimeUtility() {
}
public static final int ALL = -1;
//private static String defaultJavaCharset;
private static String escapedChars = "\"\\\r\n";
private static String linearWhiteSpace = " \t\r\n";
//private static String QP_WORD_SPECIALS = "=_?\"#$%&'(),.:;<>@[\\]^`{|}~";
//private static String QP_TEXT_SPECIALS = "=_?";
// the javamail spec includes the ability to map java encoding names to MIME-specified names. Normally,
// these values are loaded from a character mapping file.
private static Map java2mime;
private static Map mime2java;
static {
// we need to load the mapping tables used by javaCharset() and mimeCharset().
loadCharacterSetMappings();
}
public static InputStream decode(InputStream in, String encoding) throws MessagingException {
encoding = encoding.toLowerCase();
// some encodies are just pass-throughs, with no real decoding.
if (encoding.equals("binary") || encoding.equals("7bit") || encoding.equals("8bit")) {
return in;
}
else if (encoding.equals("base64")) {
return new Base64DecoderStream(in);
}
// UUEncode is known by a couple historical extension names too.
else if (encoding.equals("uuencode") || encoding.equals("x-uuencode") || encoding.equals("x-uue")) {
return new UUDecoderStream(in);
}
else if (encoding.equals("quoted-printable")) {
return new QuotedPrintableInputStream(in);
}
else {
throw new MessagingException("Unknown encoding " + encoding);
}
}
/**
* Decode a string of text obtained from a mail header into
* it's proper form. The text generally will consist of a
* string of tokens, some of which may be encoded using
* base64 encoding.
*
* @param text The text to decode.
*
* @return The decoded test string.
* @exception UnsupportedEncodingException
*/
public static String decodeText(String text) throws UnsupportedEncodingException {
// if the text contains any encoded tokens, those tokens will be marked with "=?". If the
// source string doesn't contain that sequent, no decoding is required.
if (text.indexOf("=?") < 0) {
return text;
}
// we have two sets of rules we can apply.
if (!SessionUtil.getBooleanProperty(MIME_DECODE_TEXT_STRICT, true)) {
return decodeTextNonStrict(text);
}
int offset = 0;
int endOffset = text.length();
int startWhiteSpace = -1;
int endWhiteSpace = -1;
StringBuffer decodedText = new StringBuffer(text.length());
boolean previousTokenEncoded = false;
while (offset < endOffset) {
char ch = text.charAt(offset);
// is this a whitespace character?
if (linearWhiteSpace.indexOf(ch) != -1) {
startWhiteSpace = offset;
while (offset < endOffset) {
// step over the white space characters.
ch = text.charAt(offset);
if (linearWhiteSpace.indexOf(ch) != -1) {
offset++;
}
else {
// record the location of the first non lwsp and drop down to process the
// token characters.
endWhiteSpace = offset;
break;
}
}
}
else {
// we have a word token. We need to scan over the word and then try to parse it.
int wordStart = offset;
while (offset < endOffset) {
// step over the white space characters.
ch = text.charAt(offset);
if (linearWhiteSpace.indexOf(ch) == -1) {
offset++;
}
else {
break;
}
//NB: Trailing whitespace on these header strings will just be discarded.
}
// pull out the word token.
String word = text.substring(wordStart, offset);
// is the token encoded? decode the word
if (word.startsWith("=?")) {
try {
// if this gives a parsing failure, treat it like a non-encoded word.
String decodedWord = decodeWord(word);
// are any whitespace characters significant? Append 'em if we've got 'em.
if (!previousTokenEncoded) {
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
}
// this is definitely a decoded token.
previousTokenEncoded = true;
// and add this to the text.
decodedText.append(decodedWord);
// we continue parsing from here...we allow parsing errors to fall through
// and get handled as normal text.
continue;
} catch (ParseException e) {
}
}
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(word);
}
}
return decodedText.toString();
}
/**
* Decode a string of text obtained from a mail header into
* it's proper form. The text generally will consist of a
* string of tokens, some of which may be encoded using
* base64 encoding. This is for non-strict decoded for mailers that
* violate the RFC 2047 restriction that decoded tokens must be delimited
* by linear white space. This will scan tokens looking for inner tokens
* enclosed in "=?" -- "?=" pairs.
*
* @param text The text to decode.
*
* @return The decoded test string.
* @exception UnsupportedEncodingException
*/
private static String decodeTextNonStrict(String text) throws UnsupportedEncodingException {
int offset = 0;
int endOffset = text.length();
int startWhiteSpace = -1;
int endWhiteSpace = -1;
StringBuffer decodedText = new StringBuffer(text.length());
boolean previousTokenEncoded = false;
while (offset < endOffset) {
char ch = text.charAt(offset);
// is this a whitespace character?
if (linearWhiteSpace.indexOf(ch) != -1) {
startWhiteSpace = offset;
while (offset < endOffset) {
// step over the white space characters.
ch = text.charAt(offset);
if (linearWhiteSpace.indexOf(ch) != -1) {
offset++;
}
else {
// record the location of the first non lwsp and drop down to process the
// token characters.
endWhiteSpace = offset;
break;
}
}
}
else {
// we're at the start of a word token. We potentially need to break this up into subtokens
int wordStart = offset;
while (offset < endOffset) {
// step over the white space characters.
ch = text.charAt(offset);
if (linearWhiteSpace.indexOf(ch) == -1) {
offset++;
}
else {
break;
}
//NB: Trailing whitespace on these header strings will just be discarded.
}
// pull out the word token.
String word = text.substring(wordStart, offset);
int decodeStart = 0;
// now scan and process each of the bits within here.
while (decodeStart < word.length()) {
int tokenStart = word.indexOf("=?", decodeStart);
if (tokenStart == -1) {
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(word.substring(decodeStart));
// we're finished.
break;
}
// we have something to process
else {
// we might have a normal token preceeding this.
if (tokenStart != decodeStart) {
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(word.substring(decodeStart, tokenStart));
}
// now find the end marker.
int tokenEnd = word.indexOf("?=", tokenStart);
// sigh, an invalid token. Treat this as plain text.
if (tokenEnd == -1) {
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(word.substring(tokenStart));
// we're finished.
break;
}
else {
// update our ticker
decodeStart = tokenEnd + 2;
String token = word.substring(tokenStart, tokenEnd);
try {
// if this gives a parsing failure, treat it like a non-encoded word.
String decodedWord = decodeWord(token);
// are any whitespace characters significant? Append 'em if we've got 'em.
if (!previousTokenEncoded) {
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
}
// this is definitely a decoded token.
previousTokenEncoded = true;
// and add this to the text.
decodedText.append(decodedWord);
// we continue parsing from here...we allow parsing errors to fall through
// and get handled as normal text.
continue;
} catch (ParseException e) {
}
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(token);
}
}
}
}
}
return decodedText.toString();
}
/**
* Parse a string using the RFC 2047 rules for an "encoded-word"
* type. This encoding has the syntax:
*
* encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
*
* @param word The possibly encoded word value.
*
* @return The decoded word.
* @exception ParseException
* @exception UnsupportedEncodingException
*/
public static String decodeWord(String word) throws ParseException, UnsupportedEncodingException {
// encoded words start with the characters "=?". If this not an encoded word, we throw a
// ParseException for the caller.
if (!word.startsWith("=?")) {
throw new ParseException("Invalid RFC 2047 encoded-word: " + word);
}
int charsetPos = word.indexOf('?', 2);
if (charsetPos == -1) {
throw new ParseException("Missing charset in RFC 2047 encoded-word: " + word);
}
// pull out the character set information (this is the MIME name at this point).
String charset = word.substring(2, charsetPos).toLowerCase();
// now pull out the encoding token the same way.
int encodingPos = word.indexOf('?', charsetPos + 1);
if (encodingPos == -1) {
throw new ParseException("Missing encoding in RFC 2047 encoded-word: " + word);
}
String encoding = word.substring(charsetPos + 1, encodingPos);
// and finally the encoded text.
int encodedTextPos = word.indexOf("?=", encodingPos + 1);
if (encodedTextPos == -1) {
throw new ParseException("Missing encoded text in RFC 2047 encoded-word: " + word);
}
String encodedText = word.substring(encodingPos + 1, encodedTextPos);
// seems a bit silly to encode a null string, but easy to deal with.
if (encodedText.length() == 0) {
return "";
}
try {
// the decoder writes directly to an output stream.
ByteArrayOutputStream out = new ByteArrayOutputStream(encodedText.length());
byte[] encodedData = encodedText.getBytes("US-ASCII");
// Base64 encoded?
if (encoding.equals("B")) {
Base64.decode(encodedData, out);
}
// maybe quoted printable.
else if (encoding.equals("Q")) {
String retVal = DecoderUtil.decodeEncodedWords(word, DecodeMonitor.SILENT);
return retVal;
//QuotedPrintableEncoder dataEncoder = new QuotedPrintableEncoder();
//dataEncoder.decodeWord(encodedData, out);
}
else {
throw new UnsupportedEncodingException("Unknown RFC 2047 encoding: " + encoding);
}
// get the decoded byte data and convert into a string.
byte[] decodedData = out.toByteArray();
return new String(decodedData, javaCharset(charset));
} catch (IOException e) {
throw new UnsupportedEncodingException("Invalid RFC 2047 encoding");
}
}
/**
* Wrap an encoder around a given output stream.
*
* @param out The output stream to wrap.
* @param encoding The name of the encoding.
*
* @return A instance of FilterOutputStream that manages on the fly
* encoding for the requested encoding type.
* @exception MessagingException
*/
public static OutputStream encode(OutputStream out, String encoding) throws MessagingException {
// no encoding specified, so assume it goes out unchanged.
if (encoding == null) {
return out;
}
encoding = encoding.toLowerCase();
// some encodies are just pass-throughs, with no real decoding.
if (encoding.equals("binary") || encoding.equals("7bit") || encoding.equals("8bit")) {
return out;
}
else if (encoding.equals("base64")) {
return new Base64EncoderStream(out);
}
// UUEncode is known by a couple historical extension names too.
else if (encoding.equals("uuencode") || encoding.equals("x-uuencode") || encoding.equals("x-uue")) {
return new UUEncoderStream(out);
}
else if (encoding.equals("quoted-printable")) {
return new QuotedPrintableOutputStream(out, false); //TODO binary false??
}
else {
throw new MessagingException("Unknown encoding " + encoding);
}
}
/**
* Wrap an encoder around a given output stream.
*
* @param out The output stream to wrap.
* @param encoding The name of the encoding.
* @param filename The filename of the data being sent (only used for UUEncode).
*
* @return A instance of FilterOutputStream that manages on the fly
* encoding for the requested encoding type.
* @exception MessagingException
*/
public static OutputStream encode(OutputStream out, String encoding, String filename) throws MessagingException {
encoding = encoding.toLowerCase();
// some encodies are just pass-throughs, with no real decoding.
if (encoding.equals("binary") || encoding.equals("7bit") || encoding.equals("8bit")) {
return out;
}
else if (encoding.equals("base64")) {
return new Base64EncoderStream(out);
}
// UUEncode is known by a couple historical extension names too.
else if (encoding.equals("uuencode") || encoding.equals("x-uuencode") || encoding.equals("x-uue")) {
return new UUEncoderStream(out, filename);
}
else if (encoding.equals("quoted-printable")) {
return new QuotedPrintableOutputStream(out, false); //TODO binary false???
}
else {
throw new MessagingException("Unknown encoding " + encoding);
}
}
public static String encodeText(String word) throws UnsupportedEncodingException {
return encodeText(word, null, null);
}
public static String encodeText(String word, String charset, String encoding) throws UnsupportedEncodingException {
return encodeWord(word, charset, encoding, false);
}
public static String encodeWord(String word) throws UnsupportedEncodingException {
return encodeWord(word, null, null);
}
public static String encodeWord(String word, String charset, String encoding) throws UnsupportedEncodingException {
return encodeWord(word, charset, encoding, true);
}
private static String encodeWord(String word, String charset, String encoding, boolean encodingWord) throws UnsupportedEncodingException {
// figure out what we need to encode this.
String encoder = ASCIIUtil.getTextTransferEncoding(word);
// all ascii? We can return this directly,
if (encoder.equals("7bit")) {
return word;
}
// if not given a charset, use the default.
if (charset == null) {
charset = getDefaultMIMECharset();
}
// sort out the encoder. If not explicitly given, use the best guess we've already established.
if (encoding != null) {
if (encoding.equalsIgnoreCase("B")) {
encoder = "base64";
}
else if (encoding.equalsIgnoreCase("Q")) {
encoder = "quoted-printable";
}
else {
throw new UnsupportedEncodingException("Unknown transfer encoding: " + encoding);
}
}
try {
// we'll format this directly into the string buffer
StringBuffer result = new StringBuffer();
// this is the maximum size of a segment of encoded data, which is based off
// of a 75 character size limit and all of the encoding overhead elements.
int sizeLimit = 75 - 7 - charset.length();
// now do the appropriate encoding work
if (encoder.equals("base64")) {
Base64Encoder dataEncoder = new Base64Encoder();
// this may recurse on the encoding if the string is too long. The left-most will not
// get a segment delimiter
encodeBase64(word, result, sizeLimit, charset, dataEncoder, true, SessionUtil.getBooleanProperty(MIME_FOLDENCODEDWORDS, false));
}
else {
//TODO MIME_FOLDENCODEDWORDS
return EncoderUtil.encodeEncodedWord(word, encodingWord ? Usage.WORD_ENTITY:Usage.TEXT_TOKEN, 0, Charset.forName(charset), Encoding.Q);
//QuotedPrintableEncoder dataEncoder = new QuotedPrintableEncoder();
//encodeQuotedPrintable(word, result, sizeLimit, charset, dataEncoder, true,
// SessionUtil.getBooleanProperty(MIME_FOLDENCODEDWORDS, false), encodingWord ? QP_WORD_SPECIALS : QP_TEXT_SPECIALS);
}
return result.toString();
} catch (IOException e) {
throw new UnsupportedEncodingException("Invalid encoding");
}
}
/**
* Encode a string into base64 encoding, taking into
* account the maximum segment length.
*
* @param data The string data to encode.
* @param out The output buffer used for the result.
* @param sizeLimit The maximum amount of encoded data we're allowed
* to have in a single encoded segment.
* @param charset The character set marker that needs to be added to the
* encoding header.
* @param encoder The encoder instance we're using.
* @param firstSegment
* If true, this is the first (left-most) segment in the
* data. Used to determine if segment delimiters need to
* be added between sections.
* @param foldSegments
* Indicates the type of delimiter to use (blank or newline sequence).
*/
static private void encodeBase64(String data, StringBuffer out, int sizeLimit, String charset, Base64Encoder encoder, boolean firstSegment, boolean foldSegments) throws IOException
{
// this needs to be converted into the appropriate transfer encoding.
byte [] bytes = data.getBytes(javaCharset(charset));
int estimatedSize = encoder.estimateEncodedLength(bytes);
// if the estimated encoding size is over our segment limit, split the string in half and
// recurse. Eventually we'll reach a point where things are small enough.
if (estimatedSize > sizeLimit) {
// the first segment indicator travels with the left half.
encodeBase64(data.substring(0, data.length() / 2), out, sizeLimit, charset, encoder, firstSegment, foldSegments);
// the second half can never be the first segment
encodeBase64(data.substring(data.length() / 2), out, sizeLimit, charset, encoder, false, foldSegments);
}
else
{
// if this is not the first sement of the encoding, we need to add either a blank or
// a newline sequence to the data
if (!firstSegment) {
if (foldSegments) {
out.append("\r\n");
}
else {
out.append(' ');
}
}
// do the encoding of the segment.
encoder.encodeWord(bytes, out, charset);
}
}
/**
* Encode a string into quoted printable encoding, taking into
* account the maximum segment length.
*
* @param data The string data to encode.
* @param out The output buffer used for the result.
* @param sizeLimit The maximum amount of encoded data we're allowed
* to have in a single encoded segment.
* @param charset The character set marker that needs to be added to the
* encoding header.
* @param encoder The encoder instance we're using.
* @param firstSegment
* If true, this is the first (left-most) segment in the
* data. Used to determine if segment delimiters need to
* be added between sections.
* @param foldSegments
* Indicates the type of delimiter to use (blank or newline sequence).
*/
/*static private void encodeQuotedPrintable(String data, StringBuffer out, int sizeLimit, String charset, QuotedPrintableEncoder encoder,
boolean firstSegment, boolean foldSegments, String specials) throws IOException
{
// this needs to be converted into the appropriate transfer encoding.
byte [] bytes = data.getBytes(javaCharset(charset));
int estimatedSize = encoder.estimateEncodedLength(bytes, specials);
// if the estimated encoding size is over our segment limit, split the string in half and
// recurse. Eventually we'll reach a point where things are small enough.
if (estimatedSize > sizeLimit) {
// the first segment indicator travels with the left half.
encodeQuotedPrintable(data.substring(0, data.length() / 2), out, sizeLimit, charset, encoder, firstSegment, foldSegments, specials);
// the second half can never be the first segment
encodeQuotedPrintable(data.substring(data.length() / 2), out, sizeLimit, charset, encoder, false, foldSegments, specials);
}
else
{
// if this is not the first sement of the encoding, we need to add either a blank or
// a newline sequence to the data
if (!firstSegment) {
if (foldSegments) {
out.append("\r\n");
}
else {
out.append(' ');
}
}
// do the encoding of the segment.
encoder.encodeWord(bytes, out, charset, specials);
}
}*/
/**
* Examine the content of a data source and decide what type
* of transfer encoding should be used. For text streams,
* we'll decided between 7bit, quoted-printable, and base64.
* For binary content types, we'll use either 7bit or base64.
*
* @param handler The DataHandler associated with the content.
*
* @return The string name of an encoding used to transfer the content.
*/
public static String getEncoding(DataHandler handler) {
// if this handler has an associated data source, we can read directly from the
// data source to make this judgment. This is generally MUCH faster than asking the
// DataHandler to write out the data for us.
DataSource ds = handler.getDataSource();
if (ds != null) {
return getEncoding(ds);
}
try {
// get a parser that allows us to make comparisons.
ContentType content = new ContentType(handler.getContentType());
// The only access to the content bytes at this point is by asking the handler to write
// the information out to a stream. We're going to pipe this through a special stream
// that examines the bytes as they go by.
ContentCheckingOutputStream checker = new ContentCheckingOutputStream();
handler.writeTo(checker);
// figure this out based on whether we believe this to be a text type or not.
if (content.match("text/*")) {
return checker.getTextTransferEncoding();
}
else {
return checker.getBinaryTransferEncoding();
}
} catch (Exception e) {
// any unexpected I/O exceptions we'll force to a "safe" fallback position.
return "base64";
}
}
/**
* Determine the what transfer encoding should be used for
* data retrieved from a DataSource.
*
* @param source The DataSource for the transmitted data.
*
* @return The string name of the encoding form that should be used for
* the data.
*/
public static String getEncoding(DataSource source) {
InputStream in = null;
try {
// get a parser that allows us to make comparisons.
ContentType content = new ContentType(source.getContentType());
// we're probably going to have to scan the data.
in = source.getInputStream();
if (!content.match("text/*")) {
// Not purporting to be a text type? Examine the content to see we might be able to
// at least pretend it is an ascii type.
return ASCIIUtil.getBinaryTransferEncoding(in);
}
else {
return ASCIIUtil.getTextTransferEncoding(in);
}
} catch (Exception e) {
// this was a problem...not sure what makes sense here, so we'll assume it's binary
// and we need to transfer this using Base64 encoding.
return "base64";
} finally {
// make sure we close the stream
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
}
/**
* Quote a "word" value. If the word contains any character from
* the specified "specials" list, this value is returned as a
* quoted strong. Otherwise, it is returned unchanged (an "atom").
*
* @param word The word requiring quoting.
* @param specials The set of special characters that can't appear in an unquoted
* string.
*
* @return The quoted value. This will be unchanged if the word doesn't contain
* any of the designated special characters.
*/
public static String quote(String word, String specials) {
int wordLength = word.length();
//boolean requiresQuoting = false;
// scan the string looking for problem characters
for (int i =0; i < wordLength; i++) {
char ch = word.charAt(i);
// special escaped characters require escaping, which also implies quoting.
if (escapedChars.indexOf(ch) >= 0) {
return quoteAndEscapeString(word);
}
// now check for control characters or the designated special characters.
if (ch < 32 || ch >= 127 || specials.indexOf(ch) >= 0) {
// we know this requires quoting, but we still need to scan the entire string to
// see if contains chars that require escaping. Just go ahead and treat it as if it does.
return quoteAndEscapeString(word);
}
}
return word;
}
/**
* Take a string and return it as a formatted quoted string, with
* all characters requiring escaping handled properly.
*
* @param word The string to quote.
*
* @return The quoted string.
*/
private static String quoteAndEscapeString(String word) {
int wordLength = word.length();
// allocate at least enough for the string and two quotes plus a reasonable number of escaped chars.
StringBuffer buffer = new StringBuffer(wordLength + 10);
// add the leading quote.
buffer.append('"');
for (int i = 0; i < wordLength; i++) {
char ch = word.charAt(i);
// is this an escaped char?
if (escapedChars.indexOf(ch) >= 0) {
// add the escape marker before appending.
buffer.append('\\');
}
buffer.append(ch);
}
// now the closing quote
buffer.append('"');
return buffer.toString();
}
/**
* Translate a MIME standard character set name into the Java
* equivalent.
*
* @param charset The MIME standard name.
*
* @return The Java equivalent for this name.
*/
public static String javaCharset(String charset) {
// nothing in, nothing out.
if (charset == null) {
return null;
}
String mappedCharset = (String)mime2java.get(charset.toLowerCase());
// if there is no mapping, then the original name is used. Many of the MIME character set
// names map directly back into Java. The reverse isn't necessarily true.
return mappedCharset == null ? charset : mappedCharset;
}
/**
* Map a Java character set name into the MIME equivalent.
*
* @param charset The java character set name.
*
* @return The MIME standard equivalent for this character set name.
*/
public static String mimeCharset(String charset) {
// nothing in, nothing out.
if (charset == null) {
return null;
}
String mappedCharset = (String)java2mime.get(charset.toLowerCase());
// if there is no mapping, then the original name is used. Many of the MIME character set
// names map directly back into Java. The reverse isn't necessarily true.
return mappedCharset == null ? charset : mappedCharset;
}
/**
* Get the default character set to use, in Java name format.
* This either be the value set with the mail.mime.charset
* system property or obtained from the file.encoding system
* property. If neither of these is set, we fall back to
* 8859_1 (basically US-ASCII).
*
* @return The character string value of the default character set.
*/
public static String getDefaultJavaCharset() {
String charset = SessionUtil.getProperty("mail.mime.charset");
if (charset != null) {
return javaCharset(charset);
}
return SessionUtil.getProperty("file.encoding", "8859_1");
}
/**
* Get the default character set to use, in MIME name format.
* This either be the value set with the mail.mime.charset
* system property or obtained from the file.encoding system
* property. If neither of these is set, we fall back to
* 8859_1 (basically US-ASCII).
*
* @return The character string value of the default character set.
*/
static String getDefaultMIMECharset() {
// if the property is specified, this can be used directly.
String charset = SessionUtil.getProperty("mail.mime.charset");
if (charset != null) {
return charset;
}
// get the Java-defined default and map back to a MIME name.
return mimeCharset(SessionUtil.getProperty("file.encoding", "8859_1"));
}
/**
* Load the default mapping tables used by the javaCharset()
* and mimeCharset() methods. By default, these tables are
* loaded from the /META-INF/javamail.charset.map file. If
* something goes wrong loading that file, we configure things
* with a default mapping table (which just happens to mimic
* what's in the default mapping file).
*/
static private void loadCharacterSetMappings() {
java2mime = new HashMap();
mime2java = new HashMap();
// normally, these come from a character map file contained in the jar file.
try {
InputStream map = javax.mail.internet.MimeUtility.class.getResourceAsStream("/META-INF/javamail.charset.map");
if (map != null) {
// get a reader for this so we can load.
BufferedReader reader = new BufferedReader(new InputStreamReader(map));
readMappings(reader, java2mime);
readMappings(reader, mime2java);
}
} catch (Exception e) {
}
// if any sort of error occurred reading the preferred file version, we could end up with empty
// mapping tables. This could cause all sorts of difficulty, so ensure they are populated with at
// least a reasonable set of defaults.
// these mappings echo what's in the default file.
if (java2mime.isEmpty()) {
java2mime.put("8859_1", "ISO-8859-1");
java2mime.put("iso8859_1", "ISO-8859-1");
java2mime.put("iso8859-1", "ISO-8859-1");
java2mime.put("8859_2", "ISO-8859-2");
java2mime.put("iso8859_2", "ISO-8859-2");
java2mime.put("iso8859-2", "ISO-8859-2");
java2mime.put("8859_3", "ISO-8859-3");
java2mime.put("iso8859_3", "ISO-8859-3");
java2mime.put("iso8859-3", "ISO-8859-3");
java2mime.put("8859_4", "ISO-8859-4");
java2mime.put("iso8859_4", "ISO-8859-4");
java2mime.put("iso8859-4", "ISO-8859-4");
java2mime.put("8859_5", "ISO-8859-5");
java2mime.put("iso8859_5", "ISO-8859-5");
java2mime.put("iso8859-5", "ISO-8859-5");
java2mime.put ("8859_6", "ISO-8859-6");
java2mime.put("iso8859_6", "ISO-8859-6");
java2mime.put("iso8859-6", "ISO-8859-6");
java2mime.put("8859_7", "ISO-8859-7");
java2mime.put("iso8859_7", "ISO-8859-7");
java2mime.put("iso8859-7", "ISO-8859-7");
java2mime.put("8859_8", "ISO-8859-8");
java2mime.put("iso8859_8", "ISO-8859-8");
java2mime.put("iso8859-8", "ISO-8859-8");
java2mime.put("8859_9", "ISO-8859-9");
java2mime.put("iso8859_9", "ISO-8859-9");
java2mime.put("iso8859-9", "ISO-8859-9");
java2mime.put("sjis", "Shift_JIS");
java2mime.put ("jis", "ISO-2022-JP");
java2mime.put("iso2022jp", "ISO-2022-JP");
java2mime.put("euc_jp", "euc-jp");
java2mime.put("koi8_r", "koi8-r");
java2mime.put("euc_cn", "euc-cn");
java2mime.put("euc_tw", "euc-tw");
java2mime.put("euc_kr", "euc-kr");
}
if (mime2java.isEmpty ()) {
mime2java.put("iso-2022-cn", "ISO2022CN");
mime2java.put("iso-2022-kr", "ISO2022KR");
mime2java.put("utf-8", "UTF8");
mime2java.put("utf8", "UTF8");
mime2java.put("ja_jp.iso2022-7", "ISO2022JP");
mime2java.put("ja_jp.eucjp", "EUCJIS");
mime2java.put ("euc-kr", "KSC5601");
mime2java.put("euckr", "KSC5601");
mime2java.put("us-ascii", "ISO-8859-1");
mime2java.put("x-us-ascii", "ISO-8859-1");
}
}
/**
* Read a section of a character map table and populate the
* target mapping table with the information. The table end
* is marked by a line starting with "--" and also ending with
* "--". Blank lines and comment lines (beginning with '#') are
* ignored.
*
* @param reader The source of the file information.
* @param table The mapping table used to store the information.
*/
static private void readMappings(BufferedReader reader, Map table) throws IOException {
// process lines to the EOF or the end of table marker.
while (true) {
String line = reader.readLine();
// no line returned is an EOF
if (line == null) {
return;
}
// trim so we're not messed up by trailing blanks
line = line.trim();
if (line.length() == 0 || line.startsWith("#")) {
continue;
}
// stop processing if this is the end-of-table marker.
if (line.startsWith("--") && line.endsWith("--")) {
return;
}
// we allow either blanks or tabs as token delimiters.
StringTokenizer tokenizer = new StringTokenizer(line, " \t");
try {
String from = tokenizer.nextToken().toLowerCase();
String to = tokenizer.nextToken();
table.put(from, to);
} catch (NoSuchElementException e) {
// just ignore the line if invalid.
}
}
}
/**
* Perform RFC 2047 text folding on a string of text.
*
* @param used The amount of text already "used up" on this line. This is
* typically the length of a message header that this text
* get getting added to.
* @param s The text to fold.
*
* @return The input text, with linebreaks inserted at appropriate fold points.
*/
public static String fold(int used, String s) {
// if folding is disable, unfolding is also. Return the string unchanged.
if (!SessionUtil.getBooleanProperty(MIME_FOLDTEXT, true)) {
return s;
}
int end;
// now we need to strip off any trailing "whitespace", where whitespace is blanks, tabs,
// and line break characters.
for (end = s.length() - 1; end >= 0; end--) {
int ch = s.charAt(end);
if (ch != ' ' && ch != '\t' ) {
break;
}
}
// did we actually find something to remove? Shorten the String to the trimmed length
if (end != s.length() - 1) {
s = s.substring(0, end + 1);
}
// does the string as it exists now not require folding? We can just had that back right off.
if (s.length() + used <= FOLD_THRESHOLD) {
return s;
}
// get a buffer for the length of the string, plus room for a few line breaks.
// these are soft line breaks, so we generally need more that just the line breaks (an escape +
// CR + LF + leading space on next line);
StringBuffer newString = new StringBuffer(s.length() + 8);
// now keep chopping this down until we've accomplished what we need.
while (used + s.length() > FOLD_THRESHOLD) {
int breakPoint = -1;
char breakChar = 0;
// now scan for the next place where we can break.
for (int i = 0; i < s.length(); i++) {
// have we passed the fold limit?
if (used + i > FOLD_THRESHOLD) {
// if we've already seen a blank, then stop now. Otherwise
// we keep going until we hit a fold point.
if (breakPoint != -1) {
break;
}
}
char ch = s.charAt(i);
// a white space character?
if (ch == ' ' || ch == '\t') {
// this might be a run of white space, so skip over those now.
breakPoint = i;
// we need to maintain the same character type after the inserted linebreak.
breakChar = ch;
i++;
while (i < s.length()) {
ch = s.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
i++;
}
}
// found an embedded new line. Escape this so that the unfolding process preserves it.
else if (ch == '\n') {
newString.append('\\');
newString.append('\n');
}
else if (ch == '\r') {
newString.append('\\');
newString.append('\n');
i++;
// if this is a CRLF pair, add the second char also
if (i < s.length() && s.charAt(i) == '\n') {
newString.append('\r');
}
}
}
// no fold point found, we punt, append the remainder and leave.
if (breakPoint == -1) {
newString.append(s);
return newString.toString();
}
newString.append(s.substring(0, breakPoint));
newString.append("\r\n");
newString.append(breakChar);
// chop the string
s = s.substring(breakPoint + 1);
// start again, and we've used the first char of the limit already with the whitespace char.
used = 1;
}
// add on the remainder, and return
newString.append(s);
return newString.toString();
}
/**
* Unfold a folded string. The unfolding process will remove
* any line breaks that are not escaped and which are also followed
* by whitespace characters.
*
* @param s The folded string.
*
* @return A new string with unfolding rules applied.
*/
public static String unfold(String s) {
// if folding is disable, unfolding is also. Return the string unchanged.
if (!SessionUtil.getBooleanProperty(MIME_FOLDTEXT, true)) {
return s;
}
// if there are no line break characters in the string, we can just return this.
if (s.indexOf('\n') < 0 && s.indexOf('\r') < 0) {
return s;
}
// we need to scan and fix things up.
int length = s.length();
StringBuffer newString = new StringBuffer(length);
// scan the entire string
for (int i = 0; i < length; i++) {
char ch = s.charAt(i);
// we have a backslash. In folded strings, escape characters are only processed as such if
// they preceed line breaks. Otherwise, we leave it be.
if (ch == '\\') {
// escape at the very end? Just add the character.
if (i == length - 1) {
newString.append(ch);
}
else {
int nextChar = s.charAt(i + 1);
// naked newline? Add the new line to the buffer, and skip the escape char.
if (nextChar == '\n') {
newString.append('\n');
i++;
}
else if (nextChar == '\r') {
// just the CR left? Add it, removing the escape.
if (i == length - 2 || s.charAt(i + 2) != '\r') {
newString.append('\r');
i++;
}
else {
// toss the escape, add both parts of the CRLF, and skip over two chars.
newString.append('\r');
newString.append('\n');
i += 2;
}
}
else {
// an escape for another purpose, just copy it over.
newString.append(ch);
}
}
}
// we have an unescaped line break
else if (ch == '\n' || ch == '\r') {
// remember the position in case we need to backtrack.
//int lineBreak = i;
boolean CRLF = false;
if (ch == '\r') {
// check to see if we need to step over this.
if (i < length - 1 && s.charAt(i + 1) == '\n') {
i++;
// flag the type so we know what we might need to preserve.
CRLF = true;
}
}
// get a temp position scanner.
int scan = i + 1;
// does a blank follow this new line? we need to scrap the new line and reduce the leading blanks
// down to a single blank.
if (scan < length && s.charAt(scan) == ' ') {
// add the character
newString.append(' ');
// scan over the rest of the blanks
i = scan + 1;
while (i < length && s.charAt(i) == ' ') {
i++;
}
// we'll increment down below, so back up to the last blank as the current char.
i--;
}
else {
// we must keep this line break. Append the appropriate style.
if (CRLF) {
newString.append("\r\n");
}
else {
newString.append(ch);
}
}
}
else {
// just a normal, ordinary character
newString.append(ch);
}
}
return newString.toString();
}
}
/**
* Utility class for examining content information written out
* by a DataHandler object. This stream gathers statistics on
* the stream so it can make transfer encoding determinations.
*/
class ContentCheckingOutputStream extends OutputStream {
private int asciiChars = 0;
private int nonAsciiChars = 0;
private boolean containsLongLines = false;
private boolean containsMalformedEOL = false;
private int previousChar = 0;
private int span = 0;
ContentCheckingOutputStream() {
}
public void write(byte[] data) throws IOException {
write(data, 0, data.length);
}
public void write(byte[] data, int offset, int length) throws IOException {
for (int i = 0; i < length; i++) {
write(data[offset + i]);
}
}
public void write(int ch) {
// 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') {
// 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') {
containsMalformedEOL = true;
}
}
// 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 (!ASCIIUtil.isAscii(ch)) {
nonAsciiChars++;
}
else {
asciiChars++;
}
}
previousChar = ch;
}
public String getBinaryTransferEncoding() {
if (nonAsciiChars != 0 || containsLongLines || containsMalformedEOL) {
return "base64";
}
else {
return "7bit";
}
}
public String getTextTransferEncoding() {
// 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";
}
}
}
}
| 1,046 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/ContentType.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;
// can be in the form major/minor; charset=jobby
/**
* @version $Rev$ $Date$
*/
public class ContentType {
private ParameterList _list;
private String _minor;
private String _major;
public ContentType() {
// the Sun version makes everything null here.
}
public ContentType(String major, String minor, ParameterList list) {
_major = major;
_minor = minor;
_list = list;
}
public ContentType(String type) throws ParseException {
// get a token parser for the type information
HeaderTokenizer tokenizer = new HeaderTokenizer(type, HeaderTokenizer.MIME);
// get the first token, which must be an ATOM
HeaderTokenizer.Token token = tokenizer.next();
if (token.getType() != HeaderTokenizer.Token.ATOM) {
throw new ParseException("Invalid content type");
}
_major = token.getValue();
// the MIME type must be major/minor
token = tokenizer.next();
if (token.getType() != '/') {
throw new ParseException("Invalid content type");
}
// this must also be an atom. Content types are not permitted to be wild cards.
token = tokenizer.next();
if (token.getType() != HeaderTokenizer.Token.ATOM) {
throw new ParseException("Invalid content type");
}
_minor = token.getValue();
// the remainder is parameters, which ParameterList will take care of parsing.
String remainder = tokenizer.getRemainder();
if (remainder != null) {
_list = new ParameterList(remainder);
}
}
public String getPrimaryType() {
return _major;
}
public String getSubType() {
return _minor;
}
public String getBaseType() {
return _major + "/" + _minor;
}
public String getParameter(String name) {
return (_list == null ? null : _list.get(name));
}
public ParameterList getParameterList() {
return _list;
}
public void setPrimaryType(String major) {
_major = major;
}
public void setSubType(String minor) {
_minor = minor;
}
public void setParameter(String name, String value) {
if (_list == null) {
_list = new ParameterList();
}
_list.set(name, value);
}
public void setParameterList(ParameterList list) {
_list = list;
}
public String toString() {
if (_major == null || _minor == null) {
return null;
}
// We need to format this as if we're doing it to set into the Content-Type
// header. So the parameter list gets added on as if the header name was
// also included.
String baseType = getBaseType();
if (_list != null) {
baseType += _list.toString(baseType.length() + "Content-Type: ".length());
}
return baseType;
}
public boolean match(ContentType other) {
return _major.equalsIgnoreCase(other._major)
&& (_minor.equalsIgnoreCase(other._minor)
|| _minor.equals("*")
|| other._minor.equals("*"));
}
public boolean match(String contentType) {
try {
return match(new ContentType(contentType));
} catch (ParseException e) {
return false;
}
}
}
| 1,047 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/HeaderTokenizer.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;
/**
* @version $Rev$ $Date$
*/
public class HeaderTokenizer {
public static class Token {
// Constant values from J2SE 1.4 API Docs (Constant values)
public static final int ATOM = -1;
public static final int COMMENT = -3;
public static final int EOF = -4;
public static final int QUOTEDSTRING = -2;
private int _type;
private String _value;
public Token(int type, String value) {
_type = type;
_value = value;
}
public int getType() {
return _type;
}
public String getValue() {
return _value;
}
}
private static final Token EOF = new Token(Token.EOF, null);
// characters not allowed in MIME
public static final String MIME = "()<>@,;:\\\"\t []/?=";
// charaters not allowed in RFC822
public static final String RFC822 = "()<>@,;:\\\"\t .[]";
private static final String WHITE = " \t\n\r";
private String _delimiters;
private String _header;
private boolean _skip;
private int pos;
public HeaderTokenizer(String header) {
this(header, RFC822);
}
public HeaderTokenizer(String header, String delimiters) {
this(header, delimiters, true);
}
public HeaderTokenizer(String header,
String delimiters,
boolean skipComments) {
_skip = skipComments;
_header = header;
_delimiters = delimiters;
}
public String getRemainder() {
return _header.substring(pos);
}
public Token next() throws ParseException {
return readToken();
}
public Token peek() throws ParseException {
int start = pos;
try {
return readToken();
} finally {
pos = start;
}
}
/**
* Read an ATOM token from the parsed header.
*
* @return A token containing the value of the atom token.
*/
private Token readAtomicToken() {
// skip to next delimiter
int start = pos;
while (++pos < _header.length()) {
// break on the first non-atom character.
char ch = _header.charAt(pos);
if (_delimiters.indexOf(_header.charAt(pos)) != -1 || ch < 32 || ch >= 127) {
break;
}
}
return new Token(Token.ATOM, _header.substring(start, pos));
}
/**
* Read the next token from the header.
*
* @return The next token from the header. White space is skipped, and comment
* tokens are also skipped if indicated.
* @exception ParseException
*/
private Token readToken() throws ParseException {
if (pos >= _header.length()) {
return EOF;
} else {
char c = _header.charAt(pos);
// comment token...read and skip over this
if (c == '(') {
Token comment = readComment();
if (_skip) {
return readToken();
} else {
return comment;
}
// quoted literal
} else if (c == '\"') {
return readQuotedString();
// white space, eat this and find a real token.
} else if (WHITE.indexOf(c) != -1) {
eatWhiteSpace();
return readToken();
// either a CTL or special. These characters have a self-defining token type.
} else if (c < 32 || c >= 127 || _delimiters.indexOf(c) != -1) {
pos++;
return new Token((int)c, String.valueOf(c));
} else {
// start of an atom, parse it off.
return readAtomicToken();
}
}
}
/**
* Extract a substring from the header string and apply any
* escaping/folding rules to the string.
*
* @param start The starting offset in the header.
* @param end The header end offset + 1.
*
* @return The processed string value.
* @exception ParseException
*/
private String getEscapedValue(int start, int end) throws ParseException {
StringBuffer value = new StringBuffer();
for (int i = start; i < end; i++) {
char ch = _header.charAt(i);
// is this an escape character?
if (ch == '\\') {
i++;
if (i == end) {
throw new ParseException("Invalid escape character");
}
value.append(_header.charAt(i));
}
// line breaks are ignored, except for naked '\n' characters, which are consider
// parts of linear whitespace.
else if (ch == '\r') {
// see if this is a CRLF sequence, and skip the second if it is.
if (i < end - 1 && _header.charAt(i + 1) == '\n') {
i++;
}
}
else {
// just append the ch value.
value.append(ch);
}
}
return value.toString();
}
/**
* Read a comment from the header, applying nesting and escape
* rules to the content.
*
* @return A comment token with the token value.
* @exception ParseException
*/
private Token readComment() throws ParseException {
int start = pos + 1;
int nesting = 1;
boolean requiresEscaping = false;
// skip to end of comment/string
while (++pos < _header.length()) {
char ch = _header.charAt(pos);
if (ch == ')') {
nesting--;
if (nesting == 0) {
break;
}
}
else if (ch == '(') {
nesting++;
}
else if (ch == '\\') {
pos++;
requiresEscaping = true;
}
// we need to process line breaks also
else if (ch == '\r') {
requiresEscaping = true;
}
}
if (nesting != 0) {
throw new ParseException("Unbalanced comments");
}
String value;
if (requiresEscaping) {
value = getEscapedValue(start, pos);
}
else {
value = _header.substring(start, pos++);
}
return new Token(Token.COMMENT, value);
}
/**
* Parse out a quoted string from the header, applying escaping
* rules to the value.
*
* @return The QUOTEDSTRING token with the value.
* @exception ParseException
*/
private Token readQuotedString() throws ParseException {
int start = pos+1;
boolean requiresEscaping = false;
// skip to end of comment/string
while (++pos < _header.length()) {
char ch = _header.charAt(pos);
if (ch == '"') {
String value;
if (requiresEscaping) {
value = getEscapedValue(start, pos++);
}
else {
value = _header.substring(start, pos++);
}
return new Token(Token.QUOTEDSTRING, value);
}
else if (ch == '\\') {
pos++;
requiresEscaping = true;
}
// we need to process line breaks also
else if (ch == '\r') {
requiresEscaping = true;
}
}
throw new ParseException("Missing '\"'");
}
/**
* Skip white space in the token string.
*/
private void eatWhiteSpace() {
// skip to end of whitespace
while (++pos < _header.length()
&& WHITE.indexOf(_header.charAt(pos)) != -1)
;
}
}
| 1,048 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/ParseException.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 javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public class ParseException extends MessagingException {
private static final long serialVersionUID = 7649991205183658089L;
public ParseException() {
super();
}
public ParseException(String message) {
super(message);
}
}
| 1,049 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/MimePartDataSource.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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownServiceException;
import javax.activation.DataSource;
import javax.mail.MessageAware;
import javax.mail.MessageContext;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public class MimePartDataSource implements DataSource, MessageAware {
// the part that provides the data form this data source.
protected MimePart part;
public MimePartDataSource(MimePart part) {
this.part = part;
}
public InputStream getInputStream() throws IOException {
try {
InputStream stream;
if (part instanceof MimeMessage) {
stream = ((MimeMessage) part).getContentStream();
} else if (part instanceof MimeBodyPart) {
stream = ((MimeBodyPart) part).getContentStream();
} else {
throw new MessagingException("Unknown part");
}
return checkPartEncoding(part, stream);
} catch (MessagingException e) {
throw (IOException) new IOException(e.getMessage()).initCause(e);
}
}
/**
* For a given part, decide it the data stream requires
* wrappering with a stream for decoding a particular
* encoding.
*
* @param part The part we're extracting.
* @param stream The raw input stream for the part.
*
* @return An input stream configured for reading the
* source part and decoding it into raw bytes.
*/
private InputStream checkPartEncoding(MimePart part, InputStream stream) throws MessagingException {
String encoding = part.getEncoding();
// if nothing is specified, there's nothing to do
if (encoding == null) {
return stream;
}
// now screen out the ones that never need decoding
encoding = encoding.toLowerCase();
if (encoding.equals("7bit") || encoding.equals("8bit") || encoding.equals("binary")) {
return stream;
}
// now we need to check the content type to prevent
// MultiPart types from getting decoded, since the part is just an envelope around other
// parts
String contentType = part.getContentType();
if (contentType != null) {
try {
ContentType type = new ContentType(contentType);
// no decoding done here
if (type.match("multipart/*")) {
return stream;
}
} catch (ParseException e) {
// ignored....bad content type means we handle as a normal part
}
}
// ok, wrap this is a decoding stream if required
return MimeUtility.decode(stream, encoding);
}
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
public String getContentType() {
try {
return part.getContentType();
} catch (MessagingException e) {
return null;
}
}
public String getName() {
try {
if (part instanceof MimeBodyPart) {
return ((MimeBodyPart) part).getFileName();
}
} catch (MessagingException mex) {
// ignore it
}
return "";
}
public synchronized MessageContext getMessageContext() {
return new MessageContext(part);
}
}
| 1,050 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/MimeMessage.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.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
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 MimeMessage extends Message implements MimePart {
private static final String MIME_ADDRESS_STRICT = "mail.mime.address.strict";
private static final String MIME_DECODEFILENAME = "mail.mime.decodefilename";
private static final String MIME_ENCODEFILENAME = "mail.mime.encodefilename";
private static final String MAIL_ALTERNATES = "mail.alternates";
private static final String MAIL_REPLYALLCC = "mail.replyallcc";
// static used to ensure message ID uniqueness
private static int messageID = 0;
/**
* Extends {@link javax.mail.Message.RecipientType} to support addition recipient types.
*/
public static class RecipientType extends Message.RecipientType {
/**
* Recipient type for Usenet news.
*/
public static final RecipientType NEWSGROUPS = new RecipientType("Newsgroups");
protected RecipientType(String type) {
super(type);
}
/**
* Ensure the singleton is returned.
*
* @return resolved object
*/
protected Object readResolve() throws ObjectStreamException {
if (this.type.equals("Newsgroups")) {
return NEWSGROUPS;
} else {
return super.readResolve();
}
}
}
/**
* The {@link DataHandler} for this Message's content.
*/
protected DataHandler dh;
/**
* This message's content (unless sourced from a SharedInputStream).
*/
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;
/**
* This message's flags.
*/
protected Flags flags;
/**
* Flag indicating that the message has been modified; set to true when
* an empty message is created or when {@link #saveChanges()} is called.
*/
protected boolean modified;
/**
* Flag indicating that the message has been saved.
*/
protected boolean saved;
private final MailDateFormat dateFormat = new MailDateFormat();
/**
* Create a new MimeMessage.
* An empty message is created, with empty {@link #headers} and empty {@link #flags}.
* The {@link #modified} flag is set.
*
* @param session the session for this message
*/
public MimeMessage(Session session) {
super(session);
headers = new InternetHeaders();
flags = new Flags();
// empty messages are modified, because the content is not there, and require saving before use.
modified = true;
saved = false;
}
/**
* Create a MimeMessage by reading an parsing the data from the supplied stream.
*
* @param session the session for this message
* @param in the stream to load from
* @throws MessagingException if there is a problem reading or parsing the stream
*/
public MimeMessage(Session session, InputStream in) throws MessagingException {
this(session);
parse(in);
// this message is complete, so marked as unmodified.
modified = false;
// and no saving required
saved = true;
}
/**
* Copy a MimeMessage.
*
* @param message the message to copy
* @throws MessagingException is there was a problem copying the message
*/
public MimeMessage(MimeMessage message) throws MessagingException {
super(message.session);
// get a copy of the source message flags
flags = message.getFlags();
// this is somewhat difficult to do. There's a lot of data in both the superclass and this
// class that needs to undergo a "deep cloning" operation. These operations don't really exist
// on the objects in question, so the only solution I can come up with is to serialize the
// message data of the source object using the write() method, then reparse the data in this
// object. I've not found a lot of uses for this particular constructor, so perhaps that's not
// really all that bad of a solution.
// serialize this out to an in-memory stream.
ByteArrayOutputStream copy = new ByteArrayOutputStream();
try {
// write this out the stream.
message.writeTo(copy);
copy.close();
// I think this ends up creating a new array for the data, but I'm not aware of any more
// efficient options.
ByteArrayInputStream inData = new ByteArrayInputStream(copy.toByteArray());
// now reparse this message into this object.
inData.close();
parse (inData);
// writing out the source data requires saving it, so we should consider this one saved also.
saved = true;
// this message is complete, so marked as unmodified.
modified = false;
} catch (IOException e) {
// I'm not sure ByteArrayInput/OutputStream actually throws IOExceptions or not, but the method
// signatures declare it, so we need to deal with it. Turning it into a messaging exception
// should fit the bill.
throw new MessagingException("Error copying MimeMessage data", e);
}
}
/**
* Create an new MimeMessage in the supplied {@link Folder} and message number.
*
* @param folder the Folder that contains the new message
* @param number the message number of the new message
*/
protected MimeMessage(Folder folder, int number) {
super(folder, number);
headers = new InternetHeaders();
flags = new Flags();
// saving primarly involves updates to the message header. Since we're taking the header info
// from a message store in this context, we mark the message as saved.
saved = true;
// we've not filled in the content yet, so this needs to be marked as modified
modified = true;
}
/**
* Create a MimeMessage by reading an parsing the data from the supplied stream.
*
* @param folder the folder for this message
* @param in the stream to load from
* @param number the message number of the new message
* @throws MessagingException if there is a problem reading or parsing the stream
*/
protected MimeMessage(Folder folder, InputStream in, int number) throws MessagingException {
this(folder, number);
parse(in);
// this message is complete, so marked as unmodified.
modified = false;
// and no saving required
saved = true;
}
/**
* Create a MimeMessage with the supplied headers and content.
*
* @param folder the folder for this message
* @param headers the headers for the new message
* @param content the content of the new message
* @param number the message number of the new message
* @throws MessagingException if there is a problem reading or parsing the stream
*/
protected MimeMessage(Folder folder, InternetHeaders headers, byte[] content, int number) throws MessagingException {
this(folder, number);
this.headers = headers;
this.content = content;
// this message is complete, so marked as unmodified.
modified = false;
}
/**
* Parse the supplied stream and initialize {@link #headers} and {@link #content} appropriately.
*
* @param in the stream to read
* @throws MessagingException if there was a problem parsing the stream
*/
protected void parse(InputStream in) throws MessagingException {
in = new BufferedInputStream(in);
// create the headers first from the stream. Note: We need to do this
// by calling createInternetHeaders because subclasses might wish to add
// additional headers to the set initialized from the stream.
headers = createInternetHeaders(in);
// now we need to get the rest of the content as a byte array...this means reading from the current
// position in the stream until the end and writing it to an accumulator ByteArrayOutputStream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte buffer[] = new byte[1024];
int count;
while ((count = in.read(buffer, 0, 1024)) != -1) {
baos.write(buffer, 0, count);
}
} catch (Exception e) {
throw new MessagingException(e.toString(), e);
}
// and finally extract the content as a byte array.
content = baos.toByteArray();
}
/**
* Get the message "From" addresses. This looks first at the
* "From" headers, and no "From" header is found, the "Sender"
* header is checked. Returns null if not found.
*
* @return An array of addresses identifying the message from target. Returns
* null if this is not resolveable from the headers.
* @exception MessagingException
*/
public Address[] getFrom() throws MessagingException {
// strict addressing controls this.
boolean strict = isStrictAddressing();
Address[] result = getHeaderAsInternetAddresses("From", strict);
if (result == null) {
result = getHeaderAsInternetAddresses("Sender", strict);
}
return result;
}
/**
* Set the current message "From" recipient. This replaces any
* existing "From" header. If the address is null, the header is
* removed.
*
* @param address The new "From" target.
*
* @exception MessagingException
*/
public void setFrom(Address address) throws MessagingException {
setHeader("From", address);
}
/**
* Set the "From" header using the value returned by {@link InternetAddress#getLocalAddress(javax.mail.Session)}.
*
* @throws MessagingException if there was a problem setting the header
*/
public void setFrom() throws MessagingException {
InternetAddress address = InternetAddress.getLocalAddress(session);
// no local address resolvable? This is an error.
if (address == null) {
throw new MessagingException("No local address defined");
}
setFrom(address);
}
/**
* Add a set of addresses to the existing From header.
*
* @param addresses The list to add.
*
* @exception MessagingException
*/
public void addFrom(Address[] addresses) throws MessagingException {
addHeader("From", addresses);
}
/**
* Return the "Sender" header as an address.
*
* @return the "Sender" header as an address, or null if not present
* @throws MessagingException if there was a problem parsing the header
*/
public Address getSender() throws MessagingException {
Address[] addrs = getHeaderAsInternetAddresses("Sender", isStrictAddressing());
return addrs != null && addrs.length > 0 ? addrs[0] : null;
}
/**
* Set the "Sender" header. If the address is null, this
* will remove the current sender header.
*
* @param address the new Sender address
*
* @throws MessagingException
* if there was a problem setting the header
*/
public void setSender(Address address) throws MessagingException {
setHeader("Sender", address);
}
/**
* Gets the recipients by type. Returns null if there are no
* headers of the specified type. Acceptable RecipientTypes are:
*
* javax.mail.Message.RecipientType.TO
* javax.mail.Message.RecipientType.CC
* javax.mail.Message.RecipientType.BCC
* javax.mail.internet.MimeMessage.RecipientType.NEWSGROUPS
*
* @param type The message RecipientType identifier.
*
* @return The array of addresses for the specified recipient types.
* @exception MessagingException
*/
public Address[] getRecipients(Message.RecipientType type) throws MessagingException {
// is this a NEWSGROUP request? We need to handle this as a special case here, because
// this needs to return NewsAddress instances instead of InternetAddress items.
if (type == RecipientType.NEWSGROUPS) {
return getHeaderAsNewsAddresses(getHeaderForRecipientType(type));
}
// the other types are all internet addresses.
return getHeaderAsInternetAddresses(getHeaderForRecipientType(type), isStrictAddressing());
}
/**
* Retrieve all of the recipients defined for this message. This
* returns a merged array of all possible message recipients
* extracted from the headers. The relevant header types are:
*
*
* javax.mail.Message.RecipientType.TO
* javax.mail.Message.RecipientType.CC
* javax.mail.Message.RecipientType.BCC
* javax.mail.internet.MimeMessage.RecipientType.NEWSGROUPS
*
* @return An array of all target message recipients.
* @exception MessagingException
*/
public Address[] getAllRecipients() throws MessagingException {
List recipients = new ArrayList();
addRecipientsToList(recipients, RecipientType.TO);
addRecipientsToList(recipients, RecipientType.CC);
addRecipientsToList(recipients, RecipientType.BCC);
addRecipientsToList(recipients, RecipientType.NEWSGROUPS);
// this is supposed to return null if nothing is there.
if (recipients.isEmpty()) {
return null;
}
return (Address[]) recipients.toArray(new Address[recipients.size()]);
}
/**
* Utility routine to merge different recipient types into a
* single list.
*
* @param list The accumulator list.
* @param type The recipient type to extract.
*
* @exception MessagingException
*/
private void addRecipientsToList(List list, Message.RecipientType type) throws MessagingException {
Address[] recipients;
if (type == RecipientType.NEWSGROUPS) {
recipients = getHeaderAsNewsAddresses(getHeaderForRecipientType(type));
}
else {
recipients = getHeaderAsInternetAddresses(getHeaderForRecipientType(type), isStrictAddressing());
}
if (recipients != null) {
list.addAll(Arrays.asList(recipients));
}
}
/**
* Set a recipients list for a particular recipient type. If the
* list is null, the corresponding header is removed.
*
* @param type The type of recipient to set.
* @param addresses The list of addresses.
*
* @exception MessagingException
*/
public void setRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException {
setHeader(getHeaderForRecipientType(type), addresses);
}
/**
* Set a recipient field to a string address (which may be a
* list or group type).
*
* If the address is null, the field is removed.
*
* @param type The type of recipient to set.
* @param address The address string.
*
* @exception MessagingException
*/
public void setRecipients(Message.RecipientType type, String address) throws MessagingException {
setOrRemoveHeader(getHeaderForRecipientType(type), address);
}
/**
* Add a list of addresses to a target recipient list.
*
* @param type The target recipient type.
* @param address An array of addresses to add.
*
* @exception MessagingException
*/
public void addRecipients(Message.RecipientType type, Address[] address) throws MessagingException {
addHeader(getHeaderForRecipientType(type), address);
}
/**
* Add an address to a target recipient list by string name.
*
* @param type The target header type.
* @param address The address to add.
*
* @exception MessagingException
*/
public void addRecipients(Message.RecipientType type, String address) throws MessagingException {
addHeader(getHeaderForRecipientType(type), address);
}
/**
* Get the ReplyTo address information. The headers are parsed
* using the "mail.mime.address.strict" setting. If the "Reply-To" header does
* not have any addresses, then the value of the "From" field is used.
*
* @return An array of addresses obtained from parsing the header.
* @exception MessagingException
*/
public Address[] getReplyTo() throws MessagingException {
Address[] addresses = getHeaderAsInternetAddresses("Reply-To", isStrictAddressing());
if (addresses == null) {
addresses = getFrom();
}
return addresses;
}
/**
* Set the Reply-To field to the provided list of addresses. If
* the address list is null, the header is removed.
*
* @param address The new field value.
*
* @exception MessagingException
*/
public void setReplyTo(Address[] address) throws MessagingException {
setHeader("Reply-To", address);
}
/**
* Returns the value of the "Subject" header. If the subject
* is encoded as an RFC 2047 value, the value is decoded before
* return. If decoding fails, the raw string value is
* returned.
*
* @return The String value of the subject field.
* @exception MessagingException
*/
public String getSubject() throws MessagingException {
String subject = getSingleHeader("Subject");
if (subject == null) {
return null;
} else {
try {
// this needs to be unfolded before decodeing.
return MimeUtility.decodeText(MimeUtility.unfold(subject));
} catch (UnsupportedEncodingException e) {
// ignored.
}
}
return subject;
}
/**
* Set the value for the "Subject" header. If the subject
* contains non US-ASCII characters, it is encoded in RFC 2047
* fashion.
*
* If the subject value is null, the Subject field is removed.
*
* @param subject The new subject value.
*
* @exception MessagingException
*/
public void setSubject(String subject) throws MessagingException {
// just set this using the default character set.
setSubject(subject, null);
}
public void setSubject(String subject, String charset) throws MessagingException {
// standard null removal (yada, yada, yada....)
if (subject == null) {
removeHeader("Subject");
}
else {
try {
String s = MimeUtility.fold(9, MimeUtility.encodeText(subject, charset, null));
// encode this, and then fold to fit the line lengths.
setHeader("Subject", MimeUtility.fold(9, MimeUtility.encodeText(subject, charset, null)));
} catch (UnsupportedEncodingException e) {
throw new MessagingException("Encoding error", e);
}
}
}
/**
* Get the value of the "Date" header field. Returns null if
* if the field is absent or the date is not in a parseable format.
*
* @return A Date object parsed according to RFC 822.
* @exception MessagingException
*/
public Date getSentDate() throws MessagingException {
String value = getSingleHeader("Date");
if (value == null) {
return null;
}
try {
return dateFormat.parse(value);
} catch (java.text.ParseException e) {
return null;
}
}
/**
* Set the message sent date. This updates the "Date" header.
* If the provided date is null, the header is removed.
*
* @param sent The new sent date value.
*
* @exception MessagingException
*/
public void setSentDate(Date sent) throws MessagingException {
setOrRemoveHeader("Date", dateFormat.format(sent));
}
/**
* Get the message received date. The Sun implementation is
* documented as always returning null, so this one does too.
*
* @return Always returns null.
* @exception MessagingException
*/
public Date getReceivedDate() throws MessagingException {
return null;
}
/**
* 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 {
int size = contentStream.available();
if (size > 0) {
return size;
}
} catch (IOException e) {
// ignore
}
}
return -1;
}
/**
* Retrieve the line count for the current message. Returns
* -1 if the count cannot be determined.
*
* The Sun implementation always returns -1, so this version
* does too.
*
* @return The content line count (always -1 in this implementation).
* @exception MessagingException
*/
public int getLineCount() throws MessagingException {
return -1;
}
/**
* Returns the current content type (defined in the "Content-Type"
* header. If not available, "text/plain" is the default.
*
* @return The String name of the message content type.
* @exception MessagingException
*/
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(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 {
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(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.
String currentHeader = getSingleHeader("Content-Disposition");
if (currentHeader != null) {
ContentDisposition content = new ContentDisposition(currentHeader);
content.setDisposition(disposition);
setHeader("Content-Disposition", content.toString());
}
else {
// set using the raw string.
setHeader("Content-Disposition", disposition);
}
}
}
/**
* Decode the Content-Transfer-Encoding header to determine
* the transfer encoding type.
*
* @return The string name of the required encoding.
* @exception MessagingException
*/
public String getEncoding() throws MessagingException {
// this might require some parsing to sort out.
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.
HeaderTokenizer tokenizer = new HeaderTokenizer(encoding, HeaderTokenizer.MIME);
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(String cid) throws MessagingException {
setOrRemoveHeader("Content-ID", cid);
}
public String getContentMD5() throws MessagingException {
return getSingleHeader("Content-MD5");
}
public void setContentMD5(String md5) throws MessagingException {
setOrRemoveHeader("Content-MD5", md5);
}
public String getDescription() throws MessagingException {
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 (UnsupportedEncodingException e) {
// ignore
}
}
// return the raw version for any errors.
return description;
}
public void setDescription(String description) throws MessagingException {
setDescription(description, null);
}
public void setDescription(String description, String charset) throws MessagingException {
if (description == null) {
removeHeader("Content-Description");
}
else {
try {
setHeader("Content-Description", MimeUtility.fold(21, MimeUtility.encodeText(description, charset, null)));
} catch (UnsupportedEncodingException e) {
throw new MessagingException(e.getMessage(), e);
}
}
}
public String[] getContentLanguage() throws MessagingException {
return getHeader("Content-Language");
}
public void setContentLanguage(String[] languages) throws MessagingException {
if (languages == null) {
removeHeader("Content-Language");
} else if (languages.length == 1) {
setHeader("Content-Language", languages[0]);
} else {
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 getMessageID() throws MessagingException {
return getSingleHeader("Message-ID");
}
public String getFileName() throws MessagingException {
// see if there is a disposition. If there is, parse off the filename parameter.
String disposition = getDisposition();
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) {
String type = getContentType();
if (type != null) {
try {
filename = new ContentType(type).getParameter("name");
} catch (ParseException e) {
}
}
}
// if we have a name, we might need to decode this if an additional property is set.
if (filename != null && SessionUtil.getBooleanProperty(session, MIME_DECODEFILENAME, false)) {
try {
filename = MimeUtility.decodeText(filename);
} catch (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(session, MIME_ENCODEFILENAME, false)) {
try {
name = MimeUtility.encodeText(name);
} catch (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.
ContentDisposition contentDisposition = new ContentDisposition(disposition);
contentDisposition.setParameter("filename", name);
// serialize this back out and reset.
setDisposition(contentDisposition.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 {
return getDataHandler().getContent();
}
public void setDataHandler(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");
}
public void setContent(Object content, String type) throws MessagingException {
setDataHandler(new DataHandler(content, type));
}
public void setText(String text) throws MessagingException {
setText(text, null, "plain");
}
public void setText(String text, String charset) throws MessagingException {
setText(text, charset, "plain");
}
public void setText(String text, String charset, 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/" + subtype + "; charset=" + MimeUtility.quote(charset, HeaderTokenizer.MIME));
}
public void setContent(Multipart part) throws MessagingException {
setDataHandler(new DataHandler(part, part.getContentType()));
part.setParent(this);
}
public Message reply(boolean replyToAll) throws MessagingException {
// create a new message in this session.
MimeMessage reply = createMimeMessage(session);
// get the header and add the "Re:" bit, if necessary.
String newSubject = getSubject();
if (newSubject != null) {
// check to see if it already begins with "Re: " (in any case).
// Add one on if we don't have it yet.
if (!newSubject.regionMatches(true, 0, "Re: ", 0, 4)) {
newSubject = "Re: " + newSubject;
}
reply.setSubject(newSubject);
}
// if this message has a message ID, then add a In-Reply-To and References
// header to the reply message
String messageID = getSingleHeader("Message-ID");
if (messageID != null) {
// this one is just set unconditionally
reply.setHeader("In-Reply-To", messageID);
// we might already have a references header. If so, then add our message id
// on the the end
String references = getSingleHeader("References");
if (references == null) {
references = messageID;
}
else {
references = references + " " + messageID;
}
// and this is a replacement for whatever might be there.
reply.setHeader("References", MimeUtility.fold("References: ".length(), references));
}
Address[] toRecipients = getReplyTo();
// set the target recipients the replyTo value
reply.setRecipients(Message.RecipientType.TO, getReplyTo());
// need to reply to everybody? More things to add.
if (replyToAll) {
// when replying, we want to remove "duplicates" in the final list.
HashMap masterList = new HashMap();
// reply to all implies add the local sender. Add this to the list if resolveable.
InternetAddress localMail = InternetAddress.getLocalAddress(session);
if (localMail != null) {
masterList.put(localMail.getAddress(), localMail);
}
// see if we have some local aliases to deal with.
String alternates = session.getProperty(MAIL_ALTERNATES);
if (alternates != null) {
// parse this string list and merge with our set.
Address[] alternateList = InternetAddress.parse(alternates, false);
mergeAddressList(masterList, alternateList);
}
// the master list now contains an a list of addresses we will exclude from
// the addresses. From this point on, we're going to prune any additional addresses
// against this list, AND add any new addresses to the list
// now merge in the main recipients, and merge in the other recipents as well
Address[] toList = pruneAddresses(masterList, getRecipients(Message.RecipientType.TO));
if (toList.length != 0) {
// now check to see what sort of reply we've been asked to send.
// if replying to all as a CC, then we need to add to the CC list, otherwise they are
// TO recipients.
if (SessionUtil.getBooleanProperty(session, MAIL_REPLYALLCC, false)) {
reply.addRecipients(Message.RecipientType.CC, toList);
}
else {
reply.addRecipients(Message.RecipientType.TO, toList);
}
}
// and repeat for the CC list.
toList = pruneAddresses(masterList, getRecipients(Message.RecipientType.CC));
if (toList.length != 0) {
reply.addRecipients(Message.RecipientType.CC, toList);
}
// a news group list is separate from the normal addresses. We just take these recepients
// asis without trying to prune duplicates.
toList = getRecipients(RecipientType.NEWSGROUPS);
if (toList != null && toList.length != 0) {
reply.addRecipients(RecipientType.NEWSGROUPS, toList);
}
}
// this is a bit of a pain. We can't set the flags here by specifying the system flag, we need to
// construct a flag item instance inorder to set it.
// this is an answered email.
setFlags(new Flags(Flags.Flag.ANSWERED), true);
// all done, return the constructed Message object.
return reply;
}
/**
* Merge a set of addresses into a master accumulator list, eliminating
* duplicates.
*
* @param master The set of addresses we've accumulated so far.
* @param list The list of addresses to merge in.
*/
private void mergeAddressList(Map master, Address[] list) {
// make sure we have a list.
if (list == null) {
return;
}
for (int i = 0; i < list.length; i++) {
InternetAddress address = (InternetAddress)list[i];
// if not in the master list already, add it now.
if (!master.containsKey(address.getAddress())) {
master.put(address.getAddress(), address);
}
}
}
/**
* Prune a list of addresses against our master address list,
* returning the "new" addresses. The master list will be
* updated with this new set of addresses.
*
* @param master The master address list of addresses we've seen before.
* @param list The new list of addresses to prune.
*
* @return An array of addresses pruned of any duplicate addresses.
*/
private Address[] pruneAddresses(Map master, Address[] list) {
// return an empy array if we don't get an input list.
if (list == null) {
return new Address[0];
}
// optimistically assume there are no addresses to eliminate (common).
ArrayList prunedList = new ArrayList(list.length);
for (int i = 0; i < list.length; i++) {
InternetAddress address = (InternetAddress)list[i];
// if not in the master list, this is a new one. Add to both the master list and
// the pruned list.
if (!master.containsKey(address.getAddress())) {
master.put(address.getAddress(), address);
prunedList.add(address);
}
}
// convert back to list form.
return (Address[])prunedList.toArray(new Address[0]);
}
/**
* Write the message out to a stream in RFC 822 format.
*
* @param out The target output stream.
*
* @exception MessagingException
* @exception IOException
*/
public void writeTo(OutputStream out) throws MessagingException, IOException {
writeTo(out, null);
}
/**
* Write the message out to a target output stream, excluding the
* specified message headers.
*
* @param out The target output stream.
* @param ignoreHeaders
* An array of header types to ignore. This can be null, which means
* write out all headers.
*
* @exception MessagingException
* @exception IOException
*/
public void writeTo(OutputStream out, String[] ignoreHeaders) throws MessagingException, IOException {
// make sure everything is saved before we write
if (!saved) {
saveChanges();
}
// write out the headers first
headers.writeTo(out, ignoreHeaders);
// add the separater between the headers and the data portion.
out.write('\r');
out.write('\n');
// if the modfied flag, we don't have current content, so the data handler needs to
// take care of writing this data out.
if (modified) {
OutputStream encoderStream = MimeUtility.encode(out, getEncoding());
dh.writeTo(encoderStream);
encoderStream.flush();
} else {
// if we have content directly, we can write this out now.
if (content != null) {
out.write(content);
}
else {
// see if we can get a content stream for this message. We might have had one
// explicitly set, or a subclass might override the get method to provide one.
InputStream in = getContentStream();
byte[] buffer = new byte[8192];
int length = in.read(buffer);
// copy the data stream-to-stream.
while (length > 0) {
out.write(buffer, 0, length);
length = in.read(buffer);
}
in.close();
}
}
// flush any data we wrote out, but do not close the stream. That's the caller's duty.
out.flush();
}
/**
* Retrieve all headers that match a given name.
*
* @param name The target name.
*
* @return The set of headers that match the given name. These headers
* will be the decoded() header values if these are RFC 2047
* encoded.
* @exception MessagingException
*/
public String[] getHeader(String name) throws MessagingException {
return headers.getHeader(name);
}
/**
* Get all headers that match a particular name, as a single string.
* Individual headers are separated by the provided delimiter. If
* the delimiter is null, only the first header is returned.
*
* @param name The source header name.
* @param delimiter The delimiter string to be used between headers. If null, only
* the first is returned.
*
* @return The headers concatenated as a single string.
* @exception MessagingException
*/
public String getHeader(String name, String delimiter) throws MessagingException {
return headers.getHeader(name, delimiter);
}
/**
* Set a new value for a named header.
*
* @param name The name of the target header.
* @param value The new value for the header.
*
* @exception MessagingException
*/
public void setHeader(String name, 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(String name, String value) throws MessagingException {
if (value == null) {
headers.removeHeader(name);
}
else {
headers.setHeader(name, value);
}
}
/**
* Add a new value to an existing header. The added value is
* created as an additional header of the same type and value.
*
* @param name The name of the target header.
* @param value The removed header.
*
* @exception MessagingException
*/
public void addHeader(String name, String value) throws MessagingException {
headers.addHeader(name, value);
}
/**
* Remove a header with the given name.
*
* @param name The name of the removed header.
*
* @exception MessagingException
*/
public void removeHeader(String name) throws MessagingException {
headers.removeHeader(name);
}
/**
* Retrieve the complete list of message headers, as an enumeration.
*
* @return An Enumeration of the message headers.
* @exception MessagingException
*/
public Enumeration getAllHeaders() throws MessagingException {
return headers.getAllHeaders();
}
public Enumeration getMatchingHeaders(String[] names) throws MessagingException {
return headers.getMatchingHeaders(names);
}
public Enumeration getNonMatchingHeaders(String[] names) throws MessagingException {
return headers.getNonMatchingHeaders(names);
}
public void addHeaderLine(String line) throws MessagingException {
headers.addHeaderLine(line);
}
public Enumeration getAllHeaderLines() throws MessagingException {
return headers.getAllHeaderLines();
}
public Enumeration getMatchingHeaderLines(String[] names) throws MessagingException {
return headers.getMatchingHeaderLines(names);
}
public Enumeration getNonMatchingHeaderLines(String[] names) throws MessagingException {
return headers.getNonMatchingHeaderLines(names);
}
/**
* 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 synchronized Flags getFlags() throws MessagingException {
return (Flags) flags.clone();
}
/**
* 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 synchronized boolean isSet(Flags.Flag flag) throws MessagingException {
return flags.contains(flag);
}
/**
* Set or clear a flag value.
*
* @param flag The set of flags to effect.
* @param set The value to set the flag to (true or false).
*
* @exception MessagingException
*/
public synchronized void setFlags(Flags flag, boolean set) throws MessagingException {
if (set) {
flags.add(flag);
}
else {
flags.remove(flag);
}
}
/**
* Saves any changes on this message. When called, the modified
* and saved flags are set to true and updateHeaders() is called
* to force updates.
*
* @exception MessagingException
*/
public void saveChanges() throws MessagingException {
// setting modified invalidates the current content.
modified = true;
saved = true;
// update message headers from the content.
updateHeaders();
}
/**
* Update the internet headers so that they make sense. This
* will attempt to make sense of the message content type
* given the state of the content.
*
* @exception MessagingException
*/
protected void updateHeaders() throws MessagingException {
DataHandler handler = getDataHandler();
try {
// figure out the content type. If not set, we'll need to figure this out.
String type = dh.getContentType();
// we might need to reconcile the content type and our explicitly set type
String explicitType = getSingleHeader("Content-Type");
// parse this content type out so we can do matches/compares.
ContentType content = new ContentType(type);
// is this a multipart content?
if (content.match("multipart/*")) {
// the content is suppose to be a MimeMultipart. Ping it to update it's headers as well.
try {
MimeMultipart part = (MimeMultipart)handler.getContent();
part.updateHeaders();
} catch (ClassCastException e) {
throw new MessagingException("Message content is not MimeMultipart", e);
}
}
else if (!content.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 content.
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(session, "MIME_MAIL_SETDEFAULTTEXTCHARSET", true)) {
// is this a text type? Figure out the encoding and make sure it is set.
if (content.match("text/*")) {
// the charset should be specified as a parameter on the MIME type. If not there,
// try to figure one out.
if (content.getParameter("charset") == null) {
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")) {
content.setParameter("charset", "us-ascii");
}
else {
// get the global default.
content.setParameter("charset", MimeUtility.getDefaultMIMECharset());
}
// replace the original type string
type = content.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.
String disp = getSingleHeader("Content-Disposition");
if (disp != null) {
// parse up the string value of the disposition
ContentDisposition disposition = new ContentDisposition(disp);
// now check for a filename value
String filename = disposition.getParameter("filename");
// copy and rename the parameter, if it exists.
if (filename != null) {
content.setParameter("name", filename);
// set the header with the updated content type information.
type = content.toString();
}
}
// if no header has been set, then copy our current type string (which may
// have been modified above)
setHeader("Content-Type", type);
}
// make sure we set the MIME version
setHeader("MIME-Version", "1.0");
// new javamail 1.4 requirement.
updateMessageID();
} catch (IOException e) {
throw new MessagingException("Error updating message headers", e);
}
}
/**
* Create a new set of internet headers from the
* InputStream
*
* @param in The header source.
*
* @return A new InternetHeaders object containing the
* appropriate headers.
* @exception MessagingException
*/
protected InternetHeaders createInternetHeaders(InputStream in) throws MessagingException {
// internet headers has a constructor for just this purpose
return new InternetHeaders(in);
}
/**
* Convert a header into an array of NewsAddress items.
*
* @param header The name of the source header.
*
* @return The parsed array of addresses.
* @exception MessagingException
*/
private Address[] getHeaderAsNewsAddresses(String header) throws MessagingException {
// NB: We're using getHeader() here to allow subclasses an opportunity to perform lazy loading
// of the headers.
String mergedHeader = getHeader(header, ",");
if (mergedHeader != null) {
return NewsAddress.parse(mergedHeader);
}
return null;
}
private Address[] getHeaderAsInternetAddresses(String header, boolean strict) throws MessagingException {
// NB: We're using getHeader() here to allow subclasses an opportunity to perform lazy loading
// of the headers.
String mergedHeader = getHeader(header, ",");
if (mergedHeader != null) {
return InternetAddress.parseHeader(mergedHeader, strict);
}
return null;
}
/**
* Check to see if we require strict addressing on parsing
* internet headers.
*
* @return The current value of the "mail.mime.address.strict" session
* property, or true, if the property is not set.
*/
private boolean isStrictAddressing() {
return SessionUtil.getBooleanProperty(session, MIME_ADDRESS_STRICT, true);
}
/**
* Set a named header to the value of an address field.
*
* @param header The header name.
* @param address The address value. If the address is null, the header is removed.
*
* @exception MessagingException
*/
private void setHeader(String header, Address address) throws MessagingException {
if (address == null) {
removeHeader(header);
}
else {
setHeader(header, address.toString());
}
}
/**
* Set a header to a list of addresses.
*
* @param header The header name.
* @param addresses An array of addresses to set the header to. If null, the
* header is removed.
*/
private void setHeader(String header, Address[] addresses) {
if (addresses == null) {
headers.removeHeader(header);
}
else {
headers.setHeader(header, addresses);
}
}
private void addHeader(String header, Address[] addresses) throws MessagingException {
headers.addHeader(header, InternetAddress.toString(addresses));
}
private String getHeaderForRecipientType(Message.RecipientType type) throws MessagingException {
if (RecipientType.TO == type) {
return "To";
} else if (RecipientType.CC == type) {
return "Cc";
} else if (RecipientType.BCC == type) {
return "Bcc";
} else if (RecipientType.NEWSGROUPS == type) {
return "Newsgroups";
} else {
throw new MessagingException("Unsupported recipient type: " + type.toString());
}
}
/**
* Utility routine to get a header as a single string value
* rather than an array of headers.
*
* @param name The name of the header.
*
* @return The single string header value. If multiple headers exist,
* the additional ones are ignored.
* @exception MessagingException
*/
private String getSingleHeader(String name) throws MessagingException {
String[] values = getHeader(name);
if (values == null || values.length == 0) {
return null;
} else {
return values[0];
}
}
/**
* Update the message identifier after headers have been updated.
*
* The default message id is composed of the following items:
*
* 1) A newly created object's hash code.
* 2) A uniqueness counter
* 3) The current time in milliseconds
* 4) The string JavaMail
* 5) The user's local address as returned by InternetAddress.getLocalAddress().
*
* @exception MessagingException
*/
protected void updateMessageID() throws MessagingException {
StringBuffer id = new StringBuffer();
id.append('<');
id.append(new Object().hashCode());
id.append('.');
id.append(messageID++);
id.append(System.currentTimeMillis());
id.append('.');
id.append("JavaMail.");
// get the local address and apply a suitable default.
InternetAddress localAddress = InternetAddress.getLocalAddress(session);
if (localAddress != null) {
id.append(localAddress.getAddress());
}
else {
id.append("javamailuser@localhost");
}
id.append('>');
setHeader("Message-ID", id.toString());
}
/**
* Method used to create a new MimeMessage instance. This method
* is used whenever the MimeMessage class needs to create a new
* Message instance (e.g, reply()). This method allows subclasses
* to override the class of message that gets created or set
* default values, if needed.
*
* @param session The session associated with this message.
*
* @return A newly create MimeMessage instance.
* @throws javax.mail.MessagingException if the MimeMessage could not be created
*/
protected MimeMessage createMimeMessage(Session session) throws javax.mail.MessagingException {
return new MimeMessage(session);
}
}
| 1,051 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/MimePart.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.util.Enumeration;
import javax.mail.MessagingException;
import javax.mail.Part;
/**
* @version $Rev$ $Date$
*/
public interface MimePart extends Part {
public abstract void addHeaderLine(String line) throws MessagingException;
public abstract Enumeration getAllHeaderLines() throws MessagingException;
public abstract String getContentID() throws MessagingException;
public abstract String[] getContentLanguage() throws MessagingException;
public abstract String getContentMD5() throws MessagingException;
public abstract String getEncoding() throws MessagingException;
public abstract String getHeader(String header, String delimiter)
throws MessagingException;
public abstract Enumeration getMatchingHeaderLines(String[] names)
throws MessagingException;
public abstract Enumeration getNonMatchingHeaderLines(String[] names)
throws MessagingException;
public abstract void setContentLanguage(String[] languages)
throws MessagingException;
public abstract void setContentMD5(String content)
throws MessagingException;
public abstract void setText(String text) throws MessagingException;
public abstract void setText(String text, String charset)
throws MessagingException;
public abstract void setText(String text, String charset, String subType)
throws MessagingException;
}
| 1,052 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/MimeMultipart.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.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.MultipartDataSource;
import org.apache.geronimo.mail.util.SessionUtil;
/**
* @version $Rev$ $Date$
*/
public class MimeMultipart extends Multipart {
private static final String MIME_IGNORE_MISSING_BOUNDARY = "mail.mime.multipart.ignoremissingendboundary";
/**
* DataSource that provides our InputStream.
*/
protected DataSource ds;
/**
* Indicates if the data has been parsed.
*/
protected boolean parsed = true;
// the content type information
private transient ContentType type;
// indicates if we've seen the final boundary line when parsing.
private boolean complete = true;
// MIME multipart preable text that can appear before the first boundary line.
private String preamble = null;
/**
* Create an empty MimeMultipart with content type "multipart/mixed"
*/
public MimeMultipart() {
this("mixed");
}
/**
* Create an empty MimeMultipart with the subtype supplied.
*
* @param subtype the subtype
*/
public MimeMultipart(String subtype) {
type = new ContentType("multipart", subtype, null);
type.setParameter("boundary", getBoundary());
contentType = type.toString();
}
/**
* Create a MimeMultipart from the supplied DataSource.
*
* @param dataSource the DataSource to use
* @throws MessagingException
*/
public MimeMultipart(DataSource dataSource) throws MessagingException {
ds = dataSource;
if (dataSource instanceof MultipartDataSource) {
super.setMultipartDataSource((MultipartDataSource) dataSource);
parsed = true;
} else {
// We keep the original, provided content type string so that we
// don't end up changing quoting/formatting of the header unless
// changes are made to the content type. James is somewhat dependent
// on that behavior.
contentType = ds.getContentType();
type = new ContentType(contentType);
parsed = false;
}
}
public void setSubType(String subtype) throws MessagingException {
type.setSubType(subtype);
contentType = type.toString();
}
public int getCount() throws MessagingException {
parse();
return super.getCount();
}
public synchronized BodyPart getBodyPart(int part) throws MessagingException {
parse();
return super.getBodyPart(part);
}
public BodyPart getBodyPart(String cid) throws MessagingException {
parse();
for (int i = 0; i < parts.size(); i++) {
MimeBodyPart bodyPart = (MimeBodyPart) parts.get(i);
if (cid.equals(bodyPart.getContentID())) {
return bodyPart;
}
}
return null;
}
protected void updateHeaders() throws MessagingException {
parse();
for (int i = 0; i < parts.size(); i++) {
MimeBodyPart bodyPart = (MimeBodyPart) parts.get(i);
bodyPart.updateHeaders();
}
}
private static byte[] dash = { '-', '-' };
private static byte[] crlf = { 13, 10 };
public void writeTo(OutputStream out) throws IOException, MessagingException {
parse();
String boundary = type.getParameter("boundary");
byte[] bytes = boundary.getBytes("ISO8859-1");
if (preamble != null) {
byte[] preambleBytes = preamble.getBytes("ISO8859-1");
// write this out, followed by a line break.
out.write(preambleBytes);
out.write(crlf);
}
for (int i = 0; i < parts.size(); i++) {
BodyPart bodyPart = (BodyPart) parts.get(i);
out.write(dash);
out.write(bytes);
out.write(crlf);
bodyPart.writeTo(out);
out.write(crlf);
}
out.write(dash);
out.write(bytes);
out.write(dash);
out.write(crlf);
out.flush();
}
protected void parse() throws MessagingException {
if (parsed) {
return;
}
try {
ContentType cType = new ContentType(contentType);
InputStream is = new BufferedInputStream(ds.getInputStream());
BufferedInputStream pushbackInStream = null;
String boundaryString = cType.getParameter("boundary");
byte[] boundary = null;
if (boundaryString == null) {
pushbackInStream = new BufferedInputStream(is, 1200);
// read until we find something that looks like a boundary string
boundary = readTillFirstBoundary(pushbackInStream);
}
else {
boundary = ("--" + boundaryString).getBytes("ISO8859-1");
pushbackInStream = new BufferedInputStream(is, boundary.length + 1000);
readTillFirstBoundary(pushbackInStream, boundary);
}
while (true) {
MimeBodyPartInputStream partStream;
partStream = new MimeBodyPartInputStream(pushbackInStream, boundary);
addBodyPart(new MimeBodyPart(partStream));
// terminated by an EOF rather than a proper boundary?
if (!partStream.boundaryFound) {
if (!SessionUtil.getBooleanProperty(MIME_IGNORE_MISSING_BOUNDARY, true)) {
throw new MessagingException("Missing Multi-part end boundary");
}
complete = false;
}
// if we hit the final boundary, stop processing this
if (partStream.finalBoundaryFound) {
break;
}
}
} catch (Exception e){
throw new MessagingException(e.toString(),e);
}
parsed = true;
}
/**
* Move the read pointer to the begining of the first part
* read till the end of first boundary. Any data read before this point are
* saved as the preamble.
*
* @param pushbackInStream
* @param boundary
* @throws MessagingException
*/
private byte[] readTillFirstBoundary(BufferedInputStream pushbackInStream) throws MessagingException {
ByteArrayOutputStream preambleStream = new ByteArrayOutputStream();
try {
while (true) {
// read the next line
byte[] line = readLine(pushbackInStream);
// hit an EOF?
if (line == null) {
throw new MessagingException("Unexpected End of Stream while searching for first Mime Boundary");
}
// if this looks like a boundary, then make it so
if (line.length > 2 && line[0] == '-' && line[1] == '-') {
// save the preamble, if there is one.
byte[] preambleBytes = preambleStream.toByteArray();
if (preambleBytes.length > 0) {
preamble = new String(preambleBytes, "ISO8859-1");
}
return stripLinearWhiteSpace(line);
}
else {
// this is part of the preamble.
preambleStream.write(line);
preambleStream.write('\r');
preambleStream.write('\n');
}
}
} catch (IOException ioe) {
throw new MessagingException(ioe.toString(), ioe);
}
}
/**
* Scan a line buffer stripping off linear whitespace
* characters, returning a new array without the
* characters, if possible.
*
* @param line The source line buffer.
*
* @return A byte array with white space characters removed,
* if necessary.
*/
private byte[] stripLinearWhiteSpace(byte[] line) {
int index = line.length - 1;
// if the last character is not a space or tab, we
// can use this unchanged
if (line[index] != ' ' && line[index] != '\t') {
return line;
}
// scan backwards for the first non-white space
for (; index > 0; index--) {
if (line[index] != ' ' && line[index] != '\t') {
break;
}
}
// make a shorter copy of this
byte[] newLine = new byte[index + 1];
System.arraycopy(line, 0, newLine, 0, index + 1);
return newLine;
}
/**
* Move the read pointer to the begining of the first part
* read till the end of first boundary. Any data read before this point are
* saved as the preamble.
*
* @param pushbackInStream
* @param boundary
* @throws MessagingException
*/
private void readTillFirstBoundary(BufferedInputStream pushbackInStream, byte[] boundary) throws MessagingException {
ByteArrayOutputStream preambleStream = new ByteArrayOutputStream();
try {
while (true) {
// read the next line
byte[] line = readLine(pushbackInStream);
// hit an EOF?
if (line == null) {
throw new MessagingException("Unexpected End of Stream while searching for first Mime Boundary");
}
// apply the boundary comparison rules to this
if (compareBoundary(line, boundary)) {
// save the preamble, if there is one.
byte[] preambleBytes = preambleStream.toByteArray();
if (preambleBytes.length > 0) {
preamble = new String(preambleBytes, "ISO8859-1");
}
return;
}
// this is part of the preamble.
preambleStream.write(line);
preambleStream.write('\r');
preambleStream.write('\n');
}
} catch (IOException ioe) {
throw new MessagingException(ioe.toString(), ioe);
}
}
/**
* Peform a boundary comparison, taking into account
* potential linear white space
*
* @param line The line to compare.
* @param boundary The boundary we're searching for
*
* @return true if this is a valid boundary line, false for
* any mismatches.
*/
private boolean compareBoundary(byte[] line, byte[] boundary) {
// if the line is too short, this is an easy failure
if (line.length < boundary.length) {
return false;
}
// this is the most common situation
if (line.length == boundary.length) {
return Arrays.equals(line, boundary);
}
// the line might have linear white space after the boundary portions
for (int i = 0; i < boundary.length; i++) {
// fail on any mismatch
if (line[i] != boundary[i]) {
return false;
}
}
// everything after the boundary portion must be linear whitespace
for (int i = boundary.length; i < line.length; i++) {
// fail on any mismatch
if (line[i] != ' ' && line[i] != '\t') {
return false;
}
}
// these are equivalent
return true;
}
/**
* Read a single line of data from the input stream,
* returning it as an array of bytes.
*
* @param in The source input stream.
*
* @return A byte array containing the line data. Returns
* null if there's nothing left in the stream.
* @exception MessagingException
*/
private byte[] readLine(BufferedInputStream in) throws IOException
{
ByteArrayOutputStream line = new ByteArrayOutputStream();
while (in.available() > 0) {
int value = in.read();
if (value == -1) {
// if we have nothing in the accumulator, signal an EOF back
if (line.size() == 0) {
return null;
}
break;
}
else if (value == '\r') {
in.mark(10);
value = in.read();
// we expect to find a linefeed after the carriage return, but
// some things play loose with the rules.
if (value != '\n') {
in.reset();
}
break;
}
else if (value == '\n') {
// naked linefeed, allow that
break;
}
else {
// write this to the line
line.write((byte)value);
}
}
// return this as an array of bytes
return line.toByteArray();
}
protected InternetHeaders createInternetHeaders(InputStream in) throws MessagingException {
return new InternetHeaders(in);
}
protected MimeBodyPart createMimeBodyPart(InternetHeaders headers, byte[] data) throws MessagingException {
return new MimeBodyPart(headers, data);
}
protected MimeBodyPart createMimeBodyPart(InputStream in) throws MessagingException {
return new MimeBodyPart(in);
}
// static used to track boudary value allocations to help ensure uniqueness.
private static int part;
private synchronized static String getBoundary() {
int i;
synchronized(MimeMultipart.class) {
i = part++;
}
StringBuffer buf = new StringBuffer(64);
buf.append("----=_Part_").append(i).append('_').append((new Object()).hashCode()).append('.').append(System.currentTimeMillis());
return buf.toString();
}
private class MimeBodyPartInputStream extends InputStream {
BufferedInputStream inStream;
public boolean boundaryFound = false;
byte[] boundary;
public boolean finalBoundaryFound = false;
public MimeBodyPartInputStream(BufferedInputStream inStream, byte[] boundary) {
super();
this.inStream = inStream;
this.boundary = boundary;
}
/**
* The base reading method for reading one character
* at a time.
*
* @return The read character, or -1 if an EOF was encountered.
* @exception IOException
*/
public int read() throws IOException {
if (boundaryFound) {
return -1;
}
// read the next value from stream
int firstChar = inStream.read();
// premature end? Handle it like a boundary located
if (firstChar == -1) {
boundaryFound = true;
// also mark this as the end
finalBoundaryFound = true;
return -1;
}
// we first need to look for a line boundary. If we find a boundary, it can be followed by the
// boundary marker, so we need to remember what sort of thing we found, then read ahead looking
// for the part boundary.
// NB:, we only handle [\r]\n--boundary marker[--]
// we need to at least accept what most mail servers would consider an
// invalid format using just '\n'
if (firstChar != '\r' && firstChar != '\n') {
// not a \r, just return the byte as is
return firstChar;
}
// we might need to rewind to this point. The padding is to allow for
// line terminators and linear whitespace on the boundary lines
inStream.mark(boundary.length + 1000);
// we need to keep track of the first read character in case we need to
// rewind back to the mark point
int value = firstChar;
// if this is a '\r', then we require the '\n'
if (value == '\r') {
// now scan ahead for the second character
value = inStream.read();
if (value != '\n') {
// only a \r, so this can't be a boundary. Return the
// \r as if it was data, after first resetting
inStream.reset();
return '\r';
}
}
value = inStream.read();
// if the next character is not a boundary start, we
// need to handle this as a normal line end
if ((byte) value != boundary[0]) {
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// we're here because we found a "\r\n-" sequence, which is a potential
// boundary marker. Read the individual characters of the next line until
// we have a mismatch
// read value is the first byte of the boundary. Start matching the
// next characters to find a boundary
int boundaryIndex = 0;
while ((boundaryIndex < boundary.length) && ((byte) value == boundary[boundaryIndex])) {
value = inStream.read();
boundaryIndex++;
}
// if we didn't match all the way, we need to push back what we've read and
// return the EOL character
if (boundaryIndex != boundary.length) {
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// The full boundary sequence should be \r\n--boundary string[--]\r\n
// if the last character we read was a '-', check for the end terminator
if (value == '-') {
value = inStream.read();
// crud, we have a bad boundary terminator. We need to unwind this all the way
// back to the lineend and pretend none of this ever happened
if (value != '-') {
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// on the home stretch, but we need to verify the LWSP/EOL sequence
value = inStream.read();
// first skip over the linear whitespace
while (value == ' ' || value == '\t') {
value = inStream.read();
}
// We've matched the final boundary, skipped any whitespace, but
// we've hit the end of the stream. This is highly likely when
// we have nested multiparts, since the linend terminator for the
// final boundary marker is eated up as the start of the outer
// boundary marker. No CRLF sequence here is ok.
if (value == -1) {
// we've hit the end of times...
finalBoundaryFound = true;
// we have a boundary, so return this as an EOF condition
boundaryFound = true;
return -1;
}
// this must be a CR or a LF...which leaves us even more to push back and forget
if (value != '\r' && value != '\n') {
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// if this is carriage return, check for a linefeed
if (value == '\r') {
// last check, this must be a line feed
value = inStream.read();
if (value != '\n') {
// SO CLOSE!
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
}
// we've hit the end of times...
finalBoundaryFound = true;
}
else {
// first skip over the linear whitespace
while (value == ' ' || value == '\t') {
value = inStream.read();
}
// this must be a CR or a LF...which leaves us even more to push back and forget
if (value != '\r' && value != '\n') {
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// if this is carriage return, check for a linefeed
if (value == '\r') {
// last check, this must be a line feed
value = inStream.read();
if (value != '\n') {
// SO CLOSE!
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
}
}
// we have a boundary, so return this as an EOF condition
boundaryFound = true;
return -1;
}
}
/**
* Return true if the final boundary line for this multipart was
* seen when parsing the data.
*
* @return
* @exception MessagingException
*/
public boolean isComplete() throws MessagingException {
// make sure we've parsed this
parse();
return complete;
}
/**
* Returns the preamble text that appears before the first bady
* part of a MIME multi part. The preamble is optional, so this
* might be null.
*
* @return The preamble text string.
* @exception MessagingException
*/
public String getPreamble() throws MessagingException {
parse();
return preamble;
}
/**
* Set the message preamble text. This will be written before
* the first boundary of a multi-part message.
*
* @param preamble The new boundary text. This is complete lines of text, including
* new lines.
*
* @exception MessagingException
*/
public void setPreamble(String preamble) throws MessagingException {
this.preamble = preamble;
}
}
| 1,053 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/PreencodedMimeBodyPart.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.IOException;
import java.io.OutputStream;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public class PreencodedMimeBodyPart extends MimeBodyPart {
// the defined transfer encoding
private String transferEncoding;
/**
* Create a new body part with the specified MIME transfer encoding.
*
* @param encoding The content encoding.
*/
public PreencodedMimeBodyPart(String encoding) {
transferEncoding = encoding;
}
/**
* Retieve the defined encoding for this body part.
*
* @return
* @exception MessagingException
*/
public String getEncoding() throws MessagingException {
return transferEncoding;
}
/**
* Write the body part content to the stream without applying
* and additional encodings.
*
* @param out The target output stream.
*
* @exception IOException
* @exception MessagingException
*/
public void writeTo(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');
// write this out without getting an encoding stream
getDataHandler().writeTo(out);
out.flush();
}
/**
* Override of update headers to ensure the transfer encoding
* is forced to the correct type.
*
* @exception MessagingException
*/
protected void updateHeaders() throws MessagingException {
super.updateHeaders();
setHeader("Content-Transfer-Encoding", transferEncoding);
}
}
| 1,054 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/NewsAddress.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.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.mail.Address;
/**
* A representation of an RFC1036 Internet newsgroup address.
*
* @version $Rev$ $Date$
*/
public class NewsAddress extends Address {
private static final long serialVersionUID = -4203797299824684143L;
/**
* The host for this newsgroup
*/
protected String host;
/**
* The name of this newsgroup
*/
protected String newsgroup;
public NewsAddress() {
}
public NewsAddress(String newsgroup) {
this.newsgroup = newsgroup;
}
public NewsAddress(String newsgroup, String host) {
this.newsgroup = newsgroup;
this.host = host;
}
/**
* The type of this address; always "news".
* @return "news"
*/
public String getType() {
return "news";
}
public void setNewsgroup(String newsgroup) {
this.newsgroup = newsgroup;
}
public String getNewsgroup() {
return newsgroup;
}
public void setHost(String host) {
this.host = host;
}
public String getHost() {
return host;
}
public String toString() {
// Sun impl only appears to return the newsgroup name, no host.
return newsgroup;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof NewsAddress)) return false;
final NewsAddress newsAddress = (NewsAddress) o;
if (host != null ? !host.equals(newsAddress.host) : newsAddress.host != null) return false;
if (newsgroup != null ? !newsgroup.equals(newsAddress.newsgroup) : newsAddress.newsgroup != null) return false;
return true;
}
public int hashCode() {
int result;
result = (host != null ? host.toLowerCase().hashCode() : 0);
result = 29 * result + (newsgroup != null ? newsgroup.hashCode() : 0);
return result;
}
/**
* Parse a comma-spearated list of addresses.
*
* @param addresses the list to parse
* @return the array of extracted addresses
* @throws AddressException if one of the addresses is invalid
*/
public static NewsAddress[] parse(String addresses) throws AddressException {
List result = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(addresses, ",");
while (tokenizer.hasMoreTokens()) {
String address = tokenizer.nextToken().trim();
int index = address.indexOf('@');
if (index == -1) {
result.add(new NewsAddress(address));
} else {
String newsgroup = address.substring(0, index).trim();
String host = address.substring(index+1).trim();
result.add(new NewsAddress(newsgroup, host));
}
}
return (NewsAddress[]) result.toArray(new NewsAddress[result.size()]);
}
/**
* Convert the supplied addresses to a comma-separated String.
* If addresses is null, returns null; if empty, returns an empty string.
*
* @param addresses the addresses to convert
* @return a comma-separated list of addresses
*/
public static String toString(Address[] addresses) {
if (addresses == null) {
return null;
}
if (addresses.length == 0) {
return "";
}
StringBuffer result = new StringBuffer(addresses.length * 32);
result.append(addresses[0]);
for (int i = 1; i < addresses.length; i++) {
result.append(',').append(addresses[i].toString());
}
return result.toString();
}
}
| 1,055 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/internet/AddressParser.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.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
class AddressParser {
// the validation strictness levels, from most lenient to most conformant.
static public final int NONSTRICT = 0;
static public final int PARSE_HEADER = 1;
static public final int STRICT = 2;
// different mailbox types
static protected final int UNKNOWN = 0;
static protected final int ROUTE_ADDR = 1;
static protected final int GROUP_ADDR = 2;
static protected final int SIMPLE_ADDR = 3;
// constants for token types.
static protected final int END_OF_TOKENS = '\0';
static protected final int PERIOD = '.';
static protected final int LEFT_ANGLE = '<';
static protected final int RIGHT_ANGLE = '>';
static protected final int COMMA = ',';
static protected final int AT_SIGN = '@';
static protected final int SEMICOLON = ';';
static protected final int COLON = ':';
static protected final int QUOTED_LITERAL = '"';
static protected final int DOMAIN_LITERAL = '[';
static protected final int COMMENT = '(';
static protected final int ATOM = 'A';
static protected final int WHITESPACE = ' ';
// the string we're parsing
private String addresses;
// the current parsing position
private int position;
// the end position of the string
private int end;
// the strictness flag
private int validationLevel;
public AddressParser(String addresses, int validation) {
this.addresses = addresses;
validationLevel = validation;
}
/**
* Parse an address list into an array of internet addresses.
*
* @return An array containing all of the non-null addresses in the list.
* @exception AddressException
* Thrown for any validation errors.
*/
public InternetAddress[] parseAddressList() throws AddressException
{
// get the address as a set of tokens we can process.
TokenStream tokens = tokenizeAddress();
// get an array list accumulator.
ArrayList addressList = new ArrayList();
// we process sections of the token stream until we run out of tokens.
while (true) {
// parse off a single address. Address lists can have null elements,
// so this might return a null value. The null value does not get added
// to the address accumulator.
addressList.addAll(parseSingleAddress(tokens, false));
// This token should be either a "," delimiter or a stream terminator. If we're
// at the end, time to get out.
AddressToken token = tokens.nextToken();
if (token.type == END_OF_TOKENS) {
break;
}
}
return (InternetAddress [])addressList.toArray(new InternetAddress[0]);
}
/**
* Parse a single internet address. This must be a single address,
* not an address list.
*
* @exception AddressException
*/
public InternetAddress parseAddress() throws AddressException
{
// get the address as a set of tokens we can process.
TokenStream tokens = tokenizeAddress();
// parse off a single address. Address lists can have null elements,
// so this might return a null value. The null value does not get added
// to the address accumulator.
List addressList = parseSingleAddress(tokens, false);
// we must get exactly one address back from this.
if (addressList.isEmpty()) {
throw new AddressException("Null address", addresses, 0);
}
// this could be a simple list of blank delimited tokens. Ensure we only got one back.
if (addressList.size() > 1) {
throw new AddressException("Illegal Address", addresses, 0);
}
// This token must be a stream stream terminator, or we have an error.
AddressToken token = tokens.nextToken();
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal Address", token);
}
return (InternetAddress)addressList.get(0);
}
/**
* Validate an internet address. This must be a single address,
* not a list of addresses. The address also must not contain
* and personal information to be valid.
*
* @exception AddressException
*/
public void validateAddress() throws AddressException
{
// get the address as a set of tokens we can process.
TokenStream tokens = tokenizeAddress();
// parse off a single address. Address lists can have null elements,
// so this might return a null value. The null value does not get added
// to the address accumulator.
List addressList = parseSingleAddress(tokens, false);
if (addressList.isEmpty()) {
throw new AddressException("Null address", addresses, 0);
}
// this could be a simple list of blank delimited tokens. Ensure we only got one back.
if (addressList.size() > 1) {
throw new AddressException("Illegal Address", addresses, 0);
}
InternetAddress address = (InternetAddress)addressList.get(0);
// validation occurs on an address that's already been split into personal and address
// data.
if (address.personal != null) {
throw new AddressException("Illegal Address", addresses, 0);
}
// This token must be a stream stream terminator, or we have an error.
AddressToken token = tokens.nextToken();
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal Address", token);
}
}
/**
* Extract the set of address from a group Internet specification.
*
* @return An array containing all of the non-null addresses in the list.
* @exception AddressException
*/
public InternetAddress[] extractGroupList() throws AddressException
{
// get the address as a set of tokens we can process.
TokenStream tokens = tokenizeAddress();
// get an array list accumulator.
ArrayList addresses = new ArrayList();
AddressToken token = tokens.nextToken();
// scan forward to the ':' that starts the group list. If we don't find one,
// this is an exception.
while (token.type != COLON) {
if (token.type == END_OF_TOKENS) {
illegalAddress("Missing ':'", token);
}
token = tokens.nextToken();
}
// we process sections of the token stream until we run out of tokens.
while (true) {
// parse off a single address. Address lists can have null elements,
// so this might return a null value. The null value does not get added
// to the address accumulator.
addresses.addAll(parseSingleAddress(tokens, true));
// This token should be either a "," delimiter or a group terminator. If we're
// at the end, this is an error.
token = tokens.nextToken();
if (token.type == SEMICOLON) {
break;
}
else if (token.type == END_OF_TOKENS) {
illegalAddress("Missing ';'", token);
}
}
return (InternetAddress [])addresses.toArray(new InternetAddress[0]);
}
/**
* Parse out a single address from a string from a string
* of address tokens, returning an InternetAddress object that
* represents the address.
*
* @param tokens The token source for this address.
*
* @return A parsed out and constructed InternetAddress object for
* the next address. Returns null if this is an "empty"
* address in a list.
* @exception AddressException
*/
private List parseSingleAddress(TokenStream tokens, boolean inGroup) throws AddressException
{
List parsedAddresses = new ArrayList();
// index markers for personal information
AddressToken personalStart = null;
AddressToken personalEnd = null;
// and similar bits for the address information.
AddressToken addressStart = null;
AddressToken addressEnd = null;
// there is a fall-back set of rules allowed that will parse the address as a set of blank delimited
// tokens. However, we do NOT allow this if we encounter any tokens that fall outside of these
// rules. For example, comment fields and quoted strings will disallow the very lenient rule set.
boolean nonStrictRules = true;
// we don't know the type of address yet
int addressType = UNKNOWN;
// the parsing goes in two stages. Stage one runs through the tokens locating the bounds
// of the address we're working on, resolving the personal information, and also validating
// some of the larger scale syntax features of an address (matched delimiters for routes and
// groups, invalid nesting checks, etc.).
// get the next token from the queue and save this. We're going to scan ahead a bit to
// figure out what type of address we're looking at, then reset to do the actually parsing
// once we've figured out a form.
AddressToken first = tokens.nextToken();
// push it back on before starting processing.
tokens.pushToken(first);
// scan ahead for a trigger token that tells us what we've got.
while (addressType == UNKNOWN) {
AddressToken token = tokens.nextToken();
switch (token.type) {
// skip these for now...after we've processed everything and found that this is a simple
// address form, then we'll check for a leading comment token in the first position and use
// if as personal information.
case COMMENT:
// comments do, however, denote that this must be parsed according to RFC822 rules.
nonStrictRules = false;
break;
// a semi-colon when processing a group is an address terminator. we need to
// process this like a comma then
case SEMICOLON:
if (inGroup) {
// we need to push the terminator back on for the caller to see.
tokens.pushToken(token);
// if we've not tagged any tokens as being the address beginning, so this must be a
// null address.
if (addressStart == null) {
// just return the empty list from this.
return parsedAddresses;
}
// the end token is the back part.
addressEnd = tokens.previousToken(token);
// without a '<' for a route addr, we can't distinguish address tokens from personal data.
// We'll use a leading comment, if there is one.
personalStart = null;
// this is just a simple form.
addressType = SIMPLE_ADDR;
break;
}
// NOTE: The above falls through if this is not a group.
// any of these tokens are a real token that can be the start of an address. Many of
// them are not valid as first tokens in this context, but we flag them later if validation
// has been requested. For now, we just mark these as the potential address start.
case DOMAIN_LITERAL:
case QUOTED_LITERAL:
// this set of tokens require fuller RFC822 parsing, so turn off the flag.
nonStrictRules = false;
case ATOM:
case AT_SIGN:
case PERIOD:
// if we're not determined the start of the address yet, then check to see if we
// need to consider this the personal start.
if (addressStart == null) {
if (personalStart == null) {
personalStart = token;
}
// This is the first real token of the address, which at this point can
// be either the personal info or the first token of the address. If we hit
// an address terminator without encountering either a route trigger or group
// trigger, then this is the real address.
addressStart = token;
}
break;
// a LEFT_ANGLE indicates we have a full RFC822 mailbox form. The leading phrase
// is the personal info. The address is inside the brackets.
case LEFT_ANGLE:
// a route address automatically switches off the blank-delimited token mode.
nonStrictRules = false;
// this is a route address
addressType = ROUTE_ADDR;
// the address is placed in the InternetAddress object without the route
// brackets, so our start is one past this.
addressStart = tokens.nextRealToken();
// push this back on the queue so the scanner picks it up properly.
tokens.pushToken(addressStart);
// make sure we flag the end of the personal section too.
if (personalStart != null) {
personalEnd = tokens.previousToken(token);
}
// scan the rest of a route address.
addressEnd = scanRouteAddress(tokens, false);
break;
// a COLON indicates this is a group specifier...parse the group.
case COLON:
// Colons would not be valid in simple lists, so turn it off.
nonStrictRules = false;
// if we're scanning a group, we shouldn't encounter a ":". This is a
// recursion error if found.
if (inGroup) {
illegalAddress("Nested group element", token);
}
addressType = GROUP_ADDR;
// groups don't have any personal sections.
personalStart = null;
// our real start was back at the beginning
addressStart = first;
addressEnd = scanGroupAddress(tokens);
break;
// a semi colon can the same as a comma if we're processing a group.
// reached the end of string...this might be a null address, or one of the very simple name
// forms used for non-strict RFC822 versions. Reset, and try that form
case END_OF_TOKENS:
// if we're scanning a group, we shouldn't encounter an end token. This is an
// error if found.
if (inGroup) {
illegalAddress("Missing ';'", token);
}
// NOTE: fall through from above.
// this is either a terminator for an address list or a a group terminator.
case COMMA:
// we need to push the terminator back on for the caller to see.
tokens.pushToken(token);
// if we've not tagged any tokens as being the address beginning, so this must be a
// null address.
if (addressStart == null) {
// just return the empty list from this.
return parsedAddresses;
}
// the end token is the back part.
addressEnd = tokens.previousToken(token);
// without a '<' for a route addr, we can't distinguish address tokens from personal data.
// We'll use a leading comment, if there is one.
personalStart = null;
// this is just a simple form.
addressType = SIMPLE_ADDR;
break;
// right angle tokens are pushed, because parsing of the bracketing is not necessarily simple.
// we need to flag these here.
case RIGHT_ANGLE:
illegalAddress("Unexpected '>'", token);
}
}
String personal = null;
// if we have personal data, then convert it to a string value.
if (personalStart != null) {
TokenStream personalTokens = tokens.section(personalStart, personalEnd);
personal = personalToString(personalTokens);
}
// if we have a simple address, then check the first token to see if it's a comment. For simple addresses,
// we'll accept the first comment token as the personal information.
else {
if (addressType == SIMPLE_ADDR && first.type == COMMENT) {
personal = first.value;
}
}
TokenStream addressTokens = tokens.section(addressStart, addressEnd);
// if this is one of the strictly RFC822 types, then we always validate the address. If this is a
// a simple address, then we only validate if strict parsing rules are in effect or we've been asked
// to validate.
if (validationLevel != PARSE_HEADER) {
switch (addressType) {
case GROUP_ADDR:
validateGroup(addressTokens);
break;
case ROUTE_ADDR:
validateRouteAddr(addressTokens, false);
break;
case SIMPLE_ADDR:
// this is a conditional validation
validateSimpleAddress(addressTokens);
break;
}
}
// more complex addresses and addresses containing tokens other than just simple addresses
// need proper handling.
if (validationLevel != NONSTRICT || addressType != SIMPLE_ADDR || !nonStrictRules) {
// we might have traversed this already when we validated, so reset the
// position before using this again.
addressTokens.reset();
String address = addressToString(addressTokens);
// get the parsed out sections as string values.
InternetAddress result = new InternetAddress();
result.setAddress(address);
try {
result.setPersonal(personal);
} catch (UnsupportedEncodingException e) {
}
// even though we have a single address, we return this as an array. Simple addresses
// can be produce an array of items, so we need to return everything.
parsedAddresses.add(result);
return parsedAddresses;
}
else {
addressTokens.reset();
TokenStream nextAddress = addressTokens.getBlankDelimitedToken();
while (nextAddress != null) {
String address = addressToString(nextAddress);
// get the parsed out sections as string values.
InternetAddress result = new InternetAddress();
result.setAddress(address);
parsedAddresses.add(result);
nextAddress = addressTokens.getBlankDelimitedToken();
}
return parsedAddresses;
}
}
/**
* Scan the token stream, parsing off a route addr spec. This
* will do some basic syntax validation, but will not actually
* validate any of the address information. Comments will be
* discarded.
*
* @param tokens The stream of tokens.
*
* @return The last token of the route address (the one preceeding the
* terminating '>'.
*/
private AddressToken scanRouteAddress(TokenStream tokens, boolean inGroup) throws AddressException {
// get the first token and ensure we have something between the "<" and ">".
AddressToken token = tokens.nextRealToken();
// the last processed non-whitespace token, which is the actual address end once the
// right angle bracket is encountered.
AddressToken previous = null;
// if this route-addr has route information, the first token after the '<' must be a '@'.
// this determines if/where a colon or comma can appear.
boolean inRoute = token.type == AT_SIGN;
// now scan until we reach the terminator. The only validation is done on illegal characters.
while (true) {
switch (token.type) {
// The following tokens are all valid between the brackets, so just skip over them.
case ATOM:
case QUOTED_LITERAL:
case DOMAIN_LITERAL:
case PERIOD:
case AT_SIGN:
break;
case COLON:
// if not processing route information, this is illegal.
if (!inRoute) {
illegalAddress("Unexpected ':'", token);
}
// this is the end of the route information, the rules now change.
inRoute = false;
break;
case COMMA:
// if not processing route information, this is illegal.
if (!inRoute) {
illegalAddress("Unexpected ','", token);
}
break;
case RIGHT_ANGLE:
// if previous is null, we've had a route address which is "<>". That's illegal.
if (previous == null) {
illegalAddress("Illegal address", token);
}
// step to the next token..this had better be either a comma for another address or
// the very end of the address list .
token = tokens.nextRealToken();
// if we're scanning part of a group, then the allowed terminators are either ',' or ';'.
if (inGroup) {
if (token.type != COMMA && token.type != SEMICOLON) {
illegalAddress("Illegal address", token);
}
}
// a normal address should have either a ',' for a list or the end.
else {
if (token.type != COMMA && token.type != END_OF_TOKENS) {
illegalAddress("Illegal address", token);
}
}
// we need to push the termination token back on.
tokens.pushToken(token);
// return the previous token as the updated position.
return previous;
case END_OF_TOKENS:
illegalAddress("Missing '>'", token);
// now for the illegal ones in this context.
case SEMICOLON:
illegalAddress("Unexpected ';'", token);
case LEFT_ANGLE:
illegalAddress("Unexpected '<'", token);
}
// remember the previous token.
previous = token;
token = tokens.nextRealToken();
}
}
/**
* Scan the token stream, parsing off a group address. This
* will do some basic syntax validation, but will not actually
* validate any of the address information. Comments will be
* ignored.
*
* @param tokens The stream of tokens.
*
* @return The last token of the group address (the terminating ':").
*/
private AddressToken scanGroupAddress(TokenStream tokens) throws AddressException {
// A group does not require that there be anything between the ':' and ';". This is
// just a group with an empty list.
AddressToken token = tokens.nextRealToken();
// now scan until we reach the terminator. The only validation is done on illegal characters.
while (true) {
switch (token.type) {
// The following tokens are all valid in group addresses, so just skip over them.
case ATOM:
case QUOTED_LITERAL:
case DOMAIN_LITERAL:
case PERIOD:
case AT_SIGN:
case COMMA:
break;
case COLON:
illegalAddress("Nested group", token);
// route address within a group specifier....we need to at least verify the bracket nesting
// and higher level syntax of the route.
case LEFT_ANGLE:
scanRouteAddress(tokens, true);
break;
// the only allowed terminator is the ';'
case END_OF_TOKENS:
illegalAddress("Missing ';'", token);
// now for the illegal ones in this context.
case SEMICOLON:
// verify there's nothing illegal after this.
AddressToken next = tokens.nextRealToken();
if (next.type != COMMA && next.type != END_OF_TOKENS) {
illegalAddress("Illegal address", token);
}
// don't forget to put this back on...our caller will need it.
tokens.pushToken(next);
return token;
case RIGHT_ANGLE:
illegalAddress("Unexpected '>'", token);
}
token = tokens.nextRealToken();
}
}
/**
* Parse the provided internet address into a set of tokens. This
* phase only does a syntax check on the tokens. The interpretation
* of the tokens is the next phase.
*
* @exception AddressException
*/
private TokenStream tokenizeAddress() throws AddressException {
// get a list for the set of tokens
TokenStream tokens = new TokenStream();
end = addresses.length(); // our parsing end marker
// now scan along the string looking for the special characters in an internet address.
while (moreCharacters()) {
char ch = currentChar();
switch (ch) {
// start of a comment bit...ignore everything until we hit a closing paren.
case '(':
scanComment(tokens);
break;
// a closing paren found outside of normal processing.
case ')':
syntaxError("Unexpected ')'", position);
// start of a quoted string
case '"':
scanQuotedLiteral(tokens);
break;
// domain literal
case '[':
scanDomainLiteral(tokens);
break;
// a naked closing bracket...not valid except as part of a domain literal.
case ']':
syntaxError("Unexpected ']'", position);
// special character delimiters
case '<':
tokens.addToken(new AddressToken(LEFT_ANGLE, position));
nextChar();
break;
// a naked closing bracket...not valid without a starting one, but
// we need to handle this in context.
case '>':
tokens.addToken(new AddressToken(RIGHT_ANGLE, position));
nextChar();
break;
case ':':
tokens.addToken(new AddressToken(COLON, position));
nextChar();
break;
case ',':
tokens.addToken(new AddressToken(COMMA, position));
nextChar();
break;
case '.':
tokens.addToken(new AddressToken(PERIOD, position));
nextChar();
break;
case ';':
tokens.addToken(new AddressToken(SEMICOLON, position));
nextChar();
break;
case '@':
tokens.addToken(new AddressToken(AT_SIGN, position));
nextChar();
break;
// white space characters. These are mostly token delimiters, but there are some relaxed
// situations where they get processed, so we need to add a white space token for the first
// one we encounter in a span.
case ' ':
case '\t':
case '\r':
case '\n':
// add a single white space token
tokens.addToken(new AddressToken(WHITESPACE, position));
nextChar();
// step over any space characters, leaving us positioned either at the end
// or the first
while (moreCharacters()) {
char nextChar = currentChar();
if (nextChar == ' ' || nextChar == '\t' || nextChar == '\r' || nextChar == '\n') {
nextChar();
}
else {
break;
}
}
break;
// potentially an atom...if it starts with an allowed atom character, we
// parse out the token, otherwise this is invalid.
default:
if (ch < 040 || ch >= 0177) {
syntaxError("Illegal character in address", position);
}
scanAtom(tokens);
break;
}
}
// for this end marker, give an end position.
tokens.addToken(new AddressToken(END_OF_TOKENS, addresses.length()));
return tokens;
}
/**
* Step to the next character position while parsing.
*/
private void nextChar() {
position++;
}
/**
* Retrieve the character at the current parsing position.
*
* @return The current character.
*/
private char currentChar() {
return addresses.charAt(position);
}
/**
* Test if there are more characters left to parse.
*
* @return True if we've hit the last character, false otherwise.
*/
private boolean moreCharacters() {
return position < end;
}
/**
* Parse a quoted string as specified by the RFC822 specification.
*
* @param tokens The TokenStream where the parsed out token is added.
*/
private void scanQuotedLiteral(TokenStream tokens) throws AddressException {
StringBuffer value = new StringBuffer();
// save the start position for the token.
//int startPosition = position;
// step over the quote delimiter.
nextChar();
while (moreCharacters()) {
char ch = currentChar();
// is this an escape char?
if (ch == '\\') {
// step past this, and grab the following character
nextChar();
if (!moreCharacters()) {
syntaxError("Missing '\"'", position);
}
value.append(currentChar());
}
// end of the string?
else if (ch == '"') {
// return the constructed string.
tokens.addToken(new AddressToken(value.toString(), QUOTED_LITERAL, position));
// step over the close delimiter for the benefit of the next token.
nextChar();
return;
}
// the RFC822 spec disallows CR characters.
else if (ch == '\r') {
syntaxError("Illegal line end in literal", position);
}
else
{
value.append(ch);
}
nextChar();
}
// missing delimiter
syntaxError("Missing '\"'", position);
}
/**
* Parse a domain literal as specified by the RFC822 specification.
*
* @param tokens The TokenStream where the parsed out token is added.
*/
private void scanDomainLiteral(TokenStream tokens) throws AddressException {
StringBuffer value = new StringBuffer();
int startPosition = position;
// step over the quote delimiter.
nextChar();
while (moreCharacters()) {
char ch = currentChar();
// is this an escape char?
if (ch == '\\') {
// because domain literals don't get extra escaping, we render them
// with the escaped characters intact. Therefore, append the '\' escape
// first, then append the escaped character without examination.
value.append(currentChar());
// step past this, and grab the following character
nextChar();
if (!moreCharacters()) {
syntaxError("Missing '\"'", position);
}
value.append(currentChar());
}
// end of the string?
else if (ch == ']') {
// return the constructed string.
tokens.addToken(new AddressToken(value.toString(), DOMAIN_LITERAL, startPosition));
// step over the close delimiter for the benefit of the next token.
nextChar();
return;
}
// the RFC822 spec says no nesting
else if (ch == '[') {
syntaxError("Unexpected '['", position);
}
// carriage returns are similarly illegal.
else if (ch == '\r') {
syntaxError("Illegal line end in domain literal", position);
}
else
{
value.append(ch);
}
nextChar();
}
// missing delimiter
syntaxError("Missing ']'", position);
}
/**
* Scan an atom in an internet address, using the RFC822 rules
* for atom delimiters.
*
* @param tokens The TokenStream where the parsed out token is added.
*/
private void scanAtom(TokenStream tokens) throws AddressException {
int start = position;
nextChar();
while (moreCharacters()) {
char ch = currentChar();
if (isAtom(ch)) {
nextChar();
}
else {
break;
}
}
// return the scanned part of the string.
tokens.addToken(new AddressToken(addresses.substring(start, position), ATOM, start));
}
/**
* Parse an internet address comment field as specified by
* RFC822. Includes support for quoted characters and nesting.
*
* @param tokens The TokenStream where the parsed out token is added.
*/
private void scanComment(TokenStream tokens) throws AddressException {
StringBuffer value = new StringBuffer();
int startPosition = position;
// step past the start character
nextChar();
// we're at the top nesting level on the comment.
int nest = 1;
// scan while we have more characters.
while (moreCharacters()) {
char ch = currentChar();
// escape character?
if (ch == '\\') {
// step over this...if escaped, we must have at least one more character
// in the string.
nextChar();
if (!moreCharacters()) {
syntaxError("Missing ')'", position);
}
value.append(currentChar());
}
// nested comment?
else if (ch == '(') {
// step the nesting level...we treat the comment as a single unit, with the delimiters
// for the nested comments embedded in the middle
nest++;
value.append(ch);
}
// is this the comment close?
else if (ch == ')') {
// reduce the nesting level. If we still have more to process, add the delimiter character
// and keep going.
nest--;
if (nest > 0) {
value.append(ch);
}
else {
// step past this and return. The outermost comment delimiter is not included in
// the string value, since this is frequently used as personal data on the
// InternetAddress objects.
nextChar();
tokens.addToken(new AddressToken(value.toString(), COMMENT, startPosition));
return;
}
}
else if (ch == '\r') {
syntaxError("Illegal line end in comment", position);
}
else {
value.append(ch);
}
// step to the next character.
nextChar();
}
// ran out of data before seeing the closing bit, not good
syntaxError("Missing ')'", position);
}
/**
* Validate the syntax of an RFC822 group internet address specification.
*
* @param tokens The stream of tokens for the address.
*
* @exception AddressException
*/
private void validateGroup(TokenStream tokens) throws AddressException {
// we know already this is an address in the form "phrase:group;". Now we need to validate the
// elements.
int phraseCount = 0;
AddressToken token = tokens.nextRealToken();
// now scan to the colon, ensuring we have only word or comment tokens.
while (token.type != COLON) {
// only these tokens are allowed here.
if (token.type != ATOM && token.type != QUOTED_LITERAL) {
invalidToken(token);
}
phraseCount++;
token = tokens.nextRealToken();
}
// RFC822 groups require a leading phrase in group specifiers.
if (phraseCount == 0) {
illegalAddress("Missing group identifier phrase", token);
}
// now we do the remainder of the parsing using the initial phrase list as the sink...the entire
// address will be converted to a string later.
// ok, we only know this has been valid up to the ":", now we have some real checks to perform.
while (true) {
// go scan off a mailbox. if everything goes according to plan, we should be positioned at either
// a comma or a semicolon.
validateGroupMailbox(tokens);
token = tokens.nextRealToken();
// we're at the end of the group. Make sure this is truely the end.
if (token.type == SEMICOLON) {
token = tokens.nextRealToken();
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal group address", token);
}
return;
}
// if not a semicolon, this better be a comma.
else if (token.type != COMMA) {
illegalAddress("Illegal group address", token);
}
}
}
/**
* Validate the syntax of single mailbox within a group address.
*
* @param tokens The stream of tokens representing the address.
*
* @exception AddressException
*/
private void validateGroupMailbox(TokenStream tokens) throws AddressException {
AddressToken token = tokens.nextRealToken();
// is this just a null address in the list? then push the terminator back and return.
if (token.type == COMMA || token.type == SEMICOLON) {
tokens.pushToken(token);
return;
}
final AddressToken firstToken = token;
// we need to scan forward to figure out what sort of address this is.
while (token != null) {
switch (token.type) {
// until we know the context, these are all just ignored.
case QUOTED_LITERAL:
case ATOM:
break;
// a LEFT_ANGLE indicates we have a full RFC822 mailbox form. The leading phrase
// is the personal info. The address is inside the brackets.
case LEFT_ANGLE:
validatePhrase(tokens.section(firstToken, token), false);
validateRouteAddr(tokens, true);
return;
// we've hit a period as the first non-word token. This should be part of a local-part
// of an address.
case PERIOD:
// we've hit an "@" as the first non-word token. This is probably a simple address in
// the form "user@domain".
case AT_SIGN:
tokens.pushToken(firstToken);
validateAddressSpec(tokens);
return;
// reached the end of string...this might be a null address, or one of the very simple name
// forms used for non-strict RFC822 versions. Reset, and try that form
case COMMA:
// this is the end of the group...handle it like a comma for now.
case SEMICOLON:
tokens.pushToken(firstToken);
validateAddressSpec(tokens);
return;
case END_OF_TOKENS:
illegalAddress("Missing ';'", token);
}
token = tokens.nextRealToken();
}
}
/**
* Utility method for throwing an AddressException caused by an
* unexpected primitive token.
*
* @param token The token causing the problem (must not be a value type token).
*
* @exception AddressException
*/
private void invalidToken(AddressToken token) throws AddressException {
illegalAddress("Unexpected '" + token.type + "'", token);
}
/**
* Raise an error about illegal syntax.
*
* @param message The message used in the thrown exception.
* @param position The parsing position within the string.
*
* @exception AddressException
*/
private void syntaxError(String message, int position) throws AddressException
{
throw new AddressException(message, addresses, position);
}
/**
* Throw an exception based on the position of an invalid token.
*
* @param message The exception message.
* @param token The token causing the error. This tokens position is used
* in the exception information.
*/
private void illegalAddress(String message, AddressToken token) throws AddressException {
throw new AddressException(message, addresses, token.position);
}
/**
* Validate that a required phrase exists.
*
* @param tokens The set of tokens to validate. positioned at the phrase start.
* @param required A flag indicating whether the phrase is optional or required.
*
* @exception AddressException
*/
private void validatePhrase(TokenStream tokens, boolean required) throws AddressException {
// we need to have at least one WORD token in the phrase...everything is optional
// after that.
AddressToken token = tokens.nextRealToken();
if (token.type != ATOM && token.type != QUOTED_LITERAL) {
if (required) {
illegalAddress("Missing group phrase", token);
}
}
// now scan forward to the end of the phrase
token = tokens.nextRealToken();
while (token.type == ATOM || token.type == QUOTED_LITERAL) {
token = tokens.nextRealToken();
}
}
/**
* validate a routeaddr specification
*
* @param tokens The tokens representing the address portion (personal information
* already removed).
* @param ingroup true indicates we're validating a route address inside a
* group list. false indicates we're validating a standalone
* address.
*
* @exception AddressException
*/
private void validateRouteAddr(TokenStream tokens, boolean ingroup) throws AddressException {
// get the next real token.
AddressToken token = tokens.nextRealToken();
// if this is an at sign, then we have a list of domains to parse.
if (token.type == AT_SIGN) {
// push the marker token back in for the route parser, and step past that part.
tokens.pushToken(token);
validateRoute(tokens);
}
else {
// we need to push this back on to validate the local part.
tokens.pushToken(token);
}
// now we expect to see an address spec.
validateAddressSpec(tokens);
token = tokens.nextRealToken();
if (ingroup) {
// if we're validating within a group specification, the angle brackets are still there (and
// required).
if (token.type != RIGHT_ANGLE) {
illegalAddress("Missing '>'", token);
}
}
else {
// the angle brackets were removed to make this an address, so we should be done. Make sure we
// have a terminator here.
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal Address", token);
}
}
}
/**
* Validate a simple address in the form "user@domain".
*
* @param tokens The stream of tokens representing the address.
*/
private void validateSimpleAddress(TokenStream tokens) throws AddressException {
// the validation routines occur after addresses have been split into
// personal and address forms. Therefore, our validation begins directly
// with the first token.
validateAddressSpec(tokens);
// get the next token and see if there is something here...anything but the terminator is an error
AddressToken token = tokens.nextRealToken();
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal Address", token);
}
}
/**
* Validate the addr-spec portion of an address. RFC822 requires
* this be of the form "local-part@domain". However, javamail also
* allows simple address of the form "local-part". We only require
* the domain if an '@' is encountered.
*
* @param tokens
*/
private void validateAddressSpec(TokenStream tokens) throws AddressException {
// all addresses, even the simple ones, must have at least a local part.
validateLocalPart(tokens);
// now see if we have a domain portion to look at.
AddressToken token = tokens.nextRealToken();
if (token.type == AT_SIGN) {
validateDomain(tokens);
}
else {
// put this back for termination
tokens.pushToken(token);
}
}
/**
* Validate the route portion of a route-addr. This is a list
* of domain values in the form 1#("@" domain) ":".
*
* @param tokens The token stream holding the address information.
*/
private void validateRoute(TokenStream tokens) throws AddressException {
while (true) {
AddressToken token = tokens.nextRealToken();
// if this is the first part of the list, go parse off a domain
if (token.type == AT_SIGN) {
validateDomain(tokens);
}
// another element in the list? Go around again
else if (token.type == COMMA) {
continue;
}
// the list is terminated by a colon...stop this part of the validation once we hit one.
else if (token.type == COLON) {
return;
}
// the list is terminated by a colon. If this isn't one of those, we have an error.
else {
illegalAddress("Missing ':'", token);
}
}
}
/**
* Parse the local part of an address spec. The local part
* is a series of "words" separated by ".".
*/
private void validateLocalPart(TokenStream tokens) throws AddressException {
while (true) {
// get the token.
final AddressToken token1 = tokens.nextRealToken();
// this must be either an atom or a literal or a period (GERONIMO-5842)
if (token1.type != ATOM && token1.type != QUOTED_LITERAL && token1.type != PERIOD) {
illegalAddress("Invalid local part", token1);
}
// get the next token (white space and comments ignored)
final AddressToken token2 = tokens.nextRealToken();
tokens.pushToken(token2); //do not consume this token
// if we encounter a @ sign or the end of the token return
if (token2.type == AT_SIGN || token2.type == COMMA || token2.type == SEMICOLON || token2.type == END_OF_TOKENS) {
return;
} else if(token2.type == ATOM && (token1.type != PERIOD)) {
illegalAddress("Invalid local part", token2);
}
}
}
/**
* Parse a domain name of the form sub-domain *("." sub-domain).
* a sub-domain is either an atom or a domain-literal.
*/
private void validateDomain(TokenStream tokens) throws AddressException {
while (true) {
// get the token.
AddressToken token = tokens.nextRealToken();
// this must be either an atom or a domain literal.
if (token.type != ATOM && token.type != DOMAIN_LITERAL) {
illegalAddress("Invalid domain", token);
}
// get the next token (white space is ignored)
token = tokens.nextRealToken();
// if this is a period, we continue parsing
if (token.type != PERIOD) {
// return the token
tokens.pushToken(token);
return;
}
}
}
/**
* Convert a list of word tokens into a phrase string. The
* rules for this are a little hard to puzzle out, but there
* is a logic to it. If the list is empty, the phrase is
* just a null value.
*
* If we have a phrase, then the quoted strings need to
* handled appropriately. In multi-token phrases, the
* quoted literals are concatenated with the quotes intact,
* regardless of content. Thus a phrase that comes in like this:
*
* "Geronimo" Apache
*
* gets converted back to the same string.
*
* If there is just a single token in the phrase, AND the token
* is a quoted string AND the string does not contain embedded
* special characters ("\.,@<>()[]:;), then the phrase
* is expressed as an atom. Thus the literal
*
* "Geronimo"
*
* becomes
*
* Geronimo
*
* but
*
* "(Geronimo)"
*
* remains
*
* "(Geronimo)"
*
* Note that we're generating a canonical form of the phrase,
* which removes comments and reduces linear whitespace down
* to a single separator token.
*
* @param phrase An array list of phrase tokens (which may be empty).
*/
private String personalToString(TokenStream tokens) {
// no tokens in the stream? This is a null value.
AddressToken token = tokens.nextToken();
if (token.type == END_OF_TOKENS) {
return null;
}
AddressToken next = tokens.nextToken();
// single element phrases get special treatment.
if (next.type == END_OF_TOKENS) {
// this can be used directly...if it contains special characters, quoting will be
// performed when it's converted to a string value.
return token.value;
}
// reset to the beginning
tokens.pushToken(token);
// have at least two tokens,
StringBuffer buffer = new StringBuffer();
// get the first token. After the first, we add these as blank delimited values.
token = tokens.nextToken();
addTokenValue(token, buffer);
token = tokens.nextToken();
while (token.type != END_OF_TOKENS) {
// add a blank separator
buffer.append(' ');
// now add the next tokens value
addTokenValue(token, buffer);
token = tokens.nextToken();
}
// and return the canonicalized value
return buffer.toString();
}
/**
* take a canonicalized set of address tokens and reformat it back into a string value,
* inserting whitespace where appropriate.
*
* @param tokens The set of tokens representing the address.
*
* @return The string value of the tokens.
*/
private String addressToString(TokenStream tokens) {
StringBuffer buffer = new StringBuffer();
// this flag controls whether we insert a blank delimiter between tokens as
// we advance through the list. Blanks are only inserted between consequtive value tokens.
// Initially, this is false, then we flip it to true whenever we add a value token, and
// back to false for any special character token.
boolean spaceRequired = false;
// we use nextToken rather than nextRealToken(), since we need to process the comments also.
AddressToken token = tokens.nextToken();
// now add each of the tokens
while (token.type != END_OF_TOKENS) {
switch (token.type) {
// the word tokens are the only ones where we need to worry about adding
// whitespace delimiters.
case ATOM:
case QUOTED_LITERAL:
// was the last token also a word? Insert a blank first.
if (spaceRequired) {
buffer.append(' ');
}
addTokenValue(token, buffer);
// let the next iteration know we just added a word to the list.
spaceRequired = true;
break;
// these special characters are just added in. The constants for the character types
// were carefully selected to be the character value in question. This allows us to
// just append the value.
case LEFT_ANGLE:
case RIGHT_ANGLE:
case COMMA:
case COLON:
case AT_SIGN:
case SEMICOLON:
case PERIOD:
buffer.append((char)token.type);
// no spaces around specials
spaceRequired = false;
break;
// Domain literals self delimiting...we can just append them and turn off the space flag.
case DOMAIN_LITERAL:
addTokenValue(token, buffer);
spaceRequired = false;
break;
// Comments are also self delimitin.
case COMMENT:
addTokenValue(token, buffer);
spaceRequired = false;
break;
}
token = tokens.nextToken();
}
return buffer.toString();
}
/**
* Append a value token on to a string buffer used to create
* the canonicalized string value.
*
* @param token The token we're adding.
* @param buffer The target string buffer.
*/
private void addTokenValue(AddressToken token, StringBuffer buffer) {
// atom values can be added directly.
if (token.type == ATOM) {
buffer.append(token.value);
}
// a literal value? Add this as a quoted string
else if (token.type == QUOTED_LITERAL) {
buffer.append(formatQuotedString(token.value));
}
// could be a domain literal of the form "[value]"
else if (token.type == DOMAIN_LITERAL) {
buffer.append('[');
buffer.append(token.value);
buffer.append(']');
}
// comments also have values
else if (token.type == COMMENT) {
buffer.append('(');
buffer.append(token.value);
buffer.append(')');
}
}
private static final byte[] CHARMAP = {
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x06, 0x02, 0x06, 0x02, 0x02, 0x06, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
};
private static final byte FLG_SPECIAL = 1;
private static final byte FLG_CONTROL = 2;
//private static final byte FLG_SPACE = 4;
/*private static boolean isSpace(char ch) {
if (ch > '\u007f') {
return false;
} else {
return (CHARMAP[ch] & FLG_SPACE) != 0;
}
}*/
/**
* Quick test to see if a character is an allowed atom character
* or not.
*
* @param ch The test character.
*
* @return true if this character is allowed in atoms, false for any
* control characters, special characters, or blanks.
*/
public static boolean isAtom(char ch) {
if (ch > '\u007f') {
return false;
}
else if (ch == ' ') {
return false;
}
else {
return (CHARMAP[ch] & (FLG_SPECIAL | FLG_CONTROL)) == 0;
}
}
/**
* Tests one string to determine if it contains any of the
* characters in a supplied test string.
*
* @param s The string we're testing.
* @param chars The set of characters we're testing against.
*
* @return true if any of the characters is found, false otherwise.
*/
public static boolean containsCharacters(String s, String chars)
{
for (int i = 0; i < s.length(); i++) {
if (chars.indexOf(s.charAt(i)) >= 0) {
return true;
}
}
return false;
}
/**
* Tests if a string contains any non-special characters that
* would require encoding the value as a quoted string rather
* than a simple atom value.
*
* @param s The test string.
*
* @return True if the string contains only blanks or allowed atom
* characters.
*/
public static boolean containsSpecials(String s)
{
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// must be either a blank or an allowed atom char.
if (ch == ' ' || isAtom(ch)) {
continue;
}
else {
return true;
}
}
return false;
}
/**
* Tests if a string contains any non-special characters that
* would require encoding the value as a quoted string rather
* than a simple atom value.
*
* @param s The test string.
*
* @return True if the string contains only blanks or allowed atom
* characters.
*/
public static boolean isAtom(String s)
{
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// must be an allowed atom character
if (!isAtom(ch)) {
return false;
}
}
return true;
}
/**
* Apply RFC822 quoting rules to a literal string value. This
* will search the string to see if there are any characters that
* require special escaping, and apply the escapes. If the
* string is just a string of blank-delimited atoms, the string
* value is returned without quotes.
*
* @param s The source string.
*
* @return A version of the string as a valid RFC822 quoted literal.
*/
public static String quoteString(String s) {
// only backslash and double quote require escaping. If the string does not
// contain any of these, then we can just slap on some quotes and go.
if (s.indexOf('\\') == -1 && s.indexOf('"') == -1) {
// if the string is an atom (or a series of blank-delimited atoms), we can just return it directly.
if (!containsSpecials(s)) {
return s;
}
StringBuffer buffer = new StringBuffer(s.length() + 2);
buffer.append('"');
buffer.append(s);
buffer.append('"');
return buffer.toString();
}
// get a buffer sufficiently large for the string, two quote characters, and a "reasonable"
// number of escaped values.
StringBuffer buffer = new StringBuffer(s.length() + 10);
buffer.append('"');
// now check all of the characters.
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// character requiring escaping?
if (ch == '\\' || ch == '"') {
// add an extra backslash
buffer.append('\\');
}
// and add on the character
buffer.append(ch);
}
buffer.append('"');
return buffer.toString();
}
/**
* Apply RFC822 quoting rules to a literal string value. This
* will search the string to see if there are any characters that
* require special escaping, and apply the escapes. The returned
* value is enclosed in quotes.
*
* @param s The source string.
*
* @return A version of the string as a valid RFC822 quoted literal.
*/
public static String formatQuotedString(String s) {
// only backslash and double quote require escaping. If the string does not
// contain any of these, then we can just slap on some quotes and go.
if (s.indexOf('\\') == -1 && s.indexOf('"') == -1) {
StringBuffer buffer = new StringBuffer(s.length() + 2);
buffer.append('"');
buffer.append(s);
buffer.append('"');
return buffer.toString();
}
// get a buffer sufficiently large for the string, two quote characters, and a "reasonable"
// number of escaped values.
StringBuffer buffer = new StringBuffer(s.length() + 10);
buffer.append('"');
// now check all of the characters.
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// character requiring escaping?
if (ch == '\\' || ch == '"') {
// add an extra backslash
buffer.append('\\');
}
// and add on the character
buffer.append(ch);
}
buffer.append('"');
return buffer.toString();
}
public class TokenStream {
// the set of tokens in the parsed address list, as determined by RFC822 syntax rules.
private List tokens;
// the current token position
int currentToken = 0;
/**
* Default constructor for a TokenStream. This creates an
* empty TokenStream for purposes of tokenizing an address.
* It is the creator's responsibility to terminate the stream
* with a terminator token.
*/
public TokenStream() {
tokens = new ArrayList();
}
/**
* Construct a TokenStream from a list of tokens. A terminator
* token is added to the end.
*
* @param tokens An existing token list.
*/
public TokenStream(List tokens) {
this.tokens = tokens;
tokens.add(new AddressToken(END_OF_TOKENS, -1));
}
/**
* Add an address token to the token list.
*
* @param t The new token to add to the list.
*/
public void addToken(AddressToken token) {
tokens.add(token);
}
/**
* Get the next token at the cursor position, advancing the
* position accordingly.
*
* @return The token at the current token position.
*/
public AddressToken nextToken() {
AddressToken token = (AddressToken)tokens.get(currentToken++);
// we skip over white space tokens when operating in this mode, so
// check the token and iterate until we get a non-white space.
while (token.type == WHITESPACE) {
token = (AddressToken)tokens.get(currentToken++);
}
return token;
}
/**
* Get the next token at the cursor position, without advancing the
* position.
*
* @return The token at the current token position.
*/
public AddressToken currentToken() {
// return the current token and step the cursor
return (AddressToken)tokens.get(currentToken);
}
/**
* Get the next non-comment token from the string. Comments are ignored, except as personal information
* for very simple address specifications.
*
* @return A token guaranteed not to be a whitespace token.
*/
public AddressToken nextRealToken()
{
AddressToken token = nextToken();
if (token.type == COMMENT) {
token = nextToken();
}
return token;
}
/**
* Push a token back on to the queue, making the index of this
* token the current cursor position.
*
* @param token The token to push.
*/
public void pushToken(AddressToken token) {
// just reset the cursor to the token's index position.
currentToken = tokenIndex(token);
}
/**
* Get the next token after a given token, without advancing the
* token position.
*
* @param token The token we're retrieving a token relative to.
*
* @return The next token in the list.
*/
public AddressToken nextToken(AddressToken token) {
return (AddressToken)tokens.get(tokenIndex(token) + 1);
}
/**
* Return the token prior to a given token.
*
* @param token The token used for the index.
*
* @return The token prior to the index token in the list.
*/
public AddressToken previousToken(AddressToken token) {
return (AddressToken)tokens.get(tokenIndex(token) - 1);
}
/**
* Retrieve a token at a given index position.
*
* @param index The target index.
*/
public AddressToken getToken(int index)
{
return (AddressToken)tokens.get(index);
}
/**
* Retrieve the index of a particular token in the stream.
*
* @param token The target token.
*
* @return The index of the token within the stream. Returns -1 if this
* token is somehow not in the stream.
*/
public int tokenIndex(AddressToken token) {
return tokens.indexOf(token);
}
/**
* Extract a new TokenStream running from the start token to the
* token preceeding the end token.
*
* @param start The starting token of the section.
* @param end The last token (+1) for the target section.
*
* @return A new TokenStream object for processing this section of tokens.
*/
public TokenStream section(AddressToken start, AddressToken end) {
int startIndex = tokenIndex(start);
int endIndex = tokenIndex(end);
// List.subList() returns a list backed by the original list. Since we need to add a
// terminator token to this list when we take the sublist, we need to manually copy the
// references so we don't end up munging the original list.
ArrayList list = new ArrayList(endIndex - startIndex + 2);
for (int i = startIndex; i <= endIndex; i++) {
list.add(tokens.get(i));
}
return new TokenStream(list);
}
/**
* Reset the token position back to the beginning of the
* stream.
*/
public void reset() {
currentToken = 0;
}
/**
* Scan forward looking for a non-blank token.
*
* @return The first non-blank token in the stream.
*/
public AddressToken getNonBlank()
{
AddressToken token = currentToken();
while (token.type == WHITESPACE) {
currentToken++;
token = currentToken();
}
return token;
}
/**
* Extract a blank delimited token from a TokenStream. A blank
* delimited token is the set of tokens up to the next real whitespace
* token (comments not included).
*
* @return A TokenStream object with the new set of tokens.
*/
public TokenStream getBlankDelimitedToken()
{
// get the next non-whitespace token.
AddressToken first = getNonBlank();
// if this is the end, we return null.
if (first.type == END_OF_TOKENS) {
return null;
}
AddressToken last = first;
// the methods for retrieving tokens skip over whitespace, so we're going to process this
// by index.
currentToken++;
AddressToken token = currentToken();
while (true) {
// if this is our marker, then pluck out the section and return it.
if (token.type == END_OF_TOKENS || token.type == WHITESPACE) {
return section(first, last);
}
last = token;
currentToken++;
// we accept any and all tokens here.
token = currentToken();
}
}
/**
* Return the index of the current cursor position.
*
* @return The integer index of the current token.
*/
public int currentIndex() {
return currentToken;
}
public void dumpTokens()
{
System.out.println(">>>>>>>>> Start dumping TokenStream tokens");
for (int i = 0; i < tokens.size(); i++) {
System.out.println("-------- Token: " + tokens.get(i));
}
System.out.println("++++++++ cursor position=" + currentToken);
System.out.println(">>>>>>>>> End dumping TokenStream tokens");
}
}
/**
* Simple utility class for representing address tokens.
*/
public class AddressToken {
// the token type
int type;
// string value of the token (can be null)
String value;
// position of the token within the address string.
int position;
AddressToken(int type, int position)
{
this.type = type;
this.value = null;
this.position = position;
}
AddressToken(String value, int type, int position)
{
this.type = type;
this.value = value;
this.position = position;
}
public String toString()
{
if (type == END_OF_TOKENS) {
return "AddressToken: type=END_OF_TOKENS";
}
if (value == null) {
return "AddressToken: type=" + (char)type;
}
else {
return "AddressToken: type=" + (char)type + " value=" + value;
}
}
}
}
| 1,056 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/MessageCountListener.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 java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface MessageCountListener extends EventListener {
public abstract void messagesAdded(MessageCountEvent event);
public abstract void messagesRemoved(MessageCountEvent event);
}
| 1,057 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/ConnectionAdapter.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;
/**
* An adaptor that receives connection events.
* This is a default implementation where the handlers perform no action.
*
* @version $Rev$ $Date$
*/
public abstract class ConnectionAdapter implements ConnectionListener {
public void closed(ConnectionEvent event) {
}
public void disconnected(ConnectionEvent event) {
}
public void opened(ConnectionEvent event) {
}
}
| 1,058 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/StoreListener.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 java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface StoreListener extends EventListener {
public abstract void notification(StoreEvent event);
}
| 1,059 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/MessageChangedListener.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 java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface MessageChangedListener extends EventListener {
public abstract void messageChanged(MessageChangedEvent event);
}
| 1,060 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/FolderEvent.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;
/**
* @version $Rev$ $Date$
*/
public class FolderEvent extends MailEvent {
private static final long serialVersionUID = 5278131310563694307L;
public static final int CREATED = 1;
public static final int DELETED = 2;
public static final int RENAMED = 3;
protected transient Folder folder;
protected transient Folder newFolder;
protected int type;
/**
* Constructor used for RENAMED events.
*
* @param source the source of the event
* @param oldFolder the folder that was renamed
* @param newFolder the folder with the new name
* @param type the event type
*/
public FolderEvent(Object source, Folder oldFolder, Folder newFolder, int type) {
super(source);
folder = oldFolder;
this.newFolder = newFolder;
this.type = type;
}
/**
* Constructor other events.
*
* @param source the source of the event
* @param folder the folder affected
* @param type the event type
*/
public FolderEvent(Object source, Folder folder, int type) {
this(source, folder, null, type);
}
public void dispatch(Object listener) {
FolderListener l = (FolderListener) listener;
switch (type) {
case CREATED:
l.folderCreated(this);
break;
case DELETED:
l.folderDeleted(this);
break;
case RENAMED:
l.folderRenamed(this);
break;
default:
throw new IllegalArgumentException("Invalid type " + type);
}
}
/**
* Return the affected folder.
* @return the affected folder
*/
public Folder getFolder() {
return folder;
}
/**
* Return the new folder; only applicable to RENAMED events.
* @return the new folder
*/
public Folder getNewFolder() {
return newFolder;
}
/**
* Return the event type.
* @return the event type
*/
public int getType() {
return type;
}
}
| 1,061 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/FolderAdapter.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;
/**
* An adaptor that receives connection events.
* This is a default implementation where the handlers perform no action.
*
* @version $Rev$ $Date$
*/
public abstract class FolderAdapter implements FolderListener {
public void folderCreated(FolderEvent event) {
}
public void folderDeleted(FolderEvent event) {
}
public void folderRenamed(FolderEvent event) {
}
}
| 1,062 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/ConnectionListener.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 java.util.EventListener;
/**
* Listener for handling connection events.
*
* @version $Rev$ $Date$
*/
public interface ConnectionListener extends EventListener {
/**
* Called when a connection is opened.
*/
public abstract void opened(ConnectionEvent event);
/**
* Called when a connection is disconnected.
*/
public abstract void disconnected(ConnectionEvent event);
/**
* Called when a connection is closed.
*/
public abstract void closed(ConnectionEvent event);
}
| 1,063 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/TransportListener.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 java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface TransportListener extends EventListener {
public abstract void messageDelivered(TransportEvent event);
public abstract void messageNotDelivered(TransportEvent event);
public abstract void messagePartiallyDelivered(TransportEvent event);
}
| 1,064 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/MessageChangedEvent.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.Message;
/**
* @version $Rev$ $Date$
*/
public class MessageChangedEvent extends MailEvent {
private static final long serialVersionUID = -4974972972105535108L;
/**
* The message's flags changed.
*/
public static final int FLAGS_CHANGED = 1;
/**
* The messages envelope changed.
*/
public static final int ENVELOPE_CHANGED = 2;
protected transient Message msg;
protected int type;
/**
* Constructor.
*
* @param source the folder that owns the message
* @param type the event type
* @param message the affected message
*/
public MessageChangedEvent(Object source, int type, Message message) {
super(source);
msg = message;
this.type = type;
}
public void dispatch(Object listener) {
MessageChangedListener l = (MessageChangedListener) listener;
l.messageChanged(this);
}
/**
* Return the affected message.
* @return the affected message
*/
public Message getMessage() {
return msg;
}
/**
* Return the type of change.
* @return the event type
*/
public int getMessageChangeType() {
return type;
}
}
| 1,065 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/MessageCountAdapter.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;
/**
* An adaptor that receives message count events.
* This is a default implementation where the handlers perform no action.
*
* @version $Rev$ $Date$
*/
public abstract class MessageCountAdapter implements MessageCountListener {
public void messagesAdded(MessageCountEvent event) {
}
public void messagesRemoved(MessageCountEvent event) {
}
}
| 1,066 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/TransportAdapter.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;
/**
* An adaptor that receives transport events.
* This is a default implementation where the handlers perform no action.
*
* @version $Rev$ $Date$
*/
public abstract class TransportAdapter implements TransportListener {
public void messageDelivered(TransportEvent event) {
}
public void messageNotDelivered(TransportEvent event) {
}
public void messagePartiallyDelivered(TransportEvent event) {
}
}
| 1,067 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/FolderListener.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 java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface FolderListener extends EventListener {
public abstract void folderCreated(FolderEvent event);
public abstract void folderDeleted(FolderEvent event);
public abstract void folderRenamed(FolderEvent event);
}
| 1,068 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/MailEvent.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 java.util.EventObject;
/**
* Common base class for mail events.
*
* @version $Rev$ $Date$
*/
public abstract class MailEvent extends EventObject {
private static final long serialVersionUID = 1846275636325456631L;
public MailEvent(Object source) {
super(source);
}
public abstract void dispatch(Object listener);
}
| 1,069 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/MessageCountEvent.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.Message;
/**
* Event indicating a change in the number of messages in a folder.
*
* @version $Rev$ $Date$
*/
public class MessageCountEvent extends MailEvent {
private static final long serialVersionUID = -7447022340837897369L;
/**
* Messages were added to the folder.
*/
public static final int ADDED = 1;
/**
* Messages were removed from the folder.
*/
public static final int REMOVED = 2;
/**
* The affected messages.
*/
protected transient Message msgs[];
/**
* The event type.
*/
protected int type;
/**
* If true, then messages were expunged from the folder by this client
* and message numbers reflect the deletion; if false, then the change
* was the result of an expunge by a different client.
*/
protected boolean removed;
/**
* Construct a new event.
*
* @param folder the folder containing the messages
* @param type the event type
* @param removed indicator of whether messages were expunged by this client
* @param messages the affected messages
*/
public MessageCountEvent(Folder folder, int type, boolean removed, Message messages[]) {
super(folder);
this.msgs = messages;
this.type = type;
this.removed = removed;
}
/**
* Return the event type.
*
* @return the event type
*/
public int getType() {
return type;
}
/**
* @return whether this event was the result of an expunge by this client
* @see MessageCountEvent#removed
*/
public boolean isRemoved() {
return removed;
}
/**
* Return the affected messages.
*
* @return the affected messages
*/
public Message[] getMessages() {
return msgs;
}
public void dispatch(Object listener) {
MessageCountListener l = (MessageCountListener) listener;
switch (type) {
case ADDED:
l.messagesAdded(this);
break;
case REMOVED:
l.messagesRemoved(this);
break;
default:
throw new IllegalArgumentException("Invalid type " + type);
}
}
}
| 1,070 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/StoreEvent.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.Store;
/**
* Event representing motifications from the Store connection.
*
* @version $Rev$ $Date$
*/
public class StoreEvent extends MailEvent {
private static final long serialVersionUID = 1938704919992515330L;
/**
* Indicates that this message is an alert.
*/
public static final int ALERT = 1;
/**
* Indicates that this message is a notice.
*/
public static final int NOTICE = 2;
/**
* The message type.
*/
protected int type;
/**
* The text to be presented to the user.
*/
protected String message;
/**
* Construct a new event.
*
* @param store the Store that initiated the notification
* @param type the message type
* @param message the text to be presented to the user
*/
public StoreEvent(Store store, int type, String message) {
super(store);
this.type = type;
this.message = message;
}
/**
* Return the message type.
*
* @return the message type
*/
public int getMessageType() {
return type;
}
/**
* Return the text to be displayed to the user.
*
* @return the text to be displayed to the user
*/
public String getMessage() {
return message;
}
public void dispatch(Object listener) {
((StoreListener) listener).notification(this);
}
}
| 1,071 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/TransportEvent.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.Address;
import javax.mail.Message;
import javax.mail.Transport;
/**
* @version $Rev$ $Date$
*/
public class TransportEvent extends MailEvent {
private static final long serialVersionUID = -4729852364684273073L;
/**
* Indicates that the message has successfully been delivered to all
* recipients.
*/
public static final int MESSAGE_DELIVERED = 1;
/**
* Indicates that no messages could be delivered.
*/
public static final int MESSAGE_NOT_DELIVERED = 2;
/**
* Indicates that some of the messages were successfully delivered
* but that some failed.
*/
public static final int MESSAGE_PARTIALLY_DELIVERED = 3;
/**
* The event type.
*/
protected int type;
/**
* Addresses to which the message was successfully delivered.
*/
protected transient Address[] validSent;
/**
* Addresses which are valid but to which the message was not sent.
*/
protected transient Address[] validUnsent;
/**
* Addresses that are invalid.
*/
protected transient Address[] invalid;
/**
* The message associated with this event.
*/
protected transient Message msg;
/**
* Construct a new event,
*
* @param transport the transport attempting to deliver the message
* @param type the event type
* @param validSent addresses to which the message was successfully delivered
* @param validUnsent addresses which are valid but to which the message was not sent
* @param invalid invalid addresses
* @param message the associated message
*/
public TransportEvent(Transport transport, int type, Address[] validSent, Address[] validUnsent, Address[] invalid, Message message) {
super(transport);
this.type = type;
this.validSent = validSent;
this.validUnsent = validUnsent;
this.invalid = invalid;
this.msg = message;
}
public Address[] getValidSentAddresses() {
return validSent;
}
public Address[] getValidUnsentAddresses() {
return validUnsent;
}
public Address[] getInvalidAddresses() {
return invalid;
}
public Message getMessage() {
return msg;
}
public int getType() {
return type;
}
public void dispatch(Object listener) {
TransportListener l = (TransportListener) listener;
switch (type) {
case MESSAGE_DELIVERED:
l.messageDelivered(this);
break;
case MESSAGE_NOT_DELIVERED:
l.messageNotDelivered(this);
break;
case MESSAGE_PARTIALLY_DELIVERED:
l.messagePartiallyDelivered(this);
break;
default:
throw new IllegalArgumentException("Invalid type " + type);
}
}
}
| 1,072 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/javax/mail/event/ConnectionEvent.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;
/**
* @version $Rev$ $Date$
*/
public class ConnectionEvent extends MailEvent {
private static final long serialVersionUID = -1855480171284792957L;
/**
* A connection was opened.
*/
public static final int OPENED = 1;
/**
* A connection was disconnected.
*/
public static final int DISCONNECTED = 2;
/**
* A connection was closed.
*/
public static final int CLOSED = 3;
protected int type;
public ConnectionEvent(Object source, int type) {
super(source);
this.type = type;
}
public int getType() {
return type;
}
public void dispatch(Object listener) {
// assume that it is the right listener type
ConnectionListener l = (ConnectionListener) listener;
switch (type) {
case OPENED:
l.opened(this);
break;
case DISCONNECTED:
l.disconnected(this);
break;
case CLOSED:
l.closed(this);
break;
default:
throw new IllegalArgumentException("Invalid type " + type);
}
}
}
| 1,073 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/xml/rpc | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/xml/rpc/handler/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.
*/
//
// 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.xml.rpc.handler;
import java.util.Iterator;
/**
* @version $Rev$ $Date$
*/
public interface MessageContext {
boolean containsProperty(String name);
Object getProperty(String name);
Iterator getPropertyNames();
void removeProperty(String name);
void setProperty(String name, Object value);
}
| 1,074 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/EJBTransactionRequiredException.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.ejb;
/**
* @version $Rev: 467742 $ $Date: 2006-10-25 12:30:38 -0700 (Wed, 25 Oct 2006) $
*/
public class EJBTransactionRequiredException extends EJBException {
public EJBTransactionRequiredException() {
super();
}
public EJBTransactionRequiredException(String message) {
super(message);
}
}
| 1,075 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/Local.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Local {
Class[] value() default {};
}
| 1,076 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/SessionBean.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.ejb;
import java.rmi.RemoteException;
/**
* @version $Rev$ $Date$
*/
public interface SessionBean extends EnterpriseBean {
void ejbActivate() throws EJBException, RemoteException;
void ejbPassivate() throws EJBException, RemoteException;
void ejbRemove() throws EJBException, RemoteException;
void setSessionContext(SessionContext ctx) throws EJBException, RemoteException;
}
| 1,077 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/DuplicateKeyException.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.ejb;
/**
* @version $Rev$ $Date$
*/
public class DuplicateKeyException extends CreateException {
public DuplicateKeyException() {
super();
}
public DuplicateKeyException(String message) {
super(message);
}
}
| 1,078 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/FinderException.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.ejb;
/**
* @version $Rev$ $Date$
*/
public class FinderException extends Exception {
public FinderException() {
super();
}
public FinderException(String message) {
super(message);
}
}
| 1,079 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/HomeHandle.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.ejb;
import java.io.Serializable;
import java.rmi.RemoteException;
/**
* @version $Rev$ $Date$
*/
public interface HomeHandle extends Serializable {
EJBHome getEJBHome() throws RemoteException;
}
| 1,080 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/Init.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Init {
String value() default "";
}
| 1,081 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/LocalHome.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LocalHome {
Class value();
}
| 1,082 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/EJBHome.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.ejb;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* @version $Rev$ $Date$
*/
public interface EJBHome extends Remote {
EJBMetaData getEJBMetaData() throws RemoteException;
HomeHandle getHomeHandle() throws RemoteException;
void remove(Handle handle) throws RemoteException, RemoveException;
void remove(Object primaryKey) throws RemoteException, RemoveException;
}
| 1,083 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/NoSuchEntityException.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.ejb;
/**
* @version $Rev$ $Date$
*/
public class NoSuchEntityException extends EJBException {
public NoSuchEntityException() {
super();
}
public NoSuchEntityException(Exception ex) {
super(ex);
}
public NoSuchEntityException(String message) {
super(message);
}
}
| 1,084 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/TimedObject.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.ejb;
/**
* @version $Rev$ $Date$
*/
public interface TimedObject {
void ejbTimeout(Timer timer);
}
| 1,085 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/TransactionManagementType.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.ejb;
/**
* @version $Rev$ $Date$
*/
public enum TransactionManagementType {
CONTAINER,
BEAN;}
| 1,086 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/ObjectNotFoundException.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.ejb;
/**
* @version $Rev$ $Date$
*/
public class ObjectNotFoundException extends FinderException {
public ObjectNotFoundException() {
super();
}
public ObjectNotFoundException(String message) {
super(message);
}
}
| 1,087 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/EJBs.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EJBs {
EJB[] value();
}
| 1,088 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/Remote.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Remote {
Class[] value() default {};
}
| 1,089 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/MessageDrivenContext.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.ejb;
/**
* @version $Rev$ $Date$
*/
public interface MessageDrivenContext extends EJBContext {
}
| 1,090 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/EJBObject.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.ejb;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* @version $Rev$ $Date$
*/
public interface EJBObject extends Remote {
EJBHome getEJBHome() throws RemoteException;
Handle getHandle() throws RemoteException;
Object getPrimaryKey() throws RemoteException;
boolean isIdentical(EJBObject obj) throws RemoteException;
void remove() throws RemoteException, RemoveException;
}
| 1,091 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/TimerService.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.ejb;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
/**
* @version $Rev$ $Date$
*/
public interface TimerService {
Timer createTimer(Date initialExpiration, long intervalDuration, Serializable info) throws IllegalArgumentException, IllegalStateException, EJBException;
Timer createTimer(Date expiration, Serializable info) throws IllegalArgumentException, IllegalStateException, EJBException;
Timer createTimer(long initialDuration, long intervalDuration, Serializable info) throws IllegalArgumentException, IllegalStateException, EJBException;
Timer createTimer(long duration, Serializable info) throws IllegalArgumentException, IllegalStateException, EJBException;
Collection getTimers() throws IllegalStateException, EJBException;
}
| 1,092 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/Stateless.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.ejb;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* @version $Rev$ $Date$
*/
@Target(TYPE)
@Retention(RUNTIME)
public @interface Stateless {
String name() default "";
String mappedName() default "";
String description() default "";
}
| 1,093 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/Remove.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Remove {
boolean retainIfException() default false;
}
| 1,094 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/EJBMetaData.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.ejb;
/**
* @version $Rev$ $Date$
*/
public interface EJBMetaData {
EJBHome getEJBHome();
Class getHomeInterfaceClass();
Class getPrimaryKeyClass();
Class getRemoteInterfaceClass();
boolean isSession();
boolean isStatelessSession();
}
| 1,095 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/TransactionAttribute.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TransactionAttribute {
TransactionAttributeType value()
default TransactionAttributeType.REQUIRED;
}
| 1,096 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/PrePassivate.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PrePassivate {
}
| 1,097 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/MessageDrivenBean.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.ejb;
/**
* @version $Rev$ $Date$
*/
public interface MessageDrivenBean extends EnterpriseBean {
void ejbRemove() throws EJBException;
void setMessageDrivenContext(MessageDrivenContext ctx) throws EJBException;
}
| 1,098 |
0 | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-ejb_3.0_spec/src/main/java/javax/ejb/Timeout.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.ejb;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* @version $Rev$ $Date$
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Timeout {
}
| 1,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.