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-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/timers/TimerManager.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.timers; import java.util.Date; /** * @version $Rev$ $Date$ */ public interface TimerManager { static final long IMMEDIATE = 0; static final long INDEFINITE = java.lang.Long.MAX_VALUE; boolean isStopped(); boolean isStopping(); boolean isSuspended() throws IllegalStateException; boolean isSuspending() throws IllegalStateException; void resume() throws IllegalStateException; Timer schedule(TimerListener listener, long delayInMillis) throws IllegalStateException, IllegalArgumentException; Timer schedule(TimerListener listener, long delayInMillis, long repeatIntervalInMillis) throws IllegalStateException, IllegalArgumentException; Timer schedule(TimerListener listener, Date scheduleDate) throws IllegalStateException, IllegalArgumentException; Timer schedule(TimerListener listener, Date scheduleDate, long repeatIntervalInMillis) throws IllegalStateException, IllegalArgumentException; Timer scheduleAtFixedRate(TimerListener listener, long delayInMillis, long repeatIntervalInMillis) throws IllegalStateException, IllegalArgumentException; Timer scheduleAtFixedRate(TimerListener listener, Date scheduleDate, long repeatIntervalInMillis) throws IllegalStateException, IllegalArgumentException; void stop() throws IllegalStateException; void suspend() throws IllegalStateException; boolean waitForStop(long timeOut) throws InterruptedException, IllegalArgumentException; boolean waitForSuspend(long timOut) throws InterruptedException, IllegalStateException, IllegalArgumentException; }
900
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/timers/TimerListener.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.timers; /** * @version $Rev$ $Date$ */ public interface TimerListener { void timerExpired(Timer timer); }
901
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/timers/StopTimerListener.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.timers; /** * @version $Rev$ $Date$ */ public interface StopTimerListener extends TimerListener { void timerStop(Timer timer); }
902
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/WorkListener.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; /** * @version $Rev$ $Date$ */ public interface WorkListener { static long IMMEDIATE = 0; static long INDEFINITE = java.lang.Long.MAX_VALUE; void workAccepted(WorkEvent event); void workCompleted(WorkEvent event); void workRejected(WorkEvent event); void workStarted(WorkEvent event); }
903
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/WorkRejectedException.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; /** * @version $Rev$ $Date$ */ public class WorkRejectedException extends WorkException { public WorkRejectedException() { super(); } public WorkRejectedException(String message) { super(message); } public WorkRejectedException(String message, Throwable cause) { super(message, cause); } public WorkRejectedException(Throwable cause) { super(cause); } }
904
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/WorkManager.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; import java.util.Collection; /** * @version $Rev$ $Date$ */ public interface WorkManager { static final long IMMEDIATE = 0; static final long INDEFINITE = java.lang.Long.MAX_VALUE; WorkItem schedule(Work work) throws WorkException, IllegalArgumentException; WorkItem schedule(Work work, WorkListener listener) throws WorkException, IllegalArgumentException; boolean waitForAll(Collection workItems, long timeout) throws InterruptedException, IllegalArgumentException; Collection waitForAny(Collection workItems, long timeout) throws InterruptedException, IllegalArgumentException; }
905
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/WorkCompletedException.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; import java.util.List; import java.util.ArrayList; import java.util.Collections; /** * @version $Rev$ $Date$ */ public class WorkCompletedException extends WorkException { private final List exceptionList; public WorkCompletedException() { super(); exceptionList = Collections.EMPTY_LIST; } public WorkCompletedException(String message) { super(message); exceptionList = Collections.EMPTY_LIST; } public WorkCompletedException(String message, Throwable cause) { super(message, cause); exceptionList = Collections.singletonList(cause); } public WorkCompletedException(Throwable cause) { super(cause); exceptionList = Collections.singletonList(cause); } public WorkCompletedException(String message, List list) { super(message); if ((list != null) && (list.size() > 0)) { initCause((Throwable) list.get(0)); exceptionList = Collections.unmodifiableList(new ArrayList(list)); } else { exceptionList = Collections.EMPTY_LIST; } } public List getExceptionList() { return exceptionList; } }
906
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/WorkItem.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; /** * @version $Rev$ $Date$ */ public interface WorkItem extends Comparable { Work getResult() throws WorkException; int getStatus(); }
907
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/RemoteWorkItem.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; import java.util.Collection; /** * @version $Rev$ $Date$ */ public interface RemoteWorkItem extends WorkItem { WorkManager getPinnedWorkManager(); void release(); }
908
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/Work.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; /** * @version $Rev$ $Date$ */ public interface Work extends Runnable { boolean isDaemon(); void release(); }
909
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/WorkEvent.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; /** * @version $Rev$ $Date$ */ public interface WorkEvent { static final int WORK_ACCEPTED = 1; static final int WORK_REJECTED = 2; static final int WORK_STARTED = 3; static final int WORK_COMPLETED = 4; WorkException getException(); int getType(); WorkItem getWorkItem(); }
910
0
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj
Create_ds/geronimo-specs/geronimo-commonj_1.1_spec/src/main/java/commonj/work/WorkException.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 BEA and IBM. // For more information, see: // http://dev2dev.bea.com/technologies/commonj/index.jsp // or // http://www.ibm.com/developerworks/library/j-commonj-sdowmt // // In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package commonj.work; /** * @version $Rev$ $Date$ */ public class WorkException extends Exception { public WorkException() { super(); } public WorkException(String message) { super(message); } public WorkException(String message, Throwable cause) { super(message, cause); } public WorkException(Throwable cause) { super(cause); } }
911
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/SimpleTextMessage.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Date; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import javax.activation.DataHandler; import javax.mail.internet.InternetAddress; /** * @version $Rev$ $Date$ */ public class SimpleTextMessage extends Message { public static final Address[] ADDRESS_ARRAY = new Address[0]; private List _bcc = new LinkedList(); private List _cc = new LinkedList(); private String _description; private Flags _flags = new Flags(); private List _from = new LinkedList(); private Date _received; private Date _sent; private String _subject; private String _text; private List _to = new LinkedList(); /** * @param folder * @param number */ public SimpleTextMessage(Folder folder, int number) { super(folder, number); } /* (non-Javadoc) * @see javax.mail.Message#addFrom(javax.mail.Address[]) */ public void addFrom(Address[] addresses) throws MessagingException { _from.addAll(Arrays.asList(addresses)); } /* (non-Javadoc) * @see javax.mail.Part#addHeader(java.lang.String, java.lang.String) */ public void addHeader(String name, String value) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Message#addRecipients(javax.mail.Message.RecipientType, javax.mail.Address[]) */ public void addRecipients(RecipientType type, Address[] addresses) throws MessagingException { getList(type).addAll(Arrays.asList(addresses)); } /* (non-Javadoc) * @see javax.mail.Part#getAllHeaders() */ public Enumeration getAllHeaders() throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#getContent() */ public Object getContent() throws IOException, MessagingException { return _text; } /* (non-Javadoc) * @see javax.mail.Part#getContentType() */ public String getContentType() throws MessagingException { return "text/plain"; } /* (non-Javadoc) * @see javax.mail.Part#getDataHandler() */ public DataHandler getDataHandler() throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#getDescription() */ public String getDescription() throws MessagingException { return _description; } /* (non-Javadoc) * @see javax.mail.Part#getDisposition() */ public String getDisposition() throws MessagingException { return Part.INLINE; } /* (non-Javadoc) * @see javax.mail.Part#getFileName() */ public String getFileName() throws MessagingException { return null; } /* (non-Javadoc) * @see javax.mail.Message#getFlags() */ public Flags getFlags() throws MessagingException { return _flags; } /* (non-Javadoc) * @see javax.mail.Message#getFrom() */ public Address[] getFrom() throws MessagingException { return (Address[]) _from.toArray(ADDRESS_ARRAY); } /* (non-Javadoc) * @see javax.mail.Part#getHeader(java.lang.String) */ public String[] getHeader(String name) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#getInputStream() */ public InputStream getInputStream() throws IOException, MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#getLineCount() */ public int getLineCount() throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } private List getList(RecipientType type) throws MessagingException { List list; if (type == RecipientType.TO) { list = _to; } else if (type == RecipientType.CC) { list = _cc; } else if (type == RecipientType.BCC) { list = _bcc; } else { throw new MessagingException("Address type not understood"); } return list; } /* (non-Javadoc) * @see javax.mail.Part#getMatchingHeaders(java.lang.String[]) */ public Enumeration getMatchingHeaders(String[] names) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#getNonMatchingHeaders(java.lang.String[]) */ public Enumeration getNonMatchingHeaders(String[] names) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Message#getReceivedDate() */ public Date getReceivedDate() throws MessagingException { return _received; } /* (non-Javadoc) * @see javax.mail.Message#getRecipients(javax.mail.Message.RecipientType) */ public Address[] getRecipients(RecipientType type) throws MessagingException { return (Address[]) getList(type).toArray(ADDRESS_ARRAY); } /* (non-Javadoc) * @see javax.mail.Message#getSentDate() */ public Date getSentDate() throws MessagingException { return _sent; } /* (non-Javadoc) * @see javax.mail.Part#getSize() */ public int getSize() throws MessagingException { return _text.length(); } /* (non-Javadoc) * @see javax.mail.Message#getSubject() */ public String getSubject() throws MessagingException { return _subject; } /* (non-Javadoc) * @see javax.mail.Part#isMimeType(java.lang.String) */ public boolean isMimeType(String mimeType) throws MessagingException { return mimeType.equals("text/plain") || mimeType.equals("text/*"); } /* (non-Javadoc) * @see javax.mail.Part#removeHeader(java.lang.String) */ public void removeHeader(String name) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Message#reply(boolean) */ public Message reply(boolean replyToAll) throws MessagingException { try { SimpleTextMessage reply = (SimpleTextMessage) this.clone(); reply._to = new LinkedList(_from); if (replyToAll) { reply._to.addAll(_cc); } return reply; } catch (CloneNotSupportedException e) { throw new MessagingException(e.getMessage()); } } /* (non-Javadoc) * @see javax.mail.Message#saveChanges() */ public void saveChanges() throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#setContent(javax.mail.Multipart) */ public void setContent(Multipart content) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#setContent(java.lang.Object, java.lang.String) */ public void setContent(Object content, String type) throws MessagingException { setText((String) content); } /* (non-Javadoc) * @see javax.mail.Part#setDataHandler(javax.activation.DataHandler) */ public void setDataHandler(DataHandler handler) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#setDescription(java.lang.String) */ public void setDescription(String description) throws MessagingException { _description = description; } /* (non-Javadoc) * @see javax.mail.Part#setDisposition(java.lang.String) */ public void setDisposition(String disposition) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Part#setFileName(java.lang.String) */ public void setFileName(String name) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Message#setFlags(javax.mail.Flags, boolean) */ public void setFlags(Flags flags, boolean set) throws MessagingException { if (set) { _flags.add(flags); } else { _flags.remove(flags); } } /* (non-Javadoc) * @see javax.mail.Message#setFrom() */ public void setFrom() throws MessagingException { setFrom(new InternetAddress("root@localhost")); } /* (non-Javadoc) * @see javax.mail.Message#setFrom(javax.mail.Address) */ public void setFrom(Address address) throws MessagingException { _from.clear(); _from.add(address); } /* (non-Javadoc) * @see javax.mail.Part#setHeader(java.lang.String, java.lang.String) */ public void setHeader(String name, String value) throws MessagingException { throw new UnsupportedOperationException("Method not implemented"); } /* (non-Javadoc) * @see javax.mail.Message#setRecipients(javax.mail.Message.RecipientType, javax.mail.Address[]) */ public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException { List list = getList(type); list.clear(); list.addAll(Arrays.asList(addresses)); } /* (non-Javadoc) * @see javax.mail.Message#setSentDate(java.util.Date) */ public void setSentDate(Date sent) throws MessagingException { _sent = sent; } /* (non-Javadoc) * @see javax.mail.Message#setSubject(java.lang.String) */ public void setSubject(String subject) throws MessagingException { _subject = subject; } /* (non-Javadoc) * @see javax.mail.Part#setText(java.lang.String) */ public void setText(String content) throws MessagingException { _text = content; } /* (non-Javadoc) * @see javax.mail.Part#writeTo(java.io.OutputStream) */ public void writeTo(OutputStream out) throws IOException, MessagingException { throw new UnsupportedOperationException("Method not implemented"); } }
912
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/AllTests.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import javax.mail.event.AllEventTests; import javax.mail.internet.AllInternetTests; import junit.framework.Test; import junit.framework.TestSuite; /** * @version $Revision $ $Date$ */ public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Test for javax.mail"); //$JUnit-BEGIN$ suite.addTest(new TestSuite(FlagsTest.class)); suite.addTest(new TestSuite(HeaderTest.class)); suite.addTest(new TestSuite(MessagingExceptionTest.class)); suite.addTest(new TestSuite(URLNameTest.class)); suite.addTest(new TestSuite(PasswordAuthenticationTest.class)); suite.addTest(AllEventTests.suite()); suite.addTest(AllInternetTests.suite()); //$JUnit-END$ return suite; } }
913
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/HeaderTest.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 junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class HeaderTest extends TestCase { public HeaderTest(String name) { super(name); } public void testHeader() { Header header = new Header("One", "Two"); assertEquals("One", header.getName()); assertEquals("Two", header.getValue()); } }
914
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/MessagingExceptionTest.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 junit.framework.TestCase; /** * @version $Revision $ $Date$ */ public class MessagingExceptionTest extends TestCase { private RuntimeException e; private MessagingException d; private MessagingException c; private MessagingException b; private MessagingException a; public MessagingExceptionTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); //Initialize cause with null, make sure the getCause will not be affected a = new MessagingException("A", null); b = new MessagingException("B"); c = new MessagingException("C"); d = new MessagingException("D"); e = new RuntimeException("E"); } public void testMessagingExceptionString() { assertEquals("A", a.getMessage()); } public void testNextException() { assertTrue(a.setNextException(b)); assertEquals(b, a.getNextException()); assertEquals(b, a.getCause()); assertTrue(a.setNextException(c)); assertEquals(b, a.getNextException()); assertEquals(c, b.getNextException()); assertEquals(c, b.getCause()); assertTrue(a.setNextException(d)); assertEquals(b, a.getNextException()); assertEquals(b, a.getCause()); assertEquals(c, b.getNextException()); assertEquals(c, b.getCause()); assertEquals(d, c.getNextException()); assertEquals(d, c.getCause()); String message = a.getMessage(); int ap = message.indexOf("A"); int bp = message.indexOf("B"); int cp = message.indexOf("C"); assertTrue("A does not contain 'A'", ap != -1); assertTrue("B does not contain 'B'", bp != -1); assertTrue("C does not contain 'C'", cp != -1); } public void testNextExceptionWrong() { assertTrue(a.setNextException(e)); assertFalse(a.setNextException(b)); } public void testNextExceptionWrong2() { assertTrue(a.setNextException(e)); assertFalse(a.setNextException(b)); } public void testMessagingExceptionStringException() { MessagingException x = new MessagingException("X", a); assertEquals("X (javax.mail.MessagingException: A)", x.getMessage()); assertEquals(a, x.getNextException()); assertEquals(a, x.getCause()); } }
915
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/PasswordAuthenticationTest.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 junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class PasswordAuthenticationTest extends TestCase { public PasswordAuthenticationTest(String name) { super(name); } public void testPA() { String user = String.valueOf(System.currentTimeMillis()); String password = "JobbyJobbyJobby" + user; PasswordAuthentication pa = new PasswordAuthentication(user, password); assertEquals(user, pa.getUserName()); assertEquals(password, pa.getPassword()); } public void testPasswordAuthentication() { PasswordAuthentication pa = new PasswordAuthentication("Alex", "xelA"); assertEquals("Alex", pa.getUserName()); assertEquals("xelA", pa.getPassword()); } }
916
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/SimpleFolder.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.Iterator; import java.util.LinkedList; import java.util.List; /** * @version $Rev$ $Date$ */ public class SimpleFolder extends Folder { private static final Message[] MESSAGE_ARRAY = new Message[0]; private List _messages = new LinkedList(); private String _name; public SimpleFolder(Store store) { this(store, "SimpleFolder"); } SimpleFolder(Store store, String name) { super(store); _name = name; } /* (non-Javadoc) * @see javax.mail.Folder#appendMessages(javax.mail.Message[]) */ public void appendMessages(Message[] messages) throws MessagingException { for (int i = 0; i < messages.length; i++) { Message message = messages[i]; _messages.add(message); } } /* (non-Javadoc) * @see javax.mail.Folder#close(boolean) */ public void close(boolean expunge) throws MessagingException { if (expunge) { expunge(); } } /* (non-Javadoc) * @see javax.mail.Folder#create(int) */ public boolean create(int type) throws MessagingException { if (type == HOLDS_MESSAGES) { return true; } else { throw new MessagingException("Cannot create folders that hold folders"); } } /* (non-Javadoc) * @see javax.mail.Folder#delete(boolean) */ public boolean delete(boolean recurse) throws MessagingException { _messages = new LinkedList(); return true; } /* (non-Javadoc) * @see javax.mail.Folder#exists() */ public boolean exists() throws MessagingException { return true; } /* (non-Javadoc) * @see javax.mail.Folder#expunge() */ public Message[] expunge() throws MessagingException { Iterator it = _messages.iterator(); List result = new LinkedList(); while (it.hasNext()) { Message message = (Message) it.next(); if (message.isSet(Flags.Flag.DELETED)) { it.remove(); result.add(message); } } // run through and renumber the messages for (int i = 0; i < _messages.size(); i++) { Message message = (Message) _messages.get(i); message.setMessageNumber(i); } return (Message[]) result.toArray(MESSAGE_ARRAY); } /* (non-Javadoc) * @see javax.mail.Folder#getFolder(java.lang.String) */ public Folder getFolder(String name) throws MessagingException { return null; } /* (non-Javadoc) * @see javax.mail.Folder#getFullName() */ public String getFullName() { return getName(); } /* (non-Javadoc) * @see javax.mail.Folder#getMessage(int) */ public Message getMessage(int id) throws MessagingException { return (Message) _messages.get(id); } /* (non-Javadoc) * @see javax.mail.Folder#getMessageCount() */ public int getMessageCount() throws MessagingException { return _messages.size(); } /* (non-Javadoc) * @see javax.mail.Folder#getName() */ public String getName() { return _name; } /* (non-Javadoc) * @see javax.mail.Folder#getParent() */ public Folder getParent() throws MessagingException { return null; } /* (non-Javadoc) * @see javax.mail.Folder#getPermanentFlags() */ public Flags getPermanentFlags() { return null; } /* (non-Javadoc) * @see javax.mail.Folder#getSeparator() */ public char getSeparator() throws MessagingException { return '/'; } /* (non-Javadoc) * @see javax.mail.Folder#getType() */ public int getType() throws MessagingException { return HOLDS_MESSAGES; } /* (non-Javadoc) * @see javax.mail.Folder#hasNewMessages() */ public boolean hasNewMessages() throws MessagingException { return false; } /* (non-Javadoc) * @see javax.mail.Folder#isOpen() */ public boolean isOpen() { return true; } /* (non-Javadoc) * @see javax.mail.Folder#list(java.lang.String) */ public Folder[] list(String pattern) throws MessagingException { return null; } /* (non-Javadoc) * @see javax.mail.Folder#open(int) */ public void open(int mode) throws MessagingException { if (mode != HOLDS_MESSAGES) { throw new MessagingException("SimpleFolder can only be opened with HOLDS_MESSAGES"); } } /* (non-Javadoc) * @see javax.mail.Folder#renameTo(javax.mail.Folder) */ public boolean renameTo(Folder newName) throws MessagingException { _name = newName.getName(); return true; } }
917
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/SessionTest.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.Properties; import javax.mail.MessagingException; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class SessionTest extends TestCase { public void testAddProvider() throws MessagingException { Properties props = System.getProperties(); // Get a Session object Session mailSession = Session.getDefaultInstance(props, null); mailSession.addProvider(new Provider(Provider.Type.TRANSPORT, "foo", NullTransport.class.getName(), "Apache", "Java 1.4 Test")); // retrieve the transport Transport trans = mailSession.getTransport("foo"); assertTrue(trans instanceof NullTransport); mailSession.setProtocolForAddress("foo", "foo"); trans = mailSession.getTransport(new FooAddress()); assertTrue(trans instanceof NullTransport); } static public class NullTransport extends Transport { public NullTransport(Session session, URLName urlName) { super(session, urlName); } public void sendMessage(Message message, Address[] addresses) throws MessagingException { // do nothing } protected boolean protocolConnect(String host, int port, String user, String password) throws MessagingException { return true; // always connect } } static public class FooAddress extends Address { public FooAddress() { } public String getType() { return "foo"; } public String toString() { return "yada"; } public boolean equals(Object other) { return true; } } }
918
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/EventQueueTest.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.MessagingException; import javax.mail.event.FolderEvent; import javax.mail.event.FolderListener; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class EventQueueTest extends TestCase { protected EventQueue queue; public void setUp() throws Exception { queue = new EventQueue(); } public void tearDown() throws Exception { queue.stop(); } public void testEvent() { doEventTests(FolderEvent.CREATED); doEventTests(FolderEvent.RENAMED); doEventTests(FolderEvent.DELETED); } private void doEventTests(int type) { // These tests are essentially the same as the // folder event tests, but done using the asynchronous // event queue. FolderEvent event = new FolderEvent(this, null, type); assertEquals(this, event.getSource()); assertEquals(type, event.getType()); FolderListenerTest listener = new FolderListenerTest(); Vector listeners = new Vector(); listeners.add(listener); queue.queueEvent(event, listeners); // we need to make sure the queue thread has a chance to dispatch // this before we check. try { Thread.currentThread().sleep(1000); } catch (InterruptedException e ) { } assertEquals("Unexpcted method dispatched", type, listener.getState()); } public static class FolderListenerTest implements FolderListener { private int state = 0; public void folderCreated(FolderEvent event) { if (state != 0) { fail("Recycled Listener"); } state = FolderEvent.CREATED; } public void folderDeleted(FolderEvent event) { if (state != 0) { fail("Recycled Listener"); } state = FolderEvent.DELETED; } public void folderRenamed(FolderEvent event) { if (state != 0) { fail("Recycled Listener"); } state = FolderEvent.RENAMED; } public int getState() { return state; } } }
919
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/MessageContextTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import javax.activation.DataHandler; import javax.mail.internet.MimeMessage; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class MessageContextTest extends TestCase { public void testNothing() { } /* public void testMessageContext() { Part p; MessageContext mc; p = new TestPart(); mc = new MessageContext(p); assertSame(p, mc.getPart()); assertNull(mc.getMessage()); assertNull(mc.getSession()); Session s = Session.getDefaultInstance(null); MimeMessage m = new MimeMessage(s); p = new TestMultipart(m); mc = new MessageContext(p); assertSame(p, mc.getPart()); assertSame(m,mc.getMessage()); assertSame(s,mc.getSession()); } private static class TestMultipart extends Multipart implements Part { public TestMultipart(Part p) { parent = p; } public void writeTo(OutputStream out) throws IOException, MessagingException { } public void addHeader(String name, String value) throws MessagingException { } public Enumeration getAllHeaders() throws MessagingException { return null; } public Object getContent() throws IOException, MessagingException { return null; } public DataHandler getDataHandler() throws MessagingException { return null; } public String getDescription() throws MessagingException { return null; } public String getDisposition() throws MessagingException { return null; } public String getFileName() throws MessagingException { return null; } public String[] getHeader(String name) throws MessagingException { return null; } public InputStream getInputStream() throws IOException, MessagingException { return null; } public int getLineCount() throws MessagingException { return 0; } public Enumeration getMatchingHeaders(String[] names) throws MessagingException { return null; } public Enumeration getNonMatchingHeaders(String[] names) throws MessagingException { return null; } public int getSize() throws MessagingException { return 0; } public boolean isMimeType(String mimeType) throws MessagingException { return false; } public void removeHeader(String name) throws MessagingException { } public void setContent(Multipart content) throws MessagingException { } public void setContent(Object content, String type) throws MessagingException { } public void setDataHandler(DataHandler handler) throws MessagingException { } public void setDescription(String description) throws MessagingException { } public void setDisposition(String disposition) throws MessagingException { } public void setFileName(String name) throws MessagingException { } public void setHeader(String name, String value) throws MessagingException { } public void setText(String content) throws MessagingException { } } private static class TestBodyPart extends BodyPart { public TestBodyPart(Multipart p) { super(); parent = p; } public void addHeader(String name, String value) throws MessagingException { } public Enumeration getAllHeaders() throws MessagingException { return null; } public Object getContent() throws IOException, MessagingException { return null; } public String getContentType() throws MessagingException { return null; } public DataHandler getDataHandler() throws MessagingException { return null; } public String getDescription() throws MessagingException { return null; } public String getDisposition() throws MessagingException { return null; } public String getFileName() throws MessagingException { return null; } public String[] getHeader(String name) throws MessagingException { return null; } public InputStream getInputStream() throws IOException, MessagingException { return null; } public int getLineCount() throws MessagingException { return 0; } public Enumeration getMatchingHeaders(String[] names) throws MessagingException { return null; } public Enumeration getNonMatchingHeaders(String[] names) throws MessagingException { return null; } public int getSize() throws MessagingException { return 0; } public boolean isMimeType(String mimeType) throws MessagingException { return false; } public void removeHeader(String name) throws MessagingException { } public void setContent(Multipart content) throws MessagingException { } public void setContent(Object content, String type) throws MessagingException { } public void setDataHandler(DataHandler handler) throws MessagingException { } public void setDescription(String description) throws MessagingException { } public void setDisposition(String disposition) throws MessagingException { } public void setFileName(String name) throws MessagingException { } public void setHeader(String name, String value) throws MessagingException { } public void setText(String content) throws MessagingException { } public void writeTo(OutputStream out) throws IOException, MessagingException { } } private static class TestPart implements Part { public void addHeader(String name, String value) throws MessagingException { } public Enumeration getAllHeaders() throws MessagingException { return null; } public Object getContent() throws IOException, MessagingException { return null; } public String getContentType() throws MessagingException { return null; } public DataHandler getDataHandler() throws MessagingException { return null; } public String getDescription() throws MessagingException { return null; } public String getDisposition() throws MessagingException { return null; } public String getFileName() throws MessagingException { return null; } public String[] getHeader(String name) throws MessagingException { return null; } public InputStream getInputStream() throws IOException, MessagingException { return null; } public int getLineCount() throws MessagingException { return 0; } public Enumeration getMatchingHeaders(String[] names) throws MessagingException { return null; } public Enumeration getNonMatchingHeaders(String[] names) throws MessagingException { return null; } public int getSize() throws MessagingException { return 0; } public boolean isMimeType(String mimeType) throws MessagingException { return false; } public void removeHeader(String name) throws MessagingException { } public void setContent(Multipart content) throws MessagingException { } public void setContent(Object content, String type) throws MessagingException { } public void setDataHandler(DataHandler handler) throws MessagingException { } public void setDescription(String description) throws MessagingException { } public void setDisposition(String disposition) throws MessagingException { } public void setFileName(String name) throws MessagingException { } public void setHeader(String name, String value) throws MessagingException { } public void setText(String content) throws MessagingException { } public void writeTo(OutputStream out) throws IOException, MessagingException { } } */ }
920
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/QuotaTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import javax.mail.MessagingException; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class QuotaTest extends TestCase { public void testQuota() throws MessagingException { Quota quota = new Quota("Fred"); assertEquals(quota.quotaRoot, "Fred"); assertNull(quota.resources); quota.setResourceLimit("Storage", 20000); assertNotNull(quota.resources); assertTrue(quota.resources.length == 1); assertEquals(quota.resources[0].name, "Storage"); assertEquals(quota.resources[0].usage, 0); assertEquals(quota.resources[0].limit, 20000); quota.setResourceLimit("Storage", 30000); assertNotNull(quota.resources); assertTrue(quota.resources.length == 1); assertEquals(quota.resources[0].name, "Storage"); assertEquals(quota.resources[0].usage, 0); assertEquals(quota.resources[0].limit, 30000); quota.setResourceLimit("Folders", 5); assertNotNull(quota.resources); assertTrue(quota.resources.length == 2); assertEquals(quota.resources[0].name, "Storage"); assertEquals(quota.resources[0].usage, 0); assertEquals(quota.resources[0].limit, 30000); assertEquals(quota.resources[1].name, "Folders"); assertEquals(quota.resources[1].usage, 0); assertEquals(quota.resources[1].limit, 5); } }
921
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/TestData.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import javax.mail.internet.MimeMessage; public class TestData { public static Store getTestStore() { return new Store( getTestSession(), new URLName("http://alex@test.com")) { public Folder getDefaultFolder() throws MessagingException { return getTestFolder(); } public Folder getFolder(String name) throws MessagingException { if (name.equals("test")) { return getTestFolder(); } else { return null; } } public Folder getFolder(URLName name) throws MessagingException { return getTestFolder(); } }; } public static Session getTestSession() { return Session.getDefaultInstance(System.getProperties()); } public static Folder getTestFolder() { return new Folder(getTestStore()) { public void appendMessages(Message[] messages) throws MessagingException { } public void close(boolean expunge) throws MessagingException { } public boolean create(int type) throws MessagingException { return false; } public boolean delete(boolean recurse) throws MessagingException { return false; } public boolean exists() throws MessagingException { return false; } public Message[] expunge() throws MessagingException { return null; } public Folder getFolder(String name) throws MessagingException { return null; } public String getFullName() { return null; } public Message getMessage(int id) throws MessagingException { return null; } public int getMessageCount() throws MessagingException { return 0; } public String getName() { return null; } public Folder getParent() throws MessagingException { return null; } public Flags getPermanentFlags() { return null; } public char getSeparator() throws MessagingException { return 0; } public int getType() throws MessagingException { return 0; } public boolean hasNewMessages() throws MessagingException { return false; } public boolean isOpen() { return false; } public Folder[] list(String pattern) throws MessagingException { return null; } public void open(int mode) throws MessagingException { } public boolean renameTo(Folder newName) throws MessagingException { return false; } }; } public static Transport getTestTransport() { return new Transport( getTestSession(), new URLName("http://host.name")) { public void sendMessage(Message message, Address[] addresses) throws MessagingException { // TODO Auto-generated method stub } }; } public static Message getMessage() { return new MimeMessage(getTestFolder(), 1) { }; } }
922
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/URLNameTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.net.MalformedURLException; import java.net.URL; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class URLNameTest extends TestCase { public URLNameTest(String name) { super(name); } public void testURLNameString() { String s; URLName name; s = "http://www.apache.org"; name = new URLName(s); assertEquals(s, name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertNull(name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL(s), name.getURL()); } catch (MalformedURLException e) { fail(); } s = "http://www.apache.org/file/file1#ref"; name = new URLName(s); assertEquals(s, name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/file1", name.getFile()); assertEquals("ref", name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL(s), name.getURL()); } catch (MalformedURLException e) { fail(); } s = "http://www.apache.org/file/"; name = new URLName(s); assertEquals(s, name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/", name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL(s), name.getURL()); } catch (MalformedURLException e) { fail(); } s = "http://john@www.apache.org/file/"; name = new URLName(s); assertEquals(s, name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/", name.getFile()); assertNull(name.getRef()); assertEquals("john", name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL(s), name.getURL()); } catch (MalformedURLException e) { fail(); } s = "http://john:doe@www.apache.org/file/"; name = new URLName(s); assertEquals(s, name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/", name.getFile()); assertNull(name.getRef()); assertEquals("john", name.getUsername()); assertEquals("doe", name.getPassword()); try { assertEquals(new URL(s), name.getURL()); } catch (MalformedURLException e) { fail(); } s = "http://john%40gmail.com:doe@www.apache.org/file/"; name = new URLName(s); assertEquals(s, name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/", name.getFile()); assertNull(name.getRef()); assertEquals("john@gmail.com", name.getUsername()); assertEquals("doe", name.getPassword()); try { assertEquals(new URL(s), name.getURL()); } catch (MalformedURLException e) { fail(); } s = "file/file2"; name = new URLName(s); assertNull(name.getProtocol()); assertNull(name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/file2", name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { name.getURL(); fail(); } catch (MalformedURLException e) { // OK } name = new URLName((String) null); assertNull( name.getProtocol()); assertNull(name.getHost()); assertEquals(-1, name.getPort()); assertNull(name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { name.getURL(); fail(); } catch (MalformedURLException e) { // OK } name = new URLName(""); assertNull( name.getProtocol()); assertNull(name.getHost()); assertEquals(-1, name.getPort()); assertNull(name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { name.getURL(); fail(); } catch (MalformedURLException e) { // OK } } public void testURLNameAll() { URLName name; name = new URLName(null, null, -1, null, null, null); assertNull(name.getProtocol()); assertNull(name.getHost()); assertEquals(-1, name.getPort()); assertNull(name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { name.getURL(); fail(); } catch (MalformedURLException e) { // OK } name = new URLName("", "", -1, "", "", ""); assertNull(name.getProtocol()); assertNull(name.getHost()); assertEquals(-1, name.getPort()); assertNull(name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { name.getURL(); fail(); } catch (MalformedURLException e) { // OK } name = new URLName("http", "www.apache.org", -1, null, null, null); assertEquals("http://www.apache.org", name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertNull(name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL("http://www.apache.org"), name.getURL()); } catch (MalformedURLException e) { fail(); } name = new URLName("http", "www.apache.org", 8080, "", "", ""); assertEquals("http://www.apache.org:8080", name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(8080, name.getPort()); assertNull(name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL("http://www.apache.org:8080"), name.getURL()); } catch (MalformedURLException e) { fail(); } name = new URLName("http", "www.apache.org", -1, "file/file2", "", ""); assertEquals("http://www.apache.org/file/file2", name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/file2", name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL("http://www.apache.org/file/file2"), name.getURL()); } catch (MalformedURLException e) { fail(); } name = new URLName("http", "www.apache.org", -1, "file/file2", "john", ""); assertEquals("http://john@www.apache.org/file/file2", name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/file2", name.getFile()); assertNull(name.getRef()); assertEquals("john", name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL("http://john@www.apache.org/file/file2"), name.getURL()); } catch (MalformedURLException e) { fail(); } name = new URLName("http", "www.apache.org", -1, "file/file2", "john", "doe"); assertEquals("http://john:doe@www.apache.org/file/file2", name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/file2", name.getFile()); assertNull(name.getRef()); assertEquals("john", name.getUsername()); assertEquals("doe", name.getPassword()); try { assertEquals(new URL("http://john:doe@www.apache.org/file/file2"), name.getURL()); } catch (MalformedURLException e) { fail(); } name = new URLName("http", "www.apache.org", -1, "file/file2", "john@gmail.com", "doe"); assertEquals("http://john%40gmail.com:doe@www.apache.org/file/file2", name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/file2", name.getFile()); assertNull(name.getRef()); assertEquals("john@gmail.com", name.getUsername()); assertEquals("doe", name.getPassword()); try { assertEquals(new URL("http://john%40gmail.com:doe@www.apache.org/file/file2"), name.getURL()); } catch (MalformedURLException e) { fail(); } name = new URLName("http", "www.apache.org", -1, "file/file2", "", "doe"); assertEquals("http://www.apache.org/file/file2", name.toString()); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("file/file2", name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { assertEquals(new URL("http://www.apache.org/file/file2"), name.getURL()); } catch (MalformedURLException e) { fail(); } } public void testURLNameURL() throws MalformedURLException { URL url; URLName name; url = new URL("http://www.apache.org"); name = new URLName(url); assertEquals("http", name.getProtocol()); assertEquals("www.apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertNull(name.getFile()); assertNull(name.getRef()); assertNull(name.getUsername()); assertNull(name.getPassword()); try { assertEquals(url, name.getURL()); } catch (MalformedURLException e) { fail(); } } public void testEquals() throws MalformedURLException { URLName name1 = new URLName("http://www.apache.org"); assertEquals(name1, new URLName("http://www.apache.org")); assertEquals(name1, new URLName(new URL("http://www.apache.org"))); assertEquals(name1, new URLName("http", "www.apache.org", -1, null, null, null)); assertEquals(name1, new URLName("http://www.apache.org#foo")); // wierd but ref is not part of the equals contract assertTrue(!name1.equals(new URLName("http://www.apache.org:8080"))); assertTrue(!name1.equals(new URLName("http://cvs.apache.org"))); assertTrue(!name1.equals(new URLName("https://www.apache.org"))); name1 = new URLName("http://john:doe@www.apache.org"); assertEquals(name1, new URLName(new URL("http://john:doe@www.apache.org"))); assertEquals(name1, new URLName("http", "www.apache.org", -1, null, "john", "doe")); assertTrue(!name1.equals(new URLName("http://john:xxx@www.apache.org"))); assertTrue(!name1.equals(new URLName("http://xxx:doe@www.apache.org"))); assertTrue(!name1.equals(new URLName("http://www.apache.org"))); assertEquals(new URLName("http://john@www.apache.org"), new URLName("http", "www.apache.org", -1, null, "john", null)); assertEquals(new URLName("http://www.apache.org"), new URLName("http", "www.apache.org", -1, null, null, "doe")); } public void testHashCode() { URLName name1 = new URLName("http://www.apache.org/file"); URLName name2 = new URLName("http://www.apache.org/file#ref"); assertTrue(name1.equals(name2)); assertTrue(name1.hashCode() == name2.hashCode()); } public void testNullProtocol() { URLName name1 = new URLName(null, "www.apache.org", -1, null, null, null); assertTrue(!name1.equals(name1)); } public void testOpaqueSchemes() { String s; URLName name; // not strictly opaque but no protocol handler installed s = "foo://jdoe@apache.org/INBOX"; name = new URLName(s); assertEquals(s, name.toString()); assertEquals("foo", name.getProtocol()); assertEquals("apache.org", name.getHost()); assertEquals(-1, name.getPort()); assertEquals("INBOX", name.getFile()); assertNull(name.getRef()); assertEquals("jdoe", name.getUsername()); assertNull(name.getPassword()); // TBD as I am not sure what other URL formats to use } }
923
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/FlagsTest.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.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class FlagsTest extends TestCase { private List flagtypes; private Flags flags; /** * Constructor for FlagsTest. * @param arg0 */ public FlagsTest(String name) { super(name); } /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); flags = new Flags(); flagtypes = new LinkedList(); flagtypes.add(Flags.Flag.ANSWERED); flagtypes.add(Flags.Flag.DELETED); flagtypes.add(Flags.Flag.DRAFT); flagtypes.add(Flags.Flag.FLAGGED); flagtypes.add(Flags.Flag.RECENT); flagtypes.add(Flags.Flag.SEEN); Collections.shuffle(flagtypes); } public void testHashCode() { int before = flags.hashCode(); flags.add("Test"); assertTrue( "Before: " + before + ", now " + flags.hashCode(), flags.hashCode() != before); assertTrue(flags.hashCode() != 0); } /* * Test for void add(Flag) */ public void testAddAndRemoveFlag() { Iterator it = flagtypes.iterator(); while (it.hasNext()) { Flags.Flag flag = (Flags.Flag) it.next(); assertFalse(flags.contains(flag)); flags.add(flag); assertTrue(flags.contains(flag)); } it = flagtypes.iterator(); while (it.hasNext()) { Flags.Flag flag = (Flags.Flag) it.next(); flags.remove(flag); assertFalse(flags.contains(flag)); } } /* * Test for void add(String) */ public void testAddString() { assertFalse(flags.contains("Frog")); flags.add("Frog"); assertTrue(flags.contains("Frog")); flags.remove("Frog"); assertFalse(flags.contains("Frog")); } /* * Test for void add(Flags) */ public void testAddFlags() { Flags other = new Flags(); other.add("Stuff"); other.add(Flags.Flag.RECENT); flags.add(other); assertTrue(flags.contains("Stuff")); assertTrue(flags.contains(Flags.Flag.RECENT)); assertTrue(flags.contains(other)); assertTrue(flags.contains(flags)); flags.add("Thing"); assertTrue(flags.contains("Thing")); flags.remove(other); assertFalse(flags.contains("Stuff")); assertFalse(flags.contains(Flags.Flag.RECENT)); assertFalse(flags.contains(other)); assertTrue(flags.contains("Thing")); } /* * Test for boolean equals(Object) */ public void testEqualsObject() { Flags other = new Flags(); other.add("Stuff"); other.add(Flags.Flag.RECENT); flags.add(other); assertEquals(flags, other); } public void testGetSystemFlags() { flags.add("Stuff"); flags.add("Another"); flags.add(Flags.Flag.FLAGGED); flags.add(Flags.Flag.RECENT); Flags.Flag[] array = flags.getSystemFlags(); assertEquals(2, array.length); assertTrue( (array[0] == Flags.Flag.FLAGGED && array[1] == Flags.Flag.RECENT) || (array[0] == Flags.Flag.RECENT && array[1] == Flags.Flag.FLAGGED)); } public void testGetUserFlags() { final String stuff = "Stuff"; final String another = "Another"; flags.add(stuff); flags.add(another); flags.add(Flags.Flag.FLAGGED); flags.add(Flags.Flag.RECENT); String[] array = flags.getUserFlags(); assertEquals(2, array.length); assertTrue( (array[0] == stuff && array[1] == another) || (array[0] == another && array[1] == stuff)); } public void testClone() throws CloneNotSupportedException { flags.add("Thing"); flags.add(Flags.Flag.RECENT); Flags other = (Flags) flags.clone(); assertTrue(other != flags); assertEquals(other, flags); } }
924
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/util/SharedFileInputStreamTest.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.File; import java.io.IOException; import java.io.InputStream; import javax.mail.internet.SharedInputStream; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class SharedFileInputStreamTest extends TestCase { File basedir = new File(System.getProperty("basedir", ".")); File testInput = new File(basedir, "src/test/resources/test.dat"); public SharedFileInputStreamTest(String arg0) { super(arg0); } public void testInput() throws Exception { doTestInput(new SharedFileInputStream(testInput)); doTestInput(new SharedFileInputStream(testInput.getPath())); doTestInput(new SharedFileInputStream(testInput, 16)); doTestInput(new SharedFileInputStream(testInput.getPath(), 16)); } public void doTestInput(SharedFileInputStream in) throws Exception { assertEquals(in.read(), '0'); assertEquals(in.getPosition(), 1); byte[] bytes = new byte[10]; assertEquals(in.read(bytes), 10); assertEquals(new String(bytes), "123456789a"); assertEquals(in.getPosition(), 11); assertEquals(in.read(bytes, 5, 5), 5); assertEquals(new String(bytes), "12345bcdef"); assertEquals(in.getPosition(), 16); assertEquals(in.skip(5), 5); assertEquals(in.getPosition(), 21); assertEquals(in.read(), 'l'); while (in.read() != '\n' ) { } assertEquals(in.read(), -1); in.close(); } public void testNewStream() throws Exception { SharedFileInputStream in = new SharedFileInputStream(testInput); SharedFileInputStream sub = (SharedFileInputStream)in.newStream(10, 10 + 26); assertEquals(sub.getPosition(), 0); assertEquals(in.read(), '0'); assertEquals(sub.read(), 'a'); sub.skip(1); assertEquals(sub.getPosition(), 2); while (sub.read() != 'z') { } assertEquals(sub.read(), -1); SharedFileInputStream sub2 = (SharedFileInputStream)sub.newStream(5, 10); sub.close(); // should not close in or sub2 assertEquals(sub2.getPosition(), 0); assertEquals(sub2.read(), 'f'); assertEquals(in.read(), '1'); // should still work sub2.close(); assertEquals(in.read(), '2'); // should still work in.close(); } public void testMark() throws Exception { doMarkTest(new SharedFileInputStream(testInput, 10)); SharedFileInputStream in = new SharedFileInputStream(testInput, 10); SharedFileInputStream sub = (SharedFileInputStream)in.newStream(5, -1); doMarkTest(sub); } private void doMarkTest(SharedFileInputStream in) throws Exception { assertTrue(in.markSupported()); byte[] buffer = new byte[60]; in.read(); in.read(); in.mark(50); int markSpot = in.read(); in.read(buffer, 0, 20); in.reset(); assertEquals(markSpot, in.read()); in.read(buffer, 0, 40); in.reset(); assertEquals(markSpot, in.read()); in.read(buffer, 0, 51); try { in.reset(); fail(); } catch (IOException e) { } } }
925
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/util/QuotedPrintableEncoderTest.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.InputStream; import java.util.Scanner; import javax.mail.Session; import javax.mail.internet.MimeMessage; import junit.framework.Assert; import junit.framework.TestCase; public class QuotedPrintableEncoderTest extends TestCase{ public void testGERONIMO6165() throws Exception{ MimeMessage msg = new MimeMessage((Session)null, QuotedPrintableEncoderTest.class.getResourceAsStream("/GERONIMO-6165.msg")); Assert.assertEquals("quoted-printable", msg.getEncoding()); Assert.assertEquals("hello there!", msg.getContent().toString()); } public void testLongMail() throws Exception{ MimeMessage msg = new MimeMessage((Session)null, QuotedPrintableEncoderTest.class.getResourceAsStream("/quoted-printable-longmail.msg")); InputStream result = QuotedPrintableEncoderTest.class.getResourceAsStream("/quoted-printable-longmail-result.txt"); Assert.assertEquals("quoted-printable", msg.getEncoding()); Assert.assertEquals(new Scanner(result,"UTF-8").useDelimiter("\\A").next(), msg.getContent()); } }
926
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/util/SharedByteArrayInputStreamTest.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; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class SharedByteArrayInputStreamTest extends TestCase { private String testString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private byte[] testData = testString.getBytes(); public SharedByteArrayInputStreamTest(String arg0) { super(arg0); } public void testInput() throws Exception { SharedByteArrayInputStream in = new SharedByteArrayInputStream(testData); assertEquals(in.read(), '0'); assertEquals(in.getPosition(), 1); byte[] bytes = new byte[10]; assertEquals(in.read(bytes), 10); assertEquals(new String(bytes), "123456789a"); assertEquals(in.getPosition(), 11); assertEquals(in.read(bytes, 5, 5), 5); assertEquals(new String(bytes), "12345bcdef"); assertEquals(in.getPosition(), 16); assertEquals(in.skip(5), 5); assertEquals(in.getPosition(), 21); assertEquals(in.read(), 'l'); while (in.read() != 'Z') { } assertEquals(in.read(), -1); } public void testNewStream() throws Exception { SharedByteArrayInputStream in = new SharedByteArrayInputStream(testData); SharedByteArrayInputStream sub = (SharedByteArrayInputStream)in.newStream(10, 10 + 26); assertEquals(sub.getPosition(), 0); assertEquals(in.read(), '0'); assertEquals(sub.read(), 'a'); sub.skip(1); assertEquals(sub.getPosition(), 2); while (sub.read() != 'z') { } assertEquals(sub.read(), -1); SharedByteArrayInputStream sub2 = (SharedByteArrayInputStream)sub.newStream(5, 10); assertEquals(sub2.getPosition(), 0); assertEquals(sub2.read(), 'f'); } }
927
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/util/ByteArrayDataSourceTest.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 junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class ByteArrayDataSourceTest extends TestCase { public ByteArrayDataSourceTest(String arg0) { super(arg0); } public void testByteArray() throws Exception { doDataSourceTest(new ByteArrayDataSource("0123456789", "text/plain"), "text/plain"); doDataSourceTest(new ByteArrayDataSource("0123456789".getBytes(), "text/xml"), "text/xml"); ByteArrayInputStream in = new ByteArrayInputStream("0123456789".getBytes()); doDataSourceTest(new ByteArrayDataSource(in, "text/html"), "text/html"); try { ByteArrayDataSource source = new ByteArrayDataSource("01234567890", "text/plain"); source.getOutputStream(); fail(); } catch (IOException e) { } ByteArrayDataSource source = new ByteArrayDataSource("01234567890", "text/plain"); assertEquals(source.getName(), ""); source.setName("fred"); assertEquals(source.getName(), "fred"); } private void doDataSourceTest(ByteArrayDataSource source, String type) throws Exception { assertEquals(type, source.getContentType()); InputStream in = source.getInputStream(); byte[] bytes = new byte[10]; int count = in.read(bytes); assertEquals(count, bytes.length); assertEquals("0123456789", new String(bytes)); } }
928
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/MimeMessageTest.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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import javax.activation.CommandMap; import javax.activation.MailcapCommandMap; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.swing.text.AbstractDocument.Content; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class MimeMessageTest extends TestCase { private CommandMap defaultMap; private Session session; public void testWriteTo() throws MessagingException, IOException { MimeMessage msg = new MimeMessage(session); msg.setSender(new InternetAddress("foo")); msg.setHeader("foo", "bar"); MimeMultipart mp = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); part1.setHeader("foo", "bar"); part1.setContent("Hello World", "text/plain"); mp.addBodyPart(part1); MimeBodyPart part2 = new MimeBodyPart(); part2.setContent("Hello Again", "text/plain"); mp.addBodyPart(part2); msg.setContent(mp); ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); InputStream in = new ByteArrayInputStream(out.toByteArray()); MimeMessage newMessage = new MimeMessage(session, in); assertEquals(((InternetAddress)newMessage.getSender()).getAddress(), "foo"); String[] headers = newMessage.getHeader("foo"); assertTrue(headers.length == 1); assertEquals(headers[0], "bar"); newMessage = new MimeMessage(msg); assertEquals(((InternetAddress)newMessage.getSender()).getAddress(), "foo"); assertEquals(newMessage.getHeader("foo")[0], "bar"); } public void testFrom() throws MessagingException { MimeMessage msg = new MimeMessage(session); InternetAddress dev = new InternetAddress("geronimo-dev@apache.org"); InternetAddress user = new InternetAddress("geronimo-user@apache.org"); msg.setSender(dev); Address[] from = msg.getFrom(); assertTrue(from.length == 1); assertEquals(from[0], dev); msg.setFrom(user); from = msg.getFrom(); assertTrue(from.length == 1); assertEquals(from[0], user); msg.addFrom(new Address[] { dev }); from = msg.getFrom(); assertTrue(from.length == 2); assertEquals(from[0], user); assertEquals(from[1], dev); msg.setFrom(); InternetAddress local = InternetAddress.getLocalAddress(session); from = msg.getFrom(); assertTrue(from.length == 1); assertEquals(local, from[0]); msg.setFrom(null); from = msg.getFrom(); assertTrue(from.length == 1); assertEquals(dev, from[0]); msg.setSender(null); from = msg.getFrom(); assertNull(from); } public void testSender() throws MessagingException { MimeMessage msg = new MimeMessage(session); InternetAddress dev = new InternetAddress("geronimo-dev@apache.org"); InternetAddress user = new InternetAddress("geronimo-user@apache.org"); msg.setSender(dev); Address[] from = msg.getFrom(); assertTrue(from.length == 1); assertEquals(from[0], dev); assertEquals(msg.getSender(), dev); msg.setSender(null); assertNull(msg.getSender()); } public void testGetAllRecipients() throws MessagingException { MimeMessage msg = new MimeMessage(session); InternetAddress dev = new InternetAddress("geronimo-dev@apache.org"); InternetAddress user = new InternetAddress("geronimo-user@apache.org"); InternetAddress user1 = new InternetAddress("geronimo-user1@apache.org"); InternetAddress user2 = new InternetAddress("geronimo-user2@apache.org"); NewsAddress group = new NewsAddress("comp.lang.rexx"); Address[] recipients = msg.getAllRecipients(); assertNull(recipients); msg.setRecipients(Message.RecipientType.TO, new Address[] { dev }); recipients = msg.getAllRecipients(); assertTrue(recipients.length == 1); assertEquals(recipients[0], dev); msg.addRecipients(Message.RecipientType.BCC, new Address[] { user }); recipients = msg.getAllRecipients(); assertTrue(recipients.length == 2); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); msg.addRecipients(Message.RecipientType.CC, new Address[] { user1, user2} ); recipients = msg.getAllRecipients(); assertTrue(recipients.length == 4); assertEquals(recipients[0], dev); assertEquals(recipients[1], user1); assertEquals(recipients[2], user2); assertEquals(recipients[3], user); msg.addRecipients(MimeMessage.RecipientType.NEWSGROUPS, new Address[] { group } ); recipients = msg.getAllRecipients(); assertTrue(recipients.length == 5); assertEquals(recipients[0], dev); assertEquals(recipients[1], user1); assertEquals(recipients[2], user2); assertEquals(recipients[3], user); assertEquals(recipients[4], group); msg.setRecipients(Message.RecipientType.CC, (String)null); recipients = msg.getAllRecipients(); assertTrue(recipients.length == 3); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); assertEquals(recipients[2], group); } public void testGetRecipients() throws MessagingException { doRecipientTest(Message.RecipientType.TO); doRecipientTest(Message.RecipientType.CC); doRecipientTest(Message.RecipientType.BCC); doNewsgroupRecipientTest(MimeMessage.RecipientType.NEWSGROUPS); } private void doRecipientTest(Message.RecipientType type) throws MessagingException { MimeMessage msg = new MimeMessage(session); InternetAddress dev = new InternetAddress("geronimo-dev@apache.org"); InternetAddress user = new InternetAddress("geronimo-user@apache.org"); Address[] recipients = msg.getRecipients(type); assertNull(recipients); msg.setRecipients(type, "geronimo-dev@apache.org"); recipients = msg.getRecipients(type); assertTrue(recipients.length == 1); assertEquals(recipients[0], dev); msg.addRecipients(type, "geronimo-user@apache.org"); recipients = msg.getRecipients(type); assertTrue(recipients.length == 2); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); msg.setRecipients(type, (String)null); recipients = msg.getRecipients(type); assertNull(recipients); msg.setRecipients(type, new Address[] { dev }); recipients = msg.getRecipients(type); assertTrue(recipients.length == 1); assertEquals(recipients[0], dev); msg.addRecipients(type, new Address[] { user }); recipients = msg.getRecipients(type); assertTrue(recipients.length == 2); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); msg.setRecipients(type, (Address[])null); recipients = msg.getRecipients(type); assertNull(recipients); msg.setRecipients(type, new Address[] { dev, user }); recipients = msg.getRecipients(type); assertTrue(recipients.length == 2); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); } private void doNewsgroupRecipientTest(Message.RecipientType type) throws MessagingException { MimeMessage msg = new MimeMessage(session); Address dev = new NewsAddress("geronimo-dev"); Address user = new NewsAddress("geronimo-user"); Address[] recipients = msg.getRecipients(type); assertNull(recipients); msg.setRecipients(type, "geronimo-dev"); recipients = msg.getRecipients(type); assertTrue(recipients.length == 1); assertEquals(recipients[0], dev); msg.addRecipients(type, "geronimo-user"); recipients = msg.getRecipients(type); assertTrue(recipients.length == 2); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); msg.setRecipients(type, (String)null); recipients = msg.getRecipients(type); assertNull(recipients); msg.setRecipients(type, new Address[] { dev }); recipients = msg.getRecipients(type); assertTrue(recipients.length == 1); assertEquals(recipients[0], dev); msg.addRecipients(type, new Address[] { user }); recipients = msg.getRecipients(type); assertTrue(recipients.length == 2); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); msg.setRecipients(type, (Address[])null); recipients = msg.getRecipients(type); assertNull(recipients); msg.setRecipients(type, new Address[] { dev, user }); recipients = msg.getRecipients(type); assertTrue(recipients.length == 2); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); } public void testReplyTo() throws MessagingException { MimeMessage msg = new MimeMessage(session); InternetAddress dev = new InternetAddress("geronimo-dev@apache.org"); InternetAddress user = new InternetAddress("geronimo-user@apache.org"); msg.setReplyTo(new Address[] { dev }); Address[] recipients = msg.getReplyTo(); assertTrue(recipients.length == 1); assertEquals(recipients[0], dev); msg.setReplyTo(new Address[] { dev, user }); recipients = msg.getReplyTo(); assertTrue(recipients.length == 2); assertEquals(recipients[0], dev); assertEquals(recipients[1], user); msg.setReplyTo(null); recipients = msg.getReplyTo(); assertNull(recipients); } public void testSetSubject() throws MessagingException { MimeMessage msg = new MimeMessage(session); String simpleSubject = "Yada, yada"; String complexSubject = "Yada, yada\u0081"; String mungedSubject = "Yada, yada\u003F"; msg.setSubject(simpleSubject); assertEquals(msg.getSubject(), simpleSubject); msg.setSubject(complexSubject, "UTF-8"); assertEquals(msg.getSubject(), complexSubject); msg.setSubject(null); assertNull(msg.getSubject()); } public void testSetDescription() throws MessagingException { MimeMessage msg = new MimeMessage(session); String simpleSubject = "Yada, yada"; String complexSubject = "Yada, yada\u0081"; String mungedSubject = "Yada, yada\u003F"; msg.setDescription(simpleSubject); assertEquals(msg.getDescription(), simpleSubject); msg.setDescription(complexSubject, "UTF-8"); assertEquals(msg.getDescription(), complexSubject); msg.setDescription(null); assertNull(msg.getDescription()); } public void testGetContentType() throws MessagingException { MimeMessage msg = new MimeMessage(session); assertEquals(msg.getContentType(), "text/plain"); msg.setHeader("Content-Type", "text/xml"); assertEquals(msg.getContentType(), "text/xml"); } public void testSetText() throws MessagingException { MimeMessage msg = new MimeMessage(session); msg.setText("Yada, yada"); msg.saveChanges(); ContentType type = new ContentType(msg.getContentType()); assertTrue(type.match("text/plain")); msg = new MimeMessage(session); msg.setText("Yada, yada", "UTF-8"); msg.saveChanges(); type = new ContentType(msg.getContentType()); assertTrue(type.match("text/plain")); assertEquals(type.getParameter("charset"), "UTF-8"); msg = new MimeMessage(session); msg.setText("Yada, yada", "UTF-8", "xml"); msg.saveChanges(); type = new ContentType(msg.getContentType()); assertTrue(type.match("text/xml")); assertEquals(type.getParameter("charset"), "UTF-8"); } protected void setUp() throws Exception { defaultMap = CommandMap.getDefaultCommandMap(); MailcapCommandMap myMap = new MailcapCommandMap(); myMap.addMailcap("text/plain;; x-java-content-handler=" + MimeMultipartTest.DummyTextHandler.class.getName()); myMap.addMailcap("multipart/*;; x-java-content-handler=" + MimeMultipartTest.DummyMultipartHandler.class.getName()); CommandMap.setDefaultCommandMap(myMap); Properties props = new Properties(); props.put("mail.user", "tester"); props.put("mail.host", "apache.org"); session = Session.getInstance(props); } protected void tearDown() throws Exception { CommandMap.setDefaultCommandMap(defaultMap); } }
929
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/ContentTypeTest.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 junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class ContentTypeTest extends TestCase { public ContentTypeTest(String arg0) { super(arg0); } public void testContentType() throws ParseException { ContentType type = new ContentType(); assertNull(type.getPrimaryType()); assertNull(type.getSubType()); assertNull(type.getParameter("charset")); } public void testContentTypeStringStringParameterList() throws ParseException { ContentType type; ParameterList list = new ParameterList(";charset=us-ascii"); type = new ContentType("text", "plain", list); assertEquals("text", type.getPrimaryType()); assertEquals("plain", type.getSubType()); assertEquals("text/plain", type.getBaseType()); ParameterList parameterList = type.getParameterList(); assertEquals("us-ascii", parameterList.get("charset")); assertEquals("us-ascii", type.getParameter("charset")); } public void testContentTypeString() throws ParseException { ContentType type; type = new ContentType("text/plain"); assertEquals("text", type.getPrimaryType()); assertEquals("plain", type.getSubType()); assertEquals("text/plain", type.getBaseType()); assertNotNull(type.getParameterList()); assertNull(type.getParameter("charset")); type = new ContentType("image/audio;charset=us-ascii"); ParameterList parameterList = type.getParameterList(); assertEquals("image", type.getPrimaryType()); assertEquals("audio", type.getSubType()); assertEquals("image/audio", type.getBaseType()); assertEquals("us-ascii", parameterList.get("charset")); assertEquals("us-ascii", type.getParameter("charset")); } public void testGetPrimaryType() throws ParseException { } public void testGetSubType() throws ParseException { } public void testGetBaseType() throws ParseException { } public void testGetParameter() throws ParseException { } public void testGetParameterList() throws ParseException { } public void testSetPrimaryType() throws ParseException { ContentType type = new ContentType("text/plain"); type.setPrimaryType("binary"); assertEquals("binary", type.getPrimaryType()); assertEquals("plain", type.getSubType()); assertEquals("binary/plain", type.getBaseType()); } public void testSetSubType() throws ParseException { ContentType type = new ContentType("text/plain"); type.setSubType("html"); assertEquals("text", type.getPrimaryType()); assertEquals("html", type.getSubType()); assertEquals("text/html", type.getBaseType()); } public void testSetParameter() throws ParseException { } public void testSetParameterList() throws ParseException { } public void testToString() throws ParseException { ContentType type = new ContentType("text/plain"); assertEquals("text/plain", type.toString()); type.setParameter("foo", "bar"); assertEquals("text/plain; foo=bar", type.toString()); type.setParameter("bar", "me@apache.org"); assertEquals("text/plain; foo=bar; bar=\"me@apache.org\"", type.toString()); type.setParameter("x", "y"); assertEquals("text/plain; foo=bar; bar=\"me@apache.org\"; x=y", type.toString()); type.setParameter("x", "z"); assertEquals("text/plain; foo=bar; bar=\"me@apache.org\"; x=z", type.toString()); type.setParameter("foo", "bar2"); assertEquals("text/plain; foo=bar2; bar=\"me@apache.org\"; x=z", type.toString()); } public void testMatchContentType() throws ParseException { ContentType type = new ContentType("text/plain"); ContentType test = new ContentType("text/plain"); assertTrue(type.match(test)); test = new ContentType("TEXT/plain"); assertTrue(type.match(test)); assertTrue(test.match(type)); test = new ContentType("text/PLAIN"); assertTrue(type.match(test)); assertTrue(test.match(type)); test = new ContentType("text/*"); assertTrue(type.match(test)); assertTrue(test.match(type)); test = new ContentType("text/xml"); assertFalse(type.match(test)); assertFalse(test.match(type)); test = new ContentType("binary/plain"); assertFalse(type.match(test)); assertFalse(test.match(type)); test = new ContentType("*/plain"); assertFalse(type.match(test)); assertFalse(test.match(type)); } public void testMatchString() throws ParseException { ContentType type = new ContentType("text/plain"); assertTrue(type.match("text/plain")); assertTrue(type.match("TEXT/plain")); assertTrue(type.match("text/PLAIN")); assertTrue(type.match("TEXT/PLAIN")); assertTrue(type.match("TEXT/*")); assertFalse(type.match("text/xml")); assertFalse(type.match("binary/plain")); assertFalse(type.match("*/plain")); assertFalse(type.match("")); assertFalse(type.match("text/plain/yada")); } public void testSOAP12ContentType() throws ParseException { ContentType type = new ContentType("multipart/related; type=\"application/xop+xml\"; start=\"<rootpart@soapui.org>\"; start-info=\"application/soap+xml; action=\\\"urn:upload\\\"\"; boundary=\"----=_Part_10_5804917.1223557742343\""); assertEquals("multipart/related", type.getBaseType()); assertEquals("application/xop+xml", type.getParameter("type")); assertEquals("<rootpart@soapui.org>", type.getParameter("start")); assertEquals("application/soap+xml; action=\"urn:upload\"", type.getParameter("start-info")); assertEquals("----=_Part_10_5804917.1223557742343", type.getParameter("boundary")); } }
930
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/MimeMultipartTest.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.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.io.OutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Message; import javax.activation.CommandMap; import javax.activation.MailcapCommandMap; import javax.activation.DataContentHandler; import javax.activation.DataSource; import javax.activation.DataHandler; import javax.activation.FileDataSource; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class MimeMultipartTest extends TestCase { private CommandMap defaultMap; public void testWriteTo() throws MessagingException, IOException, Exception { writeToSetUp(); MimeMultipart mp = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); part1.setHeader("foo", "bar"); part1.setContent("Hello World", "text/plain"); mp.addBodyPart(part1); MimeBodyPart part2 = new MimeBodyPart(); part2.setContent("Hello Again", "text/plain"); mp.addBodyPart(part2); mp.writeTo(System.out); writeToTearDown(); } public void testPreamble() throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props); session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("rickmcg@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("rick@us.ibm.com")); message.setSubject("test subject"); BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setHeader("Content-Type", "text/xml"); messageBodyPart1.setHeader("Content-Transfer-Encoding", "binary"); messageBodyPart1.setText("This is a test"); MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); multipart.setPreamble("This is a preamble"); assertEquals("This is a preamble", multipart.getPreamble()); message.setContent(multipart); ByteArrayOutputStream out = new ByteArrayOutputStream(); message.writeTo(out); out.writeTo(System.out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); MimeMessage newMessage = new MimeMessage(session, in); assertEquals("This is a preamble\r\n", ((MimeMultipart)newMessage.getContent()).getPreamble()); } public void testMIMEWriting() throws IOException, MessagingException { File basedir = new File(System.getProperty("basedir", ".")); File testInput = new File(basedir, "src/test/resources/wmtom.bin"); FileInputStream inStream = new FileInputStream(testInput); Properties props = new Properties(); javax.mail.Session session = javax.mail.Session .getInstance(props, null); MimeMessage mimeMessage = new MimeMessage(session, inStream); DataHandler dh = mimeMessage.getDataHandler(); MimeMultipart multiPart = new MimeMultipart(dh.getDataSource()); MimeBodyPart mimeBodyPart0 = (MimeBodyPart) multiPart.getBodyPart(0); Object object0 = mimeBodyPart0.getContent(); assertNotNull(object0); MimeBodyPart mimeBodyPart1 = (MimeBodyPart) multiPart.getBodyPart(1); Object object1 = mimeBodyPart1.getContent(); assertNotNull(object1); assertEquals(multiPart.getCount(), 2); } protected void writeToSetUp() throws Exception { defaultMap = CommandMap.getDefaultCommandMap(); MailcapCommandMap myMap = new MailcapCommandMap(); myMap.addMailcap("text/plain;; x-java-content-handler=" + DummyTextHandler.class.getName()); myMap.addMailcap("multipart/*;; x-java-content-handler=" + DummyMultipartHandler.class.getName()); CommandMap.setDefaultCommandMap(myMap); } protected void writeToTearDown() throws Exception { CommandMap.setDefaultCommandMap(defaultMap); } public static class DummyTextHandler implements DataContentHandler { public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[0]; //To change body of implemented methods use File | Settings | File Templates. } public Object getTransferData(DataFlavor df, DataSource ds) throws UnsupportedFlavorException, IOException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object getContent(DataSource ds) throws IOException { return null; //To change body of implemented methods use File | Settings | File Templates. } public void writeTo(Object obj, String mimeType, OutputStream os) throws IOException { os.write(((String)obj).getBytes("ISO8859-1")); } } public static class DummyMultipartHandler implements DataContentHandler { public DataFlavor[] getTransferDataFlavors() { throw new UnsupportedOperationException(); } public Object getTransferData(DataFlavor df, DataSource ds) throws UnsupportedFlavorException, IOException { throw new UnsupportedOperationException(); } public Object getContent(DataSource ds) throws IOException { throw new UnsupportedOperationException(); } public void writeTo(Object obj, String mimeType, OutputStream os) throws IOException { MimeMultipart mp = (MimeMultipart) obj; try { mp.writeTo(os); } catch (MessagingException e) { throw (IOException) new IOException(e.getMessage()).initCause(e); } } } }
931
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/ParameterListTest.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 junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class ParameterListTest extends TestCase { public ParameterListTest(String arg0) { super(arg0); } public void testParameters() throws ParseException { ParameterList list = new ParameterList(";thing=value;thong=vulue;thung=git"); assertEquals("value", list.get("thing")); assertEquals("vulue", list.get("thong")); assertEquals("git", list.get("thung")); } public void testQuotedParameter() throws ParseException { ParameterList list = new ParameterList(";foo=one;bar=\"two\""); assertEquals("one", list.get("foo")); assertEquals("two", list.get("bar")); } public void testEncodeDecode() throws Exception { System.setProperty("mail.mime.encodeparameters", "true"); System.setProperty("mail.mime.decodeparameters", "true"); String value = " '*% abc \u0081\u0082\r\n\t"; String encodedTest = "; one*=UTF-8''%20%27%2A%25%20abc%20%C2%81%C2%82%0D%0A%09"; ParameterList list = new ParameterList(); list.set("one", value, "UTF-8"); assertEquals(value, list.get("one")); String encoded = list.toString(); assertEquals(encoded, encodedTest); ParameterList list2 = new ParameterList(encoded); assertEquals(value, list.get("one")); assertEquals(list2.toString(), encodedTest); } }
932
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/MimeTest.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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Session; import junit.framework.TestCase; import org.apache.geronimo.mail.util.Base64; public class MimeTest extends TestCase { public void testWriteRead() throws Exception { System.setProperty("mail.mime.decodefilename", "true"); Session session = Session.getDefaultInstance(new Properties(), null); MimeMessage mime = new MimeMessage(session); MimeMultipart parts = new MimeMultipart("related; type=\"text/xml\"; start=\"<xml>\""); MimeBodyPart xmlPart = new MimeBodyPart(); xmlPart.setContentID("<xml>"); xmlPart.setDataHandler(new DataHandler(new ByteArrayDataSource("<hello/>".getBytes(), "text/xml"))); parts.addBodyPart(xmlPart); MimeBodyPart jpegPart = new MimeBodyPart(); jpegPart.setContentID("<jpeg>"); String filename = "filename"; String encodedFilename = "=?UTF-8?B?" + new String(Base64.encode(filename.getBytes()), "ISO8859-1") + "?="; jpegPart.setFileName(encodedFilename); jpegPart.setDataHandler(new DataHandler(new ByteArrayDataSource(new byte[] { 0, 1, 2, 3, 4, 5 }, "image/jpeg"))); parts.addBodyPart(jpegPart); mime.setContent(parts); mime.setHeader("Content-Type", parts.getContentType()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mime.writeTo(baos); MimeMessage mime2 = new MimeMessage(session, new ByteArrayInputStream(baos.toByteArray())); assertTrue(mime2.getContent() instanceof MimeMultipart); MimeMultipart parts2 = (MimeMultipart) mime2.getContent(); assertEquals(mime.getContentType(), mime2.getContentType()); assertEquals(parts.getCount(), parts2.getCount()); assertTrue(parts2.getBodyPart(0) instanceof MimeBodyPart); assertTrue(parts2.getBodyPart(1) instanceof MimeBodyPart); MimeBodyPart xmlPart2 = (MimeBodyPart) parts2.getBodyPart(0); assertEquals(xmlPart.getContentID(), xmlPart2.getContentID()); ByteArrayOutputStream xmlBaos = new ByteArrayOutputStream(); copyInputStream(xmlPart.getDataHandler().getInputStream(), xmlBaos); ByteArrayOutputStream xmlBaos2 = new ByteArrayOutputStream(); copyInputStream(xmlPart2.getDataHandler().getInputStream(), xmlBaos2); assertEquals(xmlBaos.toString(), xmlBaos2.toString()); MimeBodyPart jpegPart2 = (MimeBodyPart) parts2.getBodyPart(1); assertEquals(jpegPart.getContentID(), jpegPart2.getContentID()); assertEquals(jpegPart.getFileName(), jpegPart2.getDataHandler().getName()); assertEquals(filename, jpegPart2.getDataHandler().getName()); ByteArrayOutputStream jpegBaos = new ByteArrayOutputStream(); copyInputStream(jpegPart.getDataHandler().getInputStream(), jpegBaos); ByteArrayOutputStream jpegBaos2 = new ByteArrayOutputStream(); copyInputStream(jpegPart2.getDataHandler().getInputStream(), jpegBaos2); assertEquals(jpegBaos.toString(), jpegBaos2.toString()); } public static class ByteArrayDataSource implements DataSource { private byte[] data; private String type; private String name = "unused"; public ByteArrayDataSource(byte[] data, String type) { this.data = data; this.type = type; } public InputStream getInputStream() throws IOException { if (data == null) throw new IOException("no data"); return new ByteArrayInputStream(data); } public OutputStream getOutputStream() throws IOException { throw new IOException("getOutputStream() not supported"); } public String getContentType() { return type; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static void copyInputStream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); } in.close(); out.close(); } }
933
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/ContentDispositionTest.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 junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class ContentDispositionTest extends TestCase { public ContentDispositionTest(String name) { super(name); } public void testContentDisposition() throws ParseException { ContentDisposition c; c = new ContentDisposition(); assertNotNull(c.getParameterList()); assertNull(c.getParameterList().get("nothing")); assertNull(c.getDisposition()); assertNull(c.toString()); c.setDisposition("inline"); assertEquals("inline",c.getDisposition()); c.setParameter("file","file.txt"); assertEquals("file.txt",c.getParameterList().get("file")); assertEquals("inline; file=file.txt",c.toString()); c = new ContentDisposition("inline"); assertEquals(0,c.getParameterList().size()); assertEquals("inline",c.getDisposition()); c = new ContentDisposition("inline",new ParameterList(";charset=us-ascii;content-type=\"text/plain\"")); assertEquals("inline",c.getDisposition()); assertEquals("us-ascii",c.getParameter("charset")); assertEquals("text/plain",c.getParameter("content-type")); c = new ContentDisposition("attachment;content-type=\"text/html\";charset=UTF-8"); assertEquals("attachment",c.getDisposition()); assertEquals("UTF-8",c.getParameter("charset")); assertEquals("text/html",c.getParameter("content-type")); } }
934
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/HeaderTokenizerTest.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.internet.HeaderTokenizer.Token; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class HeaderTokenizerTest extends TestCase { public void testTokenizer() throws ParseException { Token t; HeaderTokenizer ht; ht = new HeaderTokenizer("To: \"Geronimo List\" <geronimo-dev@apache.org>, \n\r Geronimo User <geronimo-user@apache.org>"); validateToken(ht.peek(), Token.ATOM, "To"); validateToken(ht.next(), Token.ATOM, "To"); validateToken(ht.peek(), ':', ":"); validateToken(ht.next(), ':', ":"); validateToken(ht.next(), Token.QUOTEDSTRING, "Geronimo List"); validateToken(ht.next(), '<', "<"); validateToken(ht.next(), Token.ATOM, "geronimo-dev"); validateToken(ht.next(), '@', "@"); validateToken(ht.next(), Token.ATOM, "apache"); validateToken(ht.next(), '.', "."); validateToken(ht.next(), Token.ATOM, "org"); validateToken(ht.next(), '>', ">"); validateToken(ht.next(), ',', ","); validateToken(ht.next(), Token.ATOM, "Geronimo"); validateToken(ht.next(), Token.ATOM, "User"); validateToken(ht.next(), '<', "<"); validateToken(ht.next(), Token.ATOM, "geronimo-user"); validateToken(ht.next(), '@', "@"); validateToken(ht.next(), Token.ATOM, "apache"); validateToken(ht.next(), '.', "."); assertEquals("org>", ht.getRemainder()); validateToken(ht.peek(), Token.ATOM, "org"); validateToken(ht.next(), Token.ATOM, "org"); validateToken(ht.next(), '>', ">"); assertEquals(Token.EOF, ht.next().getType()); ht = new HeaderTokenizer(" "); assertEquals(Token.EOF, ht.next().getType()); ht = new HeaderTokenizer("J2EE"); validateToken(ht.next(), Token.ATOM, "J2EE"); assertEquals(Token.EOF, ht.next().getType()); // test comments doComment(true); doComment(false); } public void testErrors() throws ParseException { checkParseError("(Geronimo"); checkParseError("((Geronimo)"); checkParseError("\"Geronimo"); checkParseError("\"Geronimo\\"); } public void testQuotedLiteral() throws ParseException { checkTokenParse("\"\"", Token.QUOTEDSTRING, ""); checkTokenParse("\"\\\"\"", Token.QUOTEDSTRING, "\""); checkTokenParse("\"\\\"\"", Token.QUOTEDSTRING, "\""); checkTokenParse("\"A\r\nB\"", Token.QUOTEDSTRING, "AB"); checkTokenParse("\"A\nB\"", Token.QUOTEDSTRING, "A\nB"); } public void testComment() throws ParseException { checkTokenParse("()", Token.COMMENT, ""); checkTokenParse("(())", Token.COMMENT, "()"); checkTokenParse("(Foo () Bar)", Token.COMMENT, "Foo () Bar"); checkTokenParse("(\"Foo () Bar)", Token.COMMENT, "\"Foo () Bar"); checkTokenParse("(\\()", Token.COMMENT, "("); checkTokenParse("(Foo \r\n Bar)", Token.COMMENT, "Foo Bar"); checkTokenParse("(Foo \n Bar)", Token.COMMENT, "Foo \n Bar"); } public void checkTokenParse(String text, int type, String value) throws ParseException { HeaderTokenizer ht; ht = new HeaderTokenizer(text, HeaderTokenizer.RFC822, false); validateToken(ht.next(), type, value); } public void checkParseError(String text) throws ParseException { Token t; HeaderTokenizer ht; ht = new HeaderTokenizer(text); doNextError(ht); ht = new HeaderTokenizer(text); doPeekError(ht); } public void doNextError(HeaderTokenizer ht) { try { ht.next(); fail("Expected ParseException"); } catch (ParseException e) { } } public void doPeekError(HeaderTokenizer ht) { try { ht.peek(); fail("Expected ParseException"); } catch (ParseException e) { } } public void doComment(boolean ignore) throws ParseException { HeaderTokenizer ht; Token t; ht = new HeaderTokenizer( "Apache(Geronimo)J2EE", HeaderTokenizer.RFC822, ignore); validateToken(ht.next(), Token.ATOM, "Apache"); if (!ignore) { validateToken(ht.next(), Token.COMMENT, "Geronimo"); } validateToken(ht.next(), Token.ATOM, "J2EE"); assertEquals(Token.EOF, ht.next().getType()); ht = new HeaderTokenizer( "Apache(Geronimo (Project))J2EE", HeaderTokenizer.RFC822, ignore); validateToken(ht.next(), Token.ATOM, "Apache"); if (!ignore) { validateToken(ht.next(), Token.COMMENT, "Geronimo (Project)"); } validateToken(ht.next(), Token.ATOM, "J2EE"); assertEquals(Token.EOF, ht.next().getType()); } private void validateToken(HeaderTokenizer.Token token, int type, String value) { assertEquals(token.getType(), type); assertEquals(token.getValue(), value); } }
935
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/AllInternetTests.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 junit.framework.Test; import junit.framework.TestSuite; /** * @version $Rev$ $Date$ */ public class AllInternetTests { public static Test suite() { TestSuite suite = new TestSuite("Test for javax.mail.internet"); //$JUnit-BEGIN$ suite.addTest(new TestSuite(ContentTypeTest.class)); suite.addTest(new TestSuite(ParameterListTest.class)); suite.addTest(new TestSuite(InternetAddressTest.class)); //$JUnit-END$ return suite; } }
936
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/MailDateFormatTest.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.ParseException; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.SimpleTimeZone; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class MailDateFormatTest extends TestCase { public void testMailDateFormat() throws ParseException { MailDateFormat mdf = new MailDateFormat(); Date date = mdf.parse("Wed, 27 Aug 2003 13:43:38 +0100 (BST)"); // don't we just love the Date class? Calendar cal = Calendar.getInstance(new SimpleTimeZone(+1 * 60 * 60 * 1000, "BST"), Locale.getDefault()); cal.setTime(date); assertEquals(2003, cal.get(Calendar.YEAR)); assertEquals(Calendar.AUGUST, cal.get(Calendar.MONTH)); assertEquals(27, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(Calendar.WEDNESDAY, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(13, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(43, cal.get(Calendar.MINUTE)); assertEquals(38, cal.get(Calendar.SECOND)); date = mdf.parse("Wed, 27-Aug-2003 13:43:38 +0100"); // don't we just love the Date class? cal = Calendar.getInstance(new SimpleTimeZone(+1 * 60 * 60 * 1000, "BST"), Locale.getDefault()); cal.setTime(date); assertEquals(2003, cal.get(Calendar.YEAR)); assertEquals(Calendar.AUGUST, cal.get(Calendar.MONTH)); assertEquals(27, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(Calendar.WEDNESDAY, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(13, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(43, cal.get(Calendar.MINUTE)); assertEquals(38, cal.get(Calendar.SECOND)); date = mdf.parse("27-Aug-2003 13:43:38 EST"); // don't we just love the Date class? cal = Calendar.getInstance(new SimpleTimeZone(-5 * 60 * 60 * 1000, "EST"), Locale.getDefault()); cal.setTime(date); assertEquals(2003, cal.get(Calendar.YEAR)); assertEquals(Calendar.AUGUST, cal.get(Calendar.MONTH)); assertEquals(27, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(Calendar.WEDNESDAY, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(13, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(43, cal.get(Calendar.MINUTE)); assertEquals(38, cal.get(Calendar.SECOND)); date = mdf.parse("27 Aug 2003 13:43 EST"); // don't we just love the Date class? cal = Calendar.getInstance(new SimpleTimeZone(-5 * 60 * 60 * 1000, "EST"), Locale.getDefault()); cal.setTime(date); assertEquals(2003, cal.get(Calendar.YEAR)); assertEquals(Calendar.AUGUST, cal.get(Calendar.MONTH)); assertEquals(27, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(Calendar.WEDNESDAY, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(13, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(43, cal.get(Calendar.MINUTE)); assertEquals(00, cal.get(Calendar.SECOND)); date = mdf.parse("27 Aug 03 13:43 EST"); // don't we just love the Date class? cal = Calendar.getInstance(new SimpleTimeZone(-5 * 60 * 60 * 1000, "EST"), Locale.getDefault()); cal.setTime(date); assertEquals(2003, cal.get(Calendar.YEAR)); assertEquals(Calendar.AUGUST, cal.get(Calendar.MONTH)); assertEquals(27, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(Calendar.WEDNESDAY, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(13, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(43, cal.get(Calendar.MINUTE)); assertEquals(00, cal.get(Calendar.SECOND)); } }
937
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/MimeBodyPartTest.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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.UnsupportedEncodingException; import javax.mail.MessagingException; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class MimeBodyPartTest extends TestCase { File basedir = new File(System.getProperty("basedir", ".")); File testInput = new File(basedir, "src/test/resources/test.dat"); public void testGetSize() throws MessagingException { MimeBodyPart part = new MimeBodyPart(); assertEquals(part.getSize(), -1); part = new MimeBodyPart(new InternetHeaders(), new byte[] {'a', 'b', 'c'}); assertEquals(part.getSize(), 3); } public void testGetLineCount() throws MessagingException { MimeBodyPart part = new MimeBodyPart(); assertEquals(part.getLineCount(), -1); part = new MimeBodyPart(new InternetHeaders(), new byte[] {'a', 'b', 'c'}); assertEquals(part.getLineCount(), -1); } public void testGetContentType() throws MessagingException { MimeBodyPart part = new MimeBodyPart(); assertEquals(part.getContentType(), "text/plain"); part.setHeader("Content-Type", "text/xml"); assertEquals(part.getContentType(), "text/xml"); part = new MimeBodyPart(); part.setText("abc"); assertEquals(part.getContentType(), "text/plain"); } public void testIsMimeType() throws MessagingException { MimeBodyPart part = new MimeBodyPart(); assertTrue(part.isMimeType("text/plain")); assertTrue(part.isMimeType("text/*")); part.setHeader("Content-Type", "text/xml"); assertTrue(part.isMimeType("text/xml")); assertTrue(part.isMimeType("text/*")); } public void testGetDisposition() throws MessagingException { MimeBodyPart part = new MimeBodyPart(); assertNull(part.getDisposition()); part.setDisposition("inline"); assertEquals(part.getDisposition(), "inline"); } public void testSetDescription() throws MessagingException, UnsupportedEncodingException { MimeBodyPart part = new MimeBodyPart(); String simpleSubject = "Yada, yada"; String complexSubject = "Yada, yada\u0081"; String mungedSubject = "Yada, yada\u003F"; part.setDescription(simpleSubject); assertEquals(part.getDescription(), simpleSubject); part.setDescription(complexSubject, "UTF-8"); assertEquals(part.getDescription(), complexSubject); assertEquals(part.getHeader("Content-Description", null), MimeUtility.encodeText(complexSubject, "UTF-8", null)); part.setDescription(mungedSubject, "UTF-8"); assertEquals(part.getDescription(), mungedSubject); assertEquals(part.getHeader("Content-Description", null), MimeUtility.encodeText(mungedSubject, "UTF-8", null)); part.setDescription(null); assertNull(part.getDescription()); } public void testSetFileName() throws Exception { MimeBodyPart part = new MimeBodyPart(); part.addHeader("Content-Type", "application/octet-stream"); //GERONIMO-6480 part.setFileName("test.dat"); assertEquals("test.dat", part.getFileName()); ContentDisposition disp = new ContentDisposition(part.getHeader("Content-Disposition", null)); assertEquals("test.dat", disp.getParameter("filename")); ContentType type = new ContentType(part.getHeader("Content-Type", null)); assertEquals("test.dat", type.getParameter("name")); MimeBodyPart part2 = new MimeBodyPart(); part2.setHeader("Content-Type", type.toString()); assertEquals("test.dat", part2.getFileName()); part2.setHeader("Content-Type", null); part2.setHeader("Content-Disposition", disp.toString()); assertEquals("test.dat", part2.getFileName()); } public void testAttachments() throws Exception { MimeBodyPart part = new MimeBodyPart(); byte[] testData = getFileData(testInput); part.attachFile(testInput); assertEquals(part.getFileName(), testInput.getName()); part.updateHeaders(); File temp1 = File.createTempFile("MIME", ".dat"); temp1.deleteOnExit(); part.saveFile(temp1); byte[] tempData = getFileData(temp1); compareFileData(testData, tempData); ByteArrayOutputStream out = new ByteArrayOutputStream(); part.writeTo(out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); MimeBodyPart part2 = new MimeBodyPart(in); temp1 = File.createTempFile("MIME", ".dat"); temp1.deleteOnExit(); part2.saveFile(temp1); tempData = getFileData(temp1); compareFileData(testData, tempData); part = new MimeBodyPart(); part.attachFile(testInput.getPath()); assertEquals(part.getFileName(), testInput.getName()); part.updateHeaders(); temp1 = File.createTempFile("MIME", ".dat"); temp1.deleteOnExit(); part.saveFile(temp1.getPath()); tempData = getFileData(temp1); compareFileData(testData, tempData); out = new ByteArrayOutputStream(); part.writeTo(out); in = new ByteArrayInputStream(out.toByteArray()); part2 = new MimeBodyPart(in); temp1 = File.createTempFile("MIME", ".dat"); temp1.deleteOnExit(); part2.saveFile(temp1.getPath()); tempData = getFileData(temp1); compareFileData(testData, tempData); } private byte[] getFileData(File source) throws Exception { FileInputStream testIn = new FileInputStream(source); byte[] testData = new byte[(int)source.length()]; testIn.read(testData); testIn.close(); return testData; } private void compareFileData(byte[] file1, byte [] file2) { assertEquals(file1.length, file2.length); for (int i = 0; i < file1.length; i++) { assertEquals(file1[i], file2[i]); } } class TestMimeBodyPart extends MimeBodyPart { public TestMimeBodyPart() { super(); } public void updateHeaders() throws MessagingException { super.updateHeaders(); } } }
938
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/InternetAddressTest.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 junit.framework.Assert; import junit.framework.TestCase; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Properties; import javax.mail.Session; /** * @version $Rev$ $Date$ */ public class InternetAddressTest extends TestCase { //private InternetAddress address; public void testQuotedLiterals() throws Exception { parseHeaderTest("\"Foo\t\n\\\\\\\"\" <foo@apache.org>", true, "foo@apache.org", "Foo\t\n\\\"", "\"Foo\t\n\\\\\\\"\" <foo@apache.org>", false); parseHeaderTest("<\"@,:;<>.[]()\"@apache.org>", true, "\"@,:;<>.[]()\"@apache.org", null, "<\"@,:;<>.[]()\"@apache.org>", false); parseHeaderTest("<\"\\F\\o\\o\"@apache.org>", true, "\"Foo\"@apache.org", null, "<\"Foo\"@apache.org>", false); parseHeaderErrorTest("\"Foo <foo@apache.org>", true); parseHeaderErrorTest("\"Foo\r\" <foo@apache.org>", true); } public void testDomainLiterals() throws Exception { parseHeaderTest("<foo@[apache].org>", true, "foo@[apache].org", null, "<foo@[apache].org>", false); parseHeaderTest("<foo@[@()<>.,:;\"\\\\].org>", true, "foo@[@()<>.,:;\"\\\\].org", null, "<foo@[@()<>.,:;\"\\\\].org>", false); parseHeaderTest("<foo@[\\[\\]].org>", true, "foo@[\\[\\]].org", null, "<foo@[\\[\\]].org>", false); parseHeaderErrorTest("<foo@[[].org>", true); parseHeaderErrorTest("<foo@[foo.org>", true); parseHeaderErrorTest("<foo@[\r].org>", true); } public void testComments() throws Exception { parseHeaderTest("Foo Bar (Fred) <foo@apache.org>", true, "foo@apache.org", "Foo Bar (Fred)", "\"Foo Bar (Fred)\" <foo@apache.org>", false); parseHeaderTest("(Fred) foo@apache.org", true, "foo@apache.org", "Fred", "Fred <foo@apache.org>", false); parseHeaderTest("(\\(Fred\\)) foo@apache.org", true, "foo@apache.org", "(Fred)", "\"(Fred)\" <foo@apache.org>", false); parseHeaderTest("(Fred (Jones)) foo@apache.org", true, "foo@apache.org", "Fred (Jones)", "\"Fred (Jones)\" <foo@apache.org>", false); parseHeaderErrorTest("(Fred foo@apache.org", true); parseHeaderErrorTest("(Fred\r) foo@apache.org", true); } public void testParseHeader() throws Exception { parseHeaderTest("<@apache.org,@apache.net:foo@apache.org>", false, "@apache.org,@apache.net:foo@apache.org", null, "<@apache.org,@apache.net:foo@apache.org>", false); parseHeaderTest("<@apache.org:foo@apache.org>", false, "@apache.org:foo@apache.org", null, "<@apache.org:foo@apache.org>", false); parseHeaderTest("Foo Bar:;", false, "Foo Bar:;", null, "Foo Bar:;", true); parseHeaderTest("\"\\\"Foo Bar\" <foo.bar@apache.org>", false, "foo.bar@apache.org", "\"Foo Bar", "\"\\\"Foo Bar\" <foo.bar@apache.org>", false); parseHeaderTest("\"Foo Bar\" <foo.bar@apache.org>", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseHeaderTest("(Foo) (Bar) foo.bar@apache.org", false, "foo.bar@apache.org", "Foo", "Foo <foo.bar@apache.org>", false); parseHeaderTest("<foo@apache.org>", false, "foo@apache.org", null, "foo@apache.org", false); parseHeaderTest("Foo Bar <foo.bar@apache.org>", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseHeaderTest("foo", false, "foo", null, "foo", false); parseHeaderTest("\"foo\"", false, "\"foo\"", null, "<\"foo\">", false); parseHeaderTest("foo@apache.org", false, "foo@apache.org", null, "foo@apache.org", false); parseHeaderTest("\"foo\"@apache.org", false, "\"foo\"@apache.org", null, "<\"foo\"@apache.org>", false); parseHeaderTest("foo@[apache].org", false, "foo@[apache].org", null, "<foo@[apache].org>", false); parseHeaderTest("foo@[apache].[org]", false, "foo@[apache].[org]", null, "<foo@[apache].[org]>", false); parseHeaderTest("foo.bar@apache.org", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseHeaderTest("(Foo Bar) <foo.bar@apache.org>", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseHeaderTest("(Foo) (Bar) <foo.bar@apache.org>", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseHeaderTest("\"Foo\" Bar <foo.bar@apache.org>", false, "foo.bar@apache.org", "\"Foo\" Bar", "\"\\\"Foo\\\" Bar\" <foo.bar@apache.org>", false); parseHeaderTest("(Foo Bar) foo.bar@apache.org", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseHeaderTest("apache.org", false, "apache.org", null, "apache.org", false); } public void testValidate() throws Exception { validateTest("@apache.org,@apache.net:foo@apache.org"); validateTest("@apache.org:foo@apache.org"); validateTest("Foo Bar:;"); validateTest("foo.bar@apache.org"); validateTest("bar@apache.org"); validateTest("foo"); validateTest("foo.bar"); validateTest("\"foo\""); validateTest("\"foo\"@apache.org"); validateTest("foo@[apache].org"); validateTest("foo@[apache].[org]"); } public void testStrictParseHeader() throws Exception { parseHeaderTest("<@apache.org,@apache.net:foo@apache.org>", true, "@apache.org,@apache.net:foo@apache.org", null, "<@apache.org,@apache.net:foo@apache.org>", false); parseHeaderTest("<@apache.org:foo@apache.org>", true, "@apache.org:foo@apache.org", null, "<@apache.org:foo@apache.org>", false); parseHeaderTest("Foo Bar:;", true, "Foo Bar:;", null, "Foo Bar:;", true); parseHeaderTest("\"\\\"Foo Bar\" <foo.bar@apache.org>", true, "foo.bar@apache.org", "\"Foo Bar", "\"\\\"Foo Bar\" <foo.bar@apache.org>", false); parseHeaderTest("\"Foo Bar\" <foo.bar@apache.org>", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseHeaderTest("(Foo) (Bar) foo.bar@apache.org", true, "foo.bar@apache.org", "Foo", "Foo <foo.bar@apache.org>", false); parseHeaderTest("<foo@apache.org>", true, "foo@apache.org", null, "foo@apache.org", false); parseHeaderTest("Foo Bar <foo.bar@apache.org>", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseHeaderTest("foo", true, "foo", null, "foo", false); parseHeaderTest("\"foo\"", true, "\"foo\"", null, "<\"foo\">", false); parseHeaderTest("foo@apache.org", true, "foo@apache.org", null, "foo@apache.org", false); parseHeaderTest("\"foo\"@apache.org", true, "\"foo\"@apache.org", null, "<\"foo\"@apache.org>", false); parseHeaderTest("foo@[apache].org", true, "foo@[apache].org", null, "<foo@[apache].org>", false); parseHeaderTest("foo@[apache].[org]", true, "foo@[apache].[org]", null, "<foo@[apache].[org]>", false); parseHeaderTest("foo.bar@apache.org", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseHeaderTest("(Foo Bar) <foo.bar@apache.org>", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseHeaderTest("(Foo) (Bar) <foo.bar@apache.org>", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseHeaderTest("\"Foo\" Bar <foo.bar@apache.org>", true, "foo.bar@apache.org", "\"Foo\" Bar", "\"\\\"Foo\\\" Bar\" <foo.bar@apache.org>", false); parseHeaderTest("(Foo Bar) foo.bar@apache.org", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseHeaderTest("apache.org", true, "apache.org", null, "apache.org", false); } public void testParse() throws Exception { parseTest("<@apache.org,@apache.net:foo@apache.org>", false, "@apache.org,@apache.net:foo@apache.org", null, "<@apache.org,@apache.net:foo@apache.org>", false); parseTest("<@apache.org:foo@apache.org>", false, "@apache.org:foo@apache.org", null, "<@apache.org:foo@apache.org>", false); parseTest("Foo Bar:;", false, "Foo Bar:;", null, "Foo Bar:;", true); parseTest("\"\\\"Foo Bar\" <foo.bar@apache.org>", false, "foo.bar@apache.org", "\"Foo Bar", "\"\\\"Foo Bar\" <foo.bar@apache.org>", false); parseTest("\"Foo Bar\" <foo.bar@apache.org>", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseTest("(Foo) (Bar) foo.bar@apache.org", false, "foo.bar@apache.org", "Foo", "Foo <foo.bar@apache.org>", false); parseTest("<foo@apache.org>", false, "foo@apache.org", null, "foo@apache.org", false); parseTest("Foo Bar <foo.bar@apache.org>", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseTest("foo", false, "foo", null, "foo", false); parseTest("\"foo\"", false, "\"foo\"", null, "<\"foo\">", false); parseTest("foo@apache.org", false, "foo@apache.org", null, "foo@apache.org", false); parseTest("\"foo\"@apache.org", false, "\"foo\"@apache.org", null, "<\"foo\"@apache.org>", false); parseTest("foo@[apache].org", false, "foo@[apache].org", null, "<foo@[apache].org>", false); parseTest("foo@[apache].[org]", false, "foo@[apache].[org]", null, "<foo@[apache].[org]>", false); parseTest("foo.bar@apache.org", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseTest("(Foo Bar) <foo.bar@apache.org>", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseTest("(Foo) (Bar) <foo.bar@apache.org>", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseTest("\"Foo\" Bar <foo.bar@apache.org>", false, "foo.bar@apache.org", "\"Foo\" Bar", "\"\\\"Foo\\\" Bar\" <foo.bar@apache.org>", false); parseTest("(Foo Bar) foo.bar@apache.org", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseTest("apache.org", false, "apache.org", null, "apache.org", false); } public void testDefaultParse() throws Exception { parseDefaultTest("<@apache.org,@apache.net:foo@apache.org>", "@apache.org,@apache.net:foo@apache.org", null, "<@apache.org,@apache.net:foo@apache.org>", false); parseDefaultTest("<@apache.org:foo@apache.org>", "@apache.org:foo@apache.org", null, "<@apache.org:foo@apache.org>", false); parseDefaultTest("Foo Bar:;", "Foo Bar:;", null, "Foo Bar:;", true); parseDefaultTest("\"\\\"Foo Bar\" <foo.bar@apache.org>", "foo.bar@apache.org", "\"Foo Bar", "\"\\\"Foo Bar\" <foo.bar@apache.org>", false); parseDefaultTest("\"Foo Bar\" <foo.bar@apache.org>", "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseDefaultTest("(Foo) (Bar) foo.bar@apache.org", "foo.bar@apache.org", "Foo", "Foo <foo.bar@apache.org>", false); parseDefaultTest("<foo@apache.org>", "foo@apache.org", null, "foo@apache.org", false); parseDefaultTest("Foo Bar <foo.bar@apache.org>", "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseDefaultTest("foo", "foo", null, "foo", false); parseDefaultTest("\"foo\"", "\"foo\"", null, "<\"foo\">", false); parseDefaultTest("foo@apache.org", "foo@apache.org", null, "foo@apache.org", false); parseDefaultTest("\"foo\"@apache.org", "\"foo\"@apache.org", null, "<\"foo\"@apache.org>", false); parseDefaultTest("foo@[apache].org", "foo@[apache].org", null, "<foo@[apache].org>", false); parseDefaultTest("foo@[apache].[org]", "foo@[apache].[org]", null, "<foo@[apache].[org]>", false); parseDefaultTest("foo.bar@apache.org", "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseDefaultTest("(Foo Bar) <foo.bar@apache.org>", "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseDefaultTest("(Foo) (Bar) <foo.bar@apache.org>", "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseDefaultTest("\"Foo\" Bar <foo.bar@apache.org>", "foo.bar@apache.org", "\"Foo\" Bar", "\"\\\"Foo\\\" Bar\" <foo.bar@apache.org>", false); parseDefaultTest("(Foo Bar) foo.bar@apache.org", "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseDefaultTest("apache.org", "apache.org", null, "apache.org", false); } public void testStrictParse() throws Exception { parseTest("<@apache.org,@apache.net:foo@apache.org>", true, "@apache.org,@apache.net:foo@apache.org", null, "<@apache.org,@apache.net:foo@apache.org>", false); parseTest("<@apache.org:foo@apache.org>", true, "@apache.org:foo@apache.org", null, "<@apache.org:foo@apache.org>", false); parseTest("Foo Bar:;", true, "Foo Bar:;", null, "Foo Bar:;", true); parseTest("\"\\\"Foo Bar\" <foo.bar@apache.org>", true, "foo.bar@apache.org", "\"Foo Bar", "\"\\\"Foo Bar\" <foo.bar@apache.org>", false); parseTest("\"Foo Bar\" <foo.bar@apache.org>", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseTest("(Foo) (Bar) foo.bar@apache.org", true, "foo.bar@apache.org", "Foo", "Foo <foo.bar@apache.org>", false); parseTest("<foo@apache.org>", true, "foo@apache.org", null, "foo@apache.org", false); parseTest("Foo Bar <foo.bar@apache.org>", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseTest("foo", true, "foo", null, "foo", false); parseTest("\"foo\"", true, "\"foo\"", null, "<\"foo\">", false); parseTest("foo@apache.org", true, "foo@apache.org", null, "foo@apache.org", false); parseTest("\"foo\"@apache.org", true, "\"foo\"@apache.org", null, "<\"foo\"@apache.org>", false); parseTest("foo@[apache].org", true, "foo@[apache].org", null, "<foo@[apache].org>", false); parseTest("foo@[apache].[org]", true, "foo@[apache].[org]", null, "<foo@[apache].[org]>", false); parseTest("foo.bar@apache.org", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseTest("(Foo Bar) <foo.bar@apache.org>", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseTest("(Foo) (Bar) <foo.bar@apache.org>", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); parseTest("\"Foo\" Bar <foo.bar@apache.org>", true, "foo.bar@apache.org", "\"Foo\" Bar", "\"\\\"Foo\\\" Bar\" <foo.bar@apache.org>", false); parseTest("(Foo Bar) foo.bar@apache.org", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); parseTest("apache.org", true, "apache.org", null, "apache.org", false); } public void testConstructor() throws Exception { constructorTest("(Foo) (Bar) foo.bar@apache.org", false, "foo.bar@apache.org", "Foo", "Foo <foo.bar@apache.org>", false); constructorTest("<@apache.org,@apache.net:foo@apache.org>", false, "@apache.org,@apache.net:foo@apache.org", null, "<@apache.org,@apache.net:foo@apache.org>", false); constructorTest("<@apache.org:foo@apache.org>", false, "@apache.org:foo@apache.org", null, "<@apache.org:foo@apache.org>", false); constructorTest("Foo Bar:;", false, "Foo Bar:;", null, "Foo Bar:;", true); constructorTest("\"\\\"Foo Bar\" <foo.bar@apache.org>", false, "foo.bar@apache.org", "\"Foo Bar", "\"\\\"Foo Bar\" <foo.bar@apache.org>", false); constructorTest("\"Foo Bar\" <foo.bar@apache.org>", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorTest("<foo@apache.org>", false, "foo@apache.org", null, "foo@apache.org", false); constructorTest("Foo Bar <foo.bar@apache.org>", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorTest("foo", false, "foo", null, "foo", false); constructorTest("\"foo\"", false, "\"foo\"", null, "<\"foo\">", false); constructorTest("foo@apache.org", false, "foo@apache.org", null, "foo@apache.org", false); constructorTest("\"foo\"@apache.org", false, "\"foo\"@apache.org", null, "<\"foo\"@apache.org>", false); constructorTest("foo@[apache].org", false, "foo@[apache].org", null, "<foo@[apache].org>", false); constructorTest("foo@[apache].[org]", false, "foo@[apache].[org]", null, "<foo@[apache].[org]>", false); constructorTest("foo.bar@apache.org", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorTest("(Foo Bar) <foo.bar@apache.org>", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorTest("(Foo) (Bar) <foo.bar@apache.org>", false, "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorTest("\"Foo\" Bar <foo.bar@apache.org>", false, "foo.bar@apache.org", "\"Foo\" Bar", "\"\\\"Foo\\\" Bar\" <foo.bar@apache.org>", false); constructorTest("(Foo Bar) foo.bar@apache.org", false, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorTest("apache.org", false, "apache.org", null, "apache.org", false); } public void testDefaultConstructor() throws Exception { constructorDefaultTest("<@apache.org,@apache.net:foo@apache.org>", "@apache.org,@apache.net:foo@apache.org", null, "<@apache.org,@apache.net:foo@apache.org>", false); constructorDefaultTest("<@apache.org:foo@apache.org>", "@apache.org:foo@apache.org", null, "<@apache.org:foo@apache.org>", false); constructorDefaultTest("Foo Bar:;", "Foo Bar:;", null, "Foo Bar:;", true); constructorDefaultTest("\"\\\"Foo Bar\" <foo.bar@apache.org>", "foo.bar@apache.org", "\"Foo Bar", "\"\\\"Foo Bar\" <foo.bar@apache.org>", false); constructorDefaultTest("\"Foo Bar\" <foo.bar@apache.org>", "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorDefaultTest("(Foo) (Bar) foo.bar@apache.org", "foo.bar@apache.org", "Foo", "Foo <foo.bar@apache.org>", false); constructorDefaultTest("<foo@apache.org>", "foo@apache.org", null, "foo@apache.org", false); constructorDefaultTest("Foo Bar <foo.bar@apache.org>", "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorDefaultTest("foo", "foo", null, "foo", false); constructorDefaultTest("\"foo\"", "\"foo\"", null, "<\"foo\">", false); constructorDefaultTest("foo@apache.org", "foo@apache.org", null, "foo@apache.org", false); constructorDefaultTest("\"foo\"@apache.org", "\"foo\"@apache.org", null, "<\"foo\"@apache.org>", false); constructorDefaultTest("foo@[apache].org", "foo@[apache].org", null, "<foo@[apache].org>", false); constructorDefaultTest("foo@[apache].[org]", "foo@[apache].[org]", null, "<foo@[apache].[org]>", false); constructorDefaultTest("foo.bar@apache.org", "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorDefaultTest("(Foo Bar) <foo.bar@apache.org>", "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorDefaultTest("(Foo) (Bar) <foo.bar@apache.org>", "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorDefaultTest("\"Foo\" Bar <foo.bar@apache.org>", "foo.bar@apache.org", "\"Foo\" Bar", "\"\\\"Foo\\\" Bar\" <foo.bar@apache.org>", false); constructorDefaultTest("(Foo Bar) foo.bar@apache.org", "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorDefaultTest("apache.org", "apache.org", null, "apache.org", false); } public void testStrictConstructor() throws Exception { constructorTest("<@apache.org,@apache.net:foo@apache.org>", true, "@apache.org,@apache.net:foo@apache.org", null, "<@apache.org,@apache.net:foo@apache.org>", false); constructorTest("<@apache.org:foo@apache.org>", true, "@apache.org:foo@apache.org", null, "<@apache.org:foo@apache.org>", false); constructorTest("Foo Bar:;", true, "Foo Bar:;", null, "Foo Bar:;", true); constructorTest("\"\\\"Foo Bar\" <foo.bar@apache.org>", true, "foo.bar@apache.org", "\"Foo Bar", "\"\\\"Foo Bar\" <foo.bar@apache.org>", false); constructorTest("\"Foo Bar\" <foo.bar@apache.org>", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorTest("(Foo) (Bar) foo.bar@apache.org", true, "foo.bar@apache.org", "Foo", "Foo <foo.bar@apache.org>", false); constructorTest("<foo@apache.org>", true, "foo@apache.org", null, "foo@apache.org", false); constructorTest("Foo Bar <foo.bar@apache.org>", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorTest("foo", true, "foo", null, "foo", false); constructorTest("\"foo\"", true, "\"foo\"", null, "<\"foo\">", false); constructorTest("foo@apache.org", true, "foo@apache.org", null, "foo@apache.org", false); constructorTest("\"foo\"@apache.org", true, "\"foo\"@apache.org", null, "<\"foo\"@apache.org>", false); constructorTest("foo@[apache].org", true, "foo@[apache].org", null, "<foo@[apache].org>", false); constructorTest("foo@[apache].[org]", true, "foo@[apache].[org]", null, "<foo@[apache].[org]>", false); constructorTest("foo.bar@apache.org", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorTest("(Foo Bar) <foo.bar@apache.org>", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorTest("(Foo) (Bar) <foo.bar@apache.org>", true, "foo.bar@apache.org", null, "foo.bar@apache.org", false); constructorTest("\"Foo\" Bar <foo.bar@apache.org>", true, "foo.bar@apache.org", "\"Foo\" Bar", "\"\\\"Foo\\\" Bar\" <foo.bar@apache.org>", false); constructorTest("(Foo Bar) foo.bar@apache.org", true, "foo.bar@apache.org", "Foo Bar", "Foo Bar <foo.bar@apache.org>", false); constructorTest("apache.org", true, "apache.org", null, "apache.org", false); } public void testParseHeaderList() throws Exception { InternetAddress[] addresses = InternetAddress.parseHeader("foo@apache.org,bar@apache.org", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = InternetAddress.parseHeader("Foo <foo@apache.org>,,Bar <bar@apache.org>", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", "Foo", "Foo <foo@apache.org>", false); validateAddress(addresses[1], "bar@apache.org", "Bar", "Bar <bar@apache.org>", false); addresses = InternetAddress.parseHeader("foo@apache.org, bar@apache.org", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = InternetAddress.parseHeader("Foo <foo@apache.org>, Bar <bar@apache.org>", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", "Foo", "Foo <foo@apache.org>", false); validateAddress(addresses[1], "bar@apache.org", "Bar", "Bar <bar@apache.org>", false); addresses = InternetAddress.parseHeader("Foo <foo@apache.org>,(yada),Bar <bar@apache.org>", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", "Foo", "Foo <foo@apache.org>", false); validateAddress(addresses[1], "bar@apache.org", "Bar", "Bar <bar@apache.org>", false); } public void testParseHeaderErrors() throws Exception { parseHeaderErrorTest("foo@apache.org bar@apache.org", true); parseHeaderErrorTest("Foo foo@apache.org", true); parseHeaderErrorTest("Foo foo@apache.org", true); parseHeaderErrorTest("Foo <foo@apache.org", true); parseHeaderErrorTest("[foo]@apache.org", true); parseHeaderErrorTest("@apache.org", true); parseHeaderErrorTest("foo@[apache.org", true); } public void testValidateErrors() throws Exception { validateErrorTest("foo@apache.org bar@apache.org"); validateErrorTest("Foo foo@apache.org"); validateErrorTest("Foo foo@apache.org"); validateErrorTest("Foo <foo@apache.org"); validateErrorTest("[foo]@apache.org"); validateErrorTest("@apache.org"); validateErrorTest("foo@[apache.org"); } public void testGroup() throws Exception { parseHeaderTest("Foo:foo@apache.org;", true, "Foo:foo@apache.org;", null, "Foo:foo@apache.org;", true); parseHeaderTest("Foo:foo@apache.org,bar@apache.org;", true, "Foo:foo@apache.org,bar@apache.org;", null, "Foo:foo@apache.org,bar@apache.org;", true); parseHeaderTest("Foo Bar:<foo@apache.org>,bar@apache.org;", true, "Foo Bar:<foo@apache.org>,bar@apache.org;", null, "Foo Bar:<foo@apache.org>,bar@apache.org;", true); parseHeaderTest("Foo Bar:Foo <foo@apache.org>,bar@apache.org;", true, "Foo Bar:Foo<foo@apache.org>,bar@apache.org;", null, "Foo Bar:Foo<foo@apache.org>,bar@apache.org;", true); parseHeaderTest("Foo:<foo@apache.org>,,bar@apache.org;", true, "Foo:<foo@apache.org>,,bar@apache.org;", null, "Foo:<foo@apache.org>,,bar@apache.org;", true); parseHeaderTest("Foo:foo,bar;", true, "Foo:foo,bar;", null, "Foo:foo,bar;", true); parseHeaderTest("Foo:;", true, "Foo:;", null, "Foo:;", true); parseHeaderTest("\"Foo\":foo@apache.org;", true, "\"Foo\":foo@apache.org;", null, "\"Foo\":foo@apache.org;", true); parseHeaderErrorTest("Foo:foo@apache.org,bar@apache.org", true); parseHeaderErrorTest("Foo:foo@apache.org,Bar:bar@apache.org;;", true); parseHeaderErrorTest(":foo@apache.org;", true); parseHeaderErrorTest("Foo Bar:<foo@apache.org,bar@apache.org;", true); } public void testGetGroup() throws Exception { InternetAddress[] addresses = getGroup("Foo:foo@apache.org;", true); assertTrue("Expecting 1 address", addresses.length == 1); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); addresses = getGroup("Foo:foo@apache.org,bar@apache.org;", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:<foo@apache.org>,bar@apache.org;", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:<foo@apache.org>,,bar@apache.org;", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:Foo <foo@apache.org>,bar@apache.org;", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", "Foo", "Foo <foo@apache.org>", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:Foo <@apache.org:foo@apache.org>,bar@apache.org;", true); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "@apache.org:foo@apache.org", "Foo", "Foo <@apache.org:foo@apache.org>", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:;", true); assertTrue("Expecting 0 addresses", addresses.length == 0); addresses = getGroup("Foo:foo@apache.org;", false); assertTrue("Expecting 1 address", addresses.length == 1); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); addresses = getGroup("Foo:foo@apache.org,bar@apache.org;", false); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:<foo@apache.org>,bar@apache.org;", false); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:<foo@apache.org>,,bar@apache.org;", false); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", null, "foo@apache.org", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:Foo <foo@apache.org>,bar@apache.org;", false); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "foo@apache.org", "Foo", "Foo <foo@apache.org>", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:Foo <@apache.org:foo@apache.org>,bar@apache.org;", false); assertTrue("Expecting 2 addresses", addresses.length == 2); validateAddress(addresses[0], "@apache.org:foo@apache.org", "Foo", "Foo <@apache.org:foo@apache.org>", false); validateAddress(addresses[1], "bar@apache.org", null, "bar@apache.org", false); addresses = getGroup("Foo:;", false); assertTrue("Expecting 0 addresses", addresses.length == 0); } public void testLocalAddress() throws Exception { System.getProperties().remove("user.name"); assertNull(InternetAddress.getLocalAddress(null)); System.setProperty("user.name", "dev"); InternetAddress localHost = null; String user = null; String host = null; try { user = System.getProperty("user.name"); host = InetAddress.getLocalHost().getHostName(); localHost = new InternetAddress(user + "@" + host); } catch (AddressException e) { // ignore } catch (UnknownHostException e) { // ignore } catch (SecurityException e) { // ignore } assertEquals(InternetAddress.getLocalAddress(null), localHost); Properties props = new Properties(); Session session = Session.getInstance(props, null); assertEquals(InternetAddress.getLocalAddress(session), localHost); props.put("mail.host", "apache.org"); session = Session.getInstance(props, null); assertEquals(InternetAddress.getLocalAddress(session), new InternetAddress(user + "@apache.org")); props.put("mail.user", "user"); props.remove("mail.host"); session = Session.getInstance(props, null); assertEquals(InternetAddress.getLocalAddress(session), new InternetAddress("user@" + host)); props.put("mail.host", "apache.org"); session = Session.getInstance(props, null); assertEquals(InternetAddress.getLocalAddress(session), new InternetAddress("user@apache.org")); props.put("mail.from", "tester@incubator.apache.org"); session = Session.getInstance(props, null); assertEquals(InternetAddress.getLocalAddress(session), new InternetAddress("tester@incubator.apache.org")); } public void testGERONIMO5842() throws AddressException { InternetAddress[] addresses = InternetAddress.parse("k..allen@apache.org"); Assert.assertNotNull(addresses); Assert.assertEquals(1, addresses.length); addresses[0].validate(); InternetAddress.parse("k..@apache.org"); InternetAddress.parse("k....@apache.org"); InternetAddress.parse("k...allen...@apache.org"); } private InternetAddress[] getGroup(String address, boolean strict) throws AddressException { InternetAddress group = new InternetAddress(address); return group.getGroup(strict); } /*protected void setUp() throws Exception { address = new InternetAddress(); }*/ private void parseHeaderTest(String address, boolean strict, String resultAddr, String personal, String toString, boolean group) throws Exception { InternetAddress[] addresses = InternetAddress.parseHeader(address, strict); assertTrue(addresses.length == 1); validateAddress(addresses[0], resultAddr, personal, toString, group); } private void parseHeaderErrorTest(String address, boolean strict) throws Exception { try { InternetAddress.parseHeader(address, strict); fail("Expected AddressException"); } catch (AddressException e) { } } private void constructorTest(String address, boolean strict, String resultAddr, String personal, String toString, boolean group) throws Exception { validateAddress(new InternetAddress(address, strict), resultAddr, personal, toString, group); } private void constructorDefaultTest(String address, String resultAddr, String personal, String toString, boolean group) throws Exception { validateAddress(new InternetAddress(address), resultAddr, personal, toString, group); } /*private void constructorErrorTest(String address, boolean strict) throws Exception { try { InternetAddress foo = new InternetAddress(address, strict); fail("Expected AddressException"); } catch (AddressException e) { } }*/ private void parseTest(String address, boolean strict, String resultAddr, String personal, String toString, boolean group) throws Exception { InternetAddress[] addresses = InternetAddress.parse(address, strict); assertTrue(addresses.length == 1); validateAddress(addresses[0], resultAddr, personal, toString, group); } /*private void parseErrorTest(String address, boolean strict) throws Exception { try { InternetAddress.parse(address, strict); fail("Expected AddressException"); } catch (AddressException e) { } }*/ private void parseDefaultTest(String address, String resultAddr, String personal, String toString, boolean group) throws Exception { InternetAddress[] addresses = InternetAddress.parse(address); assertTrue(addresses.length == 1); validateAddress(addresses[0], resultAddr, personal, toString, group); } /*private void parseDefaultErrorTest(String address) throws Exception { try { InternetAddress.parse(address); fail("Expected AddressException"); } catch (AddressException e) { } }*/ private void validateTest(String address) throws Exception { InternetAddress test = new InternetAddress(); test.setAddress(address); test.validate(); } private void validateErrorTest(String address) throws Exception { InternetAddress test = new InternetAddress(); test.setAddress(address); try { test.validate(); fail("Expected AddressException"); } catch (AddressException e) { } } private void validateAddress(InternetAddress a, String address, String personal, String toString, boolean group) { assertEquals("Invalid address:", a.getAddress(), address); if (personal == null) { assertNull("Personal must be null", a.getPersonal()); } else { assertEquals("Invalid Personal:", a.getPersonal(), personal); } assertEquals("Invalid string value:", a.toString(), toString); assertTrue("Incorrect group value:", group == a.isGroup()); } }
939
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/NewsAddressTest.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 junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class NewsAddressTest extends TestCase { public void testNewsAddress() throws AddressException { NewsAddress na = new NewsAddress("geronimo-dev", "news.apache.org"); assertEquals("geronimo-dev", na.getNewsgroup()); assertEquals("news.apache.org", na.getHost()); assertEquals("news", na.getType()); assertEquals("geronimo-dev", na.toString()); NewsAddress[] nas = NewsAddress.parse( "geronimo-dev@news.apache.org, geronimo-user@news.apache.org"); assertEquals(2, nas.length); assertEquals("geronimo-dev", nas[0].getNewsgroup()); assertEquals("news.apache.org", nas[0].getHost()); assertEquals("geronimo-user", nas[1].getNewsgroup()); assertEquals("news.apache.org", nas[1].getHost()); } }
940
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/MimeUtilityTest.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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Session; import javax.mail.util.ByteArrayDataSource; import junit.framework.TestCase; public class MimeUtilityTest extends TestCase { private byte[] encodeBytes = new byte[] { 32, 104, -61, -87, 33, 32, -61, -96, -61, -88, -61, -76, 117, 32, 33, 33, 33 }; public void testEncodeDecode() throws Exception { byte [] data = new byte[256]; for (int i = 0; i < data.length; i++) { data[i] = (byte)i; } // different lengths test boundary conditions doEncodingTest(data, 256, "uuencode"); doEncodingTest(data, 255, "uuencode"); doEncodingTest(data, 254, "uuencode"); doEncodingTest(data, 256, "binary"); doEncodingTest(data, 256, "7bit"); doEncodingTest(data, 256, "8bit"); doEncodingTest(data, 256, "base64"); doEncodingTest(data, 255, "base64"); doEncodingTest(data, 254, "base64"); doEncodingTest(data, 256, "x-uuencode"); doEncodingTest(data, 256, "x-uue"); doEncodingTest(data, 256, "quoted-printable"); doEncodingTest(data, 255, "quoted-printable"); doEncodingTest(data, 254, "quoted-printable"); } public void testFoldUnfold() throws Exception { doFoldTest(0, "This is a short string", "This is a short string"); doFoldTest(0, "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.", "The quick brown fox jumped over the lazy dog. The quick brown fox jumped\r\n over the lazy dog. The quick brown fox jumped over the lazy dog."); doFoldTest(50, "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.", "The quick brown fox jumped\r\n over the lazy dog. The quick brown fox jumped over the lazy dog. The quick\r\n brown fox jumped over the lazy dog."); doFoldTest(20, "======================================================================================================================= break should be here", "=======================================================================================================================\r\n break should be here"); } public void doEncodingTest(byte[] data, int length, String encoding) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream encoder = MimeUtility.encode(out, encoding); encoder.write(data, 0, length); encoder.flush(); byte[] encodedData = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(encodedData); InputStream decoder = MimeUtility.decode(in, encoding); byte[] decodedData = new byte[length]; int count = decoder.read(decodedData); assertEquals(length, count); for (int i = 0; i < length; i++) { assertEquals(data[i], decodedData[i]); } } public void doFoldTest(int used, String source, String folded) throws Exception { String newFolded = MimeUtility.fold(used, source); String newUnfolded = MimeUtility.unfold(newFolded); assertEquals(folded, newFolded); assertEquals(source, newUnfolded); } public void testEncodeWord() throws Exception { assertEquals("abc", MimeUtility.encodeWord("abc")); String encodeString = new String(encodeBytes, "UTF-8"); // default code page dependent, hard to directly test the encoded results // The following disabled because it will not succeed on all locales because the // code points used in the test string won't round trip properly for all code pages. // assertEquals(encodeString, MimeUtility.decodeWord(MimeUtility.encodeWord(encodeString))); String encoded = MimeUtility.encodeWord(encodeString, "UTF-8", "Q"); assertEquals("=?UTF-8?Q?_h=C3=A9!_=C3=A0=C3=A8=C3=B4u_!!!?=", encoded); assertEquals(encodeString, MimeUtility.decodeWord(encoded)); encoded = MimeUtility.encodeWord(encodeString, "UTF-8", "B"); assertEquals("=?UTF-8?B?IGjDqSEgw6DDqMO0dSAhISE=?=", encoded); assertEquals(encodeString, MimeUtility.decodeWord(encoded)); } public void testEncodeText() throws Exception { assertEquals("abc", MimeUtility.encodeWord("abc")); String encodeString = new String(encodeBytes, "UTF-8"); // default code page dependent, hard to directly test the encoded results // The following disabled because it will not succeed on all locales because the // code points used in the test string won't round trip properly for all code pages. // assertEquals(encodeString, MimeUtility.decodeText(MimeUtility.encodeText(encodeString))); String encoded = MimeUtility.encodeText(encodeString, "UTF-8", "Q"); assertEquals("=?UTF-8?Q?_h=C3=A9!_=C3=A0=C3=A8=C3=B4u_!!!?=", encoded); assertEquals(encodeString, MimeUtility.decodeText(encoded)); encoded = MimeUtility.encodeText(encodeString, "UTF-8", "B"); assertEquals("=?UTF-8?B?IGjDqSEgw6DDqMO0dSAhISE=?=", encoded); assertEquals(encodeString, MimeUtility.decodeText(encoded)); // this has multiple byte characters and is longer than the 76 character grouping, so this // hits a lot of different boundary conditions String subject = "\u03a0\u03a1\u03a2\u03a3\u03a4\u03a5\u03a6\u03a7 \u03a8\u03a9\u03aa\u03ab \u03ac\u03ad\u03ae\u03af\u03b0 \u03b1\u03b2\u03b3\u03b4\u03b5 \u03b6\u03b7\u03b8\u03b9\u03ba \u03bb\u03bc\u03bd\u03be\u03bf\u03c0 \u03c1\u03c2\u03c3\u03c4\u03c5\u03c6\u03c7 \u03c8\u03c9\u03ca\u03cb\u03cd\u03ce \u03cf\u03d0\u03d1\u03d2"; encoded = MimeUtility.encodeText(subject, "utf-8", "Q"); assertEquals(subject, MimeUtility.decodeText(encoded)); encoded = MimeUtility.encodeText(subject, "utf-8", "B"); assertEquals(subject, MimeUtility.decodeText(encoded)); } public void testGetEncoding() throws Exception { ByteArrayDataSource source = new ByteArrayDataSource(new byte[] { 'a', 'b', 'c'}, "text/plain"); assertEquals("7bit", MimeUtility.getEncoding(source)); source = new ByteArrayDataSource(new byte[] { 'a', 'b', (byte)0x81}, "text/plain"); assertEquals("quoted-printable", MimeUtility.getEncoding(source)); source = new ByteArrayDataSource(new byte[] { 'a', (byte)0x82, (byte)0x81}, "text/plain"); assertEquals("base64", MimeUtility.getEncoding(source)); source = new ByteArrayDataSource(new byte[] { 'a', 'b', 'c'}, "application/binary"); assertEquals("7bit", MimeUtility.getEncoding(source)); source = new ByteArrayDataSource(new byte[] { 'a', 'b', (byte)0x81}, "application/binary"); assertEquals("base64", MimeUtility.getEncoding(source)); source = new ByteArrayDataSource(new byte[] { 'a', (byte)0x82, (byte)0x81}, "application/binary"); assertEquals("base64", MimeUtility.getEncoding(source)); } public void testQuote() throws Exception { assertEquals("abc", MimeUtility.quote("abc", "&*%")); assertEquals("\"abc&\"", MimeUtility.quote("abc&", "&*%")); assertEquals("\"abc\\\"\"", MimeUtility.quote("abc\"", "&*%")); assertEquals("\"abc\\\\\"", MimeUtility.quote("abc\\", "&*%")); assertEquals("\"abc\\\r\"", MimeUtility.quote("abc\r", "&*%")); assertEquals("\"abc\\\n\"", MimeUtility.quote("abc\n", "&*%")); } }
941
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/PreencodedMimeBodyPartTest.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 javax.mail.MessagingException; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class PreencodedMimeBodyPartTest extends TestCase { public void testEncoding() throws Exception { PreencodedMimeBodyPart part = new PreencodedMimeBodyPart("base64"); assertEquals("base64", part.getEncoding()); } public void testUpdateHeaders() throws Exception { TestBodyPart part = new TestBodyPart("base64"); part.updateHeaders(); assertEquals("base64", part.getHeader("Content-Transfer-Encoding", null)); } public void testWriteTo() throws Exception { PreencodedMimeBodyPart part = new PreencodedMimeBodyPart("binary"); byte[] content = new byte[] { 81, 82, 83, 84, 85, 86 }; part.setContent(new String(content, "UTF-8"), "text/plain; charset=\"UTF-8\""); ByteArrayOutputStream out = new ByteArrayOutputStream(); part.writeTo(out); byte[] data = out.toByteArray(); // we need to scan forward to the actual content and verify it has been written without additional // encoding. Our marker is a "crlfcrlf" sequence. for (int i = 0; i < data.length; i++) { if (data[i] == '\r') { if (data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n') { for (int j = 0; j < content.length; j++) { assertEquals(data[i + 4 + j], content[j]); } } } } } public class TestBodyPart extends PreencodedMimeBodyPart { public TestBodyPart(String encoding) { super(encoding); } public void updateHeaders() throws MessagingException { super.updateHeaders(); } } }
942
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/internet/InternetHeadersTest.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.ByteArrayInputStream; import javax.mail.MessagingException; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class InternetHeadersTest extends TestCase { private InternetHeaders headers; public void testLoadSingleHeader() throws MessagingException { String stream = "content-type: text/plain\r\n\r\n"; headers.load(new ByteArrayInputStream(stream.getBytes())); String[] header = headers.getHeader("content-type"); assertNotNull(header); assertEquals("text/plain", header[0]); } protected void setUp() throws Exception { headers = new InternetHeaders(); } }
943
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/event/StoreEventTest.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; import javax.mail.TestData; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class StoreEventTest extends TestCase { public StoreEventTest(String name) { super(name); } public void testEvent() { doEventTests(StoreEvent.ALERT); doEventTests(StoreEvent.NOTICE); try { StoreEvent event = new StoreEvent(null, -12345, "Hello World"); fail( "Expected exception due to invalid type " + event.getMessageType()); } catch (IllegalArgumentException e) { } } private void doEventTests(int type) { Store source = TestData.getTestStore(); StoreEvent event = new StoreEvent(source, type, "Hello World"); assertEquals(source, event.getSource()); assertEquals("Hello World", event.getMessage()); assertEquals(type, event.getMessageType()); StoreListenerTest listener = new StoreListenerTest(); event.dispatch(listener); assertEquals("Unexpcted method dispatched", type, listener.getState()); } public static class StoreListenerTest implements StoreListener { private int state = 0; public void notification(StoreEvent event) { if (state != 0) { fail("Recycled Listener"); } state = event.getMessageType(); } public int getState() { return state; } } }
944
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/event/TransportEventTest.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.Folder; import javax.mail.Message; import javax.mail.TestData; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class TransportEventTest extends TestCase { public TransportEventTest(String name) { super(name); } public void testEvent() throws AddressException { doEventTests(TransportEvent.MESSAGE_DELIVERED); doEventTests(TransportEvent.MESSAGE_PARTIALLY_DELIVERED); doEventTests(TransportEvent.MESSAGE_NOT_DELIVERED); } private void doEventTests(int type) throws AddressException { Folder folder = TestData.getTestFolder(); Message message = TestData.getMessage(); Transport transport = TestData.getTestTransport(); Address[] sent = new Address[] { new InternetAddress("alex@here.com")}; Address[] empty = new Address[0]; TransportEvent event = new TransportEvent(transport, type, sent, empty, empty, message); assertEquals(transport, event.getSource()); assertEquals(type, event.getType()); TransportListenerTest listener = new TransportListenerTest(); event.dispatch(listener); assertEquals("Unexpcted method dispatched", type, listener.getState()); } public static class TransportListenerTest implements TransportListener { private int state = 0; public void messageDelivered(TransportEvent event) { if (state != 0) { fail("Recycled Listener"); } state = TransportEvent.MESSAGE_DELIVERED; } public void messagePartiallyDelivered(TransportEvent event) { if (state != 0) { fail("Recycled Listener"); } state = TransportEvent.MESSAGE_PARTIALLY_DELIVERED; } public void messageNotDelivered(TransportEvent event) { if (state != 0) { fail("Recycled Listener"); } state = TransportEvent.MESSAGE_NOT_DELIVERED; } public int getState() { return state; } } }
945
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/event/MessageChangedEventTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail.event; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class MessageChangedEventTest extends TestCase { public MessageChangedEventTest(String name) { super(name); } public void testEvent() { doEventTests(MessageChangedEvent.ENVELOPE_CHANGED); doEventTests(MessageChangedEvent.FLAGS_CHANGED); } private void doEventTests(int type) { MessageChangedEvent event = new MessageChangedEvent(this, type, null); assertEquals(this, event.getSource()); assertEquals(type, event.getMessageChangeType()); MessageChangedListenerTest listener = new MessageChangedListenerTest(); event.dispatch(listener); assertEquals("Unexpcted method dispatched", type, listener.getState()); } public static class MessageChangedListenerTest implements MessageChangedListener { private int state = 0; public void messageChanged(MessageChangedEvent event) { if (state != 0) { fail("Recycled Listener"); } state = event.getMessageChangeType(); } public int getState() { return state; } } }
946
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/event/AllEventTests.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail.event; import junit.framework.Test; import junit.framework.TestSuite; /** * @version $Rev$ $Date$ */ public class AllEventTests { public static Test suite() { TestSuite suite = new TestSuite("Test for javax.mail.event"); //$JUnit-BEGIN$ suite.addTest(new TestSuite(ConnectionEventTest.class)); suite.addTest(new TestSuite(FolderEventTest.class)); suite.addTest(new TestSuite(MessageChangedEventTest.class)); suite.addTest(new TestSuite(StoreEventTest.class)); suite.addTest(new TestSuite(MessageCountEventTest.class)); suite.addTest(new TestSuite(TransportEventTest.class)); //$JUnit-END$ return suite; } }
947
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/event/FolderEventTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail.event; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class FolderEventTest extends TestCase { public FolderEventTest(String name) { super(name); } public void testEvent() { doEventTests(FolderEvent.CREATED); doEventTests(FolderEvent.RENAMED); doEventTests(FolderEvent.DELETED); } private void doEventTests(int type) { FolderEvent event = new FolderEvent(this, null, type); assertEquals(this, event.getSource()); assertEquals(type, event.getType()); FolderListenerTest listener = new FolderListenerTest(); event.dispatch(listener); assertEquals("Unexpcted method dispatched", type, listener.getState()); } public static class FolderListenerTest implements FolderListener { private int state = 0; public void folderCreated(FolderEvent event) { if (state != 0) { fail("Recycled Listener"); } state = FolderEvent.CREATED; } public void folderDeleted(FolderEvent event) { if (state != 0) { fail("Recycled Listener"); } state = FolderEvent.DELETED; } public void folderRenamed(FolderEvent event) { if (state != 0) { fail("Recycled Listener"); } state = FolderEvent.RENAMED; } public int getState() { return state; } } }
948
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/event/MessageCountEventTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail.event; import javax.mail.Folder; import javax.mail.TestData; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class MessageCountEventTest extends TestCase { public MessageCountEventTest(String name) { super(name); } public void testEvent() { doEventTests(MessageCountEvent.ADDED); doEventTests(MessageCountEvent.REMOVED); try { doEventTests(-12345); fail("Expected exception due to invalid type -12345"); } catch (IllegalArgumentException e) { } } private void doEventTests(int type) { Folder folder = TestData.getTestFolder(); MessageCountEvent event = new MessageCountEvent(folder, type, false, null); assertEquals(folder, event.getSource()); assertEquals(type, event.getType()); MessageCountListenerTest listener = new MessageCountListenerTest(); event.dispatch(listener); assertEquals("Unexpcted method dispatched", type, listener.getState()); } public static class MessageCountListenerTest implements MessageCountListener { private int state = 0; public void messagesAdded(MessageCountEvent event) { if (state != 0) { fail("Recycled Listener"); } state = MessageCountEvent.ADDED; } public void messagesRemoved(MessageCountEvent event) { if (state != 0) { fail("Recycled Listener"); } state = MessageCountEvent.REMOVED; } public int getState() { return state; } } }
949
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/test/java/javax/mail/event/ConnectionEventTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail.event; import junit.framework.TestCase; /** * @version $Rev$ $Date$ */ public class ConnectionEventTest extends TestCase { public static class ConnectionListenerTest implements ConnectionListener { private int state = 0; public void closed(ConnectionEvent event) { if (state != 0) { fail("Recycled ConnectionListener"); } state = ConnectionEvent.CLOSED; } public void disconnected(ConnectionEvent event) { if (state != 0) { fail("Recycled ConnectionListener"); } state = ConnectionEvent.DISCONNECTED; } public int getState() { return state; } public void opened(ConnectionEvent event) { if (state != 0) { fail("Recycled ConnectionListener"); } state = ConnectionEvent.OPENED; } } public ConnectionEventTest(String name) { super(name); } private void doEventTests(int type) { ConnectionEvent event = new ConnectionEvent(this, type); assertEquals(this, event.getSource()); assertEquals(type, event.getType()); ConnectionListenerTest listener = new ConnectionListenerTest(); event.dispatch(listener); assertEquals("Unexpcted method dispatched", type, listener.getState()); } public void testEvent() { doEventTests(ConnectionEvent.CLOSED); doEventTests(ConnectionEvent.OPENED); doEventTests(ConnectionEvent.DISCONNECTED); } }
950
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/MailProviderBundleTrackerCustomizer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail; import java.net.URL; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.Bundle; import org.osgi.framework.BundleEvent; import org.osgi.service.log.LogService; import org.osgi.util.tracker.BundleTrackerCustomizer; public class MailProviderBundleTrackerCustomizer implements BundleTrackerCustomizer { // our base Activator (used as a service source) private Activator activator; // the bundle hosting the activation code private Bundle activationBundle; public MailProviderBundleTrackerCustomizer(Activator a, Bundle b) { activator = a; activationBundle = b; } /** * Handle the activation of a new bundle. * * @param bundle The source bundle. * @param event The bundle event information. * * @return A return object. */ public Object addingBundle(Bundle bundle, BundleEvent event) { if (bundle.equals(activationBundle)) { return null; } return MailProviderRegistry.registerBundle(bundle); } public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) { // this will update for the new bundle MailProviderRegistry.registerBundle(bundle); } public void removedBundle(Bundle bundle, BundleEvent event, Object object) { MailProviderRegistry.unregisterBundle(bundle); } private void log(int level, String message) { activator.log(level, message); } private void log(int level, String message, Throwable th) { activator.log(level, message, th); } }
951
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/Activator.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogService; import org.osgi.util.tracker.BundleTracker; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; /** * The activator that starts and manages the tracking of * JAF activation command maps */ public class Activator extends org.apache.geronimo.osgi.locator.Activator { // tracker to watch for bundle updates protected BundleTracker bt; // service tracker for a logging service protected ServiceTracker lst; // an array of all active logging services. protected List<LogService> logServices = new ArrayList<LogService>(); @Override public synchronized void start(final BundleContext context) throws Exception { super.start(context); lst = new LogServiceTracker(context, LogService.class.getName(), null); lst.open(); bt = new BundleTracker(context, Bundle.ACTIVE, new MailProviderBundleTrackerCustomizer(this, context.getBundle())); bt.open(); } @Override public synchronized void stop(BundleContext context) throws Exception { bt.close(); lst.close(); super.stop(context); } void log(int level, String message) { synchronized (logServices) { for (LogService log : logServices) { log.log(level, message); } } } void log(int level, String message, Throwable th) { synchronized (logServices) { for (LogService log : logServices) { log.log(level, message, th); } } } private final class LogServiceTracker extends ServiceTracker { private LogServiceTracker(BundleContext context, String clazz, ServiceTrackerCustomizer customizer) { super(context, clazz, customizer); } @Override public Object addingService(ServiceReference reference) { Object svc = super.addingService(reference); if (svc instanceof LogService) { synchronized (logServices) { logServices.add((LogService) svc); } } return svc; } @Override public void removedService(ServiceReference reference, Object service) { synchronized (logServices) { logServices.remove(service); } super.removedService(reference, service); } } }
952
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/MailProviderRegistry.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogService; import org.osgi.util.tracker.BundleTracker; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; /** * The activator that starts and manages the tracking of * JAF activation command maps */ public class MailProviderRegistry { // a list of all active mail provider config files static ConcurrentMap<Long, URL> providers = new ConcurrentHashMap<Long, URL>(); // a list of all active default provider config files static ConcurrentMap<Long, URL> defaultProviders = new ConcurrentHashMap<Long, URL>(); /** * Perform the check for an existing mailcap file when * a bundle is registered. * * @param bundle The potential provider bundle. * * @return A URL object if this bundle contains a mailcap file. */ static Object registerBundle(Bundle bundle) { // potential tracker return result Object result = null; // a given bundle might have a javamail.providers definition and/or a // default providers definition. URL url = bundle.getResource("META-INF/javamail.providers"); if (url != null) { providers.put(bundle.getBundleId(), url); // this indicates our interest result = url; } url = bundle.getResource("META-INF/javamail.default.providers"); if (url != null) { defaultProviders.put(bundle.getBundleId(), url); // this indicates our interest result = url; } // the url marks our interest in additional activity for this // bundle. return result; } /** * Remove a bundle from our potential mailcap pool. * * @param bundle The potential source bundle. */ static void unregisterBundle(Bundle bundle) { // remove these items providers.remove(bundle.getBundleId()); defaultProviders.remove(bundle.getBundleId()); } /** * Retrieve any located provider definitions * from bundles. * * @return A collection of the provider definition file * URLs. */ public static Collection<URL> getProviders() { return providers.values(); } /** * Retrieve any located default provider definitions * from bundles. * * @return A collection of the default provider definition file * URLs. */ public static Collection<URL> getDefaultProviders() { return defaultProviders.values(); } }
953
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/ASCIIUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.IOException; /** * Set of utility classes for handling common encoding-related * manipulations. */ public class ASCIIUtil { /** * Test to see if this string contains only US-ASCII (i.e., 7-bit * ASCII) charactes. * * @param s The test string. * * @return true if this is a valid 7-bit ASCII encoding, false if it * contains any non-US ASCII characters. */ static public boolean isAscii(String s) { for (int i = 0; i < s.length(); i++) { if (!isAscii(s.charAt(i))) { return false; } } return true; } /** * Test to see if a given character can be considered "valid" ASCII. * The excluded characters are the control characters less than * 32, 8-bit characters greater than 127, EXCEPT the CR, LF and * tab characters ARE considered value (all less than 32). * * @param ch The test character. * * @return true if this character meets the "ascii-ness" criteria, false * otherwise. */ static public boolean isAscii(int ch) { // these are explicitly considered valid. if (ch == '\r' || ch == '\n' || ch == '\t') { return true; } // anything else outside the range is just plain wrong. if (ch >= 127 || ch < 32) { return false; } return true; } /** * Examine a stream of text and make a judgement on what encoding * type should be used for the text. Ideally, we want to use 7bit * encoding to determine this, but we may need to use either quoted-printable * or base64. The choice is made on the ratio of 7-bit characters to non-7bit. * * @param content An input stream for the content we're examining. * * @exception IOException */ public static String getTextTransferEncoding(InputStream content) throws IOException { // for efficiency, we'll read in blocks. BufferedInputStream in = new BufferedInputStream(content, 4096); int span = 0; // span of characters without a line break. boolean containsLongLines = false; int asciiChars = 0; int nonAsciiChars = 0; while (true) { int ch = in.read(); // if we hit an EOF here, go decide what type we've actually found. if (ch == -1) { break; } // we found a linebreak. Reset the line length counters on either one. We don't // really need to validate here. if (ch == '\n' || ch == '\r') { // hit a line end, reset our line length counter span = 0; } else { span++; // the text has long lines, we can't transfer this as unencoded text. if (span > 998) { containsLongLines = true; } // non-ascii character, we have to transfer this in binary. if (!isAscii(ch)) { nonAsciiChars++; } else { asciiChars++; } } } // looking good so far, only valid chars here. if (nonAsciiChars == 0) { // does this contain long text lines? We need to use a Q-P encoding which will // be only slightly longer, but handles folding the longer lines. if (containsLongLines) { return "quoted-printable"; } else { // ideal! Easiest one to handle. return "7bit"; } } else { // mostly characters requiring encoding? Base64 is our best bet. if (nonAsciiChars > asciiChars) { return "base64"; } else { // Q-P encoding will use fewer bytes than the full Base64. return "quoted-printable"; } } } /** * Examine a stream of text and make a judgement on what encoding * type should be used for the text. Ideally, we want to use 7bit * encoding to determine this, but we may need to use either quoted-printable * or base64. The choice is made on the ratio of 7-bit characters to non-7bit. * * @param content A string for the content we're examining. */ public static String getTextTransferEncoding(String content) { int asciiChars = 0; int nonAsciiChars = 0; for (int i = 0; i < content.length(); i++) { int ch = content.charAt(i); // non-ascii character, we have to transfer this in binary. if (!isAscii(ch)) { nonAsciiChars++; } else { asciiChars++; } } // looking good so far, only valid chars here. if (nonAsciiChars == 0) { // ideal! Easiest one to handle. return "7bit"; } else { // mostly characters requiring encoding? Base64 is our best bet. if (nonAsciiChars > asciiChars) { return "base64"; } else { // Q-P encoding will use fewer bytes than the full Base64. return "quoted-printable"; } } } /** * Determine if the transfer encoding looks like it might be * valid ascii text, and thus transferable as 7bit code. In * order for this to be true, all characters must be valid * 7-bit ASCII code AND all line breaks must be properly formed * (JUST '\r\n' sequences). 7-bit transfers also * typically have a line limit of 1000 bytes (998 + the CRLF), so any * stretch of charactes longer than that will also force Base64 encoding. * * @param content An input stream for the content we're examining. * * @exception IOException */ public static String getBinaryTransferEncoding(InputStream content) throws IOException { // for efficiency, we'll read in blocks. BufferedInputStream in = new BufferedInputStream(content, 4096); int previousChar = 0; int span = 0; // span of characters without a line break. while (true) { int ch = in.read(); // if we hit an EOF here, we've only found valid text so far, so we can transfer this as // 7-bit ascii. if (ch == -1) { return "7bit"; } // we found a newline, this is only valid if the previous char was the '\r' if (ch == '\n') { // malformed linebreak? force this to base64 encoding. if (previousChar != '\r') { return "base64"; } // hit a line end, reset our line length counter span = 0; } else { span++; // the text has long lines, we can't transfer this as unencoded text. if (span > 998) { return "base64"; } // non-ascii character, we have to transfer this in binary. if (!isAscii(ch)) { return "base64"; } } previousChar = ch; } } }
954
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/Base64DecoderStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.IOException; import java.io.InputStream; import java.io.FilterInputStream; /** * An implementation of a FilterInputStream that decodes the * stream data in BASE64 encoding format. This version does the * decoding "on the fly" rather than decoding a single block of * data. Since this version is intended for use by the MimeUtilty class, * it also handles line breaks in the encoded data. */ public class Base64DecoderStream extends FilterInputStream { static protected final String MAIL_BASE64_IGNOREERRORS = "mail.mime.base64.ignoreerrors"; // number of decodeable units we'll try to process at one time. We'll attempt to read that much // data from the input stream and decode in blocks. static protected final int BUFFERED_UNITS = 2000; // our decoder for processing the data protected Base64Encoder decoder = new Base64Encoder(); // can be overridden by a system property. protected boolean ignoreErrors = false; // buffer for reading in chars for decoding (which can support larger bulk reads) protected byte[] encodedChars = new byte[BUFFERED_UNITS * 4]; // a buffer for one decoding unit's worth of data (3 bytes). This is the minimum amount we // can read at one time. protected byte[] decodedChars = new byte[BUFFERED_UNITS * 3]; // count of characters in the buffer protected int decodedCount = 0; // index of the next decoded character protected int decodedIndex = 0; public Base64DecoderStream(InputStream in) { super(in); // make sure we get the ignore errors flag ignoreErrors = SessionUtil.getBooleanProperty(MAIL_BASE64_IGNOREERRORS, false); } /** * Test for the existance of decoded characters in our buffer * of decoded data. * * @return True if we currently have buffered characters. */ private boolean dataAvailable() { return decodedCount != 0; } /** * Get the next buffered decoded character. * * @return The next decoded character in the buffer. */ private byte getBufferedChar() { decodedCount--; return decodedChars[decodedIndex++]; } /** * Decode a requested number of bytes of data into a buffer. * * @return true if we were able to obtain more data, false otherwise. */ private boolean decodeStreamData() throws IOException { decodedIndex = 0; // fill up a data buffer with input data int readCharacters = fillEncodedBuffer(); if (readCharacters > 0) { decodedCount = decoder.decode(encodedChars, 0, readCharacters, decodedChars); return true; } return false; } /** * Retrieve a single byte from the decoded characters buffer. * * @return The decoded character or -1 if there was an EOF condition. */ private int getByte() throws IOException { if (!dataAvailable()) { if (!decodeStreamData()) { return -1; } } decodedCount--; // we need to ensure this doesn't get sign extended return decodedChars[decodedIndex++] & 0xff; } private int getBytes(byte[] data, int offset, int length) throws IOException { int readCharacters = 0; while (length > 0) { // need data? Try to get some if (!dataAvailable()) { // if we can't get this, return a count of how much we did get (which may be -1). if (!decodeStreamData()) { return readCharacters > 0 ? readCharacters : -1; } } // now copy some of the data from the decoded buffer to the target buffer int copyCount = Math.min(decodedCount, length); System.arraycopy(decodedChars, decodedIndex, data, offset, copyCount); decodedIndex += copyCount; decodedCount -= copyCount; offset += copyCount; length -= copyCount; readCharacters += copyCount; } return readCharacters; } /** * Fill our buffer of input characters for decoding from the * stream. This will attempt read a full buffer, but will * terminate on an EOF or read error. This will filter out * non-Base64 encoding chars and will only return a valid * multiple of 4 number of bytes. * * @return The count of characters read. */ private int fillEncodedBuffer() throws IOException { int readCharacters = 0; while (true) { // get the next character from the stream int ch = in.read(); // did we hit an EOF condition? if (ch == -1) { // now check to see if this is normal, or potentially an error // if we didn't get characters as a multiple of 4, we may need to complain about this. if ((readCharacters % 4) != 0) { // the error checking can be turned off...normally it isn't if (!ignoreErrors) { throw new IOException("Base64 encoding error, data truncated"); } // we're ignoring errors, so round down to a multiple and return that. return (readCharacters / 4) * 4; } // return the count. return readCharacters; } // if this character is valid in a Base64 stream, copy it to the buffer. else if (decoder.isValidBase64(ch)) { encodedChars[readCharacters++] = (byte)ch; // if we've filled up the buffer, time to quit. if (readCharacters >= encodedChars.length) { return readCharacters; } } // we're filtering out whitespace and CRLF characters, so just ignore these } } // in order to function as a filter, these streams need to override the different // read() signature. public int read() throws IOException { return getByte(); } public int read(byte [] buffer, int offset, int length) throws IOException { return getBytes(buffer, offset, length); } public boolean markSupported() { return false; } public int available() throws IOException { return ((in.available() / 4) * 3) + decodedCount; } }
955
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/Base64Encoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; public class Base64Encoder implements Encoder { protected final byte[] encodingTable = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; protected byte padding = (byte)'='; /* * set up the decoding table. */ protected final byte[] decodingTable = new byte[256]; protected void initialiseDecodingTable() { for (int i = 0; i < encodingTable.length; i++) { decodingTable[encodingTable[i]] = (byte)i; } } public Base64Encoder() { initialiseDecodingTable(); } /** * encode the input data producing a base 64 output stream. * * @return the number of bytes produced. */ public int encode( byte[] data, int off, int length, OutputStream out) throws IOException { int modulus = length % 3; int dataLength = (length - modulus); int a1, a2, a3; for (int i = off; i < off + dataLength; i += 3) { a1 = data[i] & 0xff; a2 = data[i + 1] & 0xff; a3 = data[i + 2] & 0xff; out.write(encodingTable[(a1 >>> 2) & 0x3f]); out.write(encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]); out.write(encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]); out.write(encodingTable[a3 & 0x3f]); } /* * process the tail end. */ int b1, b2, b3; int d1, d2; switch (modulus) { case 0: /* nothing left to do */ break; case 1: d1 = data[off + dataLength] & 0xff; b1 = (d1 >>> 2) & 0x3f; b2 = (d1 << 4) & 0x3f; out.write(encodingTable[b1]); out.write(encodingTable[b2]); out.write(padding); out.write(padding); break; case 2: d1 = data[off + dataLength] & 0xff; d2 = data[off + dataLength + 1] & 0xff; b1 = (d1 >>> 2) & 0x3f; b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f; b3 = (d2 << 2) & 0x3f; out.write(encodingTable[b1]); out.write(encodingTable[b2]); out.write(encodingTable[b3]); out.write(padding); break; } return (dataLength / 3) * 4 + ((modulus == 0) ? 0 : 4); } private boolean ignore( char c) { return (c == '\n' || c =='\r' || c == '\t' || c == ' '); } /** * decode the base 64 encoded byte data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode( byte[] data, int off, int length, OutputStream out) throws IOException { byte[] bytes; byte b1, b2, b3, b4; int outLen = 0; int end = off + length; while (end > 0) { if (!ignore((char)data[end - 1])) { break; } end--; } int i = off; int finish = end - 4; while (i < finish) { while ((i < finish) && ignore((char)data[i])) { i++; } b1 = decodingTable[data[i++]]; while ((i < finish) && ignore((char)data[i])) { i++; } b2 = decodingTable[data[i++]]; while ((i < finish) && ignore((char)data[i])) { i++; } b3 = decodingTable[data[i++]]; while ((i < finish) && ignore((char)data[i])) { i++; } b4 = decodingTable[data[i++]]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); outLen += 3; } if (data[end - 2] == padding) { b1 = decodingTable[data[end - 4]]; b2 = decodingTable[data[end - 3]]; out.write((b1 << 2) | (b2 >> 4)); outLen += 1; } else if (data[end - 1] == padding) { b1 = decodingTable[data[end - 4]]; b2 = decodingTable[data[end - 3]]; b3 = decodingTable[data[end - 2]]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); outLen += 2; } else { b1 = decodingTable[data[end - 4]]; b2 = decodingTable[data[end - 3]]; b3 = decodingTable[data[end - 2]]; b4 = decodingTable[data[end - 1]]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); outLen += 3; } return outLen; } /** * decode the base 64 encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode( String data, OutputStream out) throws IOException { byte[] bytes; byte b1, b2, b3, b4; int length = 0; int end = data.length(); while (end > 0) { if (!ignore(data.charAt(end - 1))) { break; } end--; } int i = 0; int finish = end - 4; while (i < finish) { while ((i < finish) && ignore(data.charAt(i))) { i++; } b1 = decodingTable[data.charAt(i++)]; while ((i < finish) && ignore(data.charAt(i))) { i++; } b2 = decodingTable[data.charAt(i++)]; while ((i < finish) && ignore(data.charAt(i))) { i++; } b3 = decodingTable[data.charAt(i++)]; while ((i < finish) && ignore(data.charAt(i))) { i++; } b4 = decodingTable[data.charAt(i++)]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); length += 3; } if (data.charAt(end - 2) == padding) { b1 = decodingTable[data.charAt(end - 4)]; b2 = decodingTable[data.charAt(end - 3)]; out.write((b1 << 2) | (b2 >> 4)); length += 1; } else if (data.charAt(end - 1) == padding) { b1 = decodingTable[data.charAt(end - 4)]; b2 = decodingTable[data.charAt(end - 3)]; b3 = decodingTable[data.charAt(end - 2)]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); length += 2; } else { b1 = decodingTable[data.charAt(end - 4)]; b2 = decodingTable[data.charAt(end - 3)]; b3 = decodingTable[data.charAt(end - 2)]; b4 = decodingTable[data.charAt(end - 1)]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); length += 3; } return length; } /** * decode the base 64 encoded byte data writing it to the provided byte array buffer. * * @return the number of bytes produced. */ public int decode(byte[] data, int off, int length, byte[] out) throws IOException { byte[] bytes; byte b1, b2, b3, b4; int outLen = 0; int end = off + length; while (end > 0) { if (!ignore((char)data[end - 1])) { break; } end--; } int i = off; int finish = end - 4; while (i < finish) { while ((i < finish) && ignore((char)data[i])) { i++; } b1 = decodingTable[data[i++]]; while ((i < finish) && ignore((char)data[i])) { i++; } b2 = decodingTable[data[i++]]; while ((i < finish) && ignore((char)data[i])) { i++; } b3 = decodingTable[data[i++]]; while ((i < finish) && ignore((char)data[i])) { i++; } b4 = decodingTable[data[i++]]; out[outLen++] = (byte)((b1 << 2) | (b2 >> 4)); out[outLen++] = (byte)((b2 << 4) | (b3 >> 2)); out[outLen++] = (byte)((b3 << 6) | b4); } if (data[end - 2] == padding) { b1 = decodingTable[data[end - 4]]; b2 = decodingTable[data[end - 3]]; out[outLen++] = (byte)((b1 << 2) | (b2 >> 4)); } else if (data[end - 1] == padding) { b1 = decodingTable[data[end - 4]]; b2 = decodingTable[data[end - 3]]; b3 = decodingTable[data[end - 2]]; out[outLen++] = (byte)((b1 << 2) | (b2 >> 4)); out[outLen++] = (byte)((b2 << 4) | (b3 >> 2)); } else { b1 = decodingTable[data[end - 4]]; b2 = decodingTable[data[end - 3]]; b3 = decodingTable[data[end - 2]]; b4 = decodingTable[data[end - 1]]; out[outLen++] = (byte)((b1 << 2) | (b2 >> 4)); out[outLen++] = (byte)((b2 << 4) | (b3 >> 2)); out[outLen++] = (byte)((b3 << 6) | b4); } return outLen; } /** * Test if a character is a valid Base64 encoding character. This * must be either a valid digit or the padding character ("="). * * @param ch The test character. * * @return true if this is valid in Base64 encoded data, false otherwise. */ public boolean isValidBase64(int ch) { // 'A' has the value 0 in the decoding table, so we need a special one for that return ch == padding || ch == 'A' || decodingTable[ch] != 0; } /** * Perform RFC-2047 word encoding using Base64 data encoding. * * @param in The source for the encoded data. * @param charset The charset tag to be added to each encoded data section. * @param out The output stream where the encoded data is to be written. * @param fold Controls whether separate sections of encoded data are separated by * linebreaks or whitespace. * * @exception IOException */ public void encodeWord(InputStream in, String charset, OutputStream out, boolean fold) throws IOException { PrintStream writer = new PrintStream(out); // encoded words are restricted to 76 bytes, including the control adornments. int limit = 75 - 7 - charset.length(); boolean firstLine = true; StringBuffer encodedString = new StringBuffer(76); while (true) { // encode the next segment. encode(in, encodedString, limit); // if we're out of data, nothing will be encoded. if (encodedString.length() == 0) { break; } // if we have more than one segment, we need to insert separators. Depending on whether folding // was requested, this is either a blank or a linebreak. if (!firstLine) { if (fold) { writer.print("\r\n"); } else { writer.print(" "); } } // add the encoded word header writer.print("=?"); writer.print(charset); writer.print("?B?"); // the data writer.print(encodedString.toString()); // and the word terminator. writer.print("?="); writer.flush(); // reset our string buffer for the next segment. encodedString.setLength(0); // we need a delimiter after this firstLine = false; } } /** * Perform RFC-2047 word encoding using Base64 data encoding. * * @param in The source for the encoded data. * @param charset The charset tag to be added to each encoded data section. * @param out The output stream where the encoded data is to be written. * @param fold Controls whether separate sections of encoded data are separated by * linebreaks or whitespace. * * @exception IOException */ public void encodeWord(byte[] data, StringBuffer out, String charset) throws IOException { // append the word header out.append("=?"); out.append(charset); out.append("?B?"); // add on the encodeded data encodeWordData(data, out); // the end of the encoding marker out.append("?="); } /** * encode the input data producing a base 64 output stream. * * @return the number of bytes produced. */ public void encodeWordData(byte[] data, StringBuffer out) { int modulus = data.length % 3; int dataLength = (data.length - modulus); int a1, a2, a3; for (int i = 0; i < dataLength; i += 3) { a1 = data[i] & 0xff; a2 = data[i + 1] & 0xff; a3 = data[i + 2] & 0xff; out.append((char)encodingTable[(a1 >>> 2) & 0x3f]); out.append((char)encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]); out.append((char)encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]); out.append((char)encodingTable[a3 & 0x3f]); } /* * process the tail end. */ int b1, b2, b3; int d1, d2; switch (modulus) { case 0: /* nothing left to do */ break; case 1: d1 = data[dataLength] & 0xff; b1 = (d1 >>> 2) & 0x3f; b2 = (d1 << 4) & 0x3f; out.append((char)encodingTable[b1]); out.append((char)encodingTable[b2]); out.append((char)padding); out.append((char)padding); break; case 2: d1 = data[dataLength] & 0xff; d2 = data[dataLength + 1] & 0xff; b1 = (d1 >>> 2) & 0x3f; b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f; b3 = (d2 << 2) & 0x3f; out.append((char)encodingTable[b1]); out.append((char)encodingTable[b2]); out.append((char)encodingTable[b3]); out.append((char)padding); break; } } /** * encode the input data producing a base 64 output stream. * * @return the number of bytes produced. */ public void encode(InputStream in, StringBuffer out, int limit) throws IOException { int count = limit / 4; byte [] inBuffer = new byte[3]; while (count-- > 0) { int readCount = in.read(inBuffer); // did we get a full triplet? that's an easy encoding. if (readCount == 3) { int a1 = inBuffer[0] & 0xff; int a2 = inBuffer[1] & 0xff; int a3 = inBuffer[2] & 0xff; out.append((char)encodingTable[(a1 >>> 2) & 0x3f]); out.append((char)encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]); out.append((char)encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]); out.append((char)encodingTable[a3 & 0x3f]); } else if (readCount <= 0) { // eof condition, don'e entirely. return; } else if (readCount == 1) { int a1 = inBuffer[0] & 0xff; out.append((char)encodingTable[(a1 >>> 2) & 0x3f]); out.append((char)encodingTable[(a1 << 4) & 0x3f]); out.append((char)padding); out.append((char)padding); return; } else if (readCount == 2) { int a1 = inBuffer[0] & 0xff; int a2 = inBuffer[1] & 0xff; out.append((char)encodingTable[(a1 >>> 2) & 0x3f]); out.append((char)encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]); out.append((char)encodingTable[(a2 << 2) & 0x3f]); out.append((char)padding); return; } } } /** * Estimate the final encoded size of a segment of data. * This is used to ensure that the encoded blocks do * not get split across a unicode character boundary and * that the encoding will fit within the bounds of * a mail header line. * * @param data The data we're anticipating encoding. * * @return The size of the byte data in encoded form. */ public int estimateEncodedLength(byte[] data) { return ((data.length + 2) / 3) * 4; } }
956
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/Base64.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; public class Base64 { private static final Encoder encoder = new Base64Encoder(); /** * encode the input data producing a base 64 encoded byte array. * * @return a byte array containing the base 64 encoded data. */ public static byte[] encode( byte[] data) { // just forward to the general array encoder. return encode(data, 0, data.length); } /** * encode the input data producing a base 64 encoded byte array. * * @param data The data array to encode. * @param offset The starting offset within the data array. * @param length The length of the data to encode. * * @return a byte array containing the base 64 encoded data. */ public static byte[] encode( byte[] data, int offset, int length) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.encode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception encoding base64 string: " + e); } return bOut.toByteArray(); } /** * Encode the byte data to base 64 writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } /** * Encode the byte data to base 64 writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, int off, int length, OutputStream out) throws IOException { return encoder.encode(data, off, length, out); } /** * decode the base 64 encoded input data. It is assumed the input data is valid. * * @return a byte array representing the decoded data. */ public static byte[] decode( byte[] data) { // just decode the entire array of data. return decode(data, 0, data.length); } /** * decode the base 64 encoded input data. It is assumed the input data is valid. * * @param data The data array to decode. * @param offset The offset of the data array. * @param length The length of data to decode. * * @return a byte array representing the decoded data. */ public static byte[] decode( byte[] data, int offset, int length) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, offset, length, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding base64 string: " + e); } return bOut.toByteArray(); } /** * decode the base 64 encoded String data - whitespace will be ignored. * * @return a byte array representing the decoded data. */ public static byte[] decode( String data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding base64 string: " + e); } return bOut.toByteArray(); } /** * decode the base 64 encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public static int decode( String data, OutputStream out) throws IOException { return encoder.decode(data, out); } /** * decode the base 64 encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @param data The array data to decode. * @param out The output stream for the data. * * @return the number of bytes produced. * @exception IOException */ public static int decode(byte [] data, OutputStream out) throws IOException { return encoder.decode(data, 0, data.length, out); } }
957
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/UUEncode.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; public class UUEncode { private static final Encoder encoder = new UUEncoder(); /** * encode the input data producing a UUEncoded byte array. * * @return a byte array containing the UUEncoded data. */ public static byte[] encode( byte[] data) { return encode(data, 0, data.length); } /** * encode the input data producing a UUEncoded byte array. * * @return a byte array containing the UUEncoded data. */ public static byte[] encode( byte[] data, int off, int length) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.encode(data, off, length, bOut); } catch (IOException e) { throw new RuntimeException("exception encoding UUEncoded string: " + e); } return bOut.toByteArray(); } /** * UUEncode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } /** * UUEncode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, int off, int length, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } /** * decode the UUEncoded input data. It is assumed the input data is valid. * * @return a byte array representing the decoded data. */ public static byte[] decode( byte[] data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding UUEncoded string: " + e); } return bOut.toByteArray(); } /** * decode the UUEncided String data. * * @return a byte array representing the decoded data. */ public static byte[] decode( String data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding UUEncoded string: " + e); } return bOut.toByteArray(); } /** * decode the UUEncoded encoded String data writing it to the given output stream. * * @return the number of bytes produced. */ public static int decode( String data, OutputStream out) throws IOException { return encoder.decode(data, out); } }
958
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/XTextEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.IOException; import java.io.OutputStream; public class XTextEncoder implements Encoder { protected final byte[] encodingTable = { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F' }; /* * set up the decoding table. */ protected final byte[] decodingTable = new byte[128]; protected void initialiseDecodingTable() { for (int i = 0; i < encodingTable.length; i++) { decodingTable[encodingTable[i]] = (byte)i; } } public XTextEncoder() { initialiseDecodingTable(); } /** * encode the input data producing an XText output stream. * * @return the number of bytes produced. */ public int encode( byte[] data, int off, int length, OutputStream out) throws IOException { int bytesWritten = 0; for (int i = off; i < (off + length); i++) { int v = data[i] & 0xff; // character tha must be encoded? Prefix with a '+' and encode in hex. if (v < 33 || v > 126 || v == '+' || v == '+') { out.write((byte)'+'); out.write(encodingTable[(v >>> 4)]); out.write(encodingTable[v & 0xf]); bytesWritten += 3; } else { // add unchanged. out.write((byte)v); bytesWritten++; } } return bytesWritten; } /** * decode the xtext encoded byte data writing it to the given output stream * * @return the number of bytes produced. */ public int decode( byte[] data, int off, int length, OutputStream out) throws IOException { byte[] bytes; byte b1, b2; int outLen = 0; int end = off + length; int i = off; while (i < end) { byte v = data[i++]; // a plus is a hex character marker, need to decode a hex value. if (v == '+') { b1 = decodingTable[data[i++]]; b2 = decodingTable[data[i++]]; out.write((b1 << 4) | b2); } else { // copied over unchanged. out.write(v); } // always just one byte added outLen++; } return outLen; } /** * decode the xtext encoded String data writing it to the given output stream. * * @return the number of bytes produced. */ public int decode( String data, OutputStream out) throws IOException { byte[] bytes; byte b1, b2, b3, b4; int length = 0; int end = data.length(); int i = 0; while (i < end) { char v = data.charAt(i++); if (v == '+') { b1 = decodingTable[data.charAt(i++)]; b2 = decodingTable[data.charAt(i++)]; out.write((b1 << 4) | b2); } else { out.write((byte)v); } length++; } return length; } }
959
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.IOException; import java.io.OutputStream; /** * An implementation of an OutputStream that writes the data directly * out to a StringBuffer object. Useful for applications where an * intermediate ByteArrayOutputStream is required to append generated * characters to a StringBuffer; */ public class StringBufferOutputStream extends OutputStream { // the target buffer protected StringBuffer buffer; /** * Create an output stream that writes to the target StringBuffer * * @param out The wrapped output stream. */ public StringBufferOutputStream(StringBuffer out) { buffer = out; } // in order for this to work, we only need override the single character form, as the others // funnel through this one by default. public void write(int ch) throws IOException { // just append the character buffer.append((char)ch); } }
960
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.ByteArrayOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; /** * An implementation of a FilterOutputStream that decodes the * stream data in UU encoding format. This version does the * decoding "on the fly" rather than decoding a single block of * data. Since this version is intended for use by the MimeUtilty class, * it also handles line breaks in the encoded data. */ public class UUDecoderStream extends FilterInputStream { // maximum number of chars that can appear in a single line protected static final int MAX_CHARS_PER_LINE = 45; // our decoder for processing the data protected UUEncoder decoder = new UUEncoder(); // a buffer for one decoding unit's worth of data (45 bytes). protected byte[] decodedChars; // count of characters in the buffer protected int decodedCount = 0; // index of the next decoded character protected int decodedIndex = 0; // indicates whether we've already processed the "begin" prefix. protected boolean beginRead = false; public UUDecoderStream(InputStream in) { super(in); } /** * Test for the existance of decoded characters in our buffer * of decoded data. * * @return True if we currently have buffered characters. */ private boolean dataAvailable() { return decodedCount != 0; } /** * Get the next buffered decoded character. * * @return The next decoded character in the buffer. */ private byte getBufferedChar() { decodedCount--; return decodedChars[decodedIndex++]; } /** * Decode a requested number of bytes of data into a buffer. * * @return true if we were able to obtain more data, false otherwise. */ private boolean decodeStreamData() throws IOException { decodedIndex = 0; // fill up a data buffer with input data return fillEncodedBuffer() != -1; } /** * Retrieve a single byte from the decoded characters buffer. * * @return The decoded character or -1 if there was an EOF condition. */ private int getByte() throws IOException { if (!dataAvailable()) { if (!decodeStreamData()) { return -1; } } decodedCount--; return decodedChars[decodedIndex++]; } private int getBytes(byte[] data, int offset, int length) throws IOException { int readCharacters = 0; while (length > 0) { // need data? Try to get some if (!dataAvailable()) { // if we can't get this, return a count of how much we did get (which may be -1). if (!decodeStreamData()) { return readCharacters > 0 ? readCharacters : -1; } } // now copy some of the data from the decoded buffer to the target buffer int copyCount = Math.min(decodedCount, length); System.arraycopy(decodedChars, decodedIndex, data, offset, copyCount); decodedIndex += copyCount; decodedCount -= copyCount; offset += copyCount; length -= copyCount; readCharacters += copyCount; } return readCharacters; } /** * Verify that the first line of the buffer is a valid begin * marker. * * @exception IOException */ private void checkBegin() throws IOException { // we only do this the first time we're requested to read from the stream. if (beginRead) { return; } // we might have to skip over lines to reach the marker. If we hit the EOF without finding // the begin, that's an error. while (true) { String line = readLine(); if (line == null) { throw new IOException("Missing UUEncode begin command"); } // is this our begin? if (line.regionMatches(true, 0, "begin ", 0, 6)) { // This is the droid we're looking for..... beginRead = true; return; } } } /** * Read a line of data. Returns null if there is an EOF. * * @return The next line read from the stream. Returns null if we * hit the end of the stream. * @exception IOException */ protected String readLine() throws IOException { decodedIndex = 0; // get an accumulator for the data StringBuffer buffer = new StringBuffer(); // now process a character at a time. int ch = in.read(); while (ch != -1) { // a naked new line completes the line. if (ch == '\n') { break; } // a carriage return by itself is ignored...we're going to assume that this is followed // by a new line because we really don't have the capability of pushing this back . else if (ch == '\r') { ; } else { // add this to our buffer buffer.append((char)ch); } ch = in.read(); } // if we didn't get any data at all, return nothing if (ch == -1 && buffer.length() == 0) { return null; } // convert this into a string. return buffer.toString(); } /** * Fill our buffer of input characters for decoding from the * stream. This will attempt read a full buffer, but will * terminate on an EOF or read error. This will filter out * non-Base64 encoding chars and will only return a valid * multiple of 4 number of bytes. * * @return The count of characters read. */ private int fillEncodedBuffer() throws IOException { checkBegin(); // reset the buffer position decodedIndex = 0; while (true) { // we read these as character lines. We need to be looking for the "end" marker for the // end of the data. String line = readLine(); // this should NOT be happening.... if (line == null) { throw new IOException("Missing end in UUEncoded data"); } // Is this the end marker? EOF baby, EOF! if (line.equalsIgnoreCase("end")) { // this indicates we got nuttin' more to do. return -1; } ByteArrayOutputStream out = new ByteArrayOutputStream(MAX_CHARS_PER_LINE); byte [] lineBytes; try { lineBytes = line.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new IOException("Invalid UUEncoding"); } // decode this line decodedCount = decoder.decode(lineBytes, 0, lineBytes.length, out); // not just a zero-length line? if (decodedCount != 0) { // get the resulting byte array decodedChars = out.toByteArray(); return decodedCount; } } } // in order to function as a filter, these streams need to override the different // read() signature. public int read() throws IOException { return getByte(); } public int read(byte [] buffer, int offset, int length) throws IOException { return getBytes(buffer, offset, length); } public boolean markSupported() { return false; } public int available() throws IOException { return ((in.available() / 4) * 3) + decodedCount; } }
961
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/Hex.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; public class Hex { private static final Encoder encoder = new HexEncoder(); /** * encode the input data producing a Hex encoded byte array. * * @return a byte array containing the Hex encoded data. */ public static byte[] encode( byte[] data) { return encode(data, 0, data.length); } /** * encode the input data producing a Hex encoded byte array. * * @return a byte array containing the Hex encoded data. */ public static byte[] encode( byte[] data, int off, int length) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.encode(data, off, length, bOut); } catch (IOException e) { throw new RuntimeException("exception encoding Hex string: " + e); } return bOut.toByteArray(); } /** * Hex encode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } /** * Hex encode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, int off, int length, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } /** * decode the Hex encoded input data. It is assumed the input data is valid. * * @return a byte array representing the decoded data. */ public static byte[] decode( byte[] data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding Hex string: " + e); } return bOut.toByteArray(); } /** * decode the Hex encoded String data - whitespace will be ignored. * * @return a byte array representing the decoded data. */ public static byte[] decode( String data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding Hex string: " + e); } return bOut.toByteArray(); } /** * decode the Hex encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public static int decode( String data, OutputStream out) throws IOException { return encoder.decode(data, out); } }
962
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/UUEncoderStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; /** * An implementation of a FilterOutputStream that encodes the * stream data in UUencoding format. This version does the * encoding "on the fly" rather than encoding a single block of * data. Since this version is intended for use by the MimeUtilty class, * it also handles line breaks in the encoded data. */ public class UUEncoderStream extends FilterOutputStream { // default values included on the "begin" prefix of the data stream. protected static final int DEFAULT_MODE = 644; protected static final String DEFAULT_NAME = "encoder.buf"; protected static final int MAX_CHARS_PER_LINE = 45; // the configured name on the "begin" command. protected String name; // the configured mode for the "begin" command. protected int mode; // since this is a filtering stream, we need to wait until we have the first byte written for encoding // to write out the "begin" marker. A real pain, but necessary. protected boolean beginWritten = false; // our encoder utility class. protected UUEncoder encoder = new UUEncoder(); // Data is generally written out in 45 character lines, so we're going to buffer that amount before // asking the encoder to process this. // the buffered byte count protected int bufferedBytes = 0; // we'll encode this part once it is filled up. protected byte[] buffer = new byte[45]; /** * Create a Base64 encoder stream that wraps a specifed stream * using the default line break size. * * @param out The wrapped output stream. */ public UUEncoderStream(OutputStream out) { this(out, DEFAULT_NAME, DEFAULT_MODE); } /** * Create a Base64 encoder stream that wraps a specifed stream * using the default line break size. * * @param out The wrapped output stream. * @param name The filename placed on the "begin" command. */ public UUEncoderStream(OutputStream out, String name) { this(out, name, DEFAULT_MODE); } public UUEncoderStream(OutputStream out, String name, int mode) { super(out); // fill in the name and mode information. this.name = name; this.mode = mode; } private void checkBegin() throws IOException { if (!beginWritten) { // grumble...OutputStream doesn't directly support writing String data. We'll wrap this in // a PrintStream() to accomplish the task of writing the begin command. PrintStream writer = new PrintStream(out); // write out the stream with a CRLF marker writer.print("begin " + mode + " " + name + "\r\n"); writer.flush(); beginWritten = true; } } private void writeEnd() throws IOException { PrintStream writer = new PrintStream(out); // write out the stream with a CRLF marker writer.print("\nend\r\n"); writer.flush(); } private void flushBuffer() throws IOException { // make sure we've written the begin marker first checkBegin(); // ask the encoder to encode and write this out. if (bufferedBytes != 0) { encoder.encode(buffer, 0, bufferedBytes, out); // reset the buffer count bufferedBytes = 0; } } private int bufferSpace() { return MAX_CHARS_PER_LINE - bufferedBytes; } private boolean isBufferFull() { return bufferedBytes >= MAX_CHARS_PER_LINE; } // in order for this to work, we need to override the 3 different signatures for write public void write(int ch) throws IOException { // store this in the buffer. buffer[bufferedBytes++] = (byte)ch; // if we filled this up, time to encode and write to the output stream. if (isBufferFull()) { flushBuffer(); } } public void write(byte [] data) throws IOException { write(data, 0, data.length); } public void write(byte [] data, int offset, int length) throws IOException { // first check to see how much space we have left in the buffer, and copy that over int copyBytes = Math.min(bufferSpace(), length); System.arraycopy(buffer, bufferedBytes, data, offset, copyBytes); bufferedBytes += copyBytes; offset += copyBytes; length -= copyBytes; // if we filled this up, time to encode and write to the output stream. if (isBufferFull()) { flushBuffer(); } // we've flushed the leading part up to the line break. Now if we have complete lines // of data left, we can have the encoder process all of these lines directly. if (length >= MAX_CHARS_PER_LINE) { int fullLinesLength = (length / MAX_CHARS_PER_LINE) * MAX_CHARS_PER_LINE; // ask the encoder to encode and write this out. encoder.encode(data, offset, fullLinesLength, out); offset += fullLinesLength; length -= fullLinesLength; } // ok, now we're down to a potential trailing bit we need to move into the // buffer for later processing. if (length > 0) { System.arraycopy(buffer, 0, data, offset, length); bufferedBytes += length; offset += length; length -= length; } } public void flush() throws IOException { // flush any unencoded characters we're holding. flushBuffer(); // write out the data end marker writeEnd(); // and flush the output stream too so that this data is available. out.flush(); } public void close() throws IOException { // flush all of the streams and close the target output stream. flush(); out.close(); } }
963
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.security.Security; import javax.mail.Session; /** * Simple utility class for managing session properties. */ public class SessionUtil { /** * Get a property associated with this mail session. Returns * the provided default if it doesn't exist. * * @param session The attached session. * @param name The name of the property. * * @return The property value (returns null if the property has not been set). */ static public String getProperty(Session session, String name) { // occasionally, we get called with a null session if an object is not attached to // a session. In that case, treat this like an unknown parameter. if (session == null) { return null; } return session.getProperty(name); } /** * Get a property associated with this mail session. Returns * the provided default if it doesn't exist. * * @param session The attached session. * @param name The name of the property. * @param defaultValue * The default value to return if the property doesn't exist. * * @return The property value (returns defaultValue if the property has not been set). */ static public String getProperty(Session session, String name, String defaultValue) { String result = getProperty(session, name); if (result == null) { return defaultValue; } return result; } /** * Process a session property as a boolean value, returning * either true or false. * * @param session The source session. * @param name * * @return True if the property value is "true". Returns false for any * other value (including null). */ static public boolean isPropertyTrue(Session session, String name) { String property = getProperty(session, name); if (property != null) { return property.equals("true"); } return false; } /** * Process a session property as a boolean value, returning * either true or false. * * @param session The source session. * @param name * * @return True if the property value is "false". Returns false for * other value (including null). */ static public boolean isPropertyFalse(Session session, String name) { String property = getProperty(session, name); if (property != null) { return property.equals("false"); } return false; } /** * Get a property associated with this mail session as an integer value. Returns * the default value if the property doesn't exist or it doesn't have a valid int value. * * @param session The source session. * @param name The name of the property. * @param defaultValue * The default value to return if the property doesn't exist. * * @return The property value converted to an int. */ static public int getIntProperty(Session session, String name, int defaultValue) { String result = getProperty(session, name); if (result != null) { try { // convert into an int value. return Integer.parseInt(result); } catch (NumberFormatException e) { } } // return default value if it doesn't exist is isn't convertable. return defaultValue; } /** * Get a property associated with this mail session as a boolean value. Returns * the default value if the property doesn't exist or it doesn't have a valid boolean value. * * @param session The source session. * @param name The name of the property. * @param defaultValue * The default value to return if the property doesn't exist. * * @return The property value converted to a boolean. */ static public boolean getBooleanProperty(Session session, String name, boolean defaultValue) { String result = getProperty(session, name); if (result != null) { return Boolean.valueOf(result).booleanValue(); } // return default value if it doesn't exist is isn't convertable. return defaultValue; } /** * Get a system property associated with this mail session as a boolean value. Returns * the default value if the property doesn't exist or it doesn't have a valid boolean value. * * @param name The name of the property. * @param defaultValue * The default value to return if the property doesn't exist. * * @return The property value converted to a boolean. */ static public boolean getBooleanProperty(String name, boolean defaultValue) { try { String result = System.getProperty(name); if (result != null) { return Boolean.valueOf(result).booleanValue(); } } catch (SecurityException e) { // we can't access the property, so for all intents, it doesn't exist. } // return default value if it doesn't exist is isn't convertable. return defaultValue; } /** * Get a system property associated with this mail session as a boolean value. Returns * the default value if the property doesn't exist. * * @param name The name of the property. * @param defaultValue * The default value to return if the property doesn't exist. * * @return The property value */ static public String getProperty(String name, String defaultValue) { try { String result = System.getProperty(name); if (result != null) { return result; } } catch (SecurityException e) { // we can't access the property, so for all intents, it doesn't exist. } // return default value if it doesn't exist is isn't convertable. return defaultValue; } /** * Get a system property associated with this mail session as a boolean value. Returns * the default value if the property doesn't exist. * * @param name The name of the property. * * @return The property value */ static public String getProperty(String name) { try { return System.getProperty(name); } catch (SecurityException e) { // we can't access the property, so for all intents, it doesn't exist. } // return null if we got an exception. return null; } }
964
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import javax.mail.internet.MimeUtility; /** * Encoder for RFC2231 encoded parameters * * RFC2231 string are encoded as * * charset'language'encoded-text * * and * * encoded-text = *(char / hexchar) * * where * * char is any ASCII character in the range 33-126, EXCEPT * the characters "%" and " ". * * hexchar is an ASCII "%" followed by two upper case * hexadecimal digits. */ public class RFC2231Encoder implements Encoder { protected final byte[] encodingTable = { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F' }; protected String DEFAULT_SPECIALS = " *'%"; protected String specials = DEFAULT_SPECIALS; /* * set up the decoding table. */ protected final byte[] decodingTable = new byte[128]; protected void initialiseDecodingTable() { for (int i = 0; i < encodingTable.length; i++) { decodingTable[encodingTable[i]] = (byte)i; } } public RFC2231Encoder() { this(null); } public RFC2231Encoder(String specials) { if (specials != null) { this.specials = DEFAULT_SPECIALS + specials; } initialiseDecodingTable(); } /** * encode the input data producing an RFC2231 output stream. * * @return the number of bytes produced. */ public int encode(byte[] data, int off, int length, OutputStream out) throws IOException { int bytesWritten = 0; for (int i = off; i < (off + length); i++) { int ch = data[i] & 0xff; // character tha must be encoded? Prefix with a '%' and encode in hex. if (ch <= 32 || ch >= 127 || specials.indexOf(ch) != -1) { out.write((byte)'%'); out.write(encodingTable[ch >> 4]); out.write(encodingTable[ch & 0xf]); bytesWritten += 3; } else { // add unchanged. out.write((byte)ch); bytesWritten++; } } return bytesWritten; } /** * decode the RFC2231 encoded byte data writing it to the given output stream * * @return the number of bytes produced. */ public int decode(byte[] data, int off, int length, OutputStream out) throws IOException { int outLen = 0; int end = off + length; int i = off; while (i < end) { byte v = data[i++]; // a percent is a hex character marker, need to decode a hex value. if (v == '%') { byte b1 = decodingTable[data[i++]]; byte b2 = decodingTable[data[i++]]; out.write((b1 << 4) | b2); } else { // copied over unchanged. out.write(v); } // always just one byte added outLen++; } return outLen; } /** * decode the RFC2231 encoded String data writing it to the given output stream. * * @return the number of bytes produced. */ public int decode(String data, OutputStream out) throws IOException { int length = 0; int end = data.length(); int i = 0; while (i < end) { char v = data.charAt(i++); if (v == '%') { byte b1 = decodingTable[data.charAt(i++)]; byte b2 = decodingTable[data.charAt(i++)]; out.write((b1 << 4) | b2); } else { out.write((byte)v); } length++; } return length; } /** * Encode a string as an RFC2231 encoded parameter, using the * given character set and language. * * @param charset The source character set (the MIME version). * @param language The encoding language. * @param data The data to encode. * * @return The encoded string. */ public String encode(String charset, String language, String data) throws IOException { byte[] bytes = null; try { // the charset we're adding is the MIME-defined name. We need the java version // in order to extract the bytes. bytes = data.getBytes(MimeUtility.javaCharset(charset)); } catch (UnsupportedEncodingException e) { // we have a translation problem here. return null; } StringBuffer result = new StringBuffer(); // append the character set, if we have it. if (charset != null) { result.append(charset); } // the field marker is required. result.append("'"); // and the same for the language. if (language != null) { result.append(language); } // the field marker is required. result.append("'"); // wrap an output stream around our buffer for the decoding OutputStream out = new StringBufferOutputStream(result); // encode the data stream encode(bytes, 0, bytes.length, out); // finis! return result.toString(); } /** * Decode an RFC2231 encoded string. * * @param data The data to decode. * * @return The decoded string. * @exception IOException * @exception UnsupportedEncodingException */ public String decode(String data) throws IOException, UnsupportedEncodingException { // get the end of the language field int charsetEnd = data.indexOf('\''); // uh oh, might not be there if (charsetEnd == -1) { throw new IOException("Missing charset in RFC2231 encoded value"); } String charset = data.substring(0, charsetEnd); // now pull out the language the same way int languageEnd = data.indexOf('\'', charsetEnd + 1); if (languageEnd == -1) { throw new IOException("Missing language in RFC2231 encoded value"); } String language = data.substring(charsetEnd + 1, languageEnd); ByteArrayOutputStream out = new ByteArrayOutputStream(data.length()); // decode the data decode(data.substring(languageEnd + 1), out); byte[] bytes = out.toByteArray(); // build a new string from this using the java version of the encoded charset. return new String(bytes, 0, bytes.length, MimeUtility.javaCharset(charset)); } }
965
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/HexEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.IOException; import java.io.OutputStream; public class HexEncoder implements Encoder { protected final byte[] encodingTable = { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f' }; /* * set up the decoding table. */ protected final byte[] decodingTable = new byte[128]; protected void initialiseDecodingTable() { for (int i = 0; i < encodingTable.length; i++) { decodingTable[encodingTable[i]] = (byte)i; } decodingTable['A'] = decodingTable['a']; decodingTable['B'] = decodingTable['b']; decodingTable['C'] = decodingTable['c']; decodingTable['D'] = decodingTable['d']; decodingTable['E'] = decodingTable['e']; decodingTable['F'] = decodingTable['f']; } public HexEncoder() { initialiseDecodingTable(); } /** * encode the input data producing a Hex output stream. * * @return the number of bytes produced. */ public int encode( byte[] data, int off, int length, OutputStream out) throws IOException { for (int i = off; i < (off + length); i++) { int v = data[i] & 0xff; out.write(encodingTable[(v >>> 4)]); out.write(encodingTable[v & 0xf]); } return length * 2; } private boolean ignore( char c) { return (c == '\n' || c =='\r' || c == '\t' || c == ' '); } /** * decode the Hex encoded byte data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode( byte[] data, int off, int length, OutputStream out) throws IOException { byte[] bytes; byte b1, b2; int outLen = 0; int end = off + length; while (end > 0) { if (!ignore((char)data[end - 1])) { break; } end--; } int i = off; while (i < end) { while (i < end && ignore((char)data[i])) { i++; } b1 = decodingTable[data[i++]]; while (i < end && ignore((char)data[i])) { i++; } b2 = decodingTable[data[i++]]; out.write((b1 << 4) | b2); outLen++; } return outLen; } /** * decode the Hex encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode( String data, OutputStream out) throws IOException { byte[] bytes; byte b1, b2, b3, b4; int length = 0; int end = data.length(); while (end > 0) { if (!ignore(data.charAt(end - 1))) { break; } end--; } int i = 0; while (i < end) { while (i < end && ignore(data.charAt(i))) { i++; } b1 = decodingTable[data.charAt(i++)]; while (i < end && ignore(data.charAt(i))) { i++; } b2 = decodingTable[data.charAt(i++)]; out.write((b1 << 4) | b2); length++; } return length; } }
966
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/XText.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Encoder for RFC1891 xtext. * * xtext strings are defined as * * xtext = *( xchar / hexchar ) * * where * * xchar is any ASCII character in the range 33-126, EXCEPT * the characters "+" and "=". * * hexchar is an ASCII "+" followed by two upper case * hexadecimal digits. */ public class XText { private static final Encoder encoder = new XTextEncoder(); /** * encode the input data producing an xtext encoded byte array. * * @return a byte array containing the xtext encoded data. */ public static byte[] encode( byte[] data) { return encode(data, 0, data.length); } /** * encode the input data producing an xtext encoded byte array. * * @return a byte array containing the xtext encoded data. */ public static byte[] encode( byte[] data, int off, int length) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.encode(data, off, length, bOut); } catch (IOException e) { throw new RuntimeException("exception encoding xtext string: " + e); } return bOut.toByteArray(); } /** * xtext encode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } /** * extext encode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, int off, int length, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } /** * decode the xtext encoded input data. It is assumed the input data is valid. * * @return a byte array representing the decoded data. */ public static byte[] decode( byte[] data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding xtext string: " + e); } return bOut.toByteArray(); } /** * decode the xtext encoded String data - whitespace will be ignored. * * @return a byte array representing the decoded data. */ public static byte[] decode( String data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding xtext string: " + e); } return bOut.toByteArray(); } /** * decode the xtext encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public static int decode( String data, OutputStream out) throws IOException { return encoder.decode(data, out); } }
967
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.IOException; import java.io.OutputStream; import java.io.FilterOutputStream; /** * An implementation of a FilterOutputStream that encodes the * stream data in BASE64 encoding format. This version does the * encoding "on the fly" rather than encoding a single block of * data. Since this version is intended for use by the MimeUtilty class, * it also handles line breaks in the encoded data. */ public class Base64EncoderStream extends FilterOutputStream { // our Filtered stream writes everything out as byte data. This allows the CRLF sequence to // be written with a single call. protected static final byte[] CRLF = { '\r', '\n' }; // our hex encoder utility class. protected Base64Encoder encoder = new Base64Encoder(); // our default for line breaks protected static final int DEFAULT_LINEBREAK = 76; // Data can only be written out in complete units of 3 bytes encoded as 4. Therefore, we need to buffer // as many as 2 bytes to fill out an encoding unit. // the buffered byte count protected int bufferedBytes = 0; // we'll encode this part once it is filled up. protected byte[] buffer = new byte[3]; // the size we process line breaks at. If this is Integer.MAX_VALUE, no line breaks are handled. protected int lineBreak; // the number of encoded characters we've written to the stream, which determines where we // insert line breaks. protected int outputCount; /** * Create a Base64 encoder stream that wraps a specifed stream * using the default line break size. * * @param out The wrapped output stream. */ public Base64EncoderStream(OutputStream out) { this(out, DEFAULT_LINEBREAK); } public Base64EncoderStream(OutputStream out, int lineBreak) { super(out); // lines are processed only in multiple of 4, so round this down. this.lineBreak = (lineBreak / 4) * 4 ; } // in order for this to work, we need to override the 3 different signatures for write public void write(int ch) throws IOException { // store this in the buffer. buffer[bufferedBytes++] = (byte)ch; // if the buffer is filled, encode these bytes if (bufferedBytes == 3) { // check for room in the current line for this character checkEOL(4); // write these directly to the stream. encoder.encode(buffer, 0, 3, out); bufferedBytes = 0; // and update the line length checkers updateLineCount(4); } } public void write(byte [] data) throws IOException { write(data, 0, data.length); } public void write(byte [] data, int offset, int length) throws IOException { // if we have something in the buffer, we need to write enough bytes out to flush // those into the output stream AND continue on to finish off a line. Once we're done there // we can write additional data out in complete blocks. while ((bufferedBytes > 0 || outputCount > 0) && length > 0) { write(data[offset++]); length--; } if (length > 0) { // no linebreaks requested? YES!!!!!, we can just dispose of the lot with one call. if (lineBreak == Integer.MAX_VALUE) { encoder.encode(data, offset, length, out); } else { // calculate the size of a segment we can encode directly as a line. int segmentSize = (lineBreak / 4) * 3; // write this out a block at a time, with separators between. while (length > segmentSize) { // encode a segment encoder.encode(data, offset, segmentSize, out); // write an EOL marker out.write(CRLF); offset += segmentSize; length -= segmentSize; } // any remainder we write out a byte at a time to manage the groupings and // the line count appropriately. if (length > 0) { while (length > 0) { write(data[offset++]); length--; } } } } } public void close() throws IOException { flush(); out.close(); } public void flush() throws IOException { if (bufferedBytes > 0) { encoder.encode(buffer, 0, bufferedBytes, out); bufferedBytes = 0; } } /** * Check for whether we're about the reach the end of our * line limit for an update that's about to occur. If we will * overflow, then a line break is inserted. * * @param required The space required for this pending write. * * @exception IOException */ private void checkEOL(int required) throws IOException { if (lineBreak != Integer.MAX_VALUE) { // if this write would exceed the line maximum, add a linebreak to the stream. if (outputCount + required > lineBreak) { out.write(CRLF); outputCount = 0; } } } /** * Update the counter of characters on the current working line. * This is conditional if we're not working with a line limit. * * @param added The number of characters just added. */ private void updateLineCount(int added) { if (lineBreak != Integer.MAX_VALUE) { outputCount += added; } } }
968
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/Encoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.IOException; import java.io.OutputStream; /** * Encode and decode byte arrays (typically from binary to 7-bit ASCII * encodings). */ public interface Encoder { int encode(byte[] data, int off, int length, OutputStream out) throws IOException; int decode(byte[] data, int off, int length, OutputStream out) throws IOException; int decode(String data, OutputStream out) throws IOException; }
969
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/util/UUEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.util; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; public class UUEncoder implements Encoder { // this is the maximum number of chars allowed per line, since we have to include a uuencoded length at // the start of each line. static private final int MAX_CHARS_PER_LINE = 45; public UUEncoder() { } /** * encode the input data producing a UUEncoded output stream. * * @param data The array of byte data. * @param off The starting offset within the data. * @param length Length of the data to encode. * @param out The output stream the encoded data is written to. * * @return the number of bytes produced. */ public int encode(byte[] data, int off, int length, OutputStream out) throws IOException { int byteCount = 0; while (true) { // keep writing complete lines until we've exhausted the data. if (length > MAX_CHARS_PER_LINE) { // encode another line and adjust the length and position byteCount += encodeLine(data, off, MAX_CHARS_PER_LINE, out); length -= MAX_CHARS_PER_LINE; off += MAX_CHARS_PER_LINE; } else { // last line. Encode the partial and quit byteCount += encodeLine(data, off, MAX_CHARS_PER_LINE, out); break; } } return byteCount; } /** * Encode a single line of data (less than or equal to 45 characters). * * @param data The array of byte data. * @param off The starting offset within the data. * @param length Length of the data to encode. * @param out The output stream the encoded data is written to. * * @return The number of bytes written to the output stream. * @exception IOException */ private int encodeLine(byte[] data, int offset, int length, OutputStream out) throws IOException { // write out the number of characters encoded in this line. out.write((byte)((length & 0x3F) + ' ')); byte a; byte b; byte c; // count the bytes written...we add 2, one for the length and 1 for the linend terminator. int bytesWritten = 2; for (int i = 0; i < length;) { // set the padding defauls b = 1; c = 1; // get the next 3 bytes (if we have them) a = data[offset + i++]; if (i < length) { b = data[offset + i++]; if (i < length) { c = data[offset + i++]; } } byte d1 = (byte)(((a >>> 2) & 0x3F) + ' '); byte d2 = (byte)(((( a << 4) & 0x30) | ((b >>> 4) & 0x0F)) + ' '); byte d3 = (byte)((((b << 2) & 0x3C) | ((c >>> 6) & 0x3)) + ' '); byte d4 = (byte)((c & 0x3F) + ' '); out.write(d1); out.write(d2); out.write(d3); out.write(d4); bytesWritten += 4; } // terminate with a linefeed alone out.write('\n'); return bytesWritten; } /** * decode the uuencoded byte data writing it to the given output stream * * @param data The array of byte data to decode. * @param off Starting offset within the array. * @param length The length of data to encode. * @param out The output stream used to return the decoded data. * * @return the number of bytes produced. * @exception IOException */ public int decode(byte[] data, int off, int length, OutputStream out) throws IOException { int bytesWritten = 0; while (length > 0) { int lineOffset = off; // scan forward looking for a EOL terminator for the next line of data. while (length > 0 && data[off] != '\n') { off++; length--; } // go decode this line of data bytesWritten += decodeLine(data, lineOffset, off - lineOffset, out); // the offset was left pointing at the EOL character, so step over that one before // scanning again. off++; length--; } return bytesWritten; } /** * decode a single line of uuencoded byte data writing it to the given output stream * * @param data The array of byte data to decode. * @param off Starting offset within the array. * @param length The length of data to decode (length does NOT include the terminating new line). * @param out The output stream used to return the decoded data. * * @return the number of bytes produced. * @exception IOException */ private int decodeLine(byte[] data, int off, int length, OutputStream out) throws IOException { int count = data[off++]; // obtain and validate the count if (count < ' ') { throw new IOException("Invalid UUEncode line length"); } count = (count - ' ') & 0x3F; // get the rounded count of characters that should have been used to encode this. The + 1 is for the // length encoded at the beginning int requiredLength = (((count * 8) + 5) / 6) + 1; if (length < requiredLength) { throw new IOException("UUEncoded data and length do not match"); } int bytesWritten = 0; // now decode the bytes. while (bytesWritten < count) { // even one byte of data requires two bytes to encode, so we should have that. byte a = (byte)((data[off++] - ' ') & 0x3F); byte b = (byte)((data[off++] - ' ') & 0x3F); byte c = 0; byte d = 0; // do the first byte byte first = (byte)(((a << 2) & 0xFC) | ((b >>> 4) & 3)); out.write(first); bytesWritten++; // still have more bytes to decode? do the second byte of the second. That requires // a third byte from the data. if (bytesWritten < count) { c = (byte)((data[off++] - ' ') & 0x3F); byte second = (byte)(((b << 4) & 0xF0) | ((c >>> 2) & 0x0F)); out.write(second); bytesWritten++; // need the third one? if (bytesWritten < count) { d = (byte)((data[off++] - ' ') & 0x3F); byte third = (byte)(((c << 6) & 0xC0) | (d & 0x3F)); out.write(third); bytesWritten++; } } } return bytesWritten; } /** * decode the UUEncoded String data writing it to the given output stream. * * @param data The String data to decode. * @param out The output stream to write the decoded data to. * * @return the number of bytes produced. * @exception IOException */ public int decode(String data, OutputStream out) throws IOException { try { // just get the byte data and decode. byte[] bytes = data.getBytes("US-ASCII"); return decode(bytes, 0, bytes.length, out); } catch (UnsupportedEncodingException e) { throw new IOException("Invalid UUEncoding"); } } }
970
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/handlers/MultipartHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.handlers; import javax.activation.ActivationDataFlavor; import javax.activation.DataContentHandler; import javax.activation.DataSource; import java.awt.datatransfer.DataFlavor; import java.io.IOException; import java.io.OutputStream; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeMessage; import javax.mail.MessagingException; public class MultipartHandler implements DataContentHandler { /** * Field dataFlavor */ ActivationDataFlavor dataFlavor; public MultipartHandler(){ dataFlavor = new ActivationDataFlavor(javax.mail.internet.MimeMultipart.class, "multipart/mixed", "Multipart"); } /** * Constructor TextHandler * * @param dataFlavor */ public MultipartHandler(ActivationDataFlavor dataFlavor) { this.dataFlavor = dataFlavor; } /** * Method getDF * * @return dataflavor */ protected ActivationDataFlavor getDF() { return dataFlavor; } /** * Method getTransferDataFlavors * * @return dataflavors */ public DataFlavor[] getTransferDataFlavors() { return (new DataFlavor[]{dataFlavor}); } /** * Method getTransferData * * @param dataflavor * @param datasource * @return * @throws IOException */ public Object getTransferData(DataFlavor dataflavor, DataSource datasource) throws IOException { if (getDF().equals(dataflavor)) { return getContent(datasource); } return null; } /** * Method getContent * * @param datasource * @return * @throws IOException */ public Object getContent(DataSource datasource) throws IOException { try { return new MimeMultipart(datasource); } catch (MessagingException e) { // if there is a syntax error from the datasource parsing, the content is // just null. return null; } } /** * Method writeTo * * @param object * @param s * @param outputstream * @throws IOException */ public void writeTo(Object object, String s, OutputStream outputstream) throws IOException { // if this object is a MimeMultipart, then delegate to the part. if (object instanceof MimeMultipart) { try { ((MimeMultipart)object).writeTo(outputstream); } catch (MessagingException e) { // we need to transform any exceptions into an IOException. throw new IOException("Exception writing MimeMultipart: " + e.toString()); } } } }
971
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/handlers/TextHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.handlers; import java.awt.datatransfer.DataFlavor; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import javax.activation.ActivationDataFlavor; import javax.activation.DataContentHandler; import javax.activation.DataSource; import javax.mail.internet.ContentType; import javax.mail.internet.MimeUtility; import javax.mail.internet.ParseException; public class TextHandler implements DataContentHandler { /** * Field dataFlavor */ ActivationDataFlavor dataFlavor; public TextHandler(){ dataFlavor = new ActivationDataFlavor(java.lang.String.class, "text/plain", "Text String"); } /** * Constructor TextHandler * * @param dataFlavor */ public TextHandler(ActivationDataFlavor dataFlavor) { this.dataFlavor = dataFlavor; } /** * Method getDF * * @return dataflavor */ protected ActivationDataFlavor getDF() { return dataFlavor; } /** * Method getTransferDataFlavors * * @return dataflavors */ public DataFlavor[] getTransferDataFlavors() { return (new DataFlavor[]{dataFlavor}); } /** * Method getTransferData * * @param dataflavor * @param datasource * @return * @throws IOException */ public Object getTransferData(DataFlavor dataflavor, DataSource datasource) throws IOException { if (getDF().equals(dataflavor)) { return getContent(datasource); } return null; } /** * Method getContent * * @param datasource * @return * @throws IOException */ public Object getContent(DataSource datasource) throws IOException { InputStream is = datasource.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); int count; byte[] buffer = new byte[1000]; try { while ((count = is.read(buffer, 0, buffer.length)) > 0) { os.write(buffer, 0, count); } } finally { is.close(); } try { return os.toString(getCharSet(datasource.getContentType())); } catch (ParseException e) { throw new UnsupportedEncodingException(e.getMessage()); } } /** * Write an object of "our" type out to the provided * output stream. The content type might modify the * result based on the content type parameters. * * @param object The object to write. * @param contentType * The content mime type, including parameters. * @param outputstream * The target output stream. * * @throws IOException */ public void writeTo(Object object, String contentType, OutputStream outputstream) throws IOException { if(object instanceof String) { OutputStreamWriter os; try { String charset = getCharSet(contentType); os = new OutputStreamWriter(outputstream, charset); } catch (Exception ex) { throw new UnsupportedEncodingException(ex.toString()); } String content = (String) object; os.write(content, 0, content.length()); os.flush(); } } /** * get the character set from content type * @param contentType * @return * @throws ParseException */ protected String getCharSet(String contentType) throws ParseException { ContentType type = new ContentType(contentType); String charset = type.getParameter("charset"); if (charset == null) { charset = "us-ascii"; } return MimeUtility.javaCharset(charset); } }
972
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/handlers/MessageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.handlers; import javax.activation.ActivationDataFlavor; import javax.activation.DataContentHandler; import javax.activation.DataSource; import javax.mail.internet.ContentType; import javax.mail.Message; import javax.mail.MessageAware; import javax.mail.MessageContext; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import javax.mail.internet.ParseException; import java.awt.datatransfer.DataFlavor; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; public class MessageHandler implements DataContentHandler { /** * Field dataFlavor */ ActivationDataFlavor dataFlavor; public MessageHandler(){ dataFlavor = new ActivationDataFlavor(java.lang.String.class, "message/rfc822", "Text"); } /** * Method getDF * * @return dataflavor */ protected ActivationDataFlavor getDF() { return dataFlavor; } /** * Method getTransferDataFlavors * * @return dataflavors */ public DataFlavor[] getTransferDataFlavors() { return (new DataFlavor[]{dataFlavor}); } /** * Method getTransferData * * @param dataflavor * @param datasource * @return * @throws IOException */ public Object getTransferData(DataFlavor dataflavor, DataSource datasource) throws IOException { if (getDF().equals(dataflavor)) { return getContent(datasource); } return null; } /** * Method getContent * * @param datasource * @return * @throws IOException */ public Object getContent(DataSource datasource) throws IOException { try { // if this is a proper message, it implements the MessageAware interface. We need this to // get the associated session. if (datasource instanceof MessageAware) { MessageContext context = ((MessageAware)datasource).getMessageContext(); // construct a mime message instance from the stream, associating it with the // data source session. return new MimeMessage(context.getSession(), datasource.getInputStream()); } } catch (MessagingException e) { // we need to transform any exceptions into an IOException. throw new IOException("Exception writing MimeMultipart: " + e.toString()); } return null; } /** * Method writeTo * * @param object * @param s * @param outputstream * @throws IOException */ public void writeTo(Object object, String s, OutputStream outputstream) throws IOException { // proper message type? if (object instanceof Message) { try { ((Message)object).writeTo(outputstream); } catch (MessagingException e) { throw new IOException("Error parsing message: " + e.toString()); } } } }
973
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/handlers/HtmlHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.handlers; import javax.activation.ActivationDataFlavor; public class HtmlHandler extends TextHandler { public HtmlHandler() { super(new ActivationDataFlavor(java.lang.String.class, "text/html", "HTML String")); } }
974
0
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail
Create_ds/geronimo-specs/geronimo-javamail_1.4_spec/src/main/java/org/apache/geronimo/mail/handlers/XMLHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mail.handlers; import javax.activation.ActivationDataFlavor; public class XMLHandler extends TextHandler { public XMLHandler() { super(new ActivationDataFlavor(java.lang.String.class, "text/xml", "XML String")); } }
975
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/StoreClosedException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class StoreClosedException extends MessagingException { private static final long serialVersionUID = -3145392336120082655L; private transient Store _store; public StoreClosedException(Store store) { super(); _store = store; } public StoreClosedException(Store store, String message) { super(message); } public Store getStore() { return _store; } }
976
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/BodyPart.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public abstract class BodyPart implements Part { protected Multipart parent; public Multipart getParent() { return parent; } // Can't be public. Not strictly required for spec, but mirrors Sun's javamail api impl. void setParent(Multipart parent) { this.parent = parent; } }
977
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/Message.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.Date; import javax.mail.search.SearchTerm; /** * @version $Rev$ $Date$ */ public abstract class Message implements Part { /** * Enumeration of types of recipients allowed by the Message class. */ public static class RecipientType implements Serializable { /** * A "To" or primary recipient. */ public static final RecipientType TO = new RecipientType("To"); /** * A "Cc" or carbon-copy recipient. */ public static final RecipientType CC = new RecipientType("Cc"); /** * A "Bcc" or blind carbon-copy recipient. */ public static final RecipientType BCC = new RecipientType("Bcc"); protected String type; protected RecipientType(String type) { this.type = type; } protected Object readResolve() throws ObjectStreamException { if (type.equals("To")) { return TO; } else if (type.equals("Cc")) { return CC; } else if (type.equals("Bcc")) { return BCC; } else { throw new InvalidObjectException("Invalid RecipientType: " + type); } } public String toString() { return type; } } /** * The index of a message within its folder, or zero if the message was not retrieved from a folder. */ protected int msgnum; /** * True if this message has been expunged from the Store. */ protected boolean expunged; /** * The {@link Folder} that contains this message, or null if it was not obtained from a folder. */ protected Folder folder; /** * The {@link Session} associated with this message. */ protected Session session; /** * Default constructor. */ protected Message() { } /** * Constructor initializing folder and message msgnum; intended to be used by implementations of Folder. * * @param folder the folder that contains the message * @param msgnum the message index within the folder */ protected Message(Folder folder, int msgnum) { this.folder = folder; this.msgnum = msgnum; // make sure we copy the session information from the folder. this.session = folder.getStore().getSession(); } /** * Constructor initializing the session; intended to by used by client created instances. * * @param session the session associated with this message */ protected Message(Session session) { this.session = session; } /** * Return the "From" header indicating the identity of the person the message is from; * in some circumstances this may be different than the actual sender. * * @return a list of addresses this message is from; may be empty if the header is present but empty, or null * if the header is not present * @throws MessagingException if there was a problem accessing the Store */ public abstract Address[] getFrom() throws MessagingException; /** * Set the "From" header for this message to the value of the "mail.user" property, * or if that property is not set, to the value of the system property "user.name" * * @throws MessagingException if there was a problem accessing the Store */ public abstract void setFrom() throws MessagingException; /** * Set the "From" header to the supplied address. * * @param address the address of the person the message is from * @throws MessagingException if there was a problem accessing the Store */ public abstract void setFrom(Address address) throws MessagingException; /** * Add multiple addresses to the "From" header. * * @param addresses the addresses to add * @throws MessagingException if there was a problem accessing the Store */ public abstract void addFrom(Address[] addresses) throws MessagingException; /** * Get all recipients of the given type. * * @param type the type of recipient to get * @return a list of addresses; may be empty if the header is present but empty, * or null if the header is not present * @throws MessagingException if there was a problem accessing the Store * @see RecipientType */ public abstract Address[] getRecipients(RecipientType type) throws MessagingException; /** * Get all recipients of this message. * The default implementation extracts the To, Cc, and Bcc recipients using {@link #getRecipients(javax.mail.Message.RecipientType)} * and then concatentates the results into a single array; it returns null if no headers are defined. * * @return an array containing all recipients * @throws MessagingException if there was a problem accessing the Store */ public Address[] getAllRecipients() throws MessagingException { Address[] to = getRecipients(RecipientType.TO); Address[] cc = getRecipients(RecipientType.CC); Address[] bcc = getRecipients(RecipientType.BCC); if (to == null && cc == null && bcc == null) { return null; } int length = (to != null ? to.length : 0) + (cc != null ? cc.length : 0) + (bcc != null ? bcc.length : 0); Address[] result = new Address[length]; int j = 0; if (to != null) { for (int i = 0; i < to.length; i++) { result[j++] = to[i]; } } if (cc != null) { for (int i = 0; i < cc.length; i++) { result[j++] = cc[i]; } } if (bcc != null) { for (int i = 0; i < bcc.length; i++) { result[j++] = bcc[i]; } } return result; } /** * Set the list of recipients for the specified type. * * @param type the type of recipient * @param addresses the new addresses * @throws MessagingException if there was a problem accessing the Store */ public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; /** * Set the list of recipients for the specified type to a single address. * * @param type the type of recipient * @param address the new address * @throws MessagingException if there was a problem accessing the Store */ public void setRecipient(RecipientType type, Address address) throws MessagingException { setRecipients(type, new Address[]{address}); } /** * Add recipents of a specified type. * * @param type the type of recipient * @param addresses the addresses to add * @throws MessagingException if there was a problem accessing the Store */ public abstract void addRecipients(RecipientType type, Address[] addresses) throws MessagingException; /** * Add a recipent of a specified type. * * @param type the type of recipient * @param address the address to add * @throws MessagingException if there was a problem accessing the Store */ public void addRecipient(RecipientType type, Address address) throws MessagingException { addRecipients(type, new Address[]{address}); } /** * Get the addresses to which replies should be directed. * <p/> * As the most common behavior is to return to sender, the default implementation * simply calls {@link #getFrom()}. * * @return a list of addresses to which replies should be directed * @throws MessagingException if there was a problem accessing the Store */ public Address[] getReplyTo() throws MessagingException { return getFrom(); } /** * Set the addresses to which replies should be directed. * <p/> * The default implementation throws a MethodNotSupportedException. * * @param addresses to which replies should be directed * @throws MessagingException if there was a problem accessing the Store */ public void setReplyTo(Address[] addresses) throws MessagingException { throw new MethodNotSupportedException("setReplyTo not supported"); } /** * Get the subject for this message. * * @return the subject * @throws MessagingException if there was a problem accessing the Store */ public abstract String getSubject() throws MessagingException; /** * Set the subject of this message * * @param subject the subject * @throws MessagingException if there was a problem accessing the Store */ public abstract void setSubject(String subject) throws MessagingException; /** * Return the date that this message was sent. * * @return the date this message was sent * @throws MessagingException if there was a problem accessing the Store */ public abstract Date getSentDate() throws MessagingException; /** * Set the date this message was sent. * * @param sent the date when this message was sent * @throws MessagingException if there was a problem accessing the Store */ public abstract void setSentDate(Date sent) throws MessagingException; /** * Return the date this message was received. * * @return the date this message was received * @throws MessagingException if there was a problem accessing the Store */ public abstract Date getReceivedDate() throws MessagingException; /** * Return a copy the flags associated with this message. * * @return a copy of the flags for this message * @throws MessagingException if there was a problem accessing the Store */ public abstract Flags getFlags() throws MessagingException; /** * Check whether the supplied flag is set. * The default implementation checks the flags returned by {@link #getFlags()}. * * @param flag the flags to check for * @return true if the flags is set * @throws MessagingException if there was a problem accessing the Store */ public boolean isSet(Flags.Flag flag) throws MessagingException { return getFlags().contains(flag); } /** * Set the flags specified to the supplied value; flags not included in the * supplied {@link Flags} parameter are not affected. * * @param flags the flags to modify * @param set the new value of those flags * @throws MessagingException if there was a problem accessing the Store */ public abstract void setFlags(Flags flags, boolean set) throws MessagingException; /** * Set a flag to the supplied value. * The default implmentation uses {@link #setFlags(Flags, boolean)}. * * @param flag the flag to set * @param set the value for that flag * @throws MessagingException if there was a problem accessing the Store */ public void setFlag(Flags.Flag flag, boolean set) throws MessagingException { setFlags(new Flags(flag), set); } /** * Return the message number for this Message. * This number refers to the relative position of this message in a Folder; the message * number for any given message can change during a session if the Folder is expunged. * Message numbers for messages in a folder start at one; the value zero indicates that * this message does not belong to a folder. * * @return the message number */ public int getMessageNumber() { return msgnum; } /** * Set the message number for this Message. * This must be invoked by implementation classes when the message number changes. * * @param number the new message number */ protected void setMessageNumber(int number) { msgnum = number; } /** * Return the folder containing this message. If this is a new or nested message * then this method returns null. * * @return the folder containing this message */ public Folder getFolder() { return folder; } /** * Checks to see if this message has been expunged. If true, all methods other than * {@link #getMessageNumber()} are invalid. * * @return true if this method has been expunged */ public boolean isExpunged() { return expunged; } /** * Set the expunged flag for this message. * * @param expunged true if this message has been expunged */ protected void setExpunged(boolean expunged) { this.expunged = expunged; } /** * Create a new message suitable as a reply to this message with all headers set * up appropriately. The message body will be empty. * <p/> * if replyToAll is set then the new message will be addressed to all recipients * of this message; otherwise the reply will be addressed only to the sender as * returned by {@link #getReplyTo()}. * <p/> * The subject field will be initialized with the subject field from the orginal * message; the text "Re:" will be prepended unless it is already present. * * @param replyToAll if true, indciates the message should be addressed to all recipients not just the sender * @return a new message suitable as a reply to this message * @throws MessagingException if there was a problem accessing the Store */ public abstract Message reply(boolean replyToAll) throws MessagingException; /** * To ensure changes are saved to the Store, this message should be invoked * before its containing Folder is closed. Implementations may save modifications * immediately but are free to defer such updates to they may be sent to the server * in one batch; if saveChanges is not called then such changes may not be made * permanent. * * @throws MessagingException if there was a problem accessing the Store */ public abstract void saveChanges() throws MessagingException; /** * Apply the specified search criteria to this message * * @param term the search criteria * @return true if this message matches the search criteria. * @throws MessagingException if there was a problem accessing the Store */ public boolean match(SearchTerm term) throws MessagingException { return term.match(this); } }
978
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/Flags.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.io.Serializable; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Representation of flags that may be associated with a message. * Flags can either be system flags, defined by the {@link Flags.Flag Flag} inner class, * or user-defined flags defined by a String. The system flags represent those expected * to be provided by most folder systems; user-defined flags allow for additional flags * on a per-provider basis. * <p/> * This class is Serializable but compatibility is not guaranteed across releases. * * @version $Rev$ $Date$ */ public class Flags implements Cloneable, Serializable { private static final long serialVersionUID = 6243590407214169028L; public static final class Flag { /** * Flag that indicates that the message has been replied to; has a bit value of 1. */ public static final Flag ANSWERED = new Flag(1); /** * Flag that indicates that the message has been marked for deletion and * should be removed on a subsequent expunge operation; has a bit value of 2. */ public static final Flag DELETED = new Flag(2); /** * Flag that indicates that the message is a draft; has a bit value of 4. */ public static final Flag DRAFT = new Flag(4); /** * Flag that indicates that the message has been flagged; has a bit value of 8. */ public static final Flag FLAGGED = new Flag(8); /** * Flag that indicates that the message has been delivered since the last time * this folder was opened; has a bit value of 16. */ public static final Flag RECENT = new Flag(16); /** * Flag that indicates that the message has been viewed; has a bit value of 32. * This flag is set by the {@link Message#getInputStream()} and {@link Message#getContent()} * methods. */ public static final Flag SEEN = new Flag(32); /** * Flags that indicates if this folder supports user-defined flags; has a bit value of 0x80000000. */ public static final Flag USER = new Flag(0x80000000); private final int mask; private Flag(int mask) { this.mask = mask; } } // the Serialized form of this class required the following two fields to be persisted // this leads to a specific type of implementation private int system_flags; private final Hashtable user_flags; /** * Construct a Flags instance with no flags set. */ public Flags() { user_flags = new Hashtable(); } /** * Construct a Flags instance with a supplied system flag set. * @param flag the system flag to set */ public Flags(Flag flag) { system_flags = flag.mask; user_flags = new Hashtable(); } /** * Construct a Flags instance with a same flags set. * @param flags the instance to copy */ public Flags(Flags flags) { system_flags = flags.system_flags; user_flags = new Hashtable(flags.user_flags); } /** * Construct a Flags instance with the supplied user flags set. * Question: should this automatically set the USER system flag? * @param name the user flag to set */ public Flags(String name) { user_flags = new Hashtable(); user_flags.put(name.toLowerCase(), name); } /** * Set a system flag. * @param flag the system flag to set */ public void add(Flag flag) { system_flags |= flag.mask; } /** * Set all system and user flags from the supplied Flags. * Question: do we need to check compatibility of USER flags? * @param flags the Flags to add */ public void add(Flags flags) { system_flags |= flags.system_flags; user_flags.putAll(flags.user_flags); } /** * Set a user flag. * Question: should this fail if the USER system flag is not set? * @param name the user flag to set */ public void add(String name) { user_flags.put(name.toLowerCase(), name); } /** * Return a copy of this instance. * @return a copy of this instance */ public Object clone() { return new Flags(this); } /** * See if the supplied system flags are set * @param flag the system flags to check for * @return true if the flags are set */ public boolean contains(Flag flag) { return (system_flags & flag.mask) != 0; } /** * See if all of the supplied Flags are set * @param flags the flags to check for * @return true if all the supplied system and user flags are set */ public boolean contains(Flags flags) { return ((system_flags & flags.system_flags) == flags.system_flags) && user_flags.keySet().containsAll(flags.user_flags.keySet()); } /** * See if the supplied user flag is set * @param name the user flag to check for * @return true if the flag is set */ public boolean contains(String name) { return user_flags.containsKey(name.toLowerCase()); } /** * Equality is defined as true if the other object is a instanceof Flags with the * same system and user flags set (using a case-insensitive name comparison for user flags). * @param other the instance to compare against * @return true if the two instance are the same */ public boolean equals(Object other) { if (other == this) return true; if (other instanceof Flags == false) return false; final Flags flags = (Flags) other; return system_flags == flags.system_flags && user_flags.keySet().equals(flags.user_flags.keySet()); } /** * Calculate a hashCode for this instance * @return a hashCode for this instance */ public int hashCode() { return system_flags ^ user_flags.keySet().hashCode(); } /** * Return a list of {@link Flags.Flag Flags} containing the system flags that have been set * @return the system flags that have been set */ public Flag[] getSystemFlags() { // assumption: it is quicker to calculate the size than it is to reallocate the array int size = 0; if ((system_flags & Flag.ANSWERED.mask) != 0) size += 1; if ((system_flags & Flag.DELETED.mask) != 0) size += 1; if ((system_flags & Flag.DRAFT.mask) != 0) size += 1; if ((system_flags & Flag.FLAGGED.mask) != 0) size += 1; if ((system_flags & Flag.RECENT.mask) != 0) size += 1; if ((system_flags & Flag.SEEN.mask) != 0) size += 1; if ((system_flags & Flag.USER.mask) != 0) size += 1; Flag[] result = new Flag[size]; if ((system_flags & Flag.USER.mask) != 0) result[--size] = Flag.USER; if ((system_flags & Flag.SEEN.mask) != 0) result[--size] = Flag.SEEN; if ((system_flags & Flag.RECENT.mask) != 0) result[--size] = Flag.RECENT; if ((system_flags & Flag.FLAGGED.mask) != 0) result[--size] = Flag.FLAGGED; if ((system_flags & Flag.DRAFT.mask) != 0) result[--size] = Flag.DRAFT; if ((system_flags & Flag.DELETED.mask) != 0) result[--size] = Flag.DELETED; if ((system_flags & Flag.ANSWERED.mask) != 0) result[--size] = Flag.ANSWERED; return result; } /** * Return a list of user flags that have been set * @return a list of user flags */ public String[] getUserFlags() { return (String[]) user_flags.values().toArray(new String[user_flags.values().size()]); } /** * Unset the supplied system flag. * Question: what happens if we unset the USER flags and user flags are set? * @param flag the flag to clear */ public void remove(Flag flag) { system_flags &= ~flag.mask; } /** * Unset all flags from the supplied instance. * @param flags the flags to clear */ public void remove(Flags flags) { system_flags &= ~flags.system_flags; user_flags.keySet().removeAll(flags.user_flags.keySet()); } /** * Unset the supplied user flag. * @param name the flag to clear */ public void remove(String name) { user_flags.remove(name.toLowerCase()); } }
979
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/MessagingException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class MessagingException extends Exception { private static final long serialVersionUID = -7569192289819959253L; // Required because serialization expects it to be here private Exception next; public MessagingException() { super(); } public MessagingException(String message) { super(message); } public MessagingException(String message, Exception cause) { super(message, cause); next = cause; } public synchronized Exception getNextException() { return next; } public synchronized boolean setNextException(Exception cause) { if (next == null) { next = cause; return true; } else if (next instanceof MessagingException) { return ((MessagingException) next).setNextException(cause); } else { return false; } } public String getMessage() { Exception next = getNextException(); if (next == null) { return super.getMessage(); } else { return super.getMessage() + " (" + next.getClass().getName() + ": " + next.getMessage() + ")"; } } /** * MessagingException uses the nextException to provide a legacy chained throwable. * override the getCause method to return the nextException. */ public synchronized Throwable getCause() { return next; } }
980
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/MessageAware.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public interface MessageAware { public abstract MessageContext getMessageContext(); }
981
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/NoSuchProviderException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class NoSuchProviderException extends MessagingException { private static final long serialVersionUID = 8058319293154708827L; public NoSuchProviderException() { super(); } public NoSuchProviderException(String message) { super(message); } }
982
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/MessageContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * The context in which a piece of message content is contained. * * @version $Rev$ $Date$ */ public class MessageContext { private final Part part; /** * Create a MessageContext object describing the context of the supplied Part. * * @param part the containing part */ public MessageContext(Part part) { this.part = part; } /** * Return the {@link Part} that contains the content. * * @return the part */ public Part getPart() { return part; } /** * Return the message that contains the content; if the Part is a {@link Multipart} * then recurse up the chain until a {@link Message} is found. * * @return */ public Message getMessage() { return getMessageFrom(part); } /** * Return the session associated with the Message containing this Part. * * @return the session associated with this context's root message */ public Session getSession() { Message message = getMessage(); if (message == null) { return null; } else { return message.session; } } /** * recurse up the chain of MultiPart/BodyPart parts until we hit a message * * @param p The starting part. * * @return The encountered Message or null if no Message parts * are found. */ private Message getMessageFrom(Part p) { while (p != null) { if (p instanceof Message) { return (Message) p; } Multipart mp = ((BodyPart) p).getParent(); if (mp == null) { return null; } p = mp.getParent(); } return null; } }
983
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/FetchProfile.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.util.ArrayList; import java.util.List; /** * A FetchProfile defines a list of message attributes that a client wishes to prefetch * from the server during a fetch operation. * * Clients can either specify individual headers, or can reference common profiles * as defined by {@link FetchProfile.Item FetchProfile.Item}. * * @version $Rev$ $Date$ */ public class FetchProfile { /** * Inner class that defines sets of headers that are commonly bundled together * in a FetchProfile. */ public static class Item { /** * Item for fetching information about the content of the message. * * This includes all the headers about the content including but not limited to: * Content-Type, Content-Disposition, Content-Description, Size and Line-Count */ public static final Item CONTENT_INFO = new Item("CONTENT_INFO"); /** * Item for fetching information about the envelope of the message. * * This includes all the headers comprising the envelope including but not limited to: * From, To, Cc, Bcc, Reply-To, Subject and Date * * For IMAP4, this should also include the ENVELOPE data item. * */ public static final Item ENVELOPE = new Item("ENVELOPE"); /** * Item for fetching information about message flags. * Generall corresponds to the X-Flags header. */ public static final Item FLAGS = new Item("FLAGS"); protected Item(String name) { // hmmm, name is passed in but we are not allowed to provide accessors // or to override equals/hashCode so what use is it? } } // use Lists as we don't expect contains to be called often and the number of elements should be small private final List items = new ArrayList(); private final List headers = new ArrayList(); /** * Add a predefined profile of headers. * * @param item the profile to add */ public void add(Item item) { items.add(item); } /** * Add a specific header. * @param header the header whose value should be prefetched */ public void add(String header) { headers.add(header); } /** * Determine if the given profile item is already included. * @param item the profile to check for * @return true if the profile item is already included */ public boolean contains(Item item) { return items.contains(item); } /** * Determine if the specified header is already included. * @param header the header to check for * @return true if the header is already included */ public boolean contains(String header) { return headers.contains(header); } /** * Get the profile items already included. * @return the items already added to this profile */ public Item[] getItems() { return (Item[]) items.toArray(new Item[items.size()]); } /** Get the headers that have already been included. * @return the headers already added to this profile */ public String[] getHeaderNames() { return (String[]) headers.toArray(new String[headers.size()]); } }
984
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/MultipartDataSource.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import javax.activation.DataSource; /** * @version $Rev$ $Date$ */ public interface MultipartDataSource extends DataSource { public abstract BodyPart getBodyPart(int index) throws MessagingException; public abstract int getCount(); }
985
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/Provider.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class Provider { /** * A enumeration inner class that defines Provider types. */ public static class Type { /** * A message store provider such as POP3 or IMAP4. */ public static final Type STORE = new Type(); /** * A message transport provider such as SMTP. */ public static final Type TRANSPORT = new Type(); private Type() { } } private final String className; private final String protocol; private final Type type; private final String vendor; private final String version; public Provider(Type type, String protocol, String className, String vendor, String version) { this.protocol = protocol; this.className = className; this.type = type; this.vendor = vendor; this.version = version; } public String getClassName() { return className; } public String getProtocol() { return protocol; } public Type getType() { return type; } public String getVendor() { return vendor; } public String getVersion() { return version; } public String toString() { return "protocol=" + protocol + "; type=" + type + "; class=" + className + (vendor == null ? "" : "; vendor=" + vendor) + (version == null ? "" : ";version=" + version); } }
986
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/FolderClosedException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class FolderClosedException extends MessagingException { private static final long serialVersionUID = 1687879213433302315L; private transient Folder _folder; public FolderClosedException(Folder folder) { this(folder, "Folder Closed: " + folder.getName()); } public FolderClosedException(Folder folder, String message) { super(message); _folder = folder; } public Folder getFolder() { return _folder; } }
987
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/Part.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import javax.activation.DataHandler; /** * Note: Parts are used in Collections so implementing classes must provide * a suitable implementation of equals and hashCode. * * @version $Rev$ $Date$ */ public interface Part { /** * This part should be presented as an attachment. */ public static final String ATTACHMENT = "attachment"; /** * This part should be presented or rendered inline. */ public static final String INLINE = "inline"; /** * Add this value to the existing headers with the given name. This method * does not replace any headers that may already exist. * * @param name The name of the target header. * @param value The value to be added to the header set. * * @exception MessagingException */ public abstract void addHeader(String name, String value) throws MessagingException; /** * Return all headers as an Enumeration of Header objects. * * @return An Enumeration containing all of the current Header objects. * @exception MessagingException */ public abstract Enumeration getAllHeaders() throws MessagingException; /** * Return a content object for this Part. The * content object type is dependent upon the * DataHandler for the Part. * * @return A content object for this Part. * @exception IOException * @exception MessagingException */ public abstract Object getContent() throws IOException, MessagingException; /** * Get the ContentType for this part, or null if the * ContentType has not been set. The ContentType * is expressed using the MIME typing system. * * @return The ContentType for this part. * @exception MessagingException */ public abstract String getContentType() throws MessagingException; /** * Returns a DataHandler instance for the content * with in the Part. * * @return A DataHandler appropriate for the Part content. * @exception MessagingException */ public abstract DataHandler getDataHandler() throws MessagingException; /** * Returns a description string for this Part. Returns * null if a description has not been set. * * @return The description string. * @exception MessagingException */ public abstract String getDescription() throws MessagingException; /** * Return the disposition of the part. The disposition * determines how the part should be presented to the * user. Two common disposition values are ATTACHMENT * and INLINE. * * @return The current disposition value. * @exception MessagingException */ public abstract String getDisposition() throws MessagingException; /** * Get a file name associated with this part. The * file name is useful for presenting attachment * parts as their original source. The file names * are generally simple names without containing * any directory information. Returns null if the * filename has not been set. * * @return The string filename, if any. * @exception MessagingException */ public abstract String getFileName() throws MessagingException; /** * Get all Headers for this header name. Returns null if no headers with * the given name exist. * * @param name The target header name. * * @return An array of all matching header values, or null if the given header * does not exist. * @exception MessagingException */ public abstract String[] getHeader(String name) throws MessagingException; /** * Return an InputStream for accessing the Part * content. Any mail-related transfer encodings * will be removed, so the data presented with * be the actual part content. * * @return An InputStream for accessing the part content. * @exception IOException * @exception MessagingException */ public abstract InputStream getInputStream() throws IOException, MessagingException; /** * Return the number of lines in the content, or * -1 if the line count cannot be determined. * * @return The estimated number of lines in the content. * @exception MessagingException */ public abstract int getLineCount() throws MessagingException; /** * Return all headers that match the list of names as an Enumeration of * Header objects. * * @param names An array of names of the desired headers. * * @return An Enumeration of Header objects containing the matching headers. * @exception MessagingException */ public abstract Enumeration getMatchingHeaders(String[] names) throws MessagingException; /** * Return an Enumeration of all Headers except those that match the names * given in the exclusion list. * * @param names An array of String header names that will be excluded from the return * Enumeration set. * * @return An Enumeration of Headers containing all headers except for those named * in the exclusion list. * @exception MessagingException */ public abstract Enumeration getNonMatchingHeaders(String[] names) throws MessagingException; /** * Return the size of this part, or -1 if the size * cannot be reliably determined. * * Note: the returned size does not take into account * internal encodings, nor is it an estimate of * how many bytes are required to transfer this * part across a network. This value is intended * to give email clients a rough idea of the amount * of space that might be required to present the * item. * * @return The estimated part size, or -1 if the size * information cannot be determined. * @exception MessagingException */ public abstract int getSize() throws MessagingException; /** * Tests if the part is of the specified MIME type. * Only the primaryPart and subPart of the MIME * type are used for the comparison; arguments are * ignored. The wildcard value of "*" may be used * to match all subTypes. * * @param mimeType The target MIME type. * * @return true if the part matches the input MIME type, * false if it is not of the requested type. * @exception MessagingException */ public abstract boolean isMimeType(String mimeType) throws MessagingException; /** * Remove all headers with the given name from the Part. * * @param name The target header name used for removal. * * @exception MessagingException */ public abstract void removeHeader(String name) throws MessagingException; public abstract void setContent(Multipart content) throws MessagingException; /** * Set a content object for this part. Internally, * the Part will use the MIME type encoded in the * type argument to wrap the provided content object. * In order for this to work properly, an appropriate * DataHandler must be installed in the Java Activation * Framework. * * @param content The content object. * @param type The MIME type for the inserted content Object. * * @exception MessagingException */ public abstract void setContent(Object content, String type) throws MessagingException; /** * Set a DataHandler for this part that defines the * Part content. The DataHandler is used to access * all Part content. * * @param handler The DataHandler instance. * * @exception MessagingException */ public abstract void setDataHandler(DataHandler handler) throws MessagingException; /** * Set a descriptive string for this part. * * @param description * The new description. * * @exception MessagingException */ public abstract void setDescription(String description) throws MessagingException; /** * Set the disposition for this Part. * * @param disposition * The disposition string. * * @exception MessagingException */ public abstract void setDisposition(String disposition) throws MessagingException; /** * Set a descriptive file name for this part. The * name should be a simple name that does not include * directory information. * * @param name The new name value. * * @exception MessagingException */ public abstract void setFileName(String name) throws MessagingException; /** * Sets a value for the given header. This operation will replace all * existing headers with the given name. * * @param name The name of the target header. * @param value The new value for the indicated header. * * @exception MessagingException */ public abstract void setHeader(String name, String value) throws MessagingException; /** * Set the Part content as text. This is a convenience method that sets * the content to a MIME type of "text/plain". * * @param content The new text content, as a String object. * * @exception MessagingException */ public abstract void setText(String content) throws MessagingException; /** * Write the Part content out to the provided OutputStream as a byte * stream using an encoding appropriate to the Part content. * * @param out The target OutputStream. * * @exception IOException * @exception MessagingException */ public abstract void writeTo(OutputStream out) throws IOException, MessagingException; }
988
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/Transport.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import javax.mail.event.TransportEvent; import javax.mail.event.TransportListener; /** * Abstract class modeling a message transport. * * @version $Rev$ $Date$ */ public abstract class Transport extends Service { /** * Send a message to all recipient addresses the message contains (as returned by {@link Message#getAllRecipients()}) * using message transports appropriate for each address. Message addresses are checked during submission, * but there is no guarantee that the ultimate address is valid or that the message will ever be delivered. * <p/> * {@link Message#saveChanges()} will be called before the message is actually sent. * * @param message the message to send * @throws MessagingException if there was a problem sending the message */ public static void send(Message message) throws MessagingException { send(message, message.getAllRecipients()); } /** * Send a message to all addresses provided irrespective of any recipients contained in the message, * using message transports appropriate for each address. Message addresses are checked during submission, * but there is no guarantee that the ultimate address is valid or that the message will ever be delivered. * <p/> * {@link Message#saveChanges()} will be called before the message is actually sent. * * @param message the message to send * @param addresses the addesses to send to * @throws MessagingException if there was a problem sending the message */ public static void send(Message message, Address[] addresses) throws MessagingException { Session session = message.session; Map msgsByTransport = new HashMap(); for (int i = 0; i < addresses.length; i++) { Address address = addresses[i]; Transport transport = session.getTransport(address); List addrs = (List) msgsByTransport.get(transport); if (addrs == null) { addrs = new ArrayList(); msgsByTransport.put(transport, addrs); } addrs.add(address); } message.saveChanges(); // Since we might be sending to multiple protocols, we need to catch and process each exception // when we send and then throw a new SendFailedException when everything is done. Unfortunately, this // also means unwrapping the information in any SendFailedExceptions we receive and building // composite failed list. MessagingException chainedException = null; ArrayList sentAddresses = new ArrayList(); ArrayList unsentAddresses = new ArrayList(); ArrayList invalidAddresses = new ArrayList(); for (Iterator i = msgsByTransport.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); Transport transport = (Transport) entry.getKey(); List addrs = (List) entry.getValue(); try { // we MUST connect to the transport before attempting to send. transport.connect(); transport.sendMessage(message, (Address[]) addrs.toArray(new Address[addrs.size()])); // if we have to throw an exception because of another failure, these addresses need to // be in the valid list. Since we succeeded here, we can add these now. sentAddresses.addAll(addrs); } catch (SendFailedException e) { // a true send failure. The exception contains a wealth of information about // the failures, including a potential chain of exceptions explaining what went wrong. We're // going to send a new one of these, so we need to merge the information. // add this to our exception chain if (chainedException == null) { chainedException = e; } else { chainedException.setNextException(e); } // now extract each of the address categories from Address[] exAddrs = e.getValidSentAddresses(); if (exAddrs != null) { for (int j = 0; j < exAddrs.length; j++) { sentAddresses.add(exAddrs[j]); } } exAddrs = e.getValidUnsentAddresses(); if (exAddrs != null) { for (int j = 0; j < exAddrs.length; j++) { unsentAddresses.add(exAddrs[j]); } } exAddrs = e.getInvalidAddresses(); if (exAddrs != null) { for (int j = 0; j < exAddrs.length; j++) { invalidAddresses.add(exAddrs[j]); } } } catch (MessagingException e) { // add this to our exception chain if (chainedException == null) { chainedException = e; } else { chainedException.setNextException(e); } } finally { transport.close(); } } // if we have an exception chain then we need to throw a new exception giving the failure // information. if (chainedException != null) { // if we're only sending to a single transport (common), and we received a SendFailedException // as a result, then we have a fully formed exception already. Rather than wrap this in another // exception, we can just rethrow the one we have. if (msgsByTransport.size() == 1 && chainedException instanceof SendFailedException) { throw chainedException; } // create our lists for notification and exception reporting from this point on. Address[] sent = (Address[])sentAddresses.toArray(new Address[0]); Address[] unsent = (Address[])unsentAddresses.toArray(new Address[0]); Address[] invalid = (Address[])invalidAddresses.toArray(new Address[0]); throw new SendFailedException("Send failure", chainedException, sent, unsent, invalid); } } /** * Constructor taking Session and URLName parameters required for {@link Service#Service(Session, URLName)}. * * @param session the Session this transport is for * @param name the location this transport is for */ public Transport(Session session, URLName name) { super(session, name); } /** * Send a message to the supplied addresses using this transport; if any of the addresses are * invalid then a {@link SendFailedException} is thrown. Whether the message is actually sent * to any of the addresses is undefined. * <p/> * Unlike the static {@link #send(Message, Address[])} method, {@link Message#saveChanges()} is * not called. A {@link TransportEvent} will be sent to registered listeners once the delivery * attempt has been made. * * @param message the message to send * @param addresses list of addresses to send it to * @throws SendFailedException if the send failed * @throws MessagingException if there was a problem sending the message */ public abstract void sendMessage(Message message, Address[] addresses) throws MessagingException; private Vector transportListeners = new Vector(); public void addTransportListener(TransportListener listener) { transportListeners.add(listener); } public void removeTransportListener(TransportListener listener) { transportListeners.remove(listener); } protected void notifyTransportListeners(int type, Address[] validSent, Address[] validUnsent, Address[] invalid, Message message) { queueEvent(new TransportEvent(this, type, validSent, validUnsent, invalid, message), transportListeners); } }
989
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/SendFailedException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class SendFailedException extends MessagingException { private static final long serialVersionUID = -6457531621682372913L; protected transient Address invalid[]; protected transient Address validSent[]; protected transient Address validUnsent[]; public SendFailedException() { super(); } public SendFailedException(String message) { super(message); } public SendFailedException(String message, Exception cause) { super(message, cause); } public SendFailedException(String message, Exception cause, Address[] validSent, Address[] validUnsent, Address[] invalid) { this(message, cause); this.invalid = invalid; this.validSent = validSent; this.validUnsent = validUnsent; } public Address[] getValidSentAddresses() { return validSent; } public Address[] getValidUnsentAddresses() { return validUnsent; } public Address[] getInvalidAddresses() { return invalid; } }
990
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/EventQueue.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // // This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.mail; import java.util.LinkedList; import java.util.List; import javax.mail.event.MailEvent; /** * This is an event queue to dispatch javamail events on separate threads * from the main thread. EventQueues are created by javamail Services * (Transport and Store instances), as well as Folders created from Store * instances. Each entity will have its own private EventQueue instance, but * will delay creating it until it has an event to dispatch to a real listener. * * NOTE: It would be nice to use the concurrency support in Java 5 to * manage the queue, but this code needs to run on Java 1.4 still. We also * don't want to have dependencies on other packages with this, so no * outside concurrency packages can be used either. * @version $Rev$ $Date$ */ class EventQueue implements Runnable { /** * The dispatch thread that handles notification events. */ protected Thread dispatchThread; /** * The dispatching queue for events. */ protected List eventQueue = new LinkedList(); /** * Create a new EventQueue, including starting the new thread. */ public EventQueue() { dispatchThread = new Thread(this, "JavaMail-EventQueue"); dispatchThread.setDaemon(true); // this is a background server thread. // start the thread up dispatchThread.start(); } /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public void run() { try { while (true) { // get the next event PendingEvent p = dequeueEvent(); // an empty event on the queue means time to shut things down. if (p.event == null) { return; } // and tap the listeners on the shoulder. dispatchEvent(p.event, p.listeners); } } catch (InterruptedException e) { // been told to stop, so we stop } } /** * Stop the EventQueue. This will terminate the dispatcher thread as soon * as it can, so there may be undispatched events in the queue that will * not get dispatched. */ public synchronized void stop() { // if the thread has not been stopped yet, interrupt it // and clear the reference. if (dispatchThread != null) { // push a dummy marker on to the event queue // to force the dispatch thread to wake up. queueEvent(null, null); dispatchThread = null; } } /** * Add a new event to the queue. * * @param event The event to dispatch. * @param listeners The List of listeners to dispatch this to. This is assumed to be a * static snapshot of the listeners that will not change between the time * the event is queued and the dispatcher thread makes the calls to the * handlers. */ public synchronized void queueEvent(MailEvent event, List listeners) { // add an element to the list, then notify the processing thread. // Note that we make a copy of the listeners list. This ensures // we're going to dispatch this to the snapshot of the listeners PendingEvent p = new PendingEvent(event, listeners); eventQueue.add(p); // wake up the dispatch thread notify(); } /** * Remove the next event from the message queue. * * @return The PendingEvent item from the queue. */ protected synchronized PendingEvent dequeueEvent() throws InterruptedException { // a little spin loop to wait for an event while (eventQueue.isEmpty()) { wait(); } // just remove the first element of this return (PendingEvent)eventQueue.remove(0); } /** * Dispatch an event to a list of listeners. Any exceptions thrown by * the listeners will be swallowed. * * @param event The event to dispatch. * @param listeners The list of listeners this gets dispatched to. */ protected void dispatchEvent(MailEvent event, List listeners) { // iterate through the listeners list calling the handlers. for (int i = 0; i < listeners.size(); i++) { try { event.dispatch(listeners.get(i)); } catch (Throwable e) { // just eat these } } } /** * Small helper class to give a single reference handle for a pending event. */ class PendingEvent { // the event we're broadcasting MailEvent event; // the list of listeners we send this to. List listeners; PendingEvent(MailEvent event, List listeners) { this.event = event; this.listeners = listeners; } } }
991
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/Address.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.io.Serializable; /** * This abstract class models the addresses in a message. * Addresses are Serializable so that they may be serialized along with other search terms. * * @version $Rev$ $Date$ */ public abstract class Address implements Serializable { private static final long serialVersionUID = -5822459626751992278L; /** * Subclasses must provide a suitable implementation of equals(). * * @param object the object to compare t * @return true if the subclass determines the other object is equal to this Address */ public abstract boolean equals(Object object); /** * Return a String that identifies this address type. * @return the type of this address */ public abstract String getType(); /** * Subclasses must provide a suitable representation of their address. * @return a representation of an Address as a String */ public abstract String toString(); }
992
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/URLName.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.io.ByteArrayOutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; /** * @version $Rev$ $Date$ */ public class URLName { private static final String nonEncodedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-.*"; private String file; private String host; private String password; private int port; private String protocol; private String ref; private String username; protected String fullURL; private int hashCode; public URLName(String url) { parseString(url); } protected void parseString(String url) { URI uri; try { if (url == null) { uri = null; } else { uri = new URI(url); } } catch (URISyntaxException e) { uri = null; } if (uri == null) { protocol = null; host = null; port = -1; file = null; ref = null; username = null; password = null; return; } protocol = checkBlank(uri.getScheme()); host = checkBlank(uri.getHost()); port = uri.getPort(); file = checkBlank(uri.getPath()); // if the file starts with "/", we need to strip that off. // URL and URLName do not have the same behavior when it comes // to keeping that there. if (file != null && file.length() > 1 && file.startsWith("/")) { file = checkBlank(file.substring(1)); } ref = checkBlank(uri.getFragment()); String userInfo = checkBlank(uri.getUserInfo()); if (userInfo == null) { username = null; password = null; } else { int pos = userInfo.indexOf(':'); if (pos == -1) { username = userInfo; password = null; } else { username = userInfo.substring(0, pos); password = userInfo.substring(pos + 1); } } updateFullURL(); } public URLName(String protocol, String host, int port, String file, String username, String password) { this.protocol = checkBlank(protocol); this.host = checkBlank(host); this.port = port; if (file == null || file.length() == 0) { this.file = null; ref = null; } else { int pos = file.indexOf('#'); if (pos == -1) { this.file = file; ref = null; } else { this.file = file.substring(0, pos); ref = file.substring(pos + 1); } } this.username = checkBlank(username); if (this.username != null) { this.password = checkBlank(password); } else { this.password = null; } username = encode(username); password = encode(password); updateFullURL(); } public URLName(URL url) { protocol = checkBlank(url.getProtocol()); host = checkBlank(url.getHost()); port = url.getPort(); file = checkBlank(url.getFile()); ref = checkBlank(url.getRef()); String userInfo = checkBlank(url.getUserInfo()); if (userInfo == null) { username = null; password = null; } else { int pos = userInfo.indexOf(':'); if (pos == -1) { username = userInfo; password = null; } else { username = userInfo.substring(0, pos); password = userInfo.substring(pos + 1); } } updateFullURL(); } private static String checkBlank(String target) { if (target == null || target.length() == 0) { return null; } else { return target; } } private void updateFullURL() { hashCode = 0; StringBuffer buf = new StringBuffer(100); if (protocol != null) { buf.append(protocol).append(':'); if (host != null) { buf.append("//"); if (username != null) { buf.append(encode(username)); if (password != null) { buf.append(':').append(encode(password)); } buf.append('@'); } buf.append(host); if (port != -1) { buf.append(':').append(port); } if (file != null) { buf.append('/').append(file); } hashCode = buf.toString().hashCode(); if (ref != null) { buf.append('#').append(ref); } } } fullURL = buf.toString(); } public boolean equals(Object o) { if (o instanceof URLName == false) { return false; } URLName other = (URLName) o; // check same protocol - false if either is null if (protocol == null || other.protocol == null || !protocol.equals(other.protocol)) { return false; } if (port != other.port) { return false; } // check host - false if not (both null or both equal) return areSame(host, other.host) && areSame(file, other.file) && areSame(username, other.username) && areSame(password, other.password); } private static boolean areSame(String s1, String s2) { if (s1 == null) { return s2 == null; } else { return s1.equals(s2); } } public int hashCode() { return hashCode; } public String toString() { return fullURL; } public String getFile() { return file; } public String getHost() { return host; } public String getPassword() { return password; } public int getPort() { return port; } public String getProtocol() { return protocol; } public String getRef() { return ref; } public URL getURL() throws MalformedURLException { return new URL(fullURL); } public String getUsername() { return username; } /** * Perform an HTTP encoding to the username and * password elements of the URLName. * * @param v The input (uncoded) string. * * @return The HTTP encoded version of the string. */ private static String encode(String v) { // make sure we don't operate on a null string if (v == null) { return null; } boolean needsEncoding = false; for (int i = 0; i < v.length(); i++) { // not in the list of things that don't need encoding? if (nonEncodedChars.indexOf(v.charAt(i)) == -1) { // got to do this the hard way needsEncoding = true; break; } } // just fine the way it is. if (!needsEncoding) { return v; } // we know we're going to be larger, but not sure by how much. // just give a little extra StringBuffer encoded = new StringBuffer(v.length() + 10); // we get the bytes so that we can have the default encoding applied to // this string. This will flag the ones we need to give special processing to. byte[] data = v.getBytes(); for (int i = 0; i < data.length; i++) { // pick this up as a one-byte character The 7-bit ascii ones will be fine // here. char ch = (char)(data[i] & 0xff); // blanks get special treatment if (ch == ' ') { encoded.append('+'); } // not in the list of things that don't need encoding? else if (nonEncodedChars.indexOf(ch) == -1) { // forDigit() uses the lowercase letters for the radix. The HTML specifications // require the uppercase letters. char firstChar = Character.toUpperCase(Character.forDigit((ch >> 4) & 0xf, 16)); char secondChar = Character.toUpperCase(Character.forDigit(ch & 0xf, 16)); // now append the encoded triplet. encoded.append('%'); encoded.append(firstChar); encoded.append(secondChar); } else { // just add this one to the buffer encoded.append(ch); } } // convert to string form. return encoded.toString(); } }
993
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/MethodNotSupportedException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class MethodNotSupportedException extends MessagingException { private static final long serialVersionUID = -3757386618726131322L; public MethodNotSupportedException() { super(); } public MethodNotSupportedException(String message) { super(message); } }
994
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/Service.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.Vector; import javax.mail.event.ConnectionEvent; import javax.mail.event.ConnectionListener; import javax.mail.event.MailEvent; /** * @version $Rev$ $Date$ */ public abstract class Service { /** * The session from which this service was created. */ protected Session session; /** * The URLName of this service */ protected URLName url; /** * Debug flag for this service, set from the Session's debug flag. */ protected boolean debug; private boolean connected; private final Vector connectionListeners = new Vector(2); // the EventQueue spins off a new thread, so we only create this // if we have actual listeners to dispatch an event to. private EventQueue queue = null; // when returning the URL, we need to ensure that the password and file information is // stripped out. private URLName exposedUrl; /** * Construct a new Service. * @param session the session from which this service was created * @param url the URLName of this service */ protected Service(Session session, URLName url) { this.session = session; this.url = url; this.debug = session.getDebug(); } /** * A generic connect method that takes no parameters allowing subclasses * to implement an appropriate authentication scheme. * The default implementation calls <code>connect(null, null, null)</code> * @throws AuthenticationFailedException if authentication fails * @throws MessagingException for other failures */ public void connect() throws MessagingException { connect(null, null, null); } /** * Connect to the specified host using a simple username/password authenticaion scheme * and the default port. * The default implementation calls <code>connect(host, -1, user, password)</code> * * @param host the host to connect to * @param user the user name * @param password the user's password * @throws AuthenticationFailedException if authentication fails * @throws MessagingException for other failures */ public void connect(String host, String user, String password) throws MessagingException { connect(host, -1, user, password); } /** * Connect to the specified host using a simple username/password authenticaion scheme * and the default host and port. * The default implementation calls <code>connect(host, -1, user, password)</code> * * @param user the user name * @param password the user's password * @throws AuthenticationFailedException if authentication fails * @throws MessagingException for other failures */ public void connect(String user, String password) throws MessagingException { connect(null, -1, user, password); } /** * Connect to the specified host at the specified port using a simple username/password authenticaion scheme. * * If this Service is already connected, an IllegalStateException is thrown. * * @param host the host to connect to * @param port the port to connect to; pass -1 to use the default for the protocol * @param user the user name * @param password the user's password * @throws AuthenticationFailedException if authentication fails * @throws MessagingException for other failures * @throws IllegalStateException if this service is already connected */ public void connect(String host, int port, String user, String password) throws MessagingException { if (isConnected()) { throw new IllegalStateException("Already connected"); } // before we try to connect, we need to derive values for some parameters that may not have // been explicitly specified. For example, the normal connect() method leaves us to derive all // of these from other sources. Some of the values are derived from our URLName value, others // from session parameters. We need to go through all of these to develop a set of values we // can connect with. // this is the protocol we're connecting with. We use this largely to derive configured values from // session properties. String protocol = null; // if we're working with the URL form, then we can retrieve the protocol from the URL. if (url != null) { protocol = url.getProtocol(); } // if the port is -1, see if we have an override from url. if (port == -1) { if (protocol != null) { port = url.getPort(); } } // now try to derive values for any of the arguments we've been given as defaults if (host == null) { // first choice is from the url, if we have if (url != null) { host = url.getHost(); // it is possible that this could return null (rare). If it does, try to get a // value from a protocol specific session variable. if (host == null) { if (protocol != null) { host = session.getProperty("mail." + protocol + ".host"); } } } // this may still be null...get the global mail property if (host == null) { host = session.getProperty("mail.host"); } } // ok, go after userid information next. if (user == null) { // first choice is from the url, if we have if (url != null) { user = url.getUsername(); // make sure we get the password from the url, if we can. if (password == null) { password = url.getPassword(); } } // user still null? We have several levels of properties to try yet if (user == null) { if (protocol != null) { user = session.getProperty("mail." + protocol + ".user"); } // this may still be null...get the global mail property if (user == null) { user = session.getProperty("mail.user"); // still null, try using the user.name system property if (user == null) { // finally, we try getting the system defined user name try { user = System.getProperty("user.name"); } catch (SecurityException e) { // we ignore this, and just us a null username. } } } } } // if we have an explicitly given user name, we need to see if this matches the url one and // grab the password from there. else { if (url != null && user.equals(url.getUsername())) { password = url.getPassword(); } } // we need to update the URLName associated with this connection once we have all of the information, // which means we also need to propogate the file portion of the URLName if we have this form when // we start. String file = null; if (url != null) { file = url.getFile(); } // see if we have cached security information to use. If this is not cached, we'll save it // after we successfully connect. boolean cachePassword = false; // still have a null password to this point, and using a url form? if (password == null && url != null) { // construct a new URL, filling in any pieces that may have been explicitly specified. setURLName(new URLName(protocol, host, port, file, user, password)); // now see if we have a saved password from a previous request. PasswordAuthentication cachedPassword = session.getPasswordAuthentication(getURLName()); // if we found a saved one, see if we need to get any the pieces from here. if (cachedPassword != null) { // not even a resolved userid? Then use both bits. if (user == null) { user = cachedPassword.getUserName(); password = cachedPassword.getPassword(); } // our user name must match the cached name to be valid. else if (user.equals(cachedPassword.getUserName())) { password = cachedPassword.getPassword(); } } else { // nothing found in the cache, so we need to save this if we can connect successfully. cachePassword = true; } } // we've done our best up to this point to obtain all of the information needed to make the // connection. Now we pass this off to the protocol handler to see if it works. If we get a // connection failure, we may need to prompt for a password before continuing. try { connected = protocolConnect(host, port, user, password); } catch (AuthenticationFailedException e) { } if (!connected) { InetAddress ipAddress = null; try { ipAddress = InetAddress.getByName(host); } catch (UnknownHostException e) { } // now ask the session to try prompting for a password. PasswordAuthentication promptPassword = session.requestPasswordAuthentication(ipAddress, port, protocol, null, user); // if we were able to obtain new information from the session, then try again using the // provided information . if (promptPassword != null) { user = promptPassword.getUserName(); password = promptPassword.getPassword(); } connected = protocolConnect(host, port, user, password); } // if we're still not connected, then this is an exception. if (!connected) { throw new AuthenticationFailedException(); } // the URL name needs to reflect the most recent information. setURLName(new URLName(protocol, host, port, file, user, password)); // we need to update the global password cache with this information. if (cachePassword) { session.setPasswordAuthentication(getURLName(), new PasswordAuthentication(user, password)); } // we're now connected....broadcast this to any interested parties. setConnected(connected); notifyConnectionListeners(ConnectionEvent.OPENED); } /** * Attempt the protocol-specific connection; subclasses should override this to establish * a connection in the appropriate manner. * * This method should return true if the connection was established. * It may return false to cause the {@link #connect(String, int, String, String)} method to * reattempt the connection after trying to obtain user and password information from the user. * Alternatively it may throw a AuthenticatedFailedException to abandon the conection attempt. * * @param host The target host name of the service. * @param port The connection port for the service. * @param user The user name used for the connection. * @param password The password used for the connection. * * @return true if a connection was established, false if there was authentication * error with the connection. * @throws AuthenticationFailedException * if authentication fails * @throws MessagingException * for other failures */ protected boolean protocolConnect(String host, int port, String user, String password) throws MessagingException { return false; } /** * Check if this service is currently connected. * The default implementation simply returns the value of a private boolean field; * subclasses may wish to override this method to verify the physical connection. * * @return true if this service is connected */ public boolean isConnected() { return connected; } /** * Notification to subclasses that the connection state has changed. * This method is called by the connect() and close() methods to indicate state change; * subclasses should also call this method if the connection is automatically closed * for some reason. * * @param connected the connection state */ protected void setConnected(boolean connected) { this.connected = connected; } /** * Close this service and terminate its physical connection. * The default implementation simply calls setConnected(false) and then * sends a CLOSED event to all registered ConnectionListeners. * Subclasses overriding this method should still ensure it is closed; they should * also ensure that it is called if the connection is closed automatically, for * for example in a finalizer. * *@throws MessagingException if there were errors closing; the connection is still closed */ public void close() throws MessagingException { setConnected(false); notifyConnectionListeners(ConnectionEvent.CLOSED); } /** * Return a copy of the URLName representing this service with the password and file information removed. * * @return the URLName for this service */ public URLName getURLName() { // if we haven't composed the URL version we hand out, create it now. But only if we really // have a URL. if (exposedUrl == null) { if (url != null) { exposedUrl = new URLName(url.getProtocol(), url.getHost(), url.getPort(), null, url.getUsername(), null); } } return exposedUrl; } /** * Set the url field. * @param url the new value */ protected void setURLName(URLName url) { this.url = url; } 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 String toString() { // NOTE: We call getURLName() rather than use the URL directly // because the get method strips out the password information. URLName url = getURLName(); return url == null ? super.toString() : url.toString(); } protected void queueEvent(MailEvent event, Vector listeners) { // if there are no listeners to dispatch this to, don't put it on the queue. // This allows us to delay creating the queue (and its new thread) until // we if (listeners.isEmpty()) { return; } // first real event? Time to get the queue kicked off. if (queue == null) { queue = new EventQueue(); } // tee it up and let it rip. queue.queueEvent(event, (List)listeners.clone()); } protected void finalize() throws Throwable { // stop our event queue if we had to create one if (queue != null) { queue.stop(); } connectionListeners.clear(); super.finalize(); } /** * Package scope utility method to allow Message instances * access to the Service's session. * * @return The Session the service is associated with. */ Session getSession() { return session; } }
995
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/Authenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; import java.net.InetAddress; /** * @version $Rev$ $Date$ */ public abstract class Authenticator { private InetAddress host; private int port; private String prompt; private String protocol; private String username; synchronized PasswordAuthentication authenticate(InetAddress host, int port, String protocol, String prompt, String username) { this.host = host; this.port = port; this.protocol = protocol; this.prompt = prompt; this.username = username; return getPasswordAuthentication(); } protected final String getDefaultUserName() { return username; } protected PasswordAuthentication getPasswordAuthentication() { return null; } protected final int getRequestingPort() { return port; } protected final String getRequestingPrompt() { return prompt; } protected final String getRequestingProtocol() { return protocol; } protected final InetAddress getRequestingSite() { return host; } }
996
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/QuotaAwareStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * An interface for Store implementations to support the IMAP RFC 2087 Quota extension. * * @version $Rev$ $Date$ */ public interface QuotaAwareStore { /** * Get the quotas for the specified root element. * * @param root The root name for the quota information. * * @return An array of Quota objects defined for the root. * @throws MessagingException if the quotas cannot be retrieved */ public Quota[] getQuota(String root) throws javax.mail.MessagingException; /** * Set a quota item. The root contained in the Quota item identifies * the quota target. * * @param quota The source quota item. * @throws MessagingException if the quota cannot be set */ public void setQuota(Quota quota) throws javax.mail.MessagingException; }
997
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/IllegalWriteException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class IllegalWriteException extends MessagingException { private static final long serialVersionUID = 3974370223328268013L; public IllegalWriteException() { super(); } public IllegalWriteException(String message) { super(message); } }
998
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/FolderNotFoundException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public class FolderNotFoundException extends MessagingException { private static final long serialVersionUID = 472612108891249403L; private transient Folder _folder; public FolderNotFoundException() { super(); } public FolderNotFoundException(Folder folder) { this(folder, "Folder not found: " + folder.getName()); } public FolderNotFoundException(Folder folder, String message) { super(message); _folder = folder; } public FolderNotFoundException(String message, Folder folder) { this(folder, message); } public Folder getFolder() { return _folder; } }
999