index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/InternetAddress.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.mail.Address;
import javax.mail.Session;
/**
* A representation of an Internet email address as specified by RFC822 in
* conjunction with a human-readable personal name that can be encoded as
* specified by RFC2047.
* A typical address is "user@host.domain" and personal name "Joe User"
*
* @version $Rev$ $Date$
*/
public class InternetAddress extends Address implements Cloneable {
private static final long serialVersionUID = -7507595530758302903L;
/**
* The address in RFC822 format.
*/
protected String address;
/**
* The personal name in RFC2047 format.
* Subclasses must ensure that this field is updated if the personal field
* is updated; alternatively, it can be invalidated by setting to null
* which will cause it to be recomputed.
*/
protected String encodedPersonal;
/**
* The personal name as a Java String.
* Subclasses must ensure that this field is updated if the encodedPersonal field
* is updated; alternatively, it can be invalidated by setting to null
* which will cause it to be recomputed.
*/
protected String personal;
public InternetAddress() {
}
public InternetAddress(final String address) throws AddressException {
this(address, true);
}
public InternetAddress(final String address, final boolean strict) throws AddressException {
// use the parse method to process the address. This has the wierd side effect of creating a new
// InternetAddress instance to create an InternetAddress, but these are lightweight objects and
// we need access to multiple pieces of data from the parsing process.
final AddressParser parser = new AddressParser(address, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
final InternetAddress parsedAddress = parser.parseAddress();
// copy the important information, which right now is just the address and
// personal info.
this.address = parsedAddress.address;
this.personal = parsedAddress.personal;
this.encodedPersonal = parsedAddress.encodedPersonal;
}
public InternetAddress(final String address, final String personal) throws UnsupportedEncodingException {
this(address, personal, null);
}
public InternetAddress(final String address, final String personal, final String charset) throws UnsupportedEncodingException {
this.address = address;
setPersonal(personal, charset);
}
/**
* Clone this object.
*
* @return a copy of this object as created by Object.clone()
*/
@Override
public Object clone() {
try {
return super.clone();
} catch (final CloneNotSupportedException e) {
throw new Error();
}
}
/**
* Return the type of this address.
*
* @return the type of this address; always "rfc822"
*/
@Override
public String getType() {
return "rfc822";
}
/**
* Set the address.
* No validation is performed; validate() can be used to check if it is valid.
*
* @param address the address to set
*/
public void setAddress(final String address) {
this.address = address;
}
/**
* Set the personal name.
* The name is first checked to see if it can be encoded; if this fails then an
* UnsupportedEncodingException is thrown and no fields are modified.
*
* @param name the new personal name
* @param charset the charset to use; see {@link MimeUtility#encodeWord(String, String, String) MimeUtilityencodeWord}
* @throws UnsupportedEncodingException if the name cannot be encoded
*/
public void setPersonal(final String name, final String charset) throws UnsupportedEncodingException {
personal = name;
if (name != null) {
encodedPersonal = MimeUtility.encodeWord(name, charset, null);
}
else {
encodedPersonal = null;
}
}
/**
* Set the personal name.
* The name is first checked to see if it can be encoded using {@link MimeUtility#encodeWord(String)}; if this fails then an
* UnsupportedEncodingException is thrown and no fields are modified.
*
* @param name the new personal name
* @throws UnsupportedEncodingException if the name cannot be encoded
*/
public void setPersonal(final String name) throws UnsupportedEncodingException {
personal = name;
if (name != null) {
encodedPersonal = MimeUtility.encodeWord(name);
}
else {
encodedPersonal = null;
}
}
/**
* Return the address.
*
* @return the address
*/
public String getAddress() {
return address;
}
/**
* Return the personal name.
* If the personal field is null, then an attempt is made to decode the encodedPersonal
* field using {@link MimeUtility#decodeWord(String)}; if this is sucessful, then
* the personal field is updated with that value and returned; if there is a problem
* decoding the text then the raw value from encodedPersonal is returned.
*
* @return the personal name
*/
public String getPersonal() {
if (personal == null && encodedPersonal != null) {
try {
personal = MimeUtility.decodeWord(encodedPersonal);
} catch (final ParseException e) {
return encodedPersonal;
} catch (final UnsupportedEncodingException e) {
return encodedPersonal;
}
}
return personal;
}
/**
* Return the encoded form of the personal name.
* If the encodedPersonal field is null, then an attempt is made to encode the
* personal field using {@link MimeUtility#encodeWord(String)}; if this is
* successful then the encodedPersonal field is updated with that value and returned;
* if there is a problem encoding the text then null is returned.
*
* @return the encoded form of the personal name
*/
private String getEncodedPersonal() {
if (encodedPersonal == null && personal != null) {
try {
encodedPersonal = MimeUtility.encodeWord(personal);
} catch (final UnsupportedEncodingException e) {
// as we could not encode this, return null
return null;
}
}
return encodedPersonal;
}
/**
* Return a string representation of this address using only US-ASCII characters.
*
* @return a string representation of this address
*/
@Override
public String toString() {
// group addresses are always returned without modification.
if (isGroup()) {
return address;
}
// if we have personal information, then we need to return this in the route-addr form:
// "personal <address>". If there is no personal information, then we typically return
// the address without the angle brackets. However, if the address contains anything other
// than atoms, '@', and '.' (e.g., uses domain literals, has specified routes, or uses
// quoted strings in the local-part), we bracket the address.
final String p = getEncodedPersonal();
if (p == null) {
return formatAddress(address);
}
else {
final StringBuffer buf = new StringBuffer(p.length() + 8 + address.length() + 3);
buf.append(AddressParser.quoteString(p));
buf.append(" <").append(address).append(">");
return buf.toString();
}
}
/**
* Check the form of an address, and enclose it within brackets
* if they are required for this address form.
*
* @param a The source address.
*
* @return A formatted address, which can be the original address string.
*/
private String formatAddress(final String a)
{
// this could be a group address....we don't muck with those.
if (address.endsWith(";") && address.indexOf(":") > 0) {
return address;
}
if (AddressParser.containsCharacters(a, "()<>,;:\"[]")) {
final StringBuffer buf = new StringBuffer(address.length() + 3);
buf.append("<").append(address).append(">");
return buf.toString();
}
return address;
}
/**
* Return a string representation of this address using Unicode characters.
*
* @return a string representation of this address
*/
public String toUnicodeString() {
// group addresses are always returned without modification.
if (isGroup()) {
return address;
}
// if we have personal information, then we need to return this in the route-addr form:
// "personal <address>". If there is no personal information, then we typically return
// the address without the angle brackets. However, if the address contains anything other
// than atoms, '@', and '.' (e.g., uses domain literals, has specified routes, or uses
// quoted strings in the local-part), we bracket the address.
// NB: The difference between toString() and toUnicodeString() is the use of getPersonal()
// vs. getEncodedPersonal() for the personal portion. If the personal information contains only
// ASCII-7 characters, these are the same.
final String p = getPersonal();
if (p == null) {
return formatAddress(address);
}
else {
final StringBuffer buf = new StringBuffer(p.length() + 8 + address.length() + 3);
buf.append(AddressParser.quoteString(p));
buf.append(" <").append(address).append(">");
return buf.toString();
}
}
/**
* Compares two addresses for equality.
* We define this as true if the other object is an InternetAddress
* and the two values returned by getAddress() are equal in a
* case-insensitive comparison.
*
* @param o the other object
* @return true if the addresses are the same
*/
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof InternetAddress)) {
return false;
}
final InternetAddress other = (InternetAddress) o;
final String myAddress = getAddress();
return myAddress == null ? (other.getAddress() == null) : myAddress.equalsIgnoreCase(other.getAddress());
}
/**
* Return the hashCode for this address.
* We define this to be the hashCode of the address after conversion to lowercase.
*
* @return a hashCode for this address
*/
@Override
public int hashCode() {
return (address == null) ? 0 : address.toLowerCase().hashCode();
}
/**
* Return true is this address is an RFC822 group address in the format
* <code>phrase ":" [#mailbox] ";"</code>.
* We check this by using the presense of a ':' character in the address, and a
* ';' as the very last character.
*
* @return true is this address represents a group
*/
public boolean isGroup() {
if (address == null) {
return false;
}
return address.endsWith(";") && address.indexOf(":") > 0;
}
/**
* Return the members of a group address.
*
* If strict is true and the address does not contain an initial phrase then an AddressException is thrown.
* Otherwise the phrase is skipped and the remainder of the address is checked to see if it is a group.
* If it is, the content and strict flag are passed to parseHeader to extract the list of addresses;
* if it is not a group then null is returned.
*
* @param strict whether strict RFC822 checking should be performed
* @return an array of InternetAddress objects for the group members, or null if this address is not a group
* @throws AddressException if there was a problem parsing the header
*/
public InternetAddress[] getGroup(final boolean strict) throws AddressException {
if (address == null) {
return null;
}
// create an address parser and use it to extract the group information.
final AddressParser parser = new AddressParser(address, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
return parser.extractGroupList();
}
/**
* Return an InternetAddress representing the current user.
* <P/>
* If session is not null, we first look for an address specified in its
* "mail.from" property; if this is not set, we look at its "mail.user"
* and "mail.host" properties and if both are not null then an address of
* the form "${mail.user}@${mail.host}" is created.
* If this fails to give an address, then an attempt is made to create
* an address by combining the value of the "user.name" System property
* with the value returned from InetAddress.getLocalHost().getHostName().
* Any SecurityException raised accessing the system property or any
* UnknownHostException raised getting the hostname are ignored.
* <P/>
* Finally, an attempt is made to convert the value obtained above to
* an InternetAddress. If this fails, then null is returned.
*
* @param session used to obtain mail properties
* @return an InternetAddress for the current user, or null if it cannot be determined
*/
public static InternetAddress getLocalAddress(final Session session) {
String host = null;
String user = null;
// ok, we have several steps for resolving this. To start with, we could have a from address
// configured already, which will be a full InternetAddress string. If we don't have that, then
// we need to resolve a user and host to compose an address from.
if (session != null) {
final String address = session.getProperty("mail.from");
// if we got this, we can skip out now
if (address != null) {
try {
return new InternetAddress(address);
} catch (final AddressException e) {
// invalid address on the from...treat this as an error and return null.
return null;
}
}
// now try for user and host information. We have both session and system properties to check here.
// we'll just handle the session ones here, and check the system ones below if we're missing information.
user = session.getProperty("mail.user");
host = session.getProperty("mail.host");
}
try {
// if either user or host is null, then we check non-session sources for the information.
if (user == null) {
user = System.getProperty("user.name");
}
if (host == null) {
host = InetAddress.getLocalHost().getHostName();
}
if (user != null && host != null) {
// if we have both a user and host, we can create a local address
return new InternetAddress(user + '@' + host);
}
} catch (final AddressException e) {
// ignore
} catch (final UnknownHostException e) {
// ignore
} catch (final SecurityException e) {
// ignore
}
return null;
}
/**
* Convert the supplied addresses into a single String of comma-separated text as
* produced by {@link InternetAddress#toString() toString()}.
* No line-break detection is performed.
*
* @param addresses the array of addresses to convert
* @return a one-line String of comma-separated addresses
*/
public static String toString(final Address[] addresses) {
if (addresses == null || addresses.length == 0) {
return null;
}
if (addresses.length == 1) {
return addresses[0].toString();
} else {
final StringBuffer buf = new StringBuffer(addresses.length * 32);
buf.append(addresses[0].toString());
for (int i = 1; i < addresses.length; i++) {
buf.append(", ");
buf.append(addresses[i].toString());
}
return buf.toString();
}
}
/**
* Convert the supplies addresses into a String of comma-separated text,
* inserting line-breaks between addresses as needed to restrict the line
* length to 72 characters. Splits will only be introduced between addresses
* so an address longer than 71 characters will still be placed on a single
* line.
*
* @param addresses the array of addresses to convert
* @param used the starting column
* @return a String of comma-separated addresses with optional line breaks
*/
public static String toString(final Address[] addresses, int used) {
if (addresses == null || addresses.length == 0) {
return null;
}
if (addresses.length == 1) {
String s = addresses[0].toString();
if (used + s.length() > 72) {
s = "\r\n " + s;
}
return s;
} else {
final StringBuffer buf = new StringBuffer(addresses.length * 32);
for (int i = 0; i < addresses.length; i++) {
final String s = addresses[1].toString();
if (i == 0) {
if (used + s.length() + 1 > 72) {
buf.append("\r\n ");
used = 2;
}
} else {
if (used + s.length() + 1 > 72) {
buf.append(",\r\n ");
used = 2;
} else {
buf.append(", ");
used += 2;
}
}
buf.append(s);
used += s.length();
}
return buf.toString();
}
}
/**
* Parse addresses out of the string with basic checking.
*
* @param addresses the addresses to parse
* @return an array of InternetAddresses parsed from the string
* @throws AddressException if addresses checking fails
*/
public static InternetAddress[] parse(final String addresses) throws AddressException {
return parse(addresses, true);
}
/**
* Parse addresses out of the string.
*
* @param addresses the addresses to parse
* @param strict if true perform detailed checking, if false just perform basic checking
* @return an array of InternetAddresses parsed from the string
* @throws AddressException if address checking fails
*/
public static InternetAddress[] parse(final String addresses, final boolean strict) throws AddressException {
return parse(addresses, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
}
/**
* Parse addresses out of the string.
*
* @param addresses the addresses to parse
* @param strict if true perform detailed checking, if false perform little checking
* @return an array of InternetAddresses parsed from the string
* @throws AddressException if address checking fails
*/
public static InternetAddress[] parseHeader(final String addresses, final boolean strict) throws AddressException {
return parse(addresses, strict ? AddressParser.STRICT : AddressParser.PARSE_HEADER);
}
/**
* Parse addresses with increasing degrees of RFC822 compliance checking.
*
* @param addresses the string to parse
* @param level The required strictness level.
*
* @return an array of InternetAddresses parsed from the string
* @throws AddressException
* if address checking fails
*/
private static InternetAddress[] parse(final String addresses, final int level) throws AddressException {
// create a parser and have it extract the list using the requested strictness leve.
final AddressParser parser = new AddressParser(addresses, level);
return parser.parseAddressList();
}
/**
* Validate the address portion of an internet address to ensure
* validity. Throws an AddressException if any validity
* problems are encountered.
*
* @exception AddressException
*/
public void validate() throws AddressException {
// create a parser using the strictest validation level.
final AddressParser parser = new AddressParser(formatAddress(address), AddressParser.STRICT);
parser.validateAddress();
}
}
| 2,000 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/ParameterList.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.ByteArrayOutputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.geronimo.mail.util.ASCIIUtil;
import org.apache.geronimo.mail.util.RFC2231Encoder;
import org.apache.geronimo.mail.util.SessionUtil;
// Represents lists in things like
// Content-Type: text/plain;charset=klingon
//
// The ;charset=klingon is the parameter list, may have more of them with ';'
//
// The string could also look like
//
// Content-Type: text/plain;para1*=val1; para2*=val2; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A
//
// And this (multisegment parameter) is also possible (since JavaMail 1.5)
//
// Content-Type: message/external-body; access-type=URL;
// URL*0="ftp://";
// URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"
//
// which is the same as:
// Content-Type: message/external-body; access-type=URL;
// URL="ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"
/*
* Content-Type: application/x-stuff
title*0*=us-ascii'en'This%20is%20even%20more%20
title*1*=%2A%2A%2Afun%2A%2A%2A%20
title*2="isn't it!"
*/
/**
* @version $Rev$ $Date$
*/
public class ParameterList {
private static final String MIME_ENCODEPARAMETERS = "mail.mime.encodeparameters";
private static final String MIME_DECODEPARAMETERS = "mail.mime.decodeparameters";
private static final String MIME_DECODEPARAMETERS_STRICT = "mail.mime.decodeparameters.strict";
private static final int HEADER_SIZE_LIMIT = 76;
private final Map<String, ParameterValue> _parameters = new HashMap<String, ParameterValue>();
/**
* A set of names for multi-segment parameters that we
* haven't processed yet. Normally such names are accumulated
* during the inital parse and processed at the end of the parse,
* but such names can also be set via the set method when the
* IMAP provider accumulates pre-parsed pieces of a parameter list.
* (A special call to the set method tells us when the IMAP provider
* is done setting parameters.)
*
* A multi-segment parameter is defined by RFC 2231. For example,
* "title*0=part1; title*1=part2", which represents a parameter
* named "title" with value "part1part2".
*
* Note also that each segment of the value might or might not be
* encoded, indicated by a trailing "*" on the parameter name.
* If any segment is encoded, the first segment must be encoded.
* Only the first segment contains the charset and language
* information needed to decode any encoded segments.
*
* RFC 2231 introduces many possible failure modes, which we try
* to handle as gracefully as possible. Generally, a failure to
* decode a parameter value causes the non-decoded parameter value
* to be used instead. Missing segments cause all later segments
* to be appear as independent parameters with names that include
* the segment number. For example, "title*0=part1; title*1=part2;
* title*3=part4" appears as two parameters named "title" and "title*3".
*/
//private Set multisegmentNames = new HashSet();
/**
* A map containing the segments for all not-yet-processed
* multi-segment parameters. The map is indexed by "name*seg".
* The value object is either a String or a Value object.
* The Value object is not decoded during the initial parse
* because the segments may appear in any order and until the
* first segment appears we don't know what charset to use to
* decode the encoded segments. The segments are hex decoded
* in order, combined into a single byte array, and converted
* to a String using the specified charset in the
* combineMultisegmentNames method.
*/
private final Map<MultiSegmentEntry, ParameterValue> _multiSegmentParameters = new TreeMap<MultiSegmentEntry, ParameterValue>();
private boolean encodeParameters = false;
private boolean decodeParameters = false;
private boolean decodeParametersStrict = false;
public ParameterList() {
// figure out how parameter handling is to be performed.
getInitialProperties();
}
public ParameterList(final String list) throws ParseException {
// figure out how parameter handling is to be performed.
getInitialProperties();
// get a token parser for the type information
final HeaderTokenizer tokenizer = new HeaderTokenizer(list, HeaderTokenizer.MIME);
while (true) {
HeaderTokenizer.Token token = tokenizer.next();
if (token.getType() == HeaderTokenizer.Token.EOF) {
// the EOF token terminates parsing.
break;
} else if (token.getType() == ';') {
// each new parameter is separated by a semicolon, including the
// first, which separates
// the parameters from the main part of the header.
// the next token needs to be a parameter name
token = tokenizer.next();
// allow a trailing semicolon on the parameters.
if (token.getType() == HeaderTokenizer.Token.EOF) {
break;
}
if (token.getType() != HeaderTokenizer.Token.ATOM) {
throw new ParseException("Invalid parameter name: " + token.getValue());
}
// get the parameter name as a lower case version for better
// mapping.
String name = token.getValue().toLowerCase();
token = tokenizer.next();
// parameters are name=value, so we must have the "=" here.
if (token.getType() != '=') {
throw new ParseException("Missing '='");
}
// now the value, which may be an atom or a literal
token = tokenizer.next();
if (token.getType() != HeaderTokenizer.Token.ATOM && token.getType() != HeaderTokenizer.Token.QUOTEDSTRING) {
throw new ParseException("Invalid parameter value: " + token.getValue());
}
final String value = token.getValue();
String decodedValue = null;
// we might have to do some additional decoding. A name that
// ends with "*"
// is marked as being encoded, so if requested, we decode the
// value.
if (decodeParameters && name.endsWith("*") && !isMultiSegmentName(name)) {
// the name needs to be pruned of the marker, and we need to
// decode the value.
name = name.substring(0, name.length() - 1);
// get a new decoder
final RFC2231Encoder decoder = new RFC2231Encoder(HeaderTokenizer.MIME);
try {
// decode the value
decodedValue = decoder.decode(value);
} catch (final Exception e) {
// if we're doing things strictly, then raise a parsing
// exception for errors.
// otherwise, leave the value in its current state.
if (decodeParametersStrict) {
throw new ParseException("Invalid RFC2231 encoded parameter");
}
}
_parameters.put(name, new ParameterValue(name, decodedValue, value));
} else if (isMultiSegmentName(name)) {
// multisegment parameter
_multiSegmentParameters.put(new MultiSegmentEntry(name), new ParameterValue(name, value));
} else {
_parameters.put(name, new ParameterValue(name, value));
}
} else {
throw new ParseException("Missing ';'");
}
}
combineSegments();
}
private static boolean isMultiSegmentName(final String name) {
if(name == null || name.length() == 0) {
return false;
}
final int firstAsterixIndex = name.indexOf('*');
if(firstAsterixIndex < 0) {
return false; //no asterix at all
}else {
if(firstAsterixIndex == name.length()-1) {
//first asterix is last char, so this is an encoded name/value pair but not a multisegment one
return false;
}
final String restOfname = name.substring(firstAsterixIndex+1);
if(Character.isDigit(restOfname.charAt(0))) {
return true;
}
return false;
}
}
/**
* Normal users of this class will use simple parameter names.
* In some cases, for example, when processing IMAP protocol
* messages, individual segments of a multi-segment name
* (specified by RFC 2231) will be encountered and passed to
* the {@link #set} method. After all these segments are added
* to this ParameterList, they need to be combined to represent
* the logical parameter name and value. This method will combine
* all segments of multi-segment names.
*
* Normal users should never need to call this method.
*
* @since JavaMail 1.5
*/
public void combineSegments() {
// title*0*=us-ascii'en'This%20is%20even%20more%20
// title*1*=%2A%2A%2Afun%2A%2A%2A%20
// title*2="isn't it!"
if (_multiSegmentParameters.size() > 0) {
final RFC2231Encoder decoder = new RFC2231Encoder(HeaderTokenizer.MIME);
String lastName = null;
int lastSegmentNumber = -1;
final StringBuilder segmentValue = new StringBuilder();
for (final Entry<MultiSegmentEntry, ParameterValue> entry : _multiSegmentParameters.entrySet()) {
final MultiSegmentEntry currentMEntry = entry.getKey();
if (lastName == null) {
lastName = currentMEntry.name;
} else {
if (!lastName.equals(currentMEntry.name)) {
_parameters.put(lastName, new ParameterValue(lastName, segmentValue.toString()));
segmentValue.setLength(0);
lastName = currentMEntry.name;
}
}
if (lastSegmentNumber == -1) {
lastSegmentNumber = currentMEntry.range;
if (lastSegmentNumber != 0) {
// does not start with 0
// skip gracefully
}
} else {
if (lastSegmentNumber + 1 != currentMEntry.range) {
// seems here is a gap
// skip gracefully
}
}
if (currentMEntry.encoded) {
try {
// decode the value
segmentValue.append(decoder.decode(entry.getValue().value));
} catch (final Exception e) {
segmentValue.append(entry.getValue().value);
}
} else {
segmentValue.append(entry.getValue().value);
}
}
_parameters.put(lastName, new ParameterValue(lastName, segmentValue.toString()));
}
}
/**
* Get the initial parameters that control parsing and values.
* These parameters are controlled by System properties.
*/
private void getInitialProperties() {
decodeParameters = SessionUtil.getBooleanProperty(MIME_DECODEPARAMETERS, true); //since JavaMail 1.5 RFC 2231 support is enabled by default
decodeParametersStrict = SessionUtil.getBooleanProperty(MIME_DECODEPARAMETERS_STRICT, false);
encodeParameters = SessionUtil.getBooleanProperty(MIME_ENCODEPARAMETERS, true); //since JavaMail 1.5 RFC 2231 support is enabled by default
}
public int size() {
return _parameters.size();
}
public String get(final String name) {
final ParameterValue value = _parameters.get(name.toLowerCase());
if (value != null) {
return value.value;
}
return null;
}
public void set(String name, final String value) {
name = name.toLowerCase();
if (isMultiSegmentName(name)) {
// multisegment parameter
_multiSegmentParameters.put(new MultiSegmentEntry(name), new ParameterValue(name, value));
} else {
_parameters.put(name, new ParameterValue(name, value));
}
}
public void set(String name, final String value, final String charset) {
name = name.toLowerCase();
// only encode if told to and this contains non-ASCII charactes.
if (encodeParameters && !ASCIIUtil.isAscii(value)) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
final RFC2231Encoder encoder = new RFC2231Encoder(HeaderTokenizer.MIME);
// extract the bytes using the given character set and encode
final byte[] valueBytes = value.getBytes(MimeUtility.javaCharset(charset));
// the string format is charset''data
out.write(charset.getBytes("ISO8859-1"));
out.write('\'');
out.write('\'');
encoder.encode(valueBytes, 0, valueBytes.length, out);
if (isMultiSegmentName(name)) {
// multisegment parameter
_multiSegmentParameters.put(new MultiSegmentEntry(name), new ParameterValue(name, value, new String(out.toByteArray(), "ISO8859-1")));
} else {
_parameters.put(name, new ParameterValue(name, value, new String(out.toByteArray(), "ISO8859-1")));
}
return;
} catch (final Exception e) {
// just fall through and set the value directly if there is an error
}
}
// default in case there is an exception
if (isMultiSegmentName(name)) {
// multisegment parameter
_multiSegmentParameters.put(new MultiSegmentEntry(name), new ParameterValue(name, value));
} else {
_parameters.put(name, new ParameterValue(name, value));
}
}
public void remove(final String name) {
_parameters.remove(name);
}
public Enumeration getNames() {
return Collections.enumeration(_parameters.keySet());
}
@Override
public String toString() {
// we need to perform folding, but out starting point is 0.
return toString(0);
}
public String toString(int used) {
final StringBuffer stringValue = new StringBuffer();
final Iterator values = _parameters.values().iterator();
while (values.hasNext()) {
final ParameterValue parm = (ParameterValue)values.next();
// get the values we're going to encode in here.
final String name = parm.getEncodedName();
final String value = parm.toString();
// add the semicolon separator. We also add a blank so that folding/unfolding rules can be used.
stringValue.append("; ");
used += 2;
// too big for the current header line?
if ((used + name.length() + value.length() + 1) > HEADER_SIZE_LIMIT) {
// and a CRLF-combo combo.
stringValue.append("\r\n\t");
// reset the counter for a fresh line
// note we use use 8 because we're using a rather than a blank
used = 8;
}
// now add the keyword/value pair.
stringValue.append(name);
stringValue.append("=");
used += name.length() + 1;
// we're not out of the woods yet. It is possible that the keyword/value pair by itself might
// be too long for a single line. If that's the case, the we need to fold the value, if possible
if (used + value.length() > HEADER_SIZE_LIMIT) {
final String foldedValue = MimeUtility.fold(used, value);
stringValue.append(foldedValue);
// now we need to sort out how much of the current line is in use.
final int lastLineBreak = foldedValue.lastIndexOf('\n');
if (lastLineBreak != -1) {
used = foldedValue.length() - lastLineBreak + 1;
}
else {
used += foldedValue.length();
}
}
else {
// no folding required, just append.
stringValue.append(value);
used += value.length();
}
}
return stringValue.toString();
}
/**
* Utility class for representing parameter values in the list.
*/
class ParameterValue {
public String name; // the name of the parameter
public String value; // the original set value
public String encodedValue; // an encoded value, if encoding is requested.
public ParameterValue(final String name, final String value) {
this.name = name;
this.value = value;
this.encodedValue = null;
}
public ParameterValue(final String name, final String value, final String encodedValue) {
this.name = name;
this.value = value;
this.encodedValue = encodedValue;
}
@Override
public String toString() {
if (encodedValue != null) {
return MimeUtility.quote(encodedValue, HeaderTokenizer.MIME);
}
return MimeUtility.quote(value, HeaderTokenizer.MIME);
}
public String getEncodedName() {
if (encodedValue != null) {
return name + "*";
}
return name;
}
}
static class MultiSegmentEntry implements Comparable<MultiSegmentEntry>{
final String original;
final String normalized;
final String name;
final int range;
final boolean encoded;
public MultiSegmentEntry(final String original) {
super();
this.original = original;
final int firstAsterixIndex1 = original.indexOf('*');
encoded=original.endsWith("*");
final int endIndex1 = encoded?original.length()-1:original.length();
name = original.substring(0, firstAsterixIndex1);
range = Integer.parseInt(original.substring(firstAsterixIndex1+1, endIndex1));
normalized = original.substring(0, endIndex1);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((normalized == null) ? 0 : normalized.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MultiSegmentEntry other = (MultiSegmentEntry) obj;
if (normalized == null) {
if (other.normalized != null) {
return false;
}
} else if (!normalized.equals(other.normalized)) {
return false;
}
return true;
}
public int compareTo(final MultiSegmentEntry o) {
if(this.equals(o)) {
return 0;
}
if(name.equals(o.name)) {
return range>o.range?1:-1;
}else
{
return name.compareTo(o.name);
}
}
@Override
public String toString() {
return "MultiSegmentEntry\n[original=" + original + ", name=" + name + ", range=" + range + "]\n";
}
}
/*class MultiSegmentComparator implements Comparator<String> {
public int compare(String o1, String o2) {
if(o1.equals(o2)) return 0;
int firstAsterixIndex1 = o1.indexOf('*');
int firstAsterixIndex2 = o2.indexOf('*');
String prefix1 = o1.substring(0, firstAsterixIndex1);
String prefix2 = o2.substring(0, firstAsterixIndex2);
if(!prefix1.equals(prefix2)) {
return prefix1.compareTo(prefix2);
}
int endIndex1 = o1.endsWith("*")?o1.length()-1:o1.length();
int endIndex2 = o2.endsWith("*")?o2.length()-1:o2.length();
int num1 = Integer.parseInt(o1.substring(firstAsterixIndex1+1, endIndex1));
int num2 = Integer.parseInt(o2.substring(firstAsterixIndex2+1, endIndex2));
return num1>num2?1:-1;
}
}*/
}
| 2,001 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/InternetHeaders.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.mail.Address;
import javax.mail.Header;
import javax.mail.MessagingException;
/**
* Class that represents the RFC822 headers associated with a message.
*
* @version $Rev$ $Date$
*/
public class InternetHeaders {
// the list of headers (to preserve order);
protected List headers = new ArrayList();
/**
* Create an empty InternetHeaders
*/
public InternetHeaders() {
// these are created in the preferred order of the headers.
addHeader("Return-Path", null);
addHeader("Received", null);
addHeader("Resent-Date", null);
addHeader("Resent-From", null);
addHeader("Resent-Sender", null);
addHeader("Resent-To", null);
addHeader("Resent-Cc", null);
addHeader("Resent-Bcc", null);
addHeader("Resent-Message-Id", null);
addHeader("Date", null);
addHeader("From", null);
addHeader("Sender", null);
addHeader("Reply-To", null);
addHeader("To", null);
addHeader("Cc", null);
addHeader("Bcc", null);
addHeader("Message-Id", null);
addHeader("In-Reply-To", null);
addHeader("References", null);
addHeader("Subject", null);
addHeader("Comments", null);
addHeader("Keywords", null);
addHeader("Errors-To", null);
addHeader("MIME-Version", null);
addHeader("Content-Type", null);
addHeader("Content-Transfer-Encoding", null);
addHeader("Content-MD5", null);
// the following is a special marker used to identify new header insertion points.
addHeader(":", null);
addHeader("Content-Length", null);
addHeader("Status", null);
}
/**
* Create a new InternetHeaders initialized by reading headers from the
* stream.
*
* @param in
* the RFC822 input stream to load from
* @throws MessagingException
* if there is a problem pasring the stream
*/
public InternetHeaders(final InputStream in) throws MessagingException {
load(in);
}
/**
* Read and parse the supplied stream and add all headers to the current
* set.
*
* @param in
* the RFC822 input stream to load from
* @throws MessagingException
* if there is a problem pasring the stream
*/
public void load(final InputStream in) throws MessagingException {
try {
final StringBuffer buffer = new StringBuffer(128);
String line;
// loop until we hit the end or a null line
while ((line = readLine(in)) != null) {
// lines beginning with white space get special handling
if (line.startsWith(" ") || line.startsWith("\t")) {
// this gets handled using the logic defined by
// the addHeaderLine method. If this line is a continuation, but
// there's nothing before it, just call addHeaderLine to add it
// to the last header in the headers list
if (buffer.length() == 0) {
addHeaderLine(line);
}
else {
// preserve the line break and append the continuation
buffer.append("\r\n");
buffer.append(line);
}
}
else {
// if we have a line pending in the buffer, flush it
if (buffer.length() > 0) {
addHeaderLine(buffer.toString());
buffer.setLength(0);
}
// add this to the accumulator
buffer.append(line);
}
}
// if we have a line pending in the buffer, flush it
if (buffer.length() > 0) {
addHeaderLine(buffer.toString());
}
} catch (final IOException e) {
throw new MessagingException("Error loading headers", e);
}
}
/**
* Read a single line from the input stream
*
* @param in The source stream for the line
*
* @return The string value of the line (without line separators)
*/
private String readLine(final InputStream in) throws IOException {
final StringBuffer buffer = new StringBuffer(128);
int c;
while ((c = in.read()) != -1) {
// a linefeed is a terminator, always.
if (c == '\n') {
break;
}
// just ignore the CR. The next character SHOULD be an NL. If not, we're
// just going to discard this
else if (c == '\r') {
continue;
}
else {
// just add to the buffer
buffer.append((char)c);
}
}
// no characters found...this was either an eof or a null line.
if (buffer.length() == 0) {
return null;
}
return buffer.toString();
}
/**
* Return all the values for the specified header.
*
* @param name
* the header to return
* @return the values for that header, or null if the header is not present
*/
public String[] getHeader(final String name) {
final List accumulator = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
if (header.getName().equalsIgnoreCase(name) && header.getValue() != null) {
accumulator.add(header.getValue());
}
}
// this is defined as returning null of nothing is found.
if (accumulator.isEmpty()) {
return null;
}
// convert this to an array.
return (String[])accumulator.toArray(new String[accumulator.size()]);
}
/**
* Return the values for the specified header as a single String. If the
* header has more than one value then all values are concatenated together
* separated by the supplied delimiter.
*
* @param name
* the header to return
* @param delimiter
* the delimiter used in concatenation
* @return the header as a single String
*/
public String getHeader(final String name, final String delimiter) {
// get all of the headers with this name
final String[] matches = getHeader(name);
// no match? return a null.
if (matches == null) {
return null;
}
// a null delimiter means just return the first one. If there's only one item, this is easy too.
if (matches.length == 1 || delimiter == null) {
return matches[0];
}
// perform the concatenation
final StringBuffer result = new StringBuffer(matches[0]);
for (int i = 1; i < matches.length; i++) {
result.append(delimiter);
result.append(matches[i]);
}
return result.toString();
}
/**
* Set the value of the header to the supplied value; any existing headers
* are removed.
*
* @param name
* the name of the header
* @param value
* the new value
*/
public void setHeader(final String name, final String value) {
// look for a header match
for (int i = 0; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
// found a matching header
if (name.equalsIgnoreCase(header.getName())) {
// we update both the name and the value for a set so that
// the header ends up with the same case as what is getting set
header.setValue(value);
header.setName(name);
// remove all of the headers from this point
removeHeaders(name, i + 1);
return;
}
}
// doesn't exist, so process as an add.
addHeader(name, value);
}
/**
* Remove all headers with the given name, starting with the
* specified start position.
*
* @param name The target header name.
* @param pos The position of the first header to examine.
*/
private void removeHeaders(final String name, final int pos) {
// now go remove all other instances of this header
for (int i = pos; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
// found a matching header
if (name.equalsIgnoreCase(header.getName())) {
// remove this item, and back up
headers.remove(i);
i--;
}
}
}
/**
* Find a header in the current list by name, returning the index.
*
* @param name The target name.
*
* @return The index of the header in the list. Returns -1 for a not found
* condition.
*/
private int findHeader(final String name) {
return findHeader(name, 0);
}
/**
* Find a header in the current list, beginning with the specified
* start index.
*
* @param name The target header name.
* @param start The search start index.
*
* @return The index of the first matching header. Returns -1 if the
* header is not located.
*/
private int findHeader(final String name, final int start) {
for (int i = start; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
// found a matching header
if (name.equalsIgnoreCase(header.getName())) {
return i;
}
}
return -1;
}
/**
* Add a new value to the header with the supplied name.
*
* @param name
* the name of the header to add a new value for
* @param value
* another value
*/
public void addHeader(final String name, final String value) {
final InternetHeader newHeader = new InternetHeader(name, value);
// The javamail spec states that "Recieved" headers need to be added in reverse order.
// Return-Path is permitted before Received, so handle it the same way.
if (name.equalsIgnoreCase("Received") || name.equalsIgnoreCase("Return-Path")) {
// see if we have one of these already
final int pos = findHeader(name);
// either insert before an existing header, or insert at the very beginning
if (pos != -1) {
// this could be a placeholder header with a null value. If it is, just update
// the value. Otherwise, insert in front of the existing header.
final InternetHeader oldHeader = (InternetHeader)headers.get(pos);
if (oldHeader.getValue() == null) {
oldHeader.setValue(value);
}
else {
headers.add(pos, newHeader);
}
}
else {
// doesn't exist, so insert at the beginning
headers.add(0, newHeader);
}
}
// normal insertion
else {
// see if we have one of these already
int pos = findHeader(name);
// either insert before an existing header, or insert at the very beginning
if (pos != -1) {
final InternetHeader oldHeader = (InternetHeader)headers.get(pos);
// if the existing header is a place holder, we can just update the value
if (oldHeader.getValue() == null) {
oldHeader.setValue(value);
}
else {
// we have at least one existing header with this name. We need to find the last occurrance,
// and insert after that spot.
int lastPos = findHeader(name, pos + 1);
while (lastPos != -1) {
pos = lastPos;
lastPos = findHeader(name, pos + 1);
}
// ok, we have the insertion position
headers.add(pos + 1, newHeader);
}
}
else {
// find the insertion marker. If that is missing somehow, insert at the end.
pos = findHeader(":");
if (pos == -1) {
pos = headers.size();
}
headers.add(pos, newHeader);
}
}
}
/**
* Remove all header entries with the supplied name
*
* @param name
* the header to remove
*/
public void removeHeader(final String name) {
// the first occurrance of a header is just zeroed out.
final int pos = findHeader(name);
if (pos != -1) {
final InternetHeader oldHeader = (InternetHeader)headers.get(pos);
// keep the header in the list, but with a null value
oldHeader.setValue(null);
// now remove all other headers with this name
removeHeaders(name, pos + 1);
}
}
/**
* Return all headers.
*
* @return an Enumeration<Header> containing all headers
*/
public Enumeration getAllHeaders() {
final List result = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
result.add(header);
}
}
// just return a list enumerator for the header list.
return Collections.enumeration(result);
}
/**
* Test if a given header name is a match for any header in the
* given list.
*
* @param name The name of the current tested header.
* @param names The list of names to match against.
*
* @return True if this is a match for any name in the list, false
* for a complete mismatch.
*/
private boolean matchHeader(final String name, final String[] names) {
// the list of names is not required, so treat this as if it
// was an empty list and we didn't get a match.
if (names == null) {
return false;
}
for (int i = 0; i < names.length; i++) {
if (name.equalsIgnoreCase(names[i])) {
return true;
}
}
return false;
}
/**
* Return all matching Header objects.
*/
public Enumeration getMatchingHeaders(final String[] names) {
final List result = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
// only add the matching ones
if (matchHeader(header.getName(), names)) {
result.add(header);
}
}
}
return Collections.enumeration(result);
}
/**
* Return all non matching Header objects.
*/
public Enumeration getNonMatchingHeaders(final String[] names) {
final List result = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
// only add the non-matching ones
if (!matchHeader(header.getName(), names)) {
result.add(header);
}
}
}
return Collections.enumeration(result);
}
/**
* Add an RFC822 header line to the header store. If the line starts with a
* space or tab (a continuation line), add it to the last header line in the
* list. Otherwise, append the new header line to the list.
*
* Note that RFC822 headers can only contain US-ASCII characters
*
* @param line
* raw RFC822 header line
*/
public void addHeaderLine(final String line) {
// null lines are a nop
if (line.length() == 0) {
return;
}
// we need to test the first character to see if this is a continuation whitespace
final char ch = line.charAt(0);
// tabs and spaces are special. This is a continuation of the last header in the list.
if (ch == ' ' || ch == '\t') {
final int size = headers.size();
// it's possible that we have a leading blank line.
if (size > 0) {
final InternetHeader header = (InternetHeader)headers.get(size - 1);
header.appendValue(line);
}
}
else {
// this just gets appended to the end, preserving the addition order.
headers.add(new InternetHeader(line));
}
}
/**
* Return all the header lines as an Enumeration of Strings.
*/
public Enumeration getAllHeaderLines() {
return new HeaderLineEnumeration(getAllHeaders());
}
/**
* Return all matching header lines as an Enumeration of Strings.
*/
public Enumeration getMatchingHeaderLines(final String[] names) {
return new HeaderLineEnumeration(getMatchingHeaders(names));
}
/**
* Return all non-matching header lines.
*/
public Enumeration getNonMatchingHeaderLines(final String[] names) {
return new HeaderLineEnumeration(getNonMatchingHeaders(names));
}
/**
* Set an internet header from a list of addresses. The
* first address item is set, followed by a series of addHeaders().
*
* @param name The name to set.
* @param addresses The list of addresses to set.
*/
void setHeader(final String name, final Address[] addresses) {
// if this is empty, then we need to replace this
if (addresses.length == 0) {
removeHeader(name);
} else {
// replace the first header
setHeader(name, addresses[0].toString());
// now add the rest as extra headers.
for (int i = 1; i < addresses.length; i++) {
final Address address = addresses[i];
addHeader(name, address.toString());
}
}
}
/**
* Write out the set of headers, except for any
* headers specified in the optional ignore list.
*
* @param out The output stream.
* @param ignore The optional ignore list.
*
* @exception IOException
*/
void writeTo(final OutputStream out, final String[] ignore) throws IOException {
if (ignore == null) {
// write out all header lines with non-null values
for (int i = 0; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
header.writeTo(out);
}
}
}
else {
// write out all matching header lines with non-null values
for (int i = 0; i < headers.size(); i++) {
final InternetHeader header = (InternetHeader)headers.get(i);
// we only include headers with real values, no placeholders
if (header.getValue() != null) {
if (!matchHeader(header.getName(), ignore)) {
header.writeTo(out);
}
}
}
}
}
protected static final class InternetHeader extends Header {
public InternetHeader(final String h) {
// initialize with null values, which we'll update once we parse the string
super("", "");
int separator = h.indexOf(':');
// no separator, then we take this as a name with a null string value.
if (separator == -1) {
name = h.trim();
}
else {
name = h.substring(0, separator);
// step past the separator. Now we need to remove any leading white space characters.
separator++;
while (separator < h.length()) {
final char ch = h.charAt(separator);
if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') {
break;
}
separator++;
}
value = h.substring(separator);
}
}
public InternetHeader(final String name, final String value) {
super(name, value);
}
/**
* Package scope method for setting the header value.
*
* @param value The new header value.
*/
void setValue(final String value) {
this.value = value;
}
/**
* Package scope method for setting the name value.
*
* @param name The new header name
*/
void setName(final String name) {
this.name = name;
}
/**
* Package scope method for extending a header value.
*
* @param value The appended header value.
*/
void appendValue(final String value) {
if (this.value == null) {
this.value = value;
}
else {
this.value = this.value + "\r\n" + value;
}
}
void writeTo(final OutputStream out) throws IOException {
out.write(name.getBytes("ISO8859-1"));
out.write(':');
out.write(' ');
out.write(value.getBytes("ISO8859-1"));
out.write('\r');
out.write('\n');
}
}
private static class HeaderLineEnumeration implements Enumeration {
private final Enumeration headers;
public HeaderLineEnumeration(final Enumeration headers) {
this.headers = headers;
}
public boolean hasMoreElements() {
return headers.hasMoreElements();
}
public Object nextElement() {
final Header h = (Header) headers.nextElement();
return h.getName() + ": " + h.getValue();
}
}
}
| 2,002 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/ContentDisposition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
// http://www.faqs.org/rfcs/rfc2183.html
/**
* @version $Rev$ $Date$
*/
public class ContentDisposition {
private String _disposition;
private ParameterList _list;
public ContentDisposition() {
setDisposition(null);
setParameterList(null);
}
public ContentDisposition(final String disposition) throws ParseException {
// get a token parser for the type information
final HeaderTokenizer tokenizer = new HeaderTokenizer(disposition, HeaderTokenizer.MIME);
// get the first token, which must be an ATOM
final HeaderTokenizer.Token token = tokenizer.next();
if (token.getType() != HeaderTokenizer.Token.ATOM) {
throw new ParseException("Invalid content disposition");
}
_disposition = token.getValue();
// the remainder is parameters, which ParameterList will take care of parsing.
final String remainder = tokenizer.getRemainder();
if (remainder != null) {
_list = new ParameterList(remainder);
}
}
public ContentDisposition(final String disposition, final ParameterList list) {
setDisposition(disposition);
setParameterList(list);
}
public String getDisposition() {
return _disposition;
}
public String getParameter(final String name) {
if (_list == null) {
return null;
} else {
return _list.get(name);
}
}
public ParameterList getParameterList() {
return _list;
}
public void setDisposition(final String string) {
_disposition = string;
}
public void setParameter(final String name, final String value) {
if (_list == null) {
_list = new ParameterList();
}
_list.set(name, value);
}
public void setParameterList(final ParameterList list) {
if (list == null) {
_list = new ParameterList();
} else {
_list = list;
}
}
/**
* Retrieve a RFC2045 style string representation of
* this ContentDisposition. Returns an empty string if
* the conversion failed.
*
* @return RFC2045 style string
* @since JavaMail 1.2
*/
@Override
public String toString() {
/* Since JavaMail 1.5:
The general contract of Object.toString is that it never returns null.
The toString methods of ContentType and ContentDisposition were defined
to return null in certain error cases. Given the general toString contract
it seems unlikely that anyone ever depended on these special cases, and
it would be more useful for these classes to obey the general contract.
These methods have been changed to return an empty string in these error
cases.
*/
// it is possible we might have a parameter list, but this is meaningless if
// there is no disposition string. Return a failure.
if (_disposition == null) {
return "";
}
// no parameter list? Just return the disposition string
if (_list == null) {
return _disposition;
}
// format this for use on a Content-Disposition header, which means we need to
// account for the length of the header part too.
return _disposition + _list.toString("Content-Disposition".length() + _disposition.length());
}
}
| 2,003 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/AddressException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
/**
* @version $Rev$ $Date$
*/
public class AddressException extends ParseException {
private static final long serialVersionUID = 9134583443539323120L;
protected int pos;
protected String ref;
public AddressException() {
this(null);
}
public AddressException(final String message) {
this(message, null);
}
public AddressException(final String message, final String ref) {
this(message, null, -1);
}
public AddressException(final String message, final String ref, final int pos) {
super(message);
this.ref = ref;
this.pos = pos;
}
public String getRef() {
return ref;
}
public int getPos() {
return pos;
}
@Override
public String toString() {
return super.toString() + " (" + ref + "," + pos + ")";
}
}
| 2,004 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/MailDateFormat.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* Formats ths date as specified by
* draft-ietf-drums-msg-fmt-08 dated January 26, 2000
* which supercedes RFC822.
* <p/>
* <p/>
* The format used is <code>EEE, d MMM yyyy HH:mm:ss Z</code> and
* locale is always US-ASCII.
*
* @version $Rev$ $Date$
*/
public class MailDateFormat extends SimpleDateFormat {
private static final long serialVersionUID = -8148227605210628779L;
public MailDateFormat() {
super("EEE, d MMM yyyy HH:mm:ss Z (z)", Locale.US);
}
@Override
public StringBuffer format(final Date date, final StringBuffer buffer, final FieldPosition position) {
return super.format(date, buffer, position);
}
/**
* Parse a Mail date into a Date object. This uses fairly
* lenient rules for the format because the Mail standards
* for dates accept multiple formats.
*
* @param string The input string.
* @param position The position argument.
*
* @return The Date object with the information inside.
*/
@Override
public Date parse(final String string, final ParsePosition position) {
final MailDateParser parser = new MailDateParser(string, position);
try {
return parser.parse(isLenient());
} catch (final ParseException e) {
e.printStackTrace();
// just return a null for any parsing errors
return null;
}
}
/**
* The calendar cannot be set
* @param calendar
* @throws UnsupportedOperationException
*/
@Override
public void setCalendar(final Calendar calendar) {
throw new UnsupportedOperationException();
}
/**
* The format cannot be set
* @param format
* @throws UnsupportedOperationException
*/
@Override
public void setNumberFormat(final NumberFormat format) {
throw new UnsupportedOperationException();
}
// utility class for handling date parsing issues
class MailDateParser {
// our list of defined whitespace characters
static final String whitespace = " \t\r\n";
// current parsing position
int current;
// our end parsing position
int endOffset;
// the date source string
String source;
// The parsing position. We update this as we move along and
// also for any parsing errors
ParsePosition pos;
public MailDateParser(final String source, final ParsePosition pos)
{
this.source = source;
this.pos = pos;
// we start using the providing parsing index.
this.current = pos.getIndex();
this.endOffset = source.length();
}
/**
* Parse the timestamp, returning a date object.
*
* @param lenient The lenient setting from the Formatter object.
*
* @return A Date object based off of parsing the date string.
* @exception ParseException
*/
public Date parse(final boolean lenient) throws ParseException {
// we just skip over any next date format, which means scanning ahead until we
// find the first numeric character
locateNumeric();
// the day can be either 1 or two digits
final int day = parseNumber(1, 2);
// step over the delimiter
skipDateDelimiter();
// parse off the month (which is in character format)
final int month = parseMonth();
// step over the delimiter
skipDateDelimiter();
// now pull of the year, which can be either 2-digit or 4-digit
final int year = parseYear();
// white space is required here
skipRequiredWhiteSpace();
// accept a 1 or 2 digit hour
final int hour = parseNumber(1, 2);
skipRequiredChar(':');
// the minutes must be two digit
final int minutes = parseNumber(2, 2);
// the seconds are optional, but the ":" tells us if they are to
// be expected.
int seconds = 0;
if (skipOptionalChar(':')) {
seconds = parseNumber(2, 2);
}
// skip over the white space
skipWhiteSpace();
// and finally the timezone information
final int offset = parseTimeZone();
// set the index of how far we've parsed this
pos.setIndex(current);
// create a calendar for creating the date
final Calendar greg = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
// we inherit the leniency rules
greg.setLenient(lenient);
greg.set(year, month, day, hour, minutes, seconds);
// now adjust by the offset. This seems a little strange, but we
// need to negate the offset because this is a UTC calendar, so we need to
// apply the reverse adjustment. for example, for the EST timezone, the offset
// value will be -300 (5 hours). If the time was 15:00:00, the UTC adjusted time
// needs to be 20:00:00, so we subract -300 minutes.
greg.add(Calendar.MINUTE, -offset);
// now return this timestamp.
return greg.getTime();
}
/**
* Skip over a position where there's a required value
* expected.
*
* @param ch The required character.
*
* @exception ParseException
*/
private void skipRequiredChar(final char ch) throws ParseException {
if (current >= endOffset) {
parseError("Delimiter '" + ch + "' expected");
}
if (source.charAt(current) != ch) {
parseError("Delimiter '" + ch + "' expected");
}
current++;
}
/**
* Skip over a position where iff the position matches the
* character
*
* @param ch The required character.
*
* @return true if the character was there, false otherwise.
* @exception ParseException
*/
private boolean skipOptionalChar(final char ch) {
if (current >= endOffset) {
return false;
}
if (source.charAt(current) != ch) {
return false;
}
current++;
return true;
}
/**
* Skip over any white space characters until we find
* the next real bit of information. Will scan completely to the
* end, if necessary.
*/
private void skipWhiteSpace() {
while (current < endOffset) {
// if this is not in the white space list, then success.
if (whitespace.indexOf(source.charAt(current)) < 0) {
return;
}
current++;
}
// everything used up, just return
}
/**
* Skip over any non-white space characters until we find
* either a whitespace char or the end of the data.
*/
private void skipNonWhiteSpace() {
while (current < endOffset) {
// if this is not in the white space list, then success.
if (whitespace.indexOf(source.charAt(current)) >= 0) {
return;
}
current++;
}
// everything used up, just return
}
/**
* Skip over any white space characters until we find
* the next real bit of information. Will scan completely to the
* end, if necessary.
*/
private void skipRequiredWhiteSpace() throws ParseException {
final int start = current;
while (current < endOffset) {
// if this is not in the white space list, then success.
if (whitespace.indexOf(source.charAt(current)) < 0) {
// we must have at least one white space character
if (start == current) {
parseError("White space character expected");
}
return;
}
current++;
}
// everything used up, just return, but make sure we had at least one
// white space
if (start == current) {
parseError("White space character expected");
}
}
private void parseError(final String message) throws ParseException {
// we've got an error, set the index to the end.
pos.setErrorIndex(current);
throw new ParseException(message, current);
}
/**
* Locate an expected numeric field.
*
* @exception ParseException
*/
private void locateNumeric() throws ParseException {
while (current < endOffset) {
// found a digit? we're done
if (Character.isDigit(source.charAt(current))) {
return;
}
current++;
}
// we've got an error, set the index to the end.
parseError("Number field expected");
}
/**
* Parse out an expected numeric field.
*
* @param minDigits The minimum number of digits we expect in this filed.
* @param maxDigits The maximum number of digits expected. Parsing will
* stop at the first non-digit character. An exception will
* be thrown if the field contained more than maxDigits
* in it.
*
* @return The parsed numeric value.
* @exception ParseException
*/
private int parseNumber(final int minDigits, final int maxDigits) throws ParseException {
final int start = current;
int accumulator = 0;
while (current < endOffset) {
final char ch = source.charAt(current);
// if this is not a digit character, then quit
if (!Character.isDigit(ch)) {
break;
}
// add the digit value into the accumulator
accumulator = accumulator * 10 + Character.digit(ch, 10);
current++;
}
final int fieldLength = current - start;
if (fieldLength < minDigits || fieldLength > maxDigits) {
parseError("Invalid number field");
}
return accumulator;
}
/**
* Skip a delimiter between the date portions of the
* string. The IMAP internal date format uses "-", so
* we either accept a single "-" or any number of white
* space characters (at least one required).
*
* @exception ParseException
*/
private void skipDateDelimiter() throws ParseException {
if (current >= endOffset) {
parseError("Invalid date field delimiter");
}
if (source.charAt(current) == '-') {
current++;
}
else {
// must be at least a single whitespace character
skipRequiredWhiteSpace();
}
}
/**
* Parse a character month name into the date month
* offset.
*
* @return
* @exception ParseException
*/
private int parseMonth() throws ParseException {
if ((endOffset - current) < 3) {
parseError("Invalid month");
}
int monthOffset = 0;
final String month = source.substring(current, current + 3).toLowerCase();
if (month.equals("jan")) {
monthOffset = 0;
}
else if (month.equals("feb")) {
monthOffset = 1;
}
else if (month.equals("mar")) {
monthOffset = 2;
}
else if (month.equals("apr")) {
monthOffset = 3;
}
else if (month.equals("may")) {
monthOffset = 4;
}
else if (month.equals("jun")) {
monthOffset = 5;
}
else if (month.equals("jul")) {
monthOffset = 6;
}
else if (month.equals("aug")) {
monthOffset = 7;
}
else if (month.equals("sep")) {
monthOffset = 8;
}
else if (month.equals("oct")) {
monthOffset = 9;
}
else if (month.equals("nov")) {
monthOffset = 10;
}
else if (month.equals("dec")) {
monthOffset = 11;
}
else {
parseError("Invalid month");
}
// ok, this is valid. Update the position and return it
current += 3;
return monthOffset;
}
/**
* Parse off a year field that might be expressed as
* either 2 or 4 digits.
*
* @return The numeric value of the year.
* @exception ParseException
*/
private int parseYear() throws ParseException {
// the year is between 2 to 4 digits
int year = parseNumber(2, 4);
// the two digit years get some sort of adjustment attempted.
if (year < 50) {
year += 2000;
}
else if (year < 100) {
year += 1990;
}
return year;
}
/**
* Parse all of the different timezone options.
*
* @return The timezone offset.
* @exception ParseException
*/
private int parseTimeZone() throws ParseException {
if (current >= endOffset) {
parseError("Missing time zone");
}
// get the first non-blank. If this is a sign character, this
// is a zone offset.
final char sign = source.charAt(current);
if (sign == '-' || sign == '+') {
// need to step over the sign character
current++;
// a numeric timezone is always a 4 digit number, but
// expressed as minutes/seconds. I'm too lazy to write a
// different parser that will bound on just a couple of characters, so
// we'll grab this as a single value and adjust
final int zoneInfo = parseNumber(4, 4);
int offset = (zoneInfo / 100) * 60 + (zoneInfo % 100);
// negate this, if we have a negativeo offset
if (sign == '-') {
offset = -offset;
}
return offset;
}
else {
// need to parse this out using the obsolete zone names. This will be
// either a 3-character code (defined set), or a single character military
// zone designation.
final int start = current;
skipNonWhiteSpace();
final String name = source.substring(start, current).toUpperCase();
if (name.length() == 1) {
return militaryZoneOffset(name);
}
else if (name.length() <= 3) {
return namedZoneOffset(name);
}
else {
parseError("Invalid time zone");
}
return 0;
}
}
/**
* Parse the obsolete mail timezone specifiers. The
* allowed set of timezones are terribly US centric.
* That's the spec. The preferred timezone form is
* the +/-mmss form.
*
* @param name The input name.
*
* @return The standard timezone offset for the specifier.
* @exception ParseException
*/
private int namedZoneOffset(final String name) throws ParseException {
// NOTE: This is "UT", NOT "UTC"
if (name.equals("UT")) {
return 0;
}
else if (name.equals("GMT")) {
return 0;
}
else if (name.equals("EST")) {
return -300;
}
else if (name.equals("EDT")) {
return -240;
}
else if (name.equals("CST")) {
return -360;
}
else if (name.equals("CDT")) {
return -300;
}
else if (name.equals("MST")) {
return -420;
}
else if (name.equals("MDT")) {
return -360;
}
else if (name.equals("PST")) {
return -480;
}
else if (name.equals("PDT")) {
return -420;
}
else {
parseError("Invalid time zone");
return 0;
}
}
/**
* Parse a single-character military timezone.
*
* @param name The one-character name.
*
* @return The offset corresponding to the military designation.
*/
private int militaryZoneOffset(final String name) throws ParseException {
switch (Character.toUpperCase(name.charAt(0))) {
case 'A':
return 60;
case 'B':
return 120;
case 'C':
return 180;
case 'D':
return 240;
case 'E':
return 300;
case 'F':
return 360;
case 'G':
return 420;
case 'H':
return 480;
case 'I':
return 540;
case 'K':
return 600;
case 'L':
return 660;
case 'M':
return 720;
case 'N':
return -60;
case 'O':
return -120;
case 'P':
return -180;
case 'Q':
return -240;
case 'R':
return -300;
case 'S':
return -360;
case 'T':
return -420;
case 'U':
return -480;
case 'V':
return -540;
case 'W':
return -600;
case 'X':
return -660;
case 'Y':
return -720;
case 'Z':
return 0;
default:
parseError("Invalid time zone");
return 0;
}
}
}
}
| 2,005 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/MimeUtility.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.EncodingAware;
import javax.mail.MessagingException;
import org.apache.geronimo.mail.util.ASCIIUtil;
import org.apache.geronimo.mail.util.Base64;
import org.apache.geronimo.mail.util.Base64DecoderStream;
import org.apache.geronimo.mail.util.Base64Encoder;
import org.apache.geronimo.mail.util.Base64EncoderStream;
import org.apache.geronimo.mail.util.QuotedPrintableDecoderStream;
import org.apache.geronimo.mail.util.QuotedPrintableEncoder;
import org.apache.geronimo.mail.util.QuotedPrintableEncoderStream;
import org.apache.geronimo.mail.util.SessionUtil;
import org.apache.geronimo.mail.util.UUDecoderStream;
import org.apache.geronimo.mail.util.UUEncoderStream;
// encodings include "base64", "quoted-printable", "7bit", "8bit" and "binary".
// In addition, "uuencode" is also supported. The
/**
* @version $Rev$ $Date$
*/
public class MimeUtility {
private static final String MIME_FOLDENCODEDWORDS = "mail.mime.foldencodedwords";
private static final String MIME_DECODE_TEXT_STRICT = "mail.mime.decodetext.strict";
private static final String MIME_FOLDTEXT = "mail.mime.foldtext";
private static final int FOLD_THRESHOLD = 76;
private MimeUtility() {
}
public static final int ALL = -1;
private static String escapedChars = "\"\\\r\n";
private static String linearWhiteSpace = " \t\r\n";
private static String QP_WORD_SPECIALS = "=_?\"#$%&'(),.:;<>@[\\]^`{|}~";
private static String QP_TEXT_SPECIALS = "=_?";
// the javamail spec includes the ability to map java encoding names to MIME-specified names. Normally,
// these values are loaded from a character mapping file.
private static Map java2mime;
private static Map mime2java;
static {
// we need to load the mapping tables used by javaCharset() and mimeCharset().
loadCharacterSetMappings();
}
public static InputStream decode(final InputStream in, String encoding) throws MessagingException {
encoding = encoding.toLowerCase();
// some encodies are just pass-throughs, with no real decoding.
if (encoding.equals("binary") || encoding.equals("7bit") || encoding.equals("8bit")) {
return in;
}
else if (encoding.equals("base64")) {
return new Base64DecoderStream(in);
}
// UUEncode is known by a couple historical extension names too.
else if (encoding.equals("uuencode") || encoding.equals("x-uuencode") || encoding.equals("x-uue")) {
return new UUDecoderStream(in);
}
else if (encoding.equals("quoted-printable")) {
return new QuotedPrintableDecoderStream(in);
}
else {
throw new MessagingException("Unknown encoding " + encoding);
}
}
/**
* Decode a string of text obtained from a mail header into
* it's proper form. The text generally will consist of a
* string of tokens, some of which may be encoded using
* base64 encoding.
*
* @param text The text to decode.
*
* @return The decoded test string.
* @exception UnsupportedEncodingException
*/
public static String decodeText(final String text) throws UnsupportedEncodingException {
// if the text contains any encoded tokens, those tokens will be marked with "=?". If the
// source string doesn't contain that sequent, no decoding is required.
if (text.indexOf("=?") < 0) {
return text;
}
// we have two sets of rules we can apply.
if (!SessionUtil.getBooleanProperty(MIME_DECODE_TEXT_STRICT, true)) {
return decodeTextNonStrict(text);
}
int offset = 0;
final int endOffset = text.length();
int startWhiteSpace = -1;
int endWhiteSpace = -1;
final StringBuffer decodedText = new StringBuffer(text.length());
boolean previousTokenEncoded = false;
while (offset < endOffset) {
char ch = text.charAt(offset);
// is this a whitespace character?
if (linearWhiteSpace.indexOf(ch) != -1) {
startWhiteSpace = offset;
while (offset < endOffset) {
// step over the white space characters.
ch = text.charAt(offset);
if (linearWhiteSpace.indexOf(ch) != -1) {
offset++;
}
else {
// record the location of the first non lwsp and drop down to process the
// token characters.
endWhiteSpace = offset;
break;
}
}
}
else {
// we have a word token. We need to scan over the word and then try to parse it.
final int wordStart = offset;
while (offset < endOffset) {
// step over the white space characters.
ch = text.charAt(offset);
if (linearWhiteSpace.indexOf(ch) == -1) {
offset++;
}
else {
break;
}
//NB: Trailing whitespace on these header strings will just be discarded.
}
// pull out the word token.
final String word = text.substring(wordStart, offset);
// is the token encoded? decode the word
if (word.startsWith("=?")) {
try {
// if this gives a parsing failure, treat it like a non-encoded word.
final String decodedWord = decodeWord(word);
// are any whitespace characters significant? Append 'em if we've got 'em.
if (!previousTokenEncoded) {
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
}
// this is definitely a decoded token.
previousTokenEncoded = true;
// and add this to the text.
decodedText.append(decodedWord);
// we continue parsing from here...we allow parsing errors to fall through
// and get handled as normal text.
continue;
} catch (final ParseException e) {
}
}
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(word);
}
}
return decodedText.toString();
}
/**
* Decode a string of text obtained from a mail header into
* it's proper form. The text generally will consist of a
* string of tokens, some of which may be encoded using
* base64 encoding. This is for non-strict decoded for mailers that
* violate the RFC 2047 restriction that decoded tokens must be delimited
* by linear white space. This will scan tokens looking for inner tokens
* enclosed in "=?" -- "?=" pairs.
*
* @param text The text to decode.
*
* @return The decoded test string.
* @exception UnsupportedEncodingException
*/
private static String decodeTextNonStrict(final String text) throws UnsupportedEncodingException {
int offset = 0;
final int endOffset = text.length();
int startWhiteSpace = -1;
int endWhiteSpace = -1;
final StringBuffer decodedText = new StringBuffer(text.length());
boolean previousTokenEncoded = false;
while (offset < endOffset) {
char ch = text.charAt(offset);
// is this a whitespace character?
if (linearWhiteSpace.indexOf(ch) != -1) {
startWhiteSpace = offset;
while (offset < endOffset) {
// step over the white space characters.
ch = text.charAt(offset);
if (linearWhiteSpace.indexOf(ch) != -1) {
offset++;
}
else {
// record the location of the first non lwsp and drop down to process the
// token characters.
endWhiteSpace = offset;
break;
}
}
}
else {
// we're at the start of a word token. We potentially need to break this up into subtokens
final int wordStart = offset;
while (offset < endOffset) {
// step over the white space characters.
ch = text.charAt(offset);
if (linearWhiteSpace.indexOf(ch) == -1) {
offset++;
}
else {
break;
}
//NB: Trailing whitespace on these header strings will just be discarded.
}
// pull out the word token.
final String word = text.substring(wordStart, offset);
int decodeStart = 0;
// now scan and process each of the bits within here.
while (decodeStart < word.length()) {
final int tokenStart = word.indexOf("=?", decodeStart);
if (tokenStart == -1) {
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(word.substring(decodeStart));
// we're finished.
break;
}
// we have something to process
else {
// we might have a normal token preceeding this.
if (tokenStart != decodeStart) {
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(word.substring(decodeStart, tokenStart));
}
// now find the end marker.
final int tokenEnd = word.indexOf("?=", tokenStart);
// sigh, an invalid token. Treat this as plain text.
if (tokenEnd == -1) {
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(word.substring(tokenStart));
// we're finished.
break;
}
else {
// update our ticker
decodeStart = tokenEnd + 2;
final String token = word.substring(tokenStart, tokenEnd);
try {
// if this gives a parsing failure, treat it like a non-encoded word.
final String decodedWord = decodeWord(token);
// are any whitespace characters significant? Append 'em if we've got 'em.
if (!previousTokenEncoded) {
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
}
// this is definitely a decoded token.
previousTokenEncoded = true;
// and add this to the text.
decodedText.append(decodedWord);
// we continue parsing from here...we allow parsing errors to fall through
// and get handled as normal text.
continue;
} catch (final ParseException e) {
}
// this is a normal token, so it doesn't matter what the previous token was. Add the white space
// if we have it.
if (startWhiteSpace != -1) {
decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));
startWhiteSpace = -1;
}
// this is not a decoded token.
previousTokenEncoded = false;
decodedText.append(token);
}
}
}
}
}
return decodedText.toString();
}
/**
* Parse a string using the RFC 2047 rules for an "encoded-word"
* type. This encoding has the syntax:
*
* encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
*
* @param word The possibly encoded word value.
*
* @return The decoded word.
* @exception ParseException
* @exception UnsupportedEncodingException
*/
public static String decodeWord(final String word) throws ParseException, UnsupportedEncodingException {
// encoded words start with the characters "=?". If this not an encoded word, we throw a
// ParseException for the caller.
if (!word.startsWith("=?")) {
throw new ParseException("Invalid RFC 2047 encoded-word: " + word);
}
final int charsetPos = word.indexOf('?', 2);
if (charsetPos == -1) {
throw new ParseException("Missing charset in RFC 2047 encoded-word: " + word);
}
// pull out the character set information (this is the MIME name at this point).
final String charset = word.substring(2, charsetPos).toLowerCase();
// now pull out the encoding token the same way.
final int encodingPos = word.indexOf('?', charsetPos + 1);
if (encodingPos == -1) {
throw new ParseException("Missing encoding in RFC 2047 encoded-word: " + word);
}
final String encoding = word.substring(charsetPos + 1, encodingPos);
// and finally the encoded text.
final int encodedTextPos = word.indexOf("?=", encodingPos + 1);
if (encodedTextPos == -1) {
throw new ParseException("Missing encoded text in RFC 2047 encoded-word: " + word);
}
final String encodedText = word.substring(encodingPos + 1, encodedTextPos);
// seems a bit silly to encode a null string, but easy to deal with.
if (encodedText.length() == 0) {
return "";
}
try {
// the decoder writes directly to an output stream.
final ByteArrayOutputStream out = new ByteArrayOutputStream(encodedText.length());
final byte[] encodedData = encodedText.getBytes("US-ASCII");
// Base64 encoded?
if (encoding.equals("B")) {
Base64.decode(encodedData, out);
}
// maybe quoted printable.
else if (encoding.equals("Q")) {
final QuotedPrintableEncoder dataEncoder = new QuotedPrintableEncoder();
dataEncoder.decodeWord(encodedData, out);
}
else {
throw new UnsupportedEncodingException("Unknown RFC 2047 encoding: " + encoding);
}
// get the decoded byte data and convert into a string.
final byte[] decodedData = out.toByteArray();
return new String(decodedData, javaCharset(charset));
} catch (final IOException e) {
throw new UnsupportedEncodingException("Invalid RFC 2047 encoding");
}
}
/**
* Wrap an encoder around a given output stream.
*
* @param out The output stream to wrap.
* @param encoding The name of the encoding.
*
* @return A instance of FilterOutputStream that manages on the fly
* encoding for the requested encoding type.
* @exception MessagingException
*/
public static OutputStream encode(final OutputStream out, String encoding) throws MessagingException {
// no encoding specified, so assume it goes out unchanged.
if (encoding == null) {
return out;
}
encoding = encoding.toLowerCase();
// some encodies are just pass-throughs, with no real decoding.
if (encoding.equals("binary") || encoding.equals("7bit") || encoding.equals("8bit")) {
return out;
}
else if (encoding.equals("base64")) {
return new Base64EncoderStream(out);
}
// UUEncode is known by a couple historical extension names too.
else if (encoding.equals("uuencode") || encoding.equals("x-uuencode") || encoding.equals("x-uue")) {
return new UUEncoderStream(out);
}
else if (encoding.equals("quoted-printable")) {
return new QuotedPrintableEncoderStream(out);
}
else {
throw new MessagingException("Unknown encoding " + encoding);
}
}
/**
* Wrap an encoder around a given output stream.
*
* @param out The output stream to wrap.
* @param encoding The name of the encoding.
* @param filename The filename of the data being sent (only used for UUEncode).
*
* @return A instance of FilterOutputStream that manages on the fly
* encoding for the requested encoding type.
* @exception MessagingException
*/
public static OutputStream encode(final OutputStream out, String encoding, final String filename) throws MessagingException {
encoding = encoding.toLowerCase();
// some encodies are just pass-throughs, with no real decoding.
if (encoding.equals("binary") || encoding.equals("7bit") || encoding.equals("8bit")) {
return out;
}
else if (encoding.equals("base64")) {
return new Base64EncoderStream(out);
}
// UUEncode is known by a couple historical extension names too.
else if (encoding.equals("uuencode") || encoding.equals("x-uuencode") || encoding.equals("x-uue")) {
return new UUEncoderStream(out, filename);
}
else if (encoding.equals("quoted-printable")) {
return new QuotedPrintableEncoderStream(out);
}
else {
throw new MessagingException("Unknown encoding " + encoding);
}
}
public static String encodeText(final String word) throws UnsupportedEncodingException {
return encodeText(word, null, null);
}
public static String encodeText(final String word, final String charset, final String encoding) throws UnsupportedEncodingException {
return encodeWord(word, charset, encoding, false);
}
public static String encodeWord(final String word) throws UnsupportedEncodingException {
return encodeWord(word, null, null);
}
public static String encodeWord(final String word, final String charset, final String encoding) throws UnsupportedEncodingException {
return encodeWord(word, charset, encoding, true);
}
private static String encodeWord(final String word, String charset, final String encoding, final boolean encodingWord) throws UnsupportedEncodingException {
// figure out what we need to encode this.
String encoder = ASCIIUtil.getTextTransferEncoding(word);
// all ascii? We can return this directly,
if (encoder.equals("7bit")) {
return word;
}
// if not given a charset, use the default.
if (charset == null) {
charset = getDefaultMIMECharset();
}
// sort out the encoder. If not explicitly given, use the best guess we've already established.
if (encoding != null) {
if (encoding.equalsIgnoreCase("B")) {
encoder = "base64";
}
else if (encoding.equalsIgnoreCase("Q")) {
encoder = "quoted-printable";
}
else {
throw new UnsupportedEncodingException("Unknown transfer encoding: " + encoding);
}
}
try {
// we'll format this directly into the string buffer
final StringBuffer result = new StringBuffer();
// this is the maximum size of a segment of encoded data, which is based off
// of a 75 character size limit and all of the encoding overhead elements.
final int sizeLimit = 75 - 7 - charset.length();
// now do the appropriate encoding work
if (encoder.equals("base64")) {
final Base64Encoder dataEncoder = new Base64Encoder();
// this may recurse on the encoding if the string is too long. The left-most will not
// get a segment delimiter
encodeBase64(word, result, sizeLimit, charset, dataEncoder, true, SessionUtil.getBooleanProperty(MIME_FOLDENCODEDWORDS, false));
}
else {
final QuotedPrintableEncoder dataEncoder = new QuotedPrintableEncoder();
encodeQuotedPrintable(word, result, sizeLimit, charset, dataEncoder, true,
SessionUtil.getBooleanProperty(MIME_FOLDENCODEDWORDS, false), encodingWord ? QP_WORD_SPECIALS : QP_TEXT_SPECIALS);
}
return result.toString();
} catch (final IOException e) {
throw new UnsupportedEncodingException("Invalid encoding");
}
}
/**
* Encode a string into base64 encoding, taking into
* account the maximum segment length.
*
* @param data The string data to encode.
* @param out The output buffer used for the result.
* @param sizeLimit The maximum amount of encoded data we're allowed
* to have in a single encoded segment.
* @param charset The character set marker that needs to be added to the
* encoding header.
* @param encoder The encoder instance we're using.
* @param firstSegment
* If true, this is the first (left-most) segment in the
* data. Used to determine if segment delimiters need to
* be added between sections.
* @param foldSegments
* Indicates the type of delimiter to use (blank or newline sequence).
*/
static private void encodeBase64(final String data, final StringBuffer out, final int sizeLimit, final String charset, final Base64Encoder encoder, final boolean firstSegment, final boolean foldSegments) throws IOException
{
// this needs to be converted into the appropriate transfer encoding.
final byte [] bytes = data.getBytes(javaCharset(charset));
final int estimatedSize = encoder.estimateEncodedLength(bytes);
// if the estimated encoding size is over our segment limit, split the string in half and
// recurse. Eventually we'll reach a point where things are small enough.
if (estimatedSize > sizeLimit) {
// the first segment indicator travels with the left half.
encodeBase64(data.substring(0, data.length() / 2), out, sizeLimit, charset, encoder, firstSegment, foldSegments);
// the second half can never be the first segment
encodeBase64(data.substring(data.length() / 2), out, sizeLimit, charset, encoder, false, foldSegments);
}
else
{
// if this is not the first sement of the encoding, we need to add either a blank or
// a newline sequence to the data
if (!firstSegment) {
if (foldSegments) {
out.append("\r\n");
}
else {
out.append(' ');
}
}
// do the encoding of the segment.
encoder.encodeWord(bytes, out, charset);
}
}
/**
* Encode a string into quoted printable encoding, taking into
* account the maximum segment length.
*
* @param data The string data to encode.
* @param out The output buffer used for the result.
* @param sizeLimit The maximum amount of encoded data we're allowed
* to have in a single encoded segment.
* @param charset The character set marker that needs to be added to the
* encoding header.
* @param encoder The encoder instance we're using.
* @param firstSegment
* If true, this is the first (left-most) segment in the
* data. Used to determine if segment delimiters need to
* be added between sections.
* @param foldSegments
* Indicates the type of delimiter to use (blank or newline sequence).
*/
static private void encodeQuotedPrintable(final String data, final StringBuffer out, final int sizeLimit, final String charset, final QuotedPrintableEncoder encoder,
final boolean firstSegment, final boolean foldSegments, final String specials) throws IOException
{
// this needs to be converted into the appropriate transfer encoding.
final byte [] bytes = data.getBytes(javaCharset(charset));
final int estimatedSize = encoder.estimateEncodedLength(bytes, specials);
// if the estimated encoding size is over our segment limit, split the string in half and
// recurse. Eventually we'll reach a point where things are small enough.
if (estimatedSize > sizeLimit) {
// the first segment indicator travels with the left half.
encodeQuotedPrintable(data.substring(0, data.length() / 2), out, sizeLimit, charset, encoder, firstSegment, foldSegments, specials);
// the second half can never be the first segment
encodeQuotedPrintable(data.substring(data.length() / 2), out, sizeLimit, charset, encoder, false, foldSegments, specials);
}
else
{
// if this is not the first sement of the encoding, we need to add either a blank or
// a newline sequence to the data
if (!firstSegment) {
if (foldSegments) {
out.append("\r\n");
}
else {
out.append(' ');
}
}
// do the encoding of the segment.
encoder.encodeWord(bytes, out, charset, specials);
}
}
/**
* Examine the content of a data source and decide what type
* of transfer encoding should be used. For text streams,
* we'll decided between 7bit, quoted-printable, and base64.
* For binary content types, we'll use either 7bit or base64.
*
* @param handler The DataHandler associated with the content.
*
* @return The string name of an encoding used to transfer the content.
*/
public static String getEncoding(final DataHandler handler) {
// if this handler has an associated data source, we can read directly from the
// data source to make this judgment. This is generally MUCH faster than asking the
// DataHandler to write out the data for us.
final DataSource ds = handler.getDataSource();
if (ds != null) {
return getEncoding(ds);
}
try {
// get a parser that allows us to make comparisons.
final ContentType content = new ContentType(handler.getContentType());
// The only access to the content bytes at this point is by asking the handler to write
// the information out to a stream. We're going to pipe this through a special stream
// that examines the bytes as they go by.
final ContentCheckingOutputStream checker = new ContentCheckingOutputStream();
handler.writeTo(checker);
// figure this out based on whether we believe this to be a text type or not.
if (content.match("text/*")) {
return checker.getTextTransferEncoding();
}
else {
return checker.getBinaryTransferEncoding();
}
} catch (final Exception e) {
// any unexpected I/O exceptions we'll force to a "safe" fallback position.
return "base64";
}
}
/**
* Determine the what transfer encoding should be used for
* data retrieved from a DataSource.
*
* @param source The DataSource for the transmitted data.
*
* @return The string name of the encoding form that should be used for
* the data.
*/
public static String getEncoding(final DataSource source) {
if(source instanceof EncodingAware) {
final String encoding = ((EncodingAware) source).getEncoding();
if(encoding != null) {
return encoding;
}
}
InputStream in = null;
try {
// get a parser that allows us to make comparisons.
final ContentType content = new ContentType(source.getContentType());
// we're probably going to have to scan the data.
in = source.getInputStream();
if (!content.match("text/*")) {
// Not purporting to be a text type? Examine the content to see we might be able to
// at least pretend it is an ascii type.
return ASCIIUtil.getBinaryTransferEncoding(in);
}
else {
return ASCIIUtil.getTextTransferEncoding(in);
}
} catch (final Exception e) {
// this was a problem...not sure what makes sense here, so we'll assume it's binary
// and we need to transfer this using Base64 encoding.
return "base64";
} finally {
// make sure we close the stream
try {
if (in != null) {
in.close();
}
} catch (final IOException e) {
}
}
}
/**
* Quote a "word" value. If the word contains any character from
* the specified "specials" list, this value is returned as a
* quoted strong. Otherwise, it is returned unchanged (an "atom").
*
* @param word The word requiring quoting.
* @param specials The set of special characters that can't appear in an unquoted
* string.
*
* @return The quoted value. This will be unchanged if the word doesn't contain
* any of the designated special characters.
*/
public static String quote(final String word, final String specials) {
final int wordLength = word.length();
// scan the string looking for problem characters
for (int i =0; i < wordLength; i++) {
final char ch = word.charAt(i);
// special escaped characters require escaping, which also implies quoting.
if (escapedChars.indexOf(ch) >= 0) {
return quoteAndEscapeString(word);
}
// now check for control characters or the designated special characters.
if (ch < 32 || ch >= 127 || specials.indexOf(ch) >= 0) {
// we know this requires quoting, but we still need to scan the entire string to
// see if contains chars that require escaping. Just go ahead and treat it as if it does.
return quoteAndEscapeString(word);
}
}
return word;
}
/**
* Take a string and return it as a formatted quoted string, with
* all characters requiring escaping handled properly.
*
* @param word The string to quote.
*
* @return The quoted string.
*/
private static String quoteAndEscapeString(final String word) {
final int wordLength = word.length();
// allocate at least enough for the string and two quotes plus a reasonable number of escaped chars.
final StringBuffer buffer = new StringBuffer(wordLength + 10);
// add the leading quote.
buffer.append('"');
for (int i = 0; i < wordLength; i++) {
final char ch = word.charAt(i);
// is this an escaped char?
if (escapedChars.indexOf(ch) >= 0) {
// add the escape marker before appending.
buffer.append('\\');
}
buffer.append(ch);
}
// now the closing quote
buffer.append('"');
return buffer.toString();
}
/**
* Translate a MIME standard character set name into the Java
* equivalent.
*
* @param charset The MIME standard name.
*
* @return The Java equivalent for this name.
*/
public static String javaCharset(final String charset) {
// nothing in, nothing out.
if (charset == null) {
return null;
}
final String mappedCharset = (String)mime2java.get(charset.toLowerCase());
// if there is no mapping, then the original name is used. Many of the MIME character set
// names map directly back into Java. The reverse isn't necessarily true.
return mappedCharset == null ? charset : mappedCharset;
}
/**
* Map a Java character set name into the MIME equivalent.
*
* @param charset The java character set name.
*
* @return The MIME standard equivalent for this character set name.
*/
public static String mimeCharset(final String charset) {
// nothing in, nothing out.
if (charset == null) {
return null;
}
final String mappedCharset = (String)java2mime.get(charset.toLowerCase());
// if there is no mapping, then the original name is used. Many of the MIME character set
// names map directly back into Java. The reverse isn't necessarily true.
return mappedCharset == null ? charset : mappedCharset;
}
/**
* Get the default character set to use, in Java name format.
* This either be the value set with the mail.mime.charset
* system property or obtained from the file.encoding system
* property. If neither of these is set, we fall back to
* 8859_1 (basically US-ASCII).
*
* @return The character string value of the default character set.
*/
public static String getDefaultJavaCharset() {
final String charset = SessionUtil.getProperty("mail.mime.charset");
if (charset != null) {
return javaCharset(charset);
}
return SessionUtil.getProperty("file.encoding", "8859_1");
}
/**
* Get the default character set to use, in MIME name format.
* This either be the value set with the mail.mime.charset
* system property or obtained from the file.encoding system
* property. If neither of these is set, we fall back to
* 8859_1 (basically US-ASCII).
*
* @return The character string value of the default character set.
*/
static String getDefaultMIMECharset() {
// if the property is specified, this can be used directly.
final String charset = SessionUtil.getProperty("mail.mime.charset");
if (charset != null) {
return charset;
}
// get the Java-defined default and map back to a MIME name.
return mimeCharset(SessionUtil.getProperty("file.encoding", "8859_1"));
}
/**
* Load the default mapping tables used by the javaCharset()
* and mimeCharset() methods. By default, these tables are
* loaded from the /META-INF/javamail.charset.map file. If
* something goes wrong loading that file, we configure things
* with a default mapping table (which just happens to mimic
* what's in the default mapping file).
*/
static private void loadCharacterSetMappings() {
java2mime = new HashMap();
mime2java = new HashMap();
// normally, these come from a character map file contained in the jar file.
try {
final InputStream map = javax.mail.internet.MimeUtility.class.getResourceAsStream("/META-INF/javamail.charset.map");
if (map != null) {
// get a reader for this so we can load.
final BufferedReader reader = new BufferedReader(new InputStreamReader(map));
readMappings(reader, java2mime);
readMappings(reader, mime2java);
}
} catch (final Exception e) {
}
// if any sort of error occurred reading the preferred file version, we could end up with empty
// mapping tables. This could cause all sorts of difficulty, so ensure they are populated with at
// least a reasonable set of defaults.
// these mappings echo what's in the default file.
if (java2mime.isEmpty()) {
java2mime.put("8859_1", "ISO-8859-1");
java2mime.put("iso8859_1", "ISO-8859-1");
java2mime.put("iso8859-1", "ISO-8859-1");
java2mime.put("8859_2", "ISO-8859-2");
java2mime.put("iso8859_2", "ISO-8859-2");
java2mime.put("iso8859-2", "ISO-8859-2");
java2mime.put("8859_3", "ISO-8859-3");
java2mime.put("iso8859_3", "ISO-8859-3");
java2mime.put("iso8859-3", "ISO-8859-3");
java2mime.put("8859_4", "ISO-8859-4");
java2mime.put("iso8859_4", "ISO-8859-4");
java2mime.put("iso8859-4", "ISO-8859-4");
java2mime.put("8859_5", "ISO-8859-5");
java2mime.put("iso8859_5", "ISO-8859-5");
java2mime.put("iso8859-5", "ISO-8859-5");
java2mime.put ("8859_6", "ISO-8859-6");
java2mime.put("iso8859_6", "ISO-8859-6");
java2mime.put("iso8859-6", "ISO-8859-6");
java2mime.put("8859_7", "ISO-8859-7");
java2mime.put("iso8859_7", "ISO-8859-7");
java2mime.put("iso8859-7", "ISO-8859-7");
java2mime.put("8859_8", "ISO-8859-8");
java2mime.put("iso8859_8", "ISO-8859-8");
java2mime.put("iso8859-8", "ISO-8859-8");
java2mime.put("8859_9", "ISO-8859-9");
java2mime.put("iso8859_9", "ISO-8859-9");
java2mime.put("iso8859-9", "ISO-8859-9");
java2mime.put("sjis", "Shift_JIS");
java2mime.put ("jis", "ISO-2022-JP");
java2mime.put("iso2022jp", "ISO-2022-JP");
java2mime.put("euc_jp", "euc-jp");
java2mime.put("koi8_r", "koi8-r");
java2mime.put("euc_cn", "euc-cn");
java2mime.put("euc_tw", "euc-tw");
java2mime.put("euc_kr", "euc-kr");
}
if (mime2java.isEmpty ()) {
mime2java.put("iso-2022-cn", "ISO2022CN");
mime2java.put("iso-2022-kr", "ISO2022KR");
mime2java.put("utf-8", "UTF8");
mime2java.put("utf8", "UTF8");
mime2java.put("ja_jp.iso2022-7", "ISO2022JP");
mime2java.put("ja_jp.eucjp", "EUCJIS");
mime2java.put ("euc-kr", "KSC5601");
mime2java.put("euckr", "KSC5601");
mime2java.put("us-ascii", "ISO-8859-1");
mime2java.put("x-us-ascii", "ISO-8859-1");
}
}
/**
* Read a section of a character map table and populate the
* target mapping table with the information. The table end
* is marked by a line starting with "--" and also ending with
* "--". Blank lines and comment lines (beginning with '#') are
* ignored.
*
* @param reader The source of the file information.
* @param table The mapping table used to store the information.
*/
static private void readMappings(final BufferedReader reader, final Map table) throws IOException {
// process lines to the EOF or the end of table marker.
while (true) {
String line = reader.readLine();
// no line returned is an EOF
if (line == null) {
return;
}
// trim so we're not messed up by trailing blanks
line = line.trim();
if (line.length() == 0 || line.startsWith("#")) {
continue;
}
// stop processing if this is the end-of-table marker.
if (line.startsWith("--") && line.endsWith("--")) {
return;
}
// we allow either blanks or tabs as token delimiters.
final StringTokenizer tokenizer = new StringTokenizer(line, " \t");
try {
final String from = tokenizer.nextToken().toLowerCase();
final String to = tokenizer.nextToken();
table.put(from, to);
} catch (final NoSuchElementException e) {
// just ignore the line if invalid.
}
}
}
/**
* Perform RFC 2047 text folding on a string of text.
*
* @param used The amount of text already "used up" on this line. This is
* typically the length of a message header that this text
* get getting added to.
* @param s The text to fold.
*
* @return The input text, with linebreaks inserted at appropriate fold points.
*/
public static String fold(int used, String s) {
// if folding is disable, unfolding is also. Return the string unchanged.
if (!SessionUtil.getBooleanProperty(MIME_FOLDTEXT, true)) {
return s;
}
int end;
// now we need to strip off any trailing "whitespace", where whitespace is blanks, tabs,
// and line break characters.
for (end = s.length() - 1; end >= 0; end--) {
final int ch = s.charAt(end);
if (ch != ' ' && ch != '\t' ) {
break;
}
}
// did we actually find something to remove? Shorten the String to the trimmed length
if (end != s.length() - 1) {
s = s.substring(0, end + 1);
}
// does the string as it exists now not require folding? We can just had that back right off.
if (s.length() + used <= FOLD_THRESHOLD) {
return s;
}
// get a buffer for the length of the string, plus room for a few line breaks.
// these are soft line breaks, so we generally need more that just the line breaks (an escape +
// CR + LF + leading space on next line);
final StringBuffer newString = new StringBuffer(s.length() + 8);
// now keep chopping this down until we've accomplished what we need.
while (used + s.length() > FOLD_THRESHOLD) {
int breakPoint = -1;
char breakChar = 0;
// now scan for the next place where we can break.
for (int i = 0; i < s.length(); i++) {
// have we passed the fold limit?
if (used + i > FOLD_THRESHOLD) {
// if we've already seen a blank, then stop now. Otherwise
// we keep going until we hit a fold point.
if (breakPoint != -1) {
break;
}
}
char ch = s.charAt(i);
// a white space character?
if (ch == ' ' || ch == '\t') {
// this might be a run of white space, so skip over those now.
breakPoint = i;
// we need to maintain the same character type after the inserted linebreak.
breakChar = ch;
i++;
while (i < s.length()) {
ch = s.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
i++;
}
}
// found an embedded new line. Escape this so that the unfolding process preserves it.
else if (ch == '\n') {
newString.append('\\');
newString.append('\n');
}
else if (ch == '\r') {
newString.append('\\');
newString.append('\n');
i++;
// if this is a CRLF pair, add the second char also
if (i < s.length() && s.charAt(i) == '\n') {
newString.append('\r');
}
}
}
// no fold point found, we punt, append the remainder and leave.
if (breakPoint == -1) {
newString.append(s);
return newString.toString();
}
newString.append(s.substring(0, breakPoint));
newString.append("\r\n");
newString.append(breakChar);
// chop the string
s = s.substring(breakPoint + 1);
// start again, and we've used the first char of the limit already with the whitespace char.
used = 1;
}
// add on the remainder, and return
newString.append(s);
return newString.toString();
}
/**
* Unfold a folded string. The unfolding process will remove
* any line breaks that are not escaped and which are also followed
* by whitespace characters.
*
* @param s The folded string.
*
* @return A new string with unfolding rules applied.
*/
public static String unfold(final String s) {
// if folding is disable, unfolding is also. Return the string unchanged.
if (!SessionUtil.getBooleanProperty(MIME_FOLDTEXT, true)) {
return s;
}
// if there are no line break characters in the string, we can just return this.
if (s.indexOf('\n') < 0 && s.indexOf('\r') < 0) {
return s;
}
// we need to scan and fix things up.
final int length = s.length();
final StringBuffer newString = new StringBuffer(length);
// scan the entire string
for (int i = 0; i < length; i++) {
final char ch = s.charAt(i);
// we have a backslash. In folded strings, escape characters are only processed as such if
// they precede line breaks. Otherwise, we leave it be.
if (ch == '\\') {
// escape at the very end? Just add the character.
if (i == length - 1) {
newString.append(ch);
}
else {
final int nextChar = s.charAt(i + 1);
// naked newline? Add the new line to the buffer, and skip the escape char.
if (nextChar == '\n') {
newString.append('\n');
i++;
}
else if (nextChar == '\r') {
// just the CR left? Add it, removing the escape.
if (i == length - 2 || s.charAt(i + 2) != '\r') {
newString.append('\r');
i++;
}
else {
// toss the escape, add both parts of the CRLF, and skip over two chars.
newString.append('\r');
newString.append('\n');
i += 2;
}
}
else {
// an escape for another purpose, just copy it over.
newString.append(ch);
}
}
}
// we have an unescaped line break
else if (ch == '\n' || ch == '\r') {
// remember the position in case we need to backtrack.
boolean CRLF = false;
if (ch == '\r') {
// check to see if we need to step over this.
if (i < length - 1 && s.charAt(i + 1) == '\n') {
i++;
// flag the type so we know what we might need to preserve.
CRLF = true;
}
}
// get a temp position scanner.
final int scan = i + 1;
// does a blank follow this new line? we need to scrap the new line and reduce the leading blanks
// down to a single blank.
if (scan < length && s.charAt(scan) == ' ') {
// add the character
newString.append(' ');
// scan over the rest of the blanks
i = scan + 1;
while (i < length && s.charAt(i) == ' ') {
i++;
}
// we'll increment down below, so back up to the last blank as the current char.
i--;
}
else {
// we must keep this line break. Append the appropriate style.
if (CRLF) {
newString.append("\r\n");
}
else {
newString.append(ch);
}
}
}
else {
// just a normal, ordinary character
newString.append(ch);
}
}
return newString.toString();
}
}
/**
* Utility class for examining content information written out
* by a DataHandler object. This stream gathers statistics on
* the stream so it can make transfer encoding determinations.
*/
class ContentCheckingOutputStream extends OutputStream {
private int asciiChars = 0;
private int nonAsciiChars = 0;
private boolean containsLongLines = false;
private boolean containsMalformedEOL = false;
private int previousChar = 0;
private int span = 0;
ContentCheckingOutputStream() {
}
@Override
public void write(final byte[] data) throws IOException {
write(data, 0, data.length);
}
@Override
public void write(final byte[] data, final int offset, final int length) throws IOException {
for (int i = 0; i < length; i++) {
write(data[offset + i]);
}
}
@Override
public void write(final int ch) {
// we found a linebreak. Reset the line length counters on either one. We don't
// really need to validate here.
if (ch == '\n' || ch == '\r') {
// we found a newline, this is only valid if the previous char was the '\r'
if (ch == '\n') {
// malformed linebreak? force this to base64 encoding.
if (previousChar != '\r') {
containsMalformedEOL = true;
}
}
// hit a line end, reset our line length counter
span = 0;
}
else {
span++;
// the text has long lines, we can't transfer this as unencoded text.
if (span > 998) {
containsLongLines = true;
}
// non-ascii character, we have to transfer this in binary.
if (!ASCIIUtil.isAscii(ch)) {
nonAsciiChars++;
}
else {
asciiChars++;
}
}
previousChar = ch;
}
public String getBinaryTransferEncoding() {
if (nonAsciiChars != 0 || containsLongLines || containsMalformedEOL) {
return "base64";
}
else {
return "7bit";
}
}
public String getTextTransferEncoding() {
// looking good so far, only valid chars here.
if (nonAsciiChars == 0) {
// does this contain long text lines? We need to use a Q-P encoding which will
// be only slightly longer, but handles folding the longer lines.
if (containsLongLines) {
return "quoted-printable";
}
else {
// ideal! Easiest one to handle.
return "7bit";
}
}
else {
// mostly characters requiring encoding? Base64 is our best bet.
if (nonAsciiChars > asciiChars) {
return "base64";
}
else {
// Q-P encoding will use fewer bytes than the full Base64.
return "quoted-printable";
}
}
}
}
| 2,006 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/ContentType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
// can be in the form major/minor; charset=jobby
/**
* @version $Rev$ $Date$
*/
public class ContentType {
private ParameterList _list;
private String _minor;
private String _major;
public ContentType() {
// the Sun version makes everything null here.
}
public ContentType(final String major, final String minor, final ParameterList list) {
_major = major;
_minor = minor;
_list = list;
}
public ContentType(final String type) throws ParseException {
// get a token parser for the type information
final HeaderTokenizer tokenizer = new HeaderTokenizer(type, HeaderTokenizer.MIME);
// get the first token, which must be an ATOM
HeaderTokenizer.Token token = tokenizer.next();
if (token.getType() != HeaderTokenizer.Token.ATOM) {
throw new ParseException("Invalid content type");
}
_major = token.getValue();
// the MIME type must be major/minor
token = tokenizer.next();
if (token.getType() != '/') {
throw new ParseException("Invalid content type");
}
// this must also be an atom. Content types are not permitted to be wild cards.
token = tokenizer.next();
if (token.getType() != HeaderTokenizer.Token.ATOM) {
throw new ParseException("Invalid content type");
}
_minor = token.getValue();
// the remainder is parameters, which ParameterList will take care of parsing.
final String remainder = tokenizer.getRemainder();
if (remainder != null) {
_list = new ParameterList(remainder);
}
}
public String getPrimaryType() {
return _major;
}
public String getSubType() {
return _minor;
}
public String getBaseType() {
return _major + "/" + _minor;
}
public String getParameter(final String name) {
return (_list == null ? null : _list.get(name));
}
public ParameterList getParameterList() {
return _list;
}
public void setPrimaryType(final String major) {
_major = major;
}
public void setSubType(final String minor) {
_minor = minor;
}
public void setParameter(final String name, final String value) {
if (_list == null) {
_list = new ParameterList();
}
_list.set(name, value);
}
public void setParameterList(final ParameterList list) {
_list = list;
}
/**
* Retrieve a RFC2045 style string representation of
* this Content-Type. Returns an empty string if
* the conversion failed.
*
* @return RFC2045 style string
*/
@Override
public String toString() {
/* Since JavaMail 1.5:
The general contract of Object.toString is that it never returns null.
The toString methods of ContentType and ContentDisposition were defined
to return null in certain error cases. Given the general toString contract
it seems unlikely that anyone ever depended on these special cases, and
it would be more useful for these classes to obey the general contract.
These methods have been changed to return an empty string in these error
cases.
*/
if (_major == null || _minor == null) {
return "";
}
// We need to format this as if we're doing it to set into the Content-Type
// header. So the parameter list gets added on as if the header name was
// also included.
String baseType = getBaseType();
if ( baseType == null) {
return "";
}
if (_list != null) {
baseType += _list.toString(baseType.length() + "Content-Type: ".length());
}
return baseType;
}
public boolean match(final ContentType other) {
if(_major == null || _minor == null) {
return false;
}
return _major.equalsIgnoreCase(other._major)
&& (_minor.equalsIgnoreCase(other._minor)
|| _minor.equals("*")
|| other._minor.equals("*"));
}
public boolean match(final String contentType) {
try {
return match(new ContentType(contentType));
} catch (final ParseException e) {
return false;
}
}
}
| 2,007 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/HeaderTokenizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
/**
* @version $Rev$ $Date$
*/
public class HeaderTokenizer {
public static class Token {
// Constant values from J2SE 1.4 API Docs (Constant values)
public static final int ATOM = -1;
public static final int COMMENT = -3;
public static final int EOF = -4;
public static final int QUOTEDSTRING = -2;
private final int _type;
private final String _value;
public Token(final int type, final String value) {
_type = type;
_value = value;
}
public int getType() {
return _type;
}
public String getValue() {
return _value;
}
}
private static final char NUL = '\0';
private static final Token EOF = new Token(Token.EOF, null);
// characters not allowed in MIME
public static final String MIME = "()<>@,;:\\\"\t []/?=";
// characters not allowed in RFC822
public static final String RFC822 = "()<>@,;:\\\"\t .[]";
private static final String WHITE = " \t\n\r";
private final String _delimiters;
private final String _header;
private final int _headerLength;
private final boolean _skip;
private int pos;
public HeaderTokenizer(final String header) {
this(header, RFC822);
}
public HeaderTokenizer(final String header, final String delimiters) {
this(header, delimiters, true);
}
public HeaderTokenizer(final String header,
final String delimiters,
final boolean skipComments) {
_skip = skipComments;
_header = header;
_delimiters = delimiters;
_headerLength=header.length();
}
//Return the rest of the Header.
//null is returned if we are already at end of header
public String getRemainder() {
if(pos > _headerLength) {
return null;
}
return _header.substring(pos);
}
public Token next() throws ParseException {
return readToken(NUL, false);
}
/**
* Parses the next token from this String.
* If endOfAtom is not NUL, the token extends until the
* endOfAtom character is seen, or to the end of the header.
* This method is useful when parsing headers that don't
* obey the MIME specification, e.g., by failing to quote
* parameter values that contain spaces.
*
* @param endOfAtom if not NUL, character marking end of token
* @return the next Token
* @exception ParseException if the parse fails
* @since JavaMail 1.5
*/
public Token next(final char endOfAtom) throws ParseException {
return next(endOfAtom, false);
}
/**
* Parses the next token from this String.
* endOfAtom is handled as above. If keepEscapes is true,
* any backslash escapes are preserved in the returned string.
* This method is useful when parsing headers that don't
* obey the MIME specification, e.g., by failing to escape
* backslashes in the filename parameter.
*
* @param endOfAtom if not NUL, character marking end of token
* @param keepEscapes keep all backslashes in returned string?
* @return the next Token
* @exception ParseException if the parse fails
* @since JavaMail 1.5
*/
public Token next(final char endOfAtom, final boolean keepEscapes)
throws ParseException {
return readToken(endOfAtom, keepEscapes);
}
public Token peek() throws ParseException {
final int start = pos;
try {
return readToken(NUL, false);
} finally {
pos = start;
}
}
/**
* Read an ATOM token from the parsed header.
*
* @return A token containing the value of the atom token.
*/
private Token readAtomicToken() {
// skip to next delimiter
final int start = pos;
final StringBuilder sb = new StringBuilder();
sb.append(_header.charAt(pos));
while (++pos < _headerLength) {
// break on the first non-atom character.
final char ch = _header.charAt(pos);
if ((_delimiters.indexOf(_header.charAt(pos)) != -1 || ch < 32 || ch >= 127)) {
break;
}
}
return new Token(Token.ATOM, _header.substring(start, pos));
}
/**
* Read the next token from the header.
*
* @return The next token from the header. White space is skipped, and comment
* tokens are also skipped if indicated.
* @exception ParseException
*/
private Token readToken(final char endOfAtom, final boolean keepEscapes) throws ParseException {
if (pos >= _headerLength) {
return EOF;
} else {
final char c = _header.charAt(pos);
// comment token...read and skip over this
if (c == '(') {
final Token comment = readComment(keepEscapes);
if (_skip) {
return readToken(endOfAtom, keepEscapes);
} else {
return comment;
}
// quoted literal
} else if (c == '\"') {
return readQuotedString('"', keepEscapes, 1);
// white space, eat this and find a real token.
} else if (WHITE.indexOf(c) != -1) {
eatWhiteSpace();
return readToken(endOfAtom, keepEscapes);
// either a CTL or special. These characters have a self-defining token type.
} else if (c < 32 || c >= 127 || _delimiters.indexOf(c) != -1) {
if (endOfAtom != NUL && c != endOfAtom) {
return readQuotedString(endOfAtom, keepEscapes, 0);
}
pos++;
return new Token(c, String.valueOf(c));
} else {
// start of an atom, parse it off.
if (endOfAtom != NUL && c != endOfAtom) {
return readQuotedString(endOfAtom, keepEscapes, 0);
}
return readAtomicToken();
}
}
}
/**
* Extract a substring from the header string and apply any
* escaping/folding rules to the string.
*
* @param start The starting offset in the header.
* @param end The header end offset + 1.
*
* @return The processed string value.
* @exception ParseException
*/
private String getEscapedValue(final int start, final int end, final boolean keepEscapes) throws ParseException {
final StringBuffer value = new StringBuffer();
for (int i = start; i < end; i++) {
final char ch = _header.charAt(i);
// is this an escape character?
if (ch == '\\') {
i++;
if (i == end) {
throw new ParseException("Invalid escape character");
}
if(keepEscapes) {
value.append("\\");
}
value.append(_header.charAt(i));
}
// line breaks are ignored, except for naked '\n' characters, which are consider
// parts of linear whitespace.
else if (ch == '\r') {
// see if this is a CRLF sequence, and skip the second if it is.
if (i < end - 1 && _header.charAt(i + 1) == '\n') {
i++;
}
}
else {
// just append the ch value.
value.append(ch);
}
}
return value.toString();
}
/**
* Read a comment from the header, applying nesting and escape
* rules to the content.
*
* @return A comment token with the token value.
* @exception ParseException
*/
private Token readComment(final boolean keepEscapes) throws ParseException {
final int start = pos + 1;
int nesting = 1;
boolean requiresEscaping = false;
// skip to end of comment/string
while (++pos < _headerLength) {
final char ch = _header.charAt(pos);
if (ch == ')') {
nesting--;
if (nesting == 0) {
break;
}
}
else if (ch == '(') {
nesting++;
}
else if (ch == '\\') {
pos++;
requiresEscaping = true;
}
// we need to process line breaks also
else if (ch == '\r') {
requiresEscaping = true;
}
}
if (nesting != 0) {
throw new ParseException("Unbalanced comments");
}
String value;
if (requiresEscaping) {
value = getEscapedValue(start, pos, keepEscapes);
}
else {
value = _header.substring(start, pos++);
}
return new Token(Token.COMMENT, value);
}
/**
* Parse out a quoted string from the header, applying escaping
* rules to the value.
*
* @return The QUOTEDSTRING token with the value.
* @exception ParseException
*/
private Token readQuotedString(final char endChar, final boolean keepEscapes, final int offset) throws ParseException {
final int start = pos+offset;
boolean requiresEscaping = false;
// skip to end of comment/string
while (++pos < _headerLength) {
final char ch = _header.charAt(pos);
if (ch == endChar) {
String value;
if (requiresEscaping) {
value = getEscapedValue(start, pos++, keepEscapes);
}
else {
value = _header.substring(start, pos++);
}
return new Token(Token.QUOTEDSTRING, value);
}
else if (ch == '\\') {
pos++;
requiresEscaping = true;
}
// we need to process line breaks also
else if (ch == '\r') {
requiresEscaping = true;
}
}
// we ran out of chars in the string. If the end char is a quote, then there
// is a missing quote somewhere
if (endChar == '"') {
throw new ParseException("Missing '\"'");
}
// otherwise, we can just return whatever is left
String value;
if (requiresEscaping) {
value = getEscapedValue(start, pos, keepEscapes);
} else {
value = _header.substring(start, pos);
}
return new Token(Token.QUOTEDSTRING, trimWhiteSpace(value));
}
/**
* Skip white space in the token string.
*/
private void eatWhiteSpace() {
// skip to end of whitespace
while (++pos < _headerLength
&& WHITE.indexOf(_header.charAt(pos)) != -1) {
;
}
}
/**
* linear white spaces must be removed from quoted text or text
*
LWSP-char = SPACE / HTAB ; semantics = SPACE
linear-white-space = 1*([CRLF] LWSP-char) ; semantics = SPACE
; CRLF => folding
text = <any CHAR, including bare ; => atoms, specials,
CR & bare LF, but NOT ; comments and
including CRLF> ; quoted-strings are
; NOT recognized.
atom = 1*<any CHAR except specials, SPACE and CTLs>
quoted-string = <"> *(qtext/quoted-pair) <">; Regular qtext or
; quoted chars.
qtext = <any CHAR excepting <">, ; => may be folded
"\" & CR, and including
linear-white-space>
domain-literal = "[" *(dtext / quoted-pair) "]"
*/
private static String trimWhiteSpace(final String s) {
char c;
int i;
for (i = s.length() - 1; i >= 0; i--) {
if ((
(c = s.charAt(i)) != ' ') && // space
(c != '\t') && // tab
(c != '\r') && // CR
(c != '\n')) { // LF
break;
}
}
if (i <= 0) {
return "";
} else {
return s.substring(0, i + 1);
}
}
}
| 2,008 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/ParseException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public class ParseException extends MessagingException {
private static final long serialVersionUID = 7649991205183658089L;
public ParseException() {
super();
}
public ParseException(final String message) {
super(message);
}
}
| 2,009 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/MimePartDataSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownServiceException;
import javax.activation.DataSource;
import javax.mail.MessageAware;
import javax.mail.MessageContext;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public class MimePartDataSource implements DataSource, MessageAware {
// the part that provides the data form this data source.
protected MimePart part;
public MimePartDataSource(final MimePart part) {
this.part = part;
}
public InputStream getInputStream() throws IOException {
try {
InputStream stream;
if (part instanceof MimeMessage) {
stream = ((MimeMessage) part).getContentStream();
} else if (part instanceof MimeBodyPart) {
stream = ((MimeBodyPart) part).getContentStream();
} else {
throw new MessagingException("Unknown part");
}
return checkPartEncoding(part, stream);
} catch (final MessagingException e) {
throw (IOException) new IOException(e.getMessage()).initCause(e);
}
}
/**
* For a given part, decide it the data stream requires
* wrappering with a stream for decoding a particular
* encoding.
*
* @param part The part we're extracting.
* @param stream The raw input stream for the part.
*
* @return An input stream configured for reading the
* source part and decoding it into raw bytes.
*/
private InputStream checkPartEncoding(final MimePart part, final InputStream stream) throws MessagingException {
String encoding = part.getEncoding();
// if nothing is specified, there's nothing to do
if (encoding == null) {
return stream;
}
// now screen out the ones that never need decoding
encoding = encoding.toLowerCase();
if (encoding.equals("7bit") || encoding.equals("8bit") || encoding.equals("binary")) {
return stream;
}
// now we need to check the content type to prevent
// MultiPart types from getting decoded, since the part is just an envelope around other
// parts
final String contentType = part.getContentType();
if (contentType != null) {
try {
final ContentType type = new ContentType(contentType);
// no decoding done here
if (type.match("multipart/*")) {
return stream;
}
} catch (final ParseException e) {
// ignored....bad content type means we handle as a normal part
}
}
// ok, wrap this is a decoding stream if required
return MimeUtility.decode(stream, encoding);
}
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
public String getContentType() {
try {
return part.getContentType();
} catch (final MessagingException e) {
return null;
}
}
public String getName() {
try {
if (part instanceof MimeBodyPart) {
return ((MimeBodyPart) part).getFileName();
}
} catch (final MessagingException mex) {
// ignore it
}
return "";
}
public synchronized MessageContext getMessageContext() {
return new MessageContext(part);
}
}
| 2,010 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/MimeMessage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.IllegalWriteException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.HeaderTokenizer.Token;
import org.apache.geronimo.mail.util.ASCIIUtil;
import org.apache.geronimo.mail.util.SessionUtil;
/**
* @version $Rev$ $Date$
*/
public class MimeMessage extends Message implements MimePart {
private static final String MIME_ADDRESS_STRICT = "mail.mime.address.strict";
private static final String MIME_DECODEFILENAME = "mail.mime.decodefilename";
private static final String MIME_ENCODEFILENAME = "mail.mime.encodefilename";
private static final String MAIL_ALTERNATES = "mail.alternates";
private static final String MAIL_REPLYALLCC = "mail.replyallcc";
// static used to ensure message ID uniqueness
private static int messageID = 0;
/**
* Extends {@link javax.mail.Message.RecipientType} to support addition recipient types.
*/
public static class RecipientType extends Message.RecipientType {
/**
* Recipient type for Usenet news.
*/
public static final RecipientType NEWSGROUPS = new RecipientType("Newsgroups");
protected RecipientType(final String type) {
super(type);
}
/**
* Ensure the singleton is returned.
*
* @return resolved object
*/
@Override
protected Object readResolve() throws ObjectStreamException {
if (this.type.equals("Newsgroups")) {
return NEWSGROUPS;
} else {
return super.readResolve();
}
}
}
/**
* The {@link DataHandler} for this Message's content.
*/
protected DataHandler dh;
/**
* This message's content (unless sourced from a SharedInputStream).
*/
/**
* If our content is a Multipart or Message object, we save it
* the first time it's created by parsing a stream so that changes
* to the contained objects will not be lost.
*
* If this field is not null, it's return by the {@link #getContent}
* method. The {@link #getContent} method sets this field if it
* would return a Multipart or MimeMessage object. This field is
* is cleared by the {@link #setDataHandler} method.
*
* @since JavaMail 1.5
*/
protected Object cachedContent;
protected byte[] content;
/**
* If the data for this message was supplied by a {@link SharedInputStream}
* then this is another such stream representing the content of this message;
* if this field is non-null, then {@link #content} will be null.
*/
protected InputStream contentStream;
/**
* This message's headers.
*/
protected InternetHeaders headers;
/**
* This message's flags.
*/
protected Flags flags;
/**
* Flag indicating that the message has been modified; set to true when
* an empty message is created or when {@link #saveChanges()} is called.
*/
protected boolean modified;
/**
* Flag indicating that the message has been saved.
*/
protected boolean saved;
private final MailDateFormat dateFormat = new MailDateFormat();
/**
* Create a new MimeMessage.
* An empty message is created, with empty {@link #headers} and empty {@link #flags}.
* The {@link #modified} flag is set.
*
* @param session the session for this message
*/
public MimeMessage(final Session session) {
super(session);
headers = new InternetHeaders();
flags = new Flags();
// empty messages are modified, because the content is not there, and require saving before use.
modified = true;
saved = false;
}
/**
* Create a MimeMessage by reading an parsing the data from the supplied stream.
*
* @param session the session for this message
* @param in the stream to load from
* @throws MessagingException if there is a problem reading or parsing the stream
*/
public MimeMessage(final Session session, final InputStream in) throws MessagingException {
this(session);
parse(in);
// this message is complete, so marked as unmodified.
modified = false;
// and no saving required
saved = true;
}
/**
* Copy a MimeMessage.
*
* @param message the message to copy
* @throws MessagingException is there was a problem copying the message
*/
public MimeMessage(final MimeMessage message) throws MessagingException {
super(message.session);
// get a copy of the source message flags
flags = message.getFlags();
// this is somewhat difficult to do. There's a lot of data in both the superclass and this
// class that needs to undergo a "deep cloning" operation. These operations don't really exist
// on the objects in question, so the only solution I can come up with is to serialize the
// message data of the source object using the write() method, then reparse the data in this
// object. I've not found a lot of uses for this particular constructor, so perhaps that's not
// really all that bad of a solution.
// serialize this out to an in-memory stream.
final ByteArrayOutputStream copy = new ByteArrayOutputStream();
try {
// write this out the stream.
message.writeTo(copy);
copy.close();
// I think this ends up creating a new array for the data, but I'm not aware of any more
// efficient options.
final ByteArrayInputStream inData = new ByteArrayInputStream(copy.toByteArray());
// now reparse this message into this object.
inData.close();
parse (inData);
// writing out the source data requires saving it, so we should consider this one saved also.
saved = true;
// this message is complete, so marked as unmodified.
modified = false;
} catch (final IOException e) {
// I'm not sure ByteArrayInput/OutputStream actually throws IOExceptions or not, but the method
// signatures declare it, so we need to deal with it. Turning it into a messaging exception
// should fit the bill.
throw new MessagingException("Error copying MimeMessage data", e);
}
}
/**
* Create an new MimeMessage in the supplied {@link Folder} and message number.
*
* @param folder the Folder that contains the new message
* @param number the message number of the new message
*/
protected MimeMessage(final Folder folder, final int number) {
super(folder, number);
headers = new InternetHeaders();
flags = new Flags();
// saving primarly involves updates to the message header. Since we're taking the header info
// from a message store in this context, we mark the message as saved.
saved = true;
// we've not filled in the content yet, so this needs to be marked as modified
modified = true;
}
/**
* Create a MimeMessage by reading an parsing the data from the supplied stream.
*
* @param folder the folder for this message
* @param in the stream to load from
* @param number the message number of the new message
* @throws MessagingException if there is a problem reading or parsing the stream
*/
protected MimeMessage(final Folder folder, final InputStream in, final int number) throws MessagingException {
this(folder, number);
parse(in);
// this message is complete, so marked as unmodified.
modified = false;
// and no saving required
saved = true;
}
/**
* Create a MimeMessage with the supplied headers and content.
*
* @param folder the folder for this message
* @param headers the headers for the new message
* @param content the content of the new message
* @param number the message number of the new message
* @throws MessagingException if there is a problem reading or parsing the stream
*/
protected MimeMessage(final Folder folder, final InternetHeaders headers, final byte[] content, final int number) throws MessagingException {
this(folder, number);
this.headers = headers;
this.content = content;
// this message is complete, so marked as unmodified.
modified = false;
}
/**
* Parse the supplied stream and initialize {@link #headers} and {@link #content} appropriately.
*
* @param in the stream to read
* @throws MessagingException if there was a problem parsing the stream
*/
protected void parse(InputStream in) throws MessagingException {
in = new BufferedInputStream(in);
// create the headers first from the stream. Note: We need to do this
// by calling createInternetHeaders because subclasses might wish to add
// additional headers to the set initialized from the stream.
headers = createInternetHeaders(in);
// now we need to get the rest of the content as a byte array...this means reading from the current
// position in the stream until the end and writing it to an accumulator ByteArrayOutputStream.
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
final byte buffer[] = new byte[1024];
int count;
while ((count = in.read(buffer, 0, 1024)) != -1) {
baos.write(buffer, 0, count);
}
} catch (final Exception e) {
throw new MessagingException(e.toString(), e);
}
// and finally extract the content as a byte array.
content = baos.toByteArray();
}
/**
* Get the message "From" addresses. This looks first at the
* "From" headers, and no "From" header is found, the "Sender"
* header is checked. Returns null if not found.
*
* @return An array of addresses identifying the message from target. Returns
* null if this is not resolveable from the headers.
* @exception MessagingException
*/
@Override
public Address[] getFrom() throws MessagingException {
// strict addressing controls this.
final boolean strict = isStrictAddressing();
Address[] result = getHeaderAsInternetAddresses("From", strict);
if (result == null) {
result = getHeaderAsInternetAddresses("Sender", strict);
}
return result;
}
/**
* Set the RFC 822 "From" header field. Any existing values are
* replaced with the given addresses. If address is null,
* this header is removed.
*
* @param address the sender(s) of this message
* @exception IllegalWriteException if the underlying
* implementation does not support modification
* of existing values
* @exception IllegalStateException if this message is
* obtained from a READ_ONLY folder.
* @exception MessagingException
* @since JvaMail 1.5
*/
public void setFrom(final String address) throws MessagingException {
setHeader("From", InternetAddress.parse(address));
}
/**
* Set the current message "From" recipient. This replaces any
* existing "From" header. If the address is null, the header is
* removed.
*
* @param address The new "From" target.
*
* @exception MessagingException
*/
@Override
public void setFrom(final Address address) throws MessagingException {
setHeader("From", address);
}
/**
* Set the "From" header using the value returned by {@link InternetAddress#getLocalAddress(javax.mail.Session)}.
*
* @throws MessagingException if there was a problem setting the header
*/
@Override
public void setFrom() throws MessagingException {
final InternetAddress address = InternetAddress.getLocalAddress(session);
// no local address resolvable? This is an error.
if (address == null) {
throw new MessagingException("No local address defined");
}
setFrom(address);
}
/**
* Add a set of addresses to the existing From header.
*
* @param addresses The list to add.
*
* @exception MessagingException
*/
@Override
public void addFrom(final Address[] addresses) throws MessagingException {
addHeader("From", addresses);
}
/**
* Return the "Sender" header as an address.
*
* @return the "Sender" header as an address, or null if not present
* @throws MessagingException if there was a problem parsing the header
*/
public Address getSender() throws MessagingException {
final Address[] addrs = getHeaderAsInternetAddresses("Sender", isStrictAddressing());
return addrs != null && addrs.length > 0 ? addrs[0] : null;
}
/**
* Set the "Sender" header. If the address is null, this
* will remove the current sender header.
*
* @param address the new Sender address
*
* @throws MessagingException
* if there was a problem setting the header
*/
public void setSender(final Address address) throws MessagingException {
setHeader("Sender", address);
}
/**
* Gets the recipients by type. Returns null if there are no
* headers of the specified type. Acceptable RecipientTypes are:
*
* javax.mail.Message.RecipientType.TO
* javax.mail.Message.RecipientType.CC
* javax.mail.Message.RecipientType.BCC
* javax.mail.internet.MimeMessage.RecipientType.NEWSGROUPS
*
* @param type The message RecipientType identifier.
*
* @return The array of addresses for the specified recipient types.
* @exception MessagingException
*/
@Override
public Address[] getRecipients(final Message.RecipientType type) throws MessagingException {
// is this a NEWSGROUP request? We need to handle this as a special case here, because
// this needs to return NewsAddress instances instead of InternetAddress items.
if (type == RecipientType.NEWSGROUPS) {
return getHeaderAsNewsAddresses(getHeaderForRecipientType(type));
}
// the other types are all internet addresses.
return getHeaderAsInternetAddresses(getHeaderForRecipientType(type), isStrictAddressing());
}
/**
* Retrieve all of the recipients defined for this message. This
* returns a merged array of all possible message recipients
* extracted from the headers. The relevant header types are:
*
*
* javax.mail.Message.RecipientType.TO
* javax.mail.Message.RecipientType.CC
* javax.mail.Message.RecipientType.BCC
* javax.mail.internet.MimeMessage.RecipientType.NEWSGROUPS
*
* @return An array of all target message recipients.
* @exception MessagingException
*/
@Override
public Address[] getAllRecipients() throws MessagingException {
final List recipients = new ArrayList();
addRecipientsToList(recipients, javax.mail.Message.RecipientType.TO);
addRecipientsToList(recipients, javax.mail.Message.RecipientType.CC);
addRecipientsToList(recipients, javax.mail.Message.RecipientType.BCC);
addRecipientsToList(recipients, RecipientType.NEWSGROUPS);
// this is supposed to return null if nothing is there.
if (recipients.isEmpty()) {
return null;
}
return (Address[]) recipients.toArray(new Address[recipients.size()]);
}
/**
* Utility routine to merge different recipient types into a
* single list.
*
* @param list The accumulator list.
* @param type The recipient type to extract.
*
* @exception MessagingException
*/
private void addRecipientsToList(final List list, final Message.RecipientType type) throws MessagingException {
Address[] recipients;
if (type == RecipientType.NEWSGROUPS) {
recipients = getHeaderAsNewsAddresses(getHeaderForRecipientType(type));
}
else {
recipients = getHeaderAsInternetAddresses(getHeaderForRecipientType(type), isStrictAddressing());
}
if (recipients != null) {
list.addAll(Arrays.asList(recipients));
}
}
/**
* Set a recipients list for a particular recipient type. If the
* list is null, the corresponding header is removed.
*
* @param type The type of recipient to set.
* @param addresses The list of addresses.
*
* @exception MessagingException
*/
@Override
public void setRecipients(final Message.RecipientType type, final Address[] addresses) throws MessagingException {
setHeader(getHeaderForRecipientType(type), addresses);
}
/**
* Set a recipient field to a string address (which may be a
* list or group type).
*
* If the address is null, the field is removed.
*
* @param type The type of recipient to set.
* @param address The address string.
*
* @exception MessagingException
*/
public void setRecipients(final Message.RecipientType type, final String address) throws MessagingException {
setOrRemoveHeader(getHeaderForRecipientType(type), address);
}
/**
* Add a list of addresses to a target recipient list.
*
* @param type The target recipient type.
* @param address An array of addresses to add.
*
* @exception MessagingException
*/
@Override
public void addRecipients(final Message.RecipientType type, final Address[] address) throws MessagingException {
addHeader(getHeaderForRecipientType(type), address);
}
/**
* Add an address to a target recipient list by string name.
*
* @param type The target header type.
* @param address The address to add.
*
* @exception MessagingException
*/
public void addRecipients(final Message.RecipientType type, final String address) throws MessagingException {
addHeader(getHeaderForRecipientType(type), address);
}
/**
* Get the ReplyTo address information. The headers are parsed
* using the "mail.mime.address.strict" setting. If the "Reply-To" header does
* not have any addresses, then the value of the "From" field is used.
*
* @return An array of addresses obtained from parsing the header.
* @exception MessagingException
*/
@Override
public Address[] getReplyTo() throws MessagingException {
Address[] addresses = getHeaderAsInternetAddresses("Reply-To", isStrictAddressing());
if (addresses == null) {
addresses = getFrom();
}
return addresses;
}
/**
* Set the Reply-To field to the provided list of addresses. If
* the address list is null, the header is removed.
*
* @param address The new field value.
*
* @exception MessagingException
*/
@Override
public void setReplyTo(final Address[] address) throws MessagingException {
setHeader("Reply-To", address);
}
/**
* Returns the value of the "Subject" header. If the subject
* is encoded as an RFC 2047 value, the value is decoded before
* return. If decoding fails, the raw string value is
* returned.
*
* @return The String value of the subject field.
* @exception MessagingException
*/
@Override
public String getSubject() throws MessagingException {
final String subject = getSingleHeader("Subject");
if (subject == null) {
return null;
} else {
try {
// this needs to be unfolded before decodeing.
return MimeUtility.decodeText(MimeUtility.unfold(subject));
} catch (final UnsupportedEncodingException e) {
// ignored.
}
}
return subject;
}
/**
* Set the value for the "Subject" header. If the subject
* contains non US-ASCII characters, it is encoded in RFC 2047
* fashion.
*
* If the subject value is null, the Subject field is removed.
*
* @param subject The new subject value.
*
* @exception MessagingException
*/
@Override
public void setSubject(final String subject) throws MessagingException {
// just set this using the default character set.
setSubject(subject, null);
}
public void setSubject(final String subject, final String charset) throws MessagingException {
// standard null removal (yada, yada, yada....)
if (subject == null) {
removeHeader("Subject");
}
else {
try {
// encode this, and then fold to fit the line lengths.
setHeader("Subject", MimeUtility.fold(9, MimeUtility.encodeText(subject, charset, null)));
} catch (final UnsupportedEncodingException e) {
throw new MessagingException("Encoding error", e);
}
}
}
/**
* Get the value of the "Date" header field. Returns null if
* if the field is absent or the date is not in a parseable format.
*
* @return A Date object parsed according to RFC 822.
* @exception MessagingException
*/
@Override
public Date getSentDate() throws MessagingException {
final String value = getSingleHeader("Date");
if (value == null) {
return null;
}
try {
return dateFormat.parse(value);
} catch (final java.text.ParseException e) {
return null;
}
}
/**
* Set the message sent date. This updates the "Date" header.
* If the provided date is null, the header is removed.
*
* @param sent The new sent date value.
*
* @exception MessagingException
*/
@Override
public void setSentDate(final Date sent) throws MessagingException {
setOrRemoveHeader("Date", dateFormat.format(sent));
}
/**
* Get the message received date. The Sun implementation is
* documented as always returning null, so this one does too.
*
* @return Always returns null.
* @exception MessagingException
*/
@Override
public Date getReceivedDate() throws MessagingException {
return null;
}
/**
* Return the content size of this message. This is obtained
* either from the size of the content field (if available) or
* from the contentStream, IFF the contentStream returns a positive
* size. Returns -1 if the size is not available.
*
* @return Size of the content in bytes.
* @exception MessagingException
*/
public int getSize() throws MessagingException {
if (content != null) {
return content.length;
}
if (contentStream != null) {
try {
final int size = contentStream.available();
if (size > 0) {
return size;
}
} catch (final IOException e) {
// ignore
}
}
return -1;
}
/**
* Retrieve the line count for the current message. Returns
* -1 if the count cannot be determined.
*
* The Sun implementation always returns -1, so this version
* does too.
*
* @return The content line count (always -1 in this implementation).
* @exception MessagingException
*/
public int getLineCount() throws MessagingException {
return -1;
}
/**
* Returns the current content type (defined in the "Content-Type"
* header. If not available, "text/plain" is the default.
*
* @return The String name of the message content type.
* @exception MessagingException
*/
public String getContentType() throws MessagingException {
String value = getSingleHeader("Content-Type");
if (value == null) {
value = "text/plain";
}
return value;
}
/**
* Tests to see if this message has a mime-type match with the
* given type name.
*
* @param type The tested type name.
*
* @return If this is a type match on the primary and secondare portion of the types.
* @exception MessagingException
*/
public boolean isMimeType(final String type) throws MessagingException {
return new ContentType(getContentType()).match(type);
}
/**
* Retrieve the message "Content-Disposition" header field.
* This value represents how the part should be represented to
* the user.
*
* @return The string value of the Content-Disposition field.
* @exception MessagingException
*/
public String getDisposition() throws MessagingException {
final String disp = getSingleHeader("Content-Disposition");
if (disp != null) {
return new ContentDisposition(disp).getDisposition();
}
return null;
}
/**
* Set a new dispostion value for the "Content-Disposition" field.
* If the new value is null, the header is removed.
*
* @param disposition
* The new disposition value.
*
* @exception MessagingException
*/
public void setDisposition(final String disposition) throws MessagingException {
if (disposition == null) {
removeHeader("Content-Disposition");
}
else {
// the disposition has parameters, which we'll attempt to preserve in any existing header.
final String currentHeader = getSingleHeader("Content-Disposition");
if (currentHeader != null) {
final ContentDisposition content = new ContentDisposition(currentHeader);
content.setDisposition(disposition);
setHeader("Content-Disposition", content.toString());
}
else {
// set using the raw string.
setHeader("Content-Disposition", disposition);
}
}
}
/**
* Decode the Content-Transfer-Encoding header to determine
* the transfer encoding type.
*
* @return The string name of the required encoding.
* @exception MessagingException
*/
public String getEncoding() throws MessagingException {
// this might require some parsing to sort out.
final String encoding = getSingleHeader("Content-Transfer-Encoding");
if (encoding != null) {
// we need to parse this into ATOMs and other constituent parts. We want the first
// ATOM token on the string.
final HeaderTokenizer tokenizer = new HeaderTokenizer(encoding, HeaderTokenizer.MIME);
final Token token = tokenizer.next();
while (token.getType() != Token.EOF) {
// if this is an ATOM type, return it.
if (token.getType() == Token.ATOM) {
return token.getValue();
}
}
// not ATOMs found, just return the entire header value....somebody might be able to make sense of
// this.
return encoding;
}
// no header, nothing to return.
return null;
}
/**
* Retrieve the value of the "Content-ID" header. Returns null
* if the header does not exist.
*
* @return The current header value or null.
* @exception MessagingException
*/
public String getContentID() throws MessagingException {
return getSingleHeader("Content-ID");
}
public void setContentID(final String cid) throws MessagingException {
setOrRemoveHeader("Content-ID", cid);
}
public String getContentMD5() throws MessagingException {
return getSingleHeader("Content-MD5");
}
public void setContentMD5(final String md5) throws MessagingException {
setOrRemoveHeader("Content-MD5", md5);
}
public String getDescription() throws MessagingException {
final String description = getSingleHeader("Content-Description");
if (description != null) {
try {
// this could be both folded and encoded. Return this to usable form.
return MimeUtility.decodeText(MimeUtility.unfold(description));
} catch (final UnsupportedEncodingException e) {
// ignore
}
}
// return the raw version for any errors.
return description;
}
public void setDescription(final String description) throws MessagingException {
setDescription(description, null);
}
public void setDescription(final String description, final String charset) throws MessagingException {
if (description == null) {
removeHeader("Content-Description");
}
else {
try {
setHeader("Content-Description", MimeUtility.fold(21, MimeUtility.encodeText(description, charset, null)));
} catch (final UnsupportedEncodingException e) {
throw new MessagingException(e.getMessage(), e);
}
}
}
public String[] getContentLanguage() throws MessagingException {
return getHeader("Content-Language");
}
public void setContentLanguage(final String[] languages) throws MessagingException {
if (languages == null) {
removeHeader("Content-Language");
} else if (languages.length == 1) {
setHeader("Content-Language", languages[0]);
} else {
final StringBuffer buf = new StringBuffer(languages.length * 20);
buf.append(languages[0]);
for (int i = 1; i < languages.length; i++) {
buf.append(',').append(languages[i]);
}
setHeader("Content-Language", buf.toString());
}
}
public String getMessageID() throws MessagingException {
return getSingleHeader("Message-ID");
}
public String getFileName() throws MessagingException {
// see if there is a disposition. If there is, parse off the filename parameter.
final String disposition = getDisposition();
String filename = null;
if (disposition != null) {
filename = new ContentDisposition(disposition).getParameter("filename");
}
// if there's no filename on the disposition, there might be a name parameter on a
// Content-Type header.
if (filename == null) {
final String type = getContentType();
if (type != null) {
try {
filename = new ContentType(type).getParameter("name");
} catch (final ParseException e) {
}
}
}
// if we have a name, we might need to decode this if an additional property is set.
if (filename != null && SessionUtil.getBooleanProperty(session, MIME_DECODEFILENAME, false)) {
try {
filename = MimeUtility.decodeText(filename);
} catch (final UnsupportedEncodingException e) {
throw new MessagingException("Unable to decode filename", e);
}
}
return filename;
}
public void setFileName(String name) throws MessagingException {
// there's an optional session property that requests file name encoding...we need to process this before
// setting the value.
if (name != null && SessionUtil.getBooleanProperty(session, MIME_ENCODEFILENAME, false)) {
try {
name = MimeUtility.encodeText(name);
} catch (final UnsupportedEncodingException e) {
throw new MessagingException("Unable to encode filename", e);
}
}
// get the disposition string.
String disposition = getDisposition();
// if not there, then this is an attachment.
if (disposition == null) {
disposition = Part.ATTACHMENT;
}
// now create a disposition object and set the parameter.
final ContentDisposition contentDisposition = new ContentDisposition(disposition);
contentDisposition.setParameter("filename", name);
// serialize this back out and reset.
setDisposition(contentDisposition.toString());
}
public InputStream getInputStream() throws MessagingException, IOException {
return getDataHandler().getInputStream();
}
protected InputStream getContentStream() throws MessagingException {
if (contentStream != null) {
return contentStream;
}
if (content != null) {
return new ByteArrayInputStream(content);
} else {
throw new MessagingException("No content");
}
}
public InputStream getRawInputStream() throws MessagingException {
return getContentStream();
}
public synchronized DataHandler getDataHandler() throws MessagingException {
if (dh == null) {
dh = new DataHandler(new MimePartDataSource(this));
}
return dh;
}
public Object getContent() throws MessagingException, IOException {
if (cachedContent != null) {
return cachedContent;
}
final Object c = getDataHandler().getContent();
if (MimeBodyPart.cacheMultipart && (c instanceof Multipart || c instanceof Message) && (content != null || contentStream != null)) {
cachedContent = c;
if (c instanceof MimeMultipart) {
((MimeMultipart) c).parse();
}
}
return c;
}
//TODO make synchronized?
public void setDataHandler(final DataHandler handler) throws MessagingException {
dh = handler;
// if we have a handler override, then we need to invalidate any content
// headers that define the types. This information will be derived from the
// data heander unless subsequently overridden.
removeHeader("Content-Type");
removeHeader("Content-Transfer-Encoding");
cachedContent = null;
}
public void setContent(final Object content, final String type) throws MessagingException {
setDataHandler(new DataHandler(content, type));
}
public void setText(final String text) throws MessagingException {
setText(text, null, "plain");
}
public void setText(final String text, final String charset) throws MessagingException {
setText(text, charset, "plain");
}
public void setText(final String text, String charset, final String subtype) throws MessagingException {
// we need to sort out the character set if one is not provided.
if (charset == null) {
// if we have non us-ascii characters here, we need to adjust this.
if (!ASCIIUtil.isAscii(text)) {
charset = MimeUtility.getDefaultMIMECharset();
}
else {
charset = "us-ascii";
}
}
setContent(text, "text/" + subtype + "; charset=" + MimeUtility.quote(charset, HeaderTokenizer.MIME));
}
public void setContent(final Multipart part) throws MessagingException {
setDataHandler(new DataHandler(part, part.getContentType()));
part.setParent(this);
}
@Override
public Message reply(final boolean replyToAll) throws MessagingException {
return reply(replyToAll, true);
}
private Message replyInternal(final boolean replyToAll, final boolean setOriginalAnswered) throws MessagingException {
// create a new message in this session.
final MimeMessage reply = createMimeMessage(session);
// get the header and add the "Re:" bit, if necessary.
String newSubject = getSubject();
if (newSubject != null) {
// check to see if it already begins with "Re: " (in any case).
// Add one on if we don't have it yet.
if (!newSubject.regionMatches(true, 0, "Re: ", 0, 4)) {
newSubject = "Re: " + newSubject;
}
reply.setSubject(newSubject);
}
// if this message has a message ID, then add a In-Reply-To and References
// header to the reply message
final String messageID = getSingleHeader("Message-ID");
if (messageID != null) {
// this one is just set unconditionally
reply.setHeader("In-Reply-To", messageID);
// we might already have a references header. If so, then add our message id
// on the the end
String references = getSingleHeader("References");
if (references == null) {
references = messageID;
}
else {
references = references + " " + messageID;
}
// and this is a replacement for whatever might be there.
reply.setHeader("References", MimeUtility.fold("References: ".length(), references));
}
// set the target recipients the replyTo value
reply.setRecipients(Message.RecipientType.TO, getReplyTo());
// need to reply to everybody? More things to add.
if (replyToAll) {
// when replying, we want to remove "duplicates" in the final list.
final HashMap masterList = new HashMap();
// reply to all implies add the local sender. Add this to the list if resolveable.
final InternetAddress localMail = InternetAddress.getLocalAddress(session);
if (localMail != null) {
masterList.put(localMail.getAddress(), localMail);
}
// see if we have some local aliases to deal with.
final String alternates = session.getProperty(MAIL_ALTERNATES);
if (alternates != null) {
// parse this string list and merge with our set.
final Address[] alternateList = InternetAddress.parse(alternates, false);
mergeAddressList(masterList, alternateList);
}
// the master list now contains an a list of addresses we will exclude from
// the addresses. From this point on, we're going to prune any additional addresses
// against this list, AND add any new addresses to the list
// now merge in the main recipients, and merge in the other recipents as well
Address[] toList = pruneAddresses(masterList, getRecipients(Message.RecipientType.TO));
if (toList.length != 0) {
// now check to see what sort of reply we've been asked to send.
// if replying to all as a CC, then we need to add to the CC list, otherwise they are
// TO recipients.
if (SessionUtil.getBooleanProperty(session, MAIL_REPLYALLCC, false)) {
reply.addRecipients(Message.RecipientType.CC, toList);
}
else {
reply.addRecipients(Message.RecipientType.TO, toList);
}
}
// and repeat for the CC list.
toList = pruneAddresses(masterList, getRecipients(Message.RecipientType.CC));
if (toList.length != 0) {
reply.addRecipients(Message.RecipientType.CC, toList);
}
// a news group list is separate from the normal addresses. We just take these recepients
// asis without trying to prune duplicates.
toList = getRecipients(RecipientType.NEWSGROUPS);
if (toList != null && toList.length != 0) {
reply.addRecipients(RecipientType.NEWSGROUPS, toList);
}
}
// this is a bit of a pain. We can't set the flags here by specifying the system flag, we need to
// construct a flag item instance inorder to set it.
// this is an answered email.
if(setOriginalAnswered) {
setFlags(new Flags(Flags.Flag.ANSWERED), true);
}
// all done, return the constructed Message object.
return reply;
}
/**
* Get a new Message suitable for a reply to this message.
* The new Message will have its attributes and headers
* set up appropriately. Note that this new message object
* will be empty, i.e., it will not have a "content".
* These will have to be suitably filled in by the client.
*
* If replyToAll is set, the new Message will be addressed
* to all recipients of this message. Otherwise, the reply will be
* addressed to only the sender of this message (using the value
* of the getReplyTo method).
*
* If setAnswered is set, the
* {@link javax.mail.Flags.Flag#ANSWERED ANSWERED} flag is set
* in this message.
*
* The "Subject" field is filled in with the original subject
* prefixed with "Re:" (unless it already starts with "Re:").
* The "In-Reply-To" header is set in the new message if this
* message has a "Message-Id" header.
*
* The current implementation also sets the "References" header
* in the new message to include the contents of the "References"
* header (or, if missing, the "In-Reply-To" header) in this message,
* plus the contents of the "Message-Id" header of this message,
* as described in RFC 2822.
*
* @param replyToAll reply should be sent to all recipients
* of this message
* @param setAnswered set the ANSWERED flag in this message?
* @return the reply Message
* @exception MessagingException
* @since JavaMail 1.5
*/
public Message reply(final boolean replyToAll, final boolean setAnswered)
throws MessagingException {
/* Since JavaMail 1.5:
* Add a method to control whether the ANSWERED flag is set in the original
message when creating a reply message.
*/
return replyInternal(replyToAll, setAnswered);
}
/**
* Merge a set of addresses into a master accumulator list, eliminating
* duplicates.
*
* @param master The set of addresses we've accumulated so far.
* @param list The list of addresses to merge in.
*/
private void mergeAddressList(final Map master, final Address[] list) {
// make sure we have a list.
if (list == null) {
return;
}
for (int i = 0; i < list.length; i++) {
final InternetAddress address = (InternetAddress)list[i];
// if not in the master list already, add it now.
if (!master.containsKey(address.getAddress())) {
master.put(address.getAddress(), address);
}
}
}
/**
* Prune a list of addresses against our master address list,
* returning the "new" addresses. The master list will be
* updated with this new set of addresses.
*
* @param master The master address list of addresses we've seen before.
* @param list The new list of addresses to prune.
*
* @return An array of addresses pruned of any duplicate addresses.
*/
private Address[] pruneAddresses(final Map master, final Address[] list) {
// return an empy array if we don't get an input list.
if (list == null) {
return new Address[0];
}
// optimistically assume there are no addresses to eliminate (common).
final ArrayList prunedList = new ArrayList(list.length);
for (int i = 0; i < list.length; i++) {
final InternetAddress address = (InternetAddress)list[i];
// if not in the master list, this is a new one. Add to both the master list and
// the pruned list.
if (!master.containsKey(address.getAddress())) {
master.put(address.getAddress(), address);
prunedList.add(address);
}
}
// convert back to list form.
return (Address[])prunedList.toArray(new Address[0]);
}
/**
* Write the message out to a stream in RFC 822 format.
*
* @param out The target output stream.
*
* @exception MessagingException
* @exception IOException
*/
public void writeTo(final OutputStream out) throws MessagingException, IOException {
writeTo(out, null);
}
/**
* Write the message out to a target output stream, excluding the
* specified message headers.
*
* @param out The target output stream.
* @param ignoreHeaders
* An array of header types to ignore. This can be null, which means
* write out all headers.
*
* @exception MessagingException
* @exception IOException
*/
public void writeTo(final OutputStream out, final String[] ignoreHeaders) throws MessagingException, IOException {
// make sure everything is saved before we write
if (!saved) {
saveChanges();
}
// write out the headers first
headers.writeTo(out, ignoreHeaders);
// add the separater between the headers and the data portion.
out.write('\r');
out.write('\n');
// if the modfied flag, we don't have current content, so the data handler needs to
// take care of writing this data out.
if (modified) {
final OutputStream encoderStream = MimeUtility.encode(out, getEncoding());
dh.writeTo(encoderStream);
encoderStream.flush();
} else {
// if we have content directly, we can write this out now.
if (content != null) {
out.write(content);
}
else {
// see if we can get a content stream for this message. We might have had one
// explicitly set, or a subclass might override the get method to provide one.
final InputStream in = getContentStream();
final byte[] buffer = new byte[8192];
int length = in.read(buffer);
// copy the data stream-to-stream.
while (length > 0) {
out.write(buffer, 0, length);
length = in.read(buffer);
}
in.close();
}
}
// flush any data we wrote out, but do not close the stream. That's the caller's duty.
out.flush();
}
/**
* Retrieve all headers that match a given name.
*
* @param name The target name.
*
* @return The set of headers that match the given name. These headers
* will be the decoded() header values if these are RFC 2047
* encoded.
* @exception MessagingException
*/
public String[] getHeader(final String name) throws MessagingException {
return headers.getHeader(name);
}
/**
* Get all headers that match a particular name, as a single string.
* Individual headers are separated by the provided delimiter. If
* the delimiter is null, only the first header is returned.
*
* @param name The source header name.
* @param delimiter The delimiter string to be used between headers. If null, only
* the first is returned.
*
* @return The headers concatenated as a single string.
* @exception MessagingException
*/
public String getHeader(final String name, final String delimiter) throws MessagingException {
return headers.getHeader(name, delimiter);
}
/**
* Set a new value for a named header.
*
* @param name The name of the target header.
* @param value The new value for the header.
*
* @exception MessagingException
*/
public void setHeader(final String name, final String value) throws MessagingException {
headers.setHeader(name, value);
}
/**
* Conditionally set or remove a named header. If the new value
* is null, the header is removed.
*
* @param name The header name.
* @param value The new header value. A null value causes the header to be
* removed.
*
* @exception MessagingException
*/
private void setOrRemoveHeader(final String name, final String value) throws MessagingException {
if (value == null) {
headers.removeHeader(name);
}
else {
headers.setHeader(name, value);
}
}
/**
* Add a new value to an existing header. The added value is
* created as an additional header of the same type and value.
*
* @param name The name of the target header.
* @param value The removed header.
*
* @exception MessagingException
*/
public void addHeader(final String name, final String value) throws MessagingException {
headers.addHeader(name, value);
}
/**
* Remove a header with the given name.
*
* @param name The name of the removed header.
*
* @exception MessagingException
*/
public void removeHeader(final String name) throws MessagingException {
headers.removeHeader(name);
}
/**
* Retrieve the complete list of message headers, as an enumeration.
*
* @return An Enumeration of the message headers.
* @exception MessagingException
*/
public Enumeration getAllHeaders() throws MessagingException {
return headers.getAllHeaders();
}
public Enumeration getMatchingHeaders(final String[] names) throws MessagingException {
return headers.getMatchingHeaders(names);
}
public Enumeration getNonMatchingHeaders(final String[] names) throws MessagingException {
return headers.getNonMatchingHeaders(names);
}
public void addHeaderLine(final String line) throws MessagingException {
headers.addHeaderLine(line);
}
public Enumeration getAllHeaderLines() throws MessagingException {
return headers.getAllHeaderLines();
}
public Enumeration getMatchingHeaderLines(final String[] names) throws MessagingException {
return headers.getMatchingHeaderLines(names);
}
public Enumeration getNonMatchingHeaderLines(final String[] names) throws MessagingException {
return headers.getNonMatchingHeaderLines(names);
}
/**
* 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
*/
@Override
public synchronized Flags getFlags() throws MessagingException {
return (Flags) flags.clone();
}
/**
* Check whether the supplied flag is set.
* The default implementation checks the flags returned by {@link #getFlags()}.
*
* @param flag the flags to check for
* @return true if the flags is set
* @throws MessagingException if there was a problem accessing the Store
*/
@Override
public synchronized boolean isSet(final Flags.Flag flag) throws MessagingException {
return flags.contains(flag);
}
/**
* Set or clear a flag value.
*
* @param flag The set of flags to effect.
* @param set The value to set the flag to (true or false).
*
* @exception MessagingException
*/
@Override
public synchronized void setFlags(final Flags flag, final boolean set) throws MessagingException {
if (set) {
flags.add(flag);
}
else {
flags.remove(flag);
}
}
/**
* Saves any changes on this message. When called, the modified
* and saved flags are set to true and updateHeaders() is called
* to force updates.
*
* @exception MessagingException
*/
@Override
public void saveChanges() throws MessagingException {
// setting modified invalidates the current content.
modified = true;
saved = true;
// update message headers from the content.
updateHeaders();
}
/**
* Update the internet headers so that they make sense. This
* will attempt to make sense of the message content type
* given the state of the content.
*
* @exception MessagingException
*/
protected void updateHeaders() throws MessagingException {
final DataHandler handler = getDataHandler();
try {
// figure out the content type. If not set, we'll need to figure this out.
String type = dh.getContentType();
// we might need to reconcile the content type and our explicitly set type
final String explicitType = getSingleHeader("Content-Type");
// parse this content type out so we can do matches/compares.
final ContentType contentType = new ContentType(type);
// is this a multipart content?
if (contentType.match("multipart/*")) {
// the content is suppose to be a MimeMultipart. Ping it to update it's headers as well.
try {
final MimeMultipart part = (MimeMultipart)handler.getContent();
part.updateHeaders();
} catch (final ClassCastException e) {
throw new MessagingException("Message content is not MimeMultipart", e);
}
}
else if (!contentType.match("message/rfc822")) {
// simple part, we need to update the header type information
// if no encoding is set yet, figure this out from the data handler content.
if (getSingleHeader("Content-Transfer-Encoding") == null) {
setHeader("Content-Transfer-Encoding", MimeUtility.getEncoding(handler));
}
// is a content type header set? Check the property to see if we need to set this.
if (explicitType == null) {
if (SessionUtil.getBooleanProperty(session, "MIME_MAIL_SETDEFAULTTEXTCHARSET", true)) {
// is this a text type? Figure out the encoding and make sure it is set.
if (contentType.match("text/*")) {
// the charset should be specified as a parameter on the MIME type. If not there,
// try to figure one out.
if (contentType.getParameter("charset") == null) {
final String encoding = getEncoding();
// if we're sending this as 7-bit ASCII, our character set need to be
// compatible.
if (encoding != null && encoding.equalsIgnoreCase("7bit")) {
contentType.setParameter("charset", "us-ascii");
}
else {
// get the global default.
contentType.setParameter("charset", MimeUtility.getDefaultMIMECharset());
}
// replace the original type string
type = contentType.toString();
}
}
}
}
}
// if we don't have a content type header, then create one.
if (explicitType == null) {
// get the disposition header, and if it is there, copy the filename parameter into the
// name parameter of the type.
final String disp = getSingleHeader("Content-Disposition");
if (disp != null) {
// parse up the string value of the disposition
final ContentDisposition disposition = new ContentDisposition(disp);
// now check for a filename value
final String filename = disposition.getParameter("filename");
// copy and rename the parameter, if it exists.
if (filename != null) {
contentType.setParameter("name", filename);
// set the header with the updated content type information.
type = contentType.toString();
}
}
// if no header has been set, then copy our current type string (which may
// have been modified above)
setHeader("Content-Type", type);
}
// make sure we set the MIME version
setHeader("MIME-Version", "1.0");
// new javamail 1.4 requirement.
updateMessageID();
if (cachedContent != null) {
dh = new DataHandler(cachedContent, getContentType());
cachedContent = null;
content = null;
if (contentStream != null) {
try {
contentStream.close();
} catch (final IOException ioex) {
//np-op
}
}
contentStream = null;
}
} catch (final IOException e) {
throw new MessagingException("Error updating message headers", e);
}
}
/**
* Create a new set of internet headers from the
* InputStream
*
* @param in The header source.
*
* @return A new InternetHeaders object containing the
* appropriate headers.
* @exception MessagingException
*/
protected InternetHeaders createInternetHeaders(final InputStream in) throws MessagingException {
// internet headers has a constructor for just this purpose
return new InternetHeaders(in);
}
/**
* Convert a header into an array of NewsAddress items.
*
* @param header The name of the source header.
*
* @return The parsed array of addresses.
* @exception MessagingException
*/
private Address[] getHeaderAsNewsAddresses(final String header) throws MessagingException {
// NB: We're using getHeader() here to allow subclasses an opportunity to perform lazy loading
// of the headers.
final String mergedHeader = getHeader(header, ",");
if (mergedHeader != null) {
return NewsAddress.parse(mergedHeader);
}
return null;
}
private Address[] getHeaderAsInternetAddresses(final String header, final boolean strict) throws MessagingException {
// NB: We're using getHeader() here to allow subclasses an opportunity to perform lazy loading
// of the headers.
final String mergedHeader = getHeader(header, ",");
if (mergedHeader != null) {
return InternetAddress.parseHeader(mergedHeader, strict);
}
return null;
}
/**
* Check to see if we require strict addressing on parsing
* internet headers.
*
* @return The current value of the "mail.mime.address.strict" session
* property, or true, if the property is not set.
*/
private boolean isStrictAddressing() {
return SessionUtil.getBooleanProperty(session, MIME_ADDRESS_STRICT, true);
}
/**
* Set a named header to the value of an address field.
*
* @param header The header name.
* @param address The address value. If the address is null, the header is removed.
*
* @exception MessagingException
*/
private void setHeader(final String header, final Address address) throws MessagingException {
if (address == null) {
removeHeader(header);
}
else {
setHeader(header, address.toString());
}
}
/**
* Set a header to a list of addresses.
*
* @param header The header name.
* @param addresses An array of addresses to set the header to. If null, the
* header is removed.
*/
private void setHeader(final String header, final Address[] addresses) {
if (addresses == null) {
headers.removeHeader(header);
}
else {
headers.setHeader(header, addresses);
}
}
private void addHeader(final String header, final Address[] addresses) throws MessagingException {
headers.addHeader(header, InternetAddress.toString(addresses));
}
private String getHeaderForRecipientType(final Message.RecipientType type) throws MessagingException {
if (javax.mail.Message.RecipientType.TO == type) {
return "To";
} else if (javax.mail.Message.RecipientType.CC == type) {
return "Cc";
} else if (javax.mail.Message.RecipientType.BCC == type) {
return "Bcc";
} else if (RecipientType.NEWSGROUPS == type) {
return "Newsgroups";
} else {
throw new MessagingException("Unsupported recipient type: " + type.toString());
}
}
/**
* Utility routine to get a header as a single string value
* rather than an array of headers.
*
* @param name The name of the header.
*
* @return The single string header value. If multiple headers exist,
* the additional ones are ignored.
* @exception MessagingException
*/
private String getSingleHeader(final String name) throws MessagingException {
final String[] values = getHeader(name);
if (values == null || values.length == 0) {
return null;
} else {
return values[0];
}
}
/**
* Update the message identifier after headers have been updated.
*
* The default message id is composed of the following items:
*
* 1) A newly created object's hash code.
* 2) A uniqueness counter
* 3) The current time in milliseconds
* 4) The string JavaMail
* 5) The user's local address as returned by InternetAddress.getLocalAddress().
*
* @exception MessagingException
*/
protected void updateMessageID() throws MessagingException {
final StringBuffer id = new StringBuffer();
id.append('<');
id.append(new Object().hashCode());
id.append('.');
id.append(messageID++);
id.append(System.currentTimeMillis());
id.append('.');
id.append("JavaMail.");
// get the local address and apply a suitable default.
final InternetAddress localAddress = InternetAddress.getLocalAddress(session);
if (localAddress != null) {
id.append(localAddress.getAddress());
}
else {
id.append("javamailuser@localhost");
}
id.append('>');
setHeader("Message-ID", id.toString());
}
/**
* Method used to create a new MimeMessage instance. This method
* is used whenever the MimeMessage class needs to create a new
* Message instance (e.g, reply()). This method allows subclasses
* to override the class of message that gets created or set
* default values, if needed.
*
* @param session The session associated with this message.
*
* @return A newly create MimeMessage instance.
* @throws javax.mail.MessagingException if the MimeMessage could not be created
*/
protected MimeMessage createMimeMessage(final Session session) throws javax.mail.MessagingException {
return new MimeMessage(session);
}
}
| 2,011 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/MimePart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.util.Enumeration;
import javax.mail.MessagingException;
import javax.mail.Part;
/**
* @version $Rev$ $Date$
*/
public interface MimePart extends Part {
public abstract void addHeaderLine(String line) throws MessagingException;
public abstract Enumeration getAllHeaderLines() throws MessagingException;
public abstract String getContentID() throws MessagingException;
public abstract String[] getContentLanguage() throws MessagingException;
public abstract String getContentMD5() throws MessagingException;
public abstract String getEncoding() throws MessagingException;
public abstract String getHeader(String header, String delimiter)
throws MessagingException;
public abstract Enumeration getMatchingHeaderLines(String[] names)
throws MessagingException;
public abstract Enumeration getNonMatchingHeaderLines(String[] names)
throws MessagingException;
public abstract void setContentLanguage(String[] languages)
throws MessagingException;
public abstract void setContentMD5(String content)
throws MessagingException;
public abstract void setText(String text) throws MessagingException;
public abstract void setText(String text, String charset)
throws MessagingException;
public abstract void setText(String text, String charset, String subType)
throws MessagingException;
}
| 2,012 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/MimeMultipart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.MultipartDataSource;
import org.apache.geronimo.mail.util.SessionUtil;
/**
* @version $Rev$ $Date$
*/
public class MimeMultipart extends Multipart {
private static final String MIME_IGNORE_MISSING_ENDBOUNDARY = "mail.mime.multipart.ignoremissingendboundary";
private static final String MIME_IGNORE_MISSING_BOUNDARY_PARAMETER = "mail.mime.multipart.ignoremissingboundaryparameter";
private static final String MIME_IGNORE_EXISTING_BOUNDARY_PARAMETER = "mail.mime.multipart.ignoreexistingboundaryparameter";
private static final String MIME_ALLOWEMPTY = "mail.mime.multipart.allowempty";
/**
* DataSource that provides our InputStream.
*/
protected DataSource ds;
/**
* Indicates if the data has been parsed.
*/
protected boolean parsed = true;
// the content type information
private transient ContentType type;
/** Have we seen the final bounary line?
*
* @since JavaMail 1.5
*/
protected boolean complete = true;
/**
* The MIME multipart preamble text, the text that
* occurs before the first boundary line.
*
* @since JavaMail 1.5
*/
protected String preamble = null;
/**
* Flag corresponding to the "mail.mime.multipart.ignoremissingendboundary"
* property, set in the {@link #initializeProperties} method called from
* constructors and the parse method.
*
* @since JavaMail 1.5
*/
protected boolean ignoreMissingEndBoundary = true;
/**
* Flag corresponding to the
* "mail.mime.multipart.ignoremissingboundaryparameter"
* property, set in the {@link #initializeProperties} method called from
* constructors and the parse method.
*
* @since JavaMail 1.5
*/
protected boolean ignoreMissingBoundaryParameter = true;
/**
* Flag corresponding to the
* "mail.mime.multipart.ignoreexistingboundaryparameter"
* property, set in the {@link #initializeProperties} method called from
* constructors and the parse method.
*
* @since JavaMail 1.5
*/
protected boolean ignoreExistingBoundaryParameter = false;
/**
* Flag corresponding to the "mail.mime.multipart.allowempty"
* property, set in the {@link #initializeProperties} method called from
* constructors and the parse method.
*
* @since JavaMail 1.5
*/
protected boolean allowEmpty = false;
/**
* Initialize flags that control parsing behavior,
* based on System properties described above in
* the class documentation.
*
* @since JavaMail 1.5
*/
protected void initializeProperties() {
ignoreMissingEndBoundary = SessionUtil.getBooleanProperty(MIME_IGNORE_MISSING_ENDBOUNDARY, true);
ignoreMissingBoundaryParameter = SessionUtil.getBooleanProperty(MIME_IGNORE_MISSING_BOUNDARY_PARAMETER, true);
ignoreExistingBoundaryParameter = SessionUtil.getBooleanProperty(MIME_IGNORE_EXISTING_BOUNDARY_PARAMETER, false);
allowEmpty = SessionUtil.getBooleanProperty(MIME_ALLOWEMPTY, false);
}
/**
* Create an empty MimeMultipart with content type "multipart/mixed"
*/
public MimeMultipart() {
this("mixed");
}
/**
* Create an empty MimeMultipart with the subtype supplied.
*
* @param subtype the subtype
*/
public MimeMultipart(final String subtype) {
type = new ContentType("multipart", subtype, null);
type.setParameter("boundary", getBoundary());
contentType = type.toString();
initializeProperties();
}
/**
* Create a MimeMultipart from the supplied DataSource.
*
* @param dataSource the DataSource to use
* @throws MessagingException
*/
public MimeMultipart(final DataSource dataSource) throws MessagingException {
ds = dataSource;
if (dataSource instanceof MultipartDataSource) {
super.setMultipartDataSource((MultipartDataSource) dataSource);
parsed = true;
} else {
// We keep the original, provided content type string so that we
// don't end up changing quoting/formatting of the header unless
// changes are made to the content type. James is somewhat dependent
// on that behavior.
contentType = ds.getContentType();
type = new ContentType(contentType);
parsed = false;
}
}
/**
* Construct a MimeMultipart object of the default "mixed" subtype,
* and with the given body parts. More body parts may be added later.
*
* @since JavaMail 1.5
*/
public MimeMultipart(final BodyPart... parts) throws MessagingException {
this("mixed");
this.parts.addAll(Arrays.asList(parts));
}
/**
* Construct a MimeMultipart object of the given subtype
* and with the given body parts. More body parts may be added later.
*
* @since JavaMail 1.5
*/
public MimeMultipart(final String subtype, final BodyPart... parts)
throws MessagingException {
this(subtype);
this.parts.addAll(Arrays.asList(parts));
}
public void setSubType(final String subtype) throws MessagingException {
type.setSubType(subtype);
contentType = type.toString();
}
@Override
public int getCount() throws MessagingException {
parse();
return super.getCount();
}
@Override
public synchronized BodyPart getBodyPart(final int part) throws MessagingException {
parse();
return super.getBodyPart(part);
}
public BodyPart getBodyPart(final String cid) throws MessagingException {
parse();
for (int i = 0; i < parts.size(); i++) {
final MimeBodyPart bodyPart = (MimeBodyPart) parts.get(i);
if (cid.equals(bodyPart.getContentID())) {
return bodyPart;
}
}
return null;
}
protected void updateHeaders() throws MessagingException {
parse();
for (int i = 0; i < parts.size(); i++) {
final MimeBodyPart bodyPart = (MimeBodyPart) parts.get(i);
bodyPart.updateHeaders();
}
}
private static byte[] dash = { '-', '-' };
private static byte[] crlf = { 13, 10 };
@Override
public void writeTo(final OutputStream out) throws IOException, MessagingException {
parse();
final String boundary = type.getParameter("boundary");
final byte[] bytes = boundary.getBytes("ISO8859-1");
if(!allowEmpty && parts.size() == 0) {
throw new MessagingException("Multipart content with no body parts is not allowed");
}
if (preamble != null) {
final byte[] preambleBytes = preamble.getBytes("ISO8859-1");
// write this out, followed by a line break.
out.write(preambleBytes);
out.write(crlf);
}
for (int i = 0; i < parts.size(); i++) {
final BodyPart bodyPart = (BodyPart) parts.get(i);
out.write(dash);
out.write(bytes);
out.write(crlf);
bodyPart.writeTo(out);
out.write(crlf);
}
out.write(dash);
out.write(bytes);
out.write(dash);
out.write(crlf);
out.flush();
}
protected void parse() throws MessagingException {
if (parsed) {
return;
}
initializeProperties();
try {
final ContentType cType = new ContentType(contentType);
final String boundaryString = cType.getParameter("boundary");
if(!ignoreMissingBoundaryParameter && boundaryString == null) {
throw new MessagingException("Missing boundary parameter in content-type");
}
final InputStream is = new BufferedInputStream(ds.getInputStream());
BufferedInputStream pushbackInStream = null;
boolean boundaryFound = false;
byte[] boundary = null;
if (boundaryString == null || ignoreExistingBoundaryParameter) {
pushbackInStream = new BufferedInputStream(is, 1200);
// read until we find something that looks like a boundary string
boundary = readTillFirstBoundary(pushbackInStream);
boundaryFound = boundary != null;
}
else {
boundary = ("--" + boundaryString).getBytes("ISO8859-1");
pushbackInStream = new BufferedInputStream(is, boundary.length + 1000);
boundaryFound = readTillFirstBoundary(pushbackInStream, boundary);
}
if(allowEmpty && !boundaryFound) {
parsed = true;
return;
}
if(!allowEmpty && !boundaryFound) {
throw new MessagingException("Multipart content with no body parts is not allowed");
}
while (true) {
MimeBodyPartInputStream partStream;
partStream = new MimeBodyPartInputStream(pushbackInStream, boundary);
addBodyPart(new MimeBodyPart(partStream));
// terminated by an EOF rather than a proper boundary?
if (!partStream.boundaryFound) {
if (!ignoreMissingEndBoundary) {
throw new MessagingException("Missing Multi-part end boundary");
}
complete = false;
break;
}
// if we hit the final boundary, stop processing this
if (partStream.finalBoundaryFound) {
break;
}
}
} catch (final Exception e){
throw new MessagingException(e.toString(),e);
}
parsed = true;
}
/**
* Move the read pointer to the beginning of the first part
* read till the end of first boundary. Any data read before this point are
* saved as the preamble.
*
* @param pushbackInStream
* @param boundary
* @throws MessagingException
*/
private byte[] readTillFirstBoundary(final BufferedInputStream pushbackInStream) throws MessagingException {
final ByteArrayOutputStream preambleStream = new ByteArrayOutputStream();
try {
while (true) {
// read the next line
final byte[] line = readLine(pushbackInStream);
// hit an EOF?
if (line == null || line.length==0) {
return null;//throw new MessagingException("Unexpected End of Stream while searching for first Mime Boundary");
}
// if this looks like a boundary, then make it so
if (line.length > 2 && line[0] == '-' && line[1] == '-') {
// save the preamble, if there is one.
final byte[] preambleBytes = preambleStream.toByteArray();
if (preambleBytes.length > 0) {
preamble = new String(preambleBytes, "ISO8859-1");
}
return stripLinearWhiteSpace(line);
}
else {
// this is part of the preamble.
preambleStream.write(line);
preambleStream.write('\r');
preambleStream.write('\n');
}
}
} catch (final IOException ioe) {
throw new MessagingException(ioe.toString(), ioe);
}
}
/**
* Scan a line buffer stripping off linear whitespace
* characters, returning a new array without the
* characters, if possible.
*
* @param line The source line buffer.
*
* @return A byte array with white space characters removed,
* if necessary.
*/
private byte[] stripLinearWhiteSpace(final byte[] line) {
int index = line.length - 1;
// if the last character is not a space or tab, we
// can use this unchanged
if (line[index] != ' ' && line[index] != '\t') {
return line;
}
// scan backwards for the first non-white space
for (; index > 0; index--) {
if (line[index] != ' ' && line[index] != '\t') {
break;
}
}
// make a shorter copy of this
final byte[] newLine = new byte[index + 1];
System.arraycopy(line, 0, newLine, 0, index + 1);
return newLine;
}
/**
* Move the read pointer to the beginning of the first part
* read till the end of first boundary. Any data read before this point are
* saved as the preamble.
*
* @param pushbackInStream
* @param boundary
* @throws MessagingException
*/
private boolean readTillFirstBoundary(final BufferedInputStream pushbackInStream, final byte[] boundary) throws MessagingException {
final ByteArrayOutputStream preambleStream = new ByteArrayOutputStream();
try {
while (true) {
// read the next line
final byte[] line = readLine(pushbackInStream);
// hit an EOF?
if (line == null || line.length==0) {
return false;//throw new MessagingException("Unexpected End of Stream while searching for first Mime Boundary");
}
// apply the boundary comparison rules to this
if (compareBoundary(line, boundary)) {
// save the preamble, if there is one.
final byte[] preambleBytes = preambleStream.toByteArray();
if (preambleBytes.length > 0) {
preamble = new String(preambleBytes, "ISO8859-1");
}
return true;
}
// this is part of the preamble.
preambleStream.write(line);
preambleStream.write('\r');
preambleStream.write('\n');
}
} catch (final IOException ioe) {
throw new MessagingException(ioe.toString(), ioe);
}
}
/**
* Perform a boundary comparison, taking into account
* potential linear white space
*
* @param line The line to compare.
* @param boundary The boundary we're searching for
*
* @return true if this is a valid boundary line, false for
* any mismatches.
*/
private boolean compareBoundary(final byte[] line, final byte[] boundary) {
// if the line is too short, this is an easy failure
if (line.length < boundary.length) {
return false;
}
// this is the most common situation
if (line.length == boundary.length) {
return Arrays.equals(line, boundary);
}
// the line might have linear white space after the boundary portions
for (int i = 0; i < boundary.length; i++) {
// fail on any mismatch
if (line[i] != boundary[i]) {
return false;
}
}
// everything after the boundary portion must be linear whitespace
for (int i = boundary.length; i < line.length; i++) {
// fail on any mismatch
if (line[i] != ' ' && line[i] != '\t') {
return false;
}
}
// these are equivalent
return true;
}
/**
* Read a single line of data from the input stream,
* returning it as an array of bytes.
*
* @param in The source input stream.
*
* @return A byte array containing the line data. Returns
* null if there's nothing left in the stream.
* @exception MessagingException
*/
private byte[] readLine(final BufferedInputStream in) throws IOException
{
final ByteArrayOutputStream line = new ByteArrayOutputStream();
while (in.available() > 0) {
int value = in.read();
if (value == -1) {
// if we have nothing in the accumulator, signal an EOF back
if (line.size() == 0) {
return null;
}
break;
}
else if (value == '\r') {
in.mark(10);
value = in.read();
// we expect to find a linefeed after the carriage return, but
// some things play loose with the rules.
if (value != '\n') {
in.reset();
}
break;
}
else if (value == '\n') {
// naked linefeed, allow that
break;
}
else {
// write this to the line
line.write((byte)value);
}
}
// return this as an array of bytes
return line.toByteArray();
}
protected InternetHeaders createInternetHeaders(final InputStream in) throws MessagingException {
return new InternetHeaders(in);
}
protected MimeBodyPart createMimeBodyPart(final InternetHeaders headers, final byte[] data) throws MessagingException {
return new MimeBodyPart(headers, data);
}
protected MimeBodyPart createMimeBodyPart(final InputStream in) throws MessagingException {
return new MimeBodyPart(in);
}
// static used to track boundary value allocations to help ensure uniqueness.
private static int part;
private synchronized static String getBoundary() {
int i;
synchronized(MimeMultipart.class) {
i = part++;
}
final StringBuffer buf = new StringBuffer(64);
buf.append("----=_Part_").append(i).append('_').append((new Object()).hashCode()).append('.').append(System.currentTimeMillis());
return buf.toString();
}
private class MimeBodyPartInputStream extends InputStream {
BufferedInputStream inStream;
public boolean boundaryFound = false;
byte[] boundary;
public boolean finalBoundaryFound = false;
public MimeBodyPartInputStream(final BufferedInputStream inStream, final byte[] boundary) {
super();
this.inStream = inStream;
this.boundary = boundary;
}
/**
* The base reading method for reading one character
* at a time.
*
* @return The read character, or -1 if an EOF was encountered.
* @exception IOException
*/
@Override
public int read() throws IOException {
if (boundaryFound) {
return -1;
}
// read the next value from stream
final int firstChar = inStream.read();
// premature end? Handle it like a boundary located
if (firstChar == -1) {
//DO NOT treat this a a boundary because if we do so we have no chance to detect missing end boundaries
return -1;
}
// we first need to look for a line boundary. If we find a boundary, it can be followed by the
// boundary marker, so we need to remember what sort of thing we found, then read ahead looking
// for the part boundary.
// NB:, we only handle [\r]\n--boundary marker[--]
// we need to at least accept what most mail servers would consider an
// invalid format using just '\n'
if (firstChar != '\r' && firstChar != '\n') {
// not a \r, just return the byte as is
return firstChar;
}
// we might need to rewind to this point. The padding is to allow for
// line terminators and linear whitespace on the boundary lines
inStream.mark(boundary.length + 1000);
// we need to keep track of the first read character in case we need to
// rewind back to the mark point
int value = firstChar;
// if this is a '\r', then we require the '\n'
if (value == '\r') {
// now scan ahead for the second character
value = inStream.read();
if (value != '\n') {
// only a \r, so this can't be a boundary. Return the
// \r as if it was data, after first resetting
inStream.reset();
return '\r';
}
}
value = inStream.read();
// if the next character is not a boundary start, we
// need to handle this as a normal line end
if ((byte) value != boundary[0]) {
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// we're here because we found a "\r\n-" sequence, which is a potential
// boundary marker. Read the individual characters of the next line until
// we have a mismatch
// read value is the first byte of the boundary. Start matching the
// next characters to find a boundary
int boundaryIndex = 0;
while ((boundaryIndex < boundary.length) && ((byte) value == boundary[boundaryIndex])) {
value = inStream.read();
boundaryIndex++;
}
// if we didn't match all the way, we need to push back what we've read and
// return the EOL character
if (boundaryIndex != boundary.length) {
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// The full boundary sequence should be \r\n--boundary string[--]\r\n
// if the last character we read was a '-', check for the end terminator
if (value == '-') {
value = inStream.read();
// crud, we have a bad boundary terminator. We need to unwind this all the way
// back to the lineend and pretend none of this ever happened
if (value != '-') {
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// on the home stretch, but we need to verify the LWSP/EOL sequence
value = inStream.read();
// first skip over the linear whitespace
while (value == ' ' || value == '\t') {
value = inStream.read();
}
// We've matched the final boundary, skipped any whitespace, but
// we've hit the end of the stream. This is highly likely when
// we have nested multiparts, since the linend terminator for the
// final boundary marker is eated up as the start of the outer
// boundary marker. No CRLF sequence here is ok.
if (value == -1) {
// we've hit the end of times...
finalBoundaryFound = true;
// we have a boundary, so return this as an EOF condition
boundaryFound = true;
return -1;
}
// this must be a CR or a LF...which leaves us even more to push back and forget
if (value != '\r' && value != '\n') {
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// if this is carriage return, check for a linefeed
if (value == '\r') {
// last check, this must be a line feed
value = inStream.read();
if (value != '\n') {
// SO CLOSE!
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
}
// we've hit the end of times...
finalBoundaryFound = true;
}
else {
// first skip over the linear whitespace
while (value == ' ' || value == '\t') {
value = inStream.read();
}
// this must be a CR or a LF...which leaves us even more to push back and forget
if (value != '\r' && value != '\n') {
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
// if this is carriage return, check for a linefeed
if (value == '\r') {
// last check, this must be a line feed
value = inStream.read();
if (value != '\n') {
// SO CLOSE!
// Boundary not found. Restoring bytes skipped.
// just reset and return the first character as data
inStream.reset();
return firstChar;
}
}
}
// we have a boundary, so return this as an EOF condition
boundaryFound = true;
return -1;
}
}
/**
* Return true if the final boundary line for this multipart was
* seen when parsing the data.
*
* @return
* @exception MessagingException
*/
public boolean isComplete() throws MessagingException {
// make sure we've parsed this
parse();
return complete;
}
/**
* Returns the preamble text that appears before the first bady
* part of a MIME multi part. The preamble is optional, so this
* might be null.
*
* @return The preamble text string.
* @exception MessagingException
*/
public String getPreamble() throws MessagingException {
parse();
return preamble;
}
/**
* Set the message preamble text. This will be written before
* the first boundary of a multi-part message.
*
* @param preamble The new boundary text. This is complete lines of text, including
* new lines.
*
* @exception MessagingException
*/
public void setPreamble(final String preamble) throws MessagingException {
this.preamble = preamble;
}
}
| 2,013 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/PreencodedMimeBodyPart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.IOException;
import java.io.OutputStream;
import javax.mail.MessagingException;
/**
* @version $Rev$ $Date$
*/
public class PreencodedMimeBodyPart extends MimeBodyPart {
// the defined transfer encoding
private final String transferEncoding;
/**
* Create a new body part with the specified MIME transfer encoding.
*
* @param encoding The content encoding.
*/
public PreencodedMimeBodyPart(final String encoding) {
transferEncoding = encoding;
}
/**
* Retieve the defined encoding for this body part.
*
* @return
* @exception MessagingException
*/
@Override
public String getEncoding() throws MessagingException {
return transferEncoding;
}
/**
* Write the body part content to the stream without applying
* and additional encodings.
*
* @param out The target output stream.
*
* @exception IOException
* @exception MessagingException
*/
@Override
public void writeTo(final OutputStream out) throws IOException, MessagingException {
headers.writeTo(out, null);
// add the separater between the headers and the data portion.
out.write('\r');
out.write('\n');
// write this out without getting an encoding stream
getDataHandler().writeTo(out);
out.flush();
}
/**
* Override of update headers to ensure the transfer encoding
* is forced to the correct type.
*
* @exception MessagingException
*/
@Override
protected void updateHeaders() throws MessagingException {
super.updateHeaders();
setHeader("Content-Transfer-Encoding", transferEncoding);
}
}
| 2,014 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/NewsAddress.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.mail.Address;
/**
* A representation of an RFC1036 Internet newsgroup address.
*
* @version $Rev$ $Date$
*/
public class NewsAddress extends Address {
private static final long serialVersionUID = -4203797299824684143L;
/**
* The host for this newsgroup
*/
protected String host;
/**
* The name of this newsgroup
*/
protected String newsgroup;
public NewsAddress() {
}
public NewsAddress(final String newsgroup) {
this.newsgroup = newsgroup;
}
public NewsAddress(final String newsgroup, final String host) {
this.newsgroup = newsgroup;
this.host = host;
}
/**
* The type of this address; always "news".
* @return "news"
*/
@Override
public String getType() {
return "news";
}
public void setNewsgroup(final String newsgroup) {
this.newsgroup = newsgroup;
}
public String getNewsgroup() {
return newsgroup;
}
public void setHost(final String host) {
this.host = host;
}
public String getHost() {
return host;
}
@Override
public String toString() {
// Sun impl only appears to return the newsgroup name, no host.
return newsgroup;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof NewsAddress)) {
return false;
}
final NewsAddress newsAddress = (NewsAddress) o;
if (host != null ? !host.equals(newsAddress.host) : newsAddress.host != null) {
return false;
}
if (newsgroup != null ? !newsgroup.equals(newsAddress.newsgroup) : newsAddress.newsgroup != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result;
result = (host != null ? host.toLowerCase().hashCode() : 0);
result = 29 * result + (newsgroup != null ? newsgroup.hashCode() : 0);
return result;
}
/**
* Parse a comma-spearated list of addresses.
*
* @param addresses the list to parse
* @return the array of extracted addresses
* @throws AddressException if one of the addresses is invalid
*/
public static NewsAddress[] parse(final String addresses) throws AddressException {
final List result = new ArrayList();
final StringTokenizer tokenizer = new StringTokenizer(addresses, ",");
while (tokenizer.hasMoreTokens()) {
final String address = tokenizer.nextToken().trim();
final int index = address.indexOf('@');
if (index == -1) {
result.add(new NewsAddress(address));
} else {
final String newsgroup = address.substring(0, index).trim();
final String host = address.substring(index+1).trim();
result.add(new NewsAddress(newsgroup, host));
}
}
return (NewsAddress[]) result.toArray(new NewsAddress[result.size()]);
}
/**
* Convert the supplied addresses to a comma-separated String.
* If addresses is null, returns null; if empty, returns an empty string.
*
* @param addresses the addresses to convert
* @return a comma-separated list of addresses
*/
public static String toString(final Address[] addresses) {
if (addresses == null) {
return null;
}
if (addresses.length == 0) {
return "";
}
final StringBuffer result = new StringBuffer(addresses.length * 32);
result.append(addresses[0]);
for (int i = 1; i < addresses.length; i++) {
result.append(',').append(addresses[i].toString());
}
return result.toString();
}
}
| 2,015 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/internet/AddressParser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.internet;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
class AddressParser {
// the validation strictness levels, from most lenient to most conformant.
static public final int NONSTRICT = 0;
static public final int PARSE_HEADER = 1;
static public final int STRICT = 2;
// different mailbox types
static protected final int UNKNOWN = 0;
static protected final int ROUTE_ADDR = 1;
static protected final int GROUP_ADDR = 2;
static protected final int SIMPLE_ADDR = 3;
// constants for token types.
static protected final int END_OF_TOKENS = '\0';
static protected final int PERIOD = '.';
static protected final int LEFT_ANGLE = '<';
static protected final int RIGHT_ANGLE = '>';
static protected final int COMMA = ',';
static protected final int AT_SIGN = '@';
static protected final int SEMICOLON = ';';
static protected final int COLON = ':';
static protected final int QUOTED_LITERAL = '"';
static protected final int DOMAIN_LITERAL = '[';
static protected final int COMMENT = '(';
static protected final int ATOM = 'A';
static protected final int WHITESPACE = ' ';
// the string we're parsing
private final String addresses;
// the current parsing position
private int position;
// the end position of the string
private int end;
// the strictness flag
private final int validationLevel;
public AddressParser(final String addresses, final int validation) {
this.addresses = addresses;
validationLevel = validation;
}
/**
* Parse an address list into an array of internet addresses.
*
* @return An array containing all of the non-null addresses in the list.
* @exception AddressException
* Thrown for any validation errors.
*/
public InternetAddress[] parseAddressList() throws AddressException
{
// get the address as a set of tokens we can process.
final TokenStream tokens = tokenizeAddress();
// get an array list accumulator.
final ArrayList addressList = new ArrayList();
// we process sections of the token stream until we run out of tokens.
while (true) {
// parse off a single address. Address lists can have null elements,
// so this might return a null value. The null value does not get added
// to the address accumulator.
addressList.addAll(parseSingleAddress(tokens, false));
// This token should be either a "," delimiter or a stream terminator. If we're
// at the end, time to get out.
final AddressToken token = tokens.nextToken();
if (token.type == END_OF_TOKENS) {
break;
}
}
return (InternetAddress [])addressList.toArray(new InternetAddress[0]);
}
/**
* Parse a single internet address. This must be a single address,
* not an address list.
*
* @exception AddressException
*/
public InternetAddress parseAddress() throws AddressException
{
// get the address as a set of tokens we can process.
final TokenStream tokens = tokenizeAddress();
// parse off a single address. Address lists can have null elements,
// so this might return a null value. The null value does not get added
// to the address accumulator.
final List addressList = parseSingleAddress(tokens, false);
// we must get exactly one address back from this.
if (addressList.isEmpty()) {
throw new AddressException("Null address", addresses, 0);
}
// this could be a simple list of blank delimited tokens. Ensure we only got one back.
if (addressList.size() > 1) {
throw new AddressException("Illegal Address", addresses, 0);
}
// This token must be a stream stream terminator, or we have an error.
final AddressToken token = tokens.nextToken();
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal Address", token);
}
return (InternetAddress)addressList.get(0);
}
/**
* Validate an internet address. This must be a single address,
* not a list of addresses. The address also must not contain
* and personal information to be valid.
*
* @exception AddressException
*/
public void validateAddress() throws AddressException
{
// get the address as a set of tokens we can process.
final TokenStream tokens = tokenizeAddress();
// parse off a single address. Address lists can have null elements,
// so this might return a null value. The null value does not get added
// to the address accumulator.
final List addressList = parseSingleAddress(tokens, false);
if (addressList.isEmpty()) {
throw new AddressException("Null address", addresses, 0);
}
// this could be a simple list of blank delimited tokens. Ensure we only got one back.
if (addressList.size() > 1) {
throw new AddressException("Illegal Address", addresses, 0);
}
final InternetAddress address = (InternetAddress)addressList.get(0);
// validation occurs on an address that's already been split into personal and address
// data.
if (address.personal != null) {
throw new AddressException("Illegal Address", addresses, 0);
}
// This token must be a stream stream terminator, or we have an error.
final AddressToken token = tokens.nextToken();
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal Address", token);
}
}
/**
* Extract the set of address from a group Internet specification.
*
* @return An array containing all of the non-null addresses in the list.
* @exception AddressException
*/
public InternetAddress[] extractGroupList() throws AddressException
{
// get the address as a set of tokens we can process.
final TokenStream tokens = tokenizeAddress();
// get an array list accumulator.
final ArrayList addresses = new ArrayList();
AddressToken token = tokens.nextToken();
// scan forward to the ':' that starts the group list. If we don't find one,
// this is an exception.
while (token.type != COLON) {
if (token.type == END_OF_TOKENS) {
illegalAddress("Missing ':'", token);
}
token = tokens.nextToken();
}
// we process sections of the token stream until we run out of tokens.
while (true) {
// parse off a single address. Address lists can have null elements,
// so this might return a null value. The null value does not get added
// to the address accumulator.
addresses.addAll(parseSingleAddress(tokens, true));
// This token should be either a "," delimiter or a group terminator. If we're
// at the end, this is an error.
token = tokens.nextToken();
if (token.type == SEMICOLON) {
break;
}
else if (token.type == END_OF_TOKENS) {
illegalAddress("Missing ';'", token);
}
}
return (InternetAddress [])addresses.toArray(new InternetAddress[0]);
}
/**
* Parse out a single address from a string from a string
* of address tokens, returning an InternetAddress object that
* represents the address.
*
* @param tokens The token source for this address.
*
* @return A parsed out and constructed InternetAddress object for
* the next address. Returns null if this is an "empty"
* address in a list.
* @exception AddressException
*/
private List parseSingleAddress(final TokenStream tokens, final boolean inGroup) throws AddressException
{
final List parsedAddresses = new ArrayList();
// index markers for personal information
AddressToken personalStart = null;
AddressToken personalEnd = null;
// and similar bits for the address information.
AddressToken addressStart = null;
AddressToken addressEnd = null;
// there is a fall-back set of rules allowed that will parse the address as a set of blank delimited
// tokens. However, we do NOT allow this if we encounter any tokens that fall outside of these
// rules. For example, comment fields and quoted strings will disallow the very lenient rule set.
boolean nonStrictRules = true;
// we don't know the type of address yet
int addressType = UNKNOWN;
// the parsing goes in two stages. Stage one runs through the tokens locating the bounds
// of the address we're working on, resolving the personal information, and also validating
// some of the larger scale syntax features of an address (matched delimiters for routes and
// groups, invalid nesting checks, etc.).
// get the next token from the queue and save this. We're going to scan ahead a bit to
// figure out what type of address we're looking at, then reset to do the actually parsing
// once we've figured out a form.
final AddressToken first = tokens.nextToken();
// push it back on before starting processing.
tokens.pushToken(first);
// scan ahead for a trigger token that tells us what we've got.
while (addressType == UNKNOWN) {
final AddressToken token = tokens.nextToken();
switch (token.type) {
// skip these for now...after we've processed everything and found that this is a simple
// address form, then we'll check for a leading comment token in the first position and use
// if as personal information.
case COMMENT:
// comments do, however, denote that this must be parsed according to RFC822 rules.
nonStrictRules = false;
break;
// a semi-colon when processing a group is an address terminator. we need to
// process this like a comma then
case SEMICOLON:
if (inGroup) {
// we need to push the terminator back on for the caller to see.
tokens.pushToken(token);
// if we've not tagged any tokens as being the address beginning, so this must be a
// null address.
if (addressStart == null) {
// just return the empty list from this.
return parsedAddresses;
}
// the end token is the back part.
addressEnd = tokens.previousToken(token);
// without a '<' for a route addr, we can't distinguish address tokens from personal data.
// We'll use a leading comment, if there is one.
personalStart = null;
// this is just a simple form.
addressType = SIMPLE_ADDR;
break;
}
// NOTE: The above falls through if this is not a group.
// any of these tokens are a real token that can be the start of an address. Many of
// them are not valid as first tokens in this context, but we flag them later if validation
// has been requested. For now, we just mark these as the potential address start.
case DOMAIN_LITERAL:
case QUOTED_LITERAL:
// this set of tokens require fuller RFC822 parsing, so turn off the flag.
nonStrictRules = false;
case ATOM:
case AT_SIGN:
case PERIOD:
// if we're not determined the start of the address yet, then check to see if we
// need to consider this the personal start.
if (addressStart == null) {
if (personalStart == null) {
personalStart = token;
}
// This is the first real token of the address, which at this point can
// be either the personal info or the first token of the address. If we hit
// an address terminator without encountering either a route trigger or group
// trigger, then this is the real address.
addressStart = token;
}
break;
// a LEFT_ANGLE indicates we have a full RFC822 mailbox form. The leading phrase
// is the personal info. The address is inside the brackets.
case LEFT_ANGLE:
// a route address automatically switches off the blank-delimited token mode.
nonStrictRules = false;
// this is a route address
addressType = ROUTE_ADDR;
// the address is placed in the InternetAddress object without the route
// brackets, so our start is one past this.
addressStart = tokens.nextRealToken();
// push this back on the queue so the scanner picks it up properly.
tokens.pushToken(addressStart);
// make sure we flag the end of the personal section too.
if (personalStart != null) {
personalEnd = tokens.previousToken(token);
}
// scan the rest of a route address.
addressEnd = scanRouteAddress(tokens, false);
break;
// a COLON indicates this is a group specifier...parse the group.
case COLON:
// Colons would not be valid in simple lists, so turn it off.
nonStrictRules = false;
// if we're scanning a group, we shouldn't encounter a ":". This is a
// recursion error if found.
if (inGroup) {
illegalAddress("Nested group element", token);
}
addressType = GROUP_ADDR;
// groups don't have any personal sections.
personalStart = null;
// our real start was back at the beginning
addressStart = first;
addressEnd = scanGroupAddress(tokens);
break;
// a semi colon can the same as a comma if we're processing a group.
// reached the end of string...this might be a null address, or one of the very simple name
// forms used for non-strict RFC822 versions. Reset, and try that form
case END_OF_TOKENS:
// if we're scanning a group, we shouldn't encounter an end token. This is an
// error if found.
if (inGroup) {
illegalAddress("Missing ';'", token);
}
// NOTE: fall through from above.
// this is either a terminator for an address list or a a group terminator.
case COMMA:
// we need to push the terminator back on for the caller to see.
tokens.pushToken(token);
// if we've not tagged any tokens as being the address beginning, so this must be a
// null address.
if (addressStart == null) {
// just return the empty list from this.
return parsedAddresses;
}
// the end token is the back part.
addressEnd = tokens.previousToken(token);
// without a '<' for a route addr, we can't distinguish address tokens from personal data.
// We'll use a leading comment, if there is one.
personalStart = null;
// this is just a simple form.
addressType = SIMPLE_ADDR;
break;
// right angle tokens are pushed, because parsing of the bracketing is not necessarily simple.
// we need to flag these here.
case RIGHT_ANGLE:
illegalAddress("Unexpected '>'", token);
}
}
String personal = null;
// if we have personal data, then convert it to a string value.
if (personalStart != null) {
final TokenStream personalTokens = tokens.section(personalStart, personalEnd);
personal = personalToString(personalTokens);
}
// if we have a simple address, then check the first token to see if it's a comment. For simple addresses,
// we'll accept the first comment token as the personal information.
else {
if (addressType == SIMPLE_ADDR && first.type == COMMENT) {
personal = first.value;
}
}
final TokenStream addressTokens = tokens.section(addressStart, addressEnd);
// if this is one of the strictly RFC822 types, then we always validate the address. If this is a
// a simple address, then we only validate if strict parsing rules are in effect or we've been asked
// to validate.
if (validationLevel != PARSE_HEADER) {
switch (addressType) {
case GROUP_ADDR:
validateGroup(addressTokens);
break;
case ROUTE_ADDR:
validateRouteAddr(addressTokens, false);
break;
case SIMPLE_ADDR:
// this is a conditional validation
validateSimpleAddress(addressTokens);
break;
}
}
// more complex addresses and addresses containing tokens other than just simple addresses
// need proper handling.
if (validationLevel != NONSTRICT || addressType != SIMPLE_ADDR || !nonStrictRules) {
// we might have traversed this already when we validated, so reset the
// position before using this again.
addressTokens.reset();
final String address = addressToString(addressTokens);
// get the parsed out sections as string values.
final InternetAddress result = new InternetAddress();
result.setAddress(address);
try {
result.setPersonal(personal);
} catch (final UnsupportedEncodingException e) {
}
// even though we have a single address, we return this as an array. Simple addresses
// can be produce an array of items, so we need to return everything.
parsedAddresses.add(result);
return parsedAddresses;
}
else {
addressTokens.reset();
TokenStream nextAddress = addressTokens.getBlankDelimitedToken();
while (nextAddress != null) {
final String address = addressToString(nextAddress);
// get the parsed out sections as string values.
final InternetAddress result = new InternetAddress();
result.setAddress(address);
parsedAddresses.add(result);
nextAddress = addressTokens.getBlankDelimitedToken();
}
return parsedAddresses;
}
}
/**
* Scan the token stream, parsing off a route addr spec. This
* will do some basic syntax validation, but will not actually
* validate any of the address information. Comments will be
* discarded.
*
* @param tokens The stream of tokens.
*
* @return The last token of the route address (the one preceeding the
* terminating '>'.
*/
private AddressToken scanRouteAddress(final TokenStream tokens, final boolean inGroup) throws AddressException {
// get the first token and ensure we have something between the "<" and ">".
AddressToken token = tokens.nextRealToken();
// the last processed non-whitespace token, which is the actual address end once the
// right angle bracket is encountered.
AddressToken previous = null;
// if this route-addr has route information, the first token after the '<' must be a '@'.
// this determines if/where a colon or comma can appear.
boolean inRoute = token.type == AT_SIGN;
// now scan until we reach the terminator. The only validation is done on illegal characters.
while (true) {
switch (token.type) {
// The following tokens are all valid between the brackets, so just skip over them.
case ATOM:
case QUOTED_LITERAL:
case DOMAIN_LITERAL:
case PERIOD:
case AT_SIGN:
break;
case COLON:
// if not processing route information, this is illegal.
if (!inRoute) {
illegalAddress("Unexpected ':'", token);
}
// this is the end of the route information, the rules now change.
inRoute = false;
break;
case COMMA:
// if not processing route information, this is illegal.
if (!inRoute) {
illegalAddress("Unexpected ','", token);
}
break;
case RIGHT_ANGLE:
// if previous is null, we've had a route address which is "<>". That's illegal.
if (previous == null) {
illegalAddress("Illegal address", token);
}
// step to the next token..this had better be either a comma for another address or
// the very end of the address list .
token = tokens.nextRealToken();
// if we're scanning part of a group, then the allowed terminators are either ',' or ';'.
if (inGroup) {
if (token.type != COMMA && token.type != SEMICOLON) {
illegalAddress("Illegal address", token);
}
}
// a normal address should have either a ',' for a list or the end.
else {
if (token.type != COMMA && token.type != END_OF_TOKENS) {
illegalAddress("Illegal address", token);
}
}
// we need to push the termination token back on.
tokens.pushToken(token);
// return the previous token as the updated position.
return previous;
case END_OF_TOKENS:
illegalAddress("Missing '>'", token);
// now for the illegal ones in this context.
case SEMICOLON:
illegalAddress("Unexpected ';'", token);
case LEFT_ANGLE:
illegalAddress("Unexpected '<'", token);
}
// remember the previous token.
previous = token;
token = tokens.nextRealToken();
}
}
/**
* Scan the token stream, parsing off a group address. This
* will do some basic syntax validation, but will not actually
* validate any of the address information. Comments will be
* ignored.
*
* @param tokens The stream of tokens.
*
* @return The last token of the group address (the terminating ':").
*/
private AddressToken scanGroupAddress(final TokenStream tokens) throws AddressException {
// A group does not require that there be anything between the ':' and ';". This is
// just a group with an empty list.
AddressToken token = tokens.nextRealToken();
// now scan until we reach the terminator. The only validation is done on illegal characters.
while (true) {
switch (token.type) {
// The following tokens are all valid in group addresses, so just skip over them.
case ATOM:
case QUOTED_LITERAL:
case DOMAIN_LITERAL:
case PERIOD:
case AT_SIGN:
case COMMA:
break;
case COLON:
illegalAddress("Nested group", token);
// route address within a group specifier....we need to at least verify the bracket nesting
// and higher level syntax of the route.
case LEFT_ANGLE:
scanRouteAddress(tokens, true);
break;
// the only allowed terminator is the ';'
case END_OF_TOKENS:
illegalAddress("Missing ';'", token);
// now for the illegal ones in this context.
case SEMICOLON:
// verify there's nothing illegal after this.
final AddressToken next = tokens.nextRealToken();
if (next.type != COMMA && next.type != END_OF_TOKENS) {
illegalAddress("Illegal address", token);
}
// don't forget to put this back on...our caller will need it.
tokens.pushToken(next);
return token;
case RIGHT_ANGLE:
illegalAddress("Unexpected '>'", token);
}
token = tokens.nextRealToken();
}
}
/**
* Parse the provided internet address into a set of tokens. This
* phase only does a syntax check on the tokens. The interpretation
* of the tokens is the next phase.
*
* @exception AddressException
*/
private TokenStream tokenizeAddress() throws AddressException {
// get a list for the set of tokens
final TokenStream tokens = new TokenStream();
end = addresses.length(); // our parsing end marker
// now scan along the string looking for the special characters in an internet address.
while (moreCharacters()) {
final char ch = currentChar();
switch (ch) {
// start of a comment bit...ignore everything until we hit a closing paren.
case '(':
scanComment(tokens);
break;
// a closing paren found outside of normal processing.
case ')':
syntaxError("Unexpected ')'", position);
// start of a quoted string
case '"':
scanQuotedLiteral(tokens);
break;
// domain literal
case '[':
scanDomainLiteral(tokens);
break;
// a naked closing bracket...not valid except as part of a domain literal.
case ']':
syntaxError("Unexpected ']'", position);
// special character delimiters
case '<':
tokens.addToken(new AddressToken(LEFT_ANGLE, position));
nextChar();
break;
// a naked closing bracket...not valid without a starting one, but
// we need to handle this in context.
case '>':
tokens.addToken(new AddressToken(RIGHT_ANGLE, position));
nextChar();
break;
case ':':
tokens.addToken(new AddressToken(COLON, position));
nextChar();
break;
case ',':
tokens.addToken(new AddressToken(COMMA, position));
nextChar();
break;
case '.':
tokens.addToken(new AddressToken(PERIOD, position));
nextChar();
break;
case ';':
tokens.addToken(new AddressToken(SEMICOLON, position));
nextChar();
break;
case '@':
tokens.addToken(new AddressToken(AT_SIGN, position));
nextChar();
break;
// white space characters. These are mostly token delimiters, but there are some relaxed
// situations where they get processed, so we need to add a white space token for the first
// one we encounter in a span.
case ' ':
case '\t':
case '\r':
case '\n':
// add a single white space token
tokens.addToken(new AddressToken(WHITESPACE, position));
nextChar();
// step over any space characters, leaving us positioned either at the end
// or the first
while (moreCharacters()) {
final char nextChar = currentChar();
if (nextChar == ' ' || nextChar == '\t' || nextChar == '\r' || nextChar == '\n') {
nextChar();
}
else {
break;
}
}
break;
// potentially an atom...if it starts with an allowed atom character, we
// parse out the token, otherwise this is invalid.
default:
if (ch < 040 || ch >= 0177) {
syntaxError("Illegal character in address", position);
}
scanAtom(tokens);
break;
}
}
// for this end marker, give an end position.
tokens.addToken(new AddressToken(END_OF_TOKENS, addresses.length()));
return tokens;
}
/**
* Step to the next character position while parsing.
*/
private void nextChar() {
position++;
}
/**
* Retrieve the character at the current parsing position.
*
* @return The current character.
*/
private char currentChar() {
return addresses.charAt(position);
}
/**
* Test if there are more characters left to parse.
*
* @return True if we've hit the last character, false otherwise.
*/
private boolean moreCharacters() {
return position < end;
}
/**
* Parse a quoted string as specified by the RFC822 specification.
*
* @param tokens The TokenStream where the parsed out token is added.
*/
private void scanQuotedLiteral(final TokenStream tokens) throws AddressException {
final StringBuffer value = new StringBuffer();
// step over the quote delimiter.
nextChar();
while (moreCharacters()) {
final char ch = currentChar();
// is this an escape char?
if (ch == '\\') {
// step past this, and grab the following character
nextChar();
if (!moreCharacters()) {
syntaxError("Missing '\"'", position);
}
value.append(currentChar());
}
// end of the string?
else if (ch == '"') {
// return the constructed string.
tokens.addToken(new AddressToken(value.toString(), QUOTED_LITERAL, position));
// step over the close delimiter for the benefit of the next token.
nextChar();
return;
}
// the RFC822 spec disallows CR characters.
else if (ch == '\r') {
syntaxError("Illegal line end in literal", position);
}
else
{
value.append(ch);
}
nextChar();
}
// missing delimiter
syntaxError("Missing '\"'", position);
}
/**
* Parse a domain literal as specified by the RFC822 specification.
*
* @param tokens The TokenStream where the parsed out token is added.
*/
private void scanDomainLiteral(final TokenStream tokens) throws AddressException {
final StringBuffer value = new StringBuffer();
final int startPosition = position;
// step over the quote delimiter.
nextChar();
while (moreCharacters()) {
final char ch = currentChar();
// is this an escape char?
if (ch == '\\') {
// because domain literals don't get extra escaping, we render them
// with the escaped characters intact. Therefore, append the '\' escape
// first, then append the escaped character without examination.
value.append(currentChar());
// step past this, and grab the following character
nextChar();
if (!moreCharacters()) {
syntaxError("Missing '\"'", position);
}
value.append(currentChar());
}
// end of the string?
else if (ch == ']') {
// return the constructed string.
tokens.addToken(new AddressToken(value.toString(), DOMAIN_LITERAL, startPosition));
// step over the close delimiter for the benefit of the next token.
nextChar();
return;
}
// the RFC822 spec says no nesting
else if (ch == '[') {
syntaxError("Unexpected '['", position);
}
// carriage returns are similarly illegal.
else if (ch == '\r') {
syntaxError("Illegal line end in domain literal", position);
}
else
{
value.append(ch);
}
nextChar();
}
// missing delimiter
syntaxError("Missing ']'", position);
}
/**
* Scan an atom in an internet address, using the RFC822 rules
* for atom delimiters.
*
* @param tokens The TokenStream where the parsed out token is added.
*/
private void scanAtom(final TokenStream tokens) throws AddressException {
final int start = position;
nextChar();
while (moreCharacters()) {
final char ch = currentChar();
if (isAtom(ch)) {
nextChar();
}
else {
break;
}
}
// return the scanned part of the string.
tokens.addToken(new AddressToken(addresses.substring(start, position), ATOM, start));
}
/**
* Parse an internet address comment field as specified by
* RFC822. Includes support for quoted characters and nesting.
*
* @param tokens The TokenStream where the parsed out token is added.
*/
private void scanComment(final TokenStream tokens) throws AddressException {
final StringBuffer value = new StringBuffer();
final int startPosition = position;
// step past the start character
nextChar();
// we're at the top nesting level on the comment.
int nest = 1;
// scan while we have more characters.
while (moreCharacters()) {
final char ch = currentChar();
// escape character?
if (ch == '\\') {
// step over this...if escaped, we must have at least one more character
// in the string.
nextChar();
if (!moreCharacters()) {
syntaxError("Missing ')'", position);
}
value.append(currentChar());
}
// nested comment?
else if (ch == '(') {
// step the nesting level...we treat the comment as a single unit, with the delimiters
// for the nested comments embedded in the middle
nest++;
value.append(ch);
}
// is this the comment close?
else if (ch == ')') {
// reduce the nesting level. If we still have more to process, add the delimiter character
// and keep going.
nest--;
if (nest > 0) {
value.append(ch);
}
else {
// step past this and return. The outermost comment delimiter is not included in
// the string value, since this is frequently used as personal data on the
// InternetAddress objects.
nextChar();
tokens.addToken(new AddressToken(value.toString(), COMMENT, startPosition));
return;
}
}
else if (ch == '\r') {
syntaxError("Illegal line end in comment", position);
}
else {
value.append(ch);
}
// step to the next character.
nextChar();
}
// ran out of data before seeing the closing bit, not good
syntaxError("Missing ')'", position);
}
/**
* Validate the syntax of an RFC822 group internet address specification.
*
* @param tokens The stream of tokens for the address.
*
* @exception AddressException
*/
private void validateGroup(final TokenStream tokens) throws AddressException {
// we know already this is an address in the form "phrase:group;". Now we need to validate the
// elements.
int phraseCount = 0;
AddressToken token = tokens.nextRealToken();
// now scan to the semi color, ensuring we have only word or comment tokens.
while (token.type != COLON) {
// only these tokens are allowed here.
if (token.type != ATOM && token.type != QUOTED_LITERAL) {
invalidToken(token);
}
phraseCount++;
token = tokens.nextRealToken();
}
// RFC822 groups require a leading phrase in group specifiers.
if (phraseCount == 0) {
illegalAddress("Missing group identifier phrase", token);
}
// now we do the remainder of the parsing using the initial phrase list as the sink...the entire
// address will be converted to a string later.
// ok, we only know this has been valid up to the ":", now we have some real checks to perform.
while (true) {
// go scan off a mailbox. if everything goes according to plan, we should be positioned at either
// a comma or a semicolon.
validateGroupMailbox(tokens);
token = tokens.nextRealToken();
// we're at the end of the group. Make sure this is truely the end.
if (token.type == SEMICOLON) {
token = tokens.nextRealToken();
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal group address", token);
}
return;
}
// if not a semicolon, this better be a comma.
else if (token.type != COMMA) {
illegalAddress("Illegal group address", token);
}
}
}
/**
* Validate the syntax of single mailbox within a group address.
*
* @param tokens The stream of tokens representing the address.
*
* @exception AddressException
*/
private void validateGroupMailbox(final TokenStream tokens) throws AddressException {
final AddressToken first = tokens.nextRealToken();
// is this just a null address in the list? then push the terminator back and return.
if (first.type == COMMA || first.type == SEMICOLON) {
tokens.pushToken(first);
return;
}
// now we need to scan ahead to see if we can determine the type.
AddressToken token = first;
// we need to scan forward to figure out what sort of address this is.
while (first != null) {
switch (token.type) {
// until we know the context, these are all just ignored.
case QUOTED_LITERAL:
case ATOM:
break;
// a LEFT_ANGLE indicates we have a full RFC822 mailbox form. The leading phrase
// is the personal info. The address is inside the brackets.
case LEFT_ANGLE:
tokens.pushToken(first);
validatePhrase(tokens, false);
validateRouteAddr(tokens, true);
return;
// we've hit a period as the first non-word token. This should be part of a local-part
// of an address.
case PERIOD:
// we've hit an "@" as the first non-word token. This is probably a simple address in
// the form "user@domain".
case AT_SIGN:
tokens.pushToken(first);
validateAddressSpec(tokens);
return;
// reached the end of string...this might be a null address, or one of the very simple name
// forms used for non-strict RFC822 versions. Reset, and try that form
case COMMA:
// this is the end of the group...handle it like a comma for now.
case SEMICOLON:
tokens.pushToken(first);
validateAddressSpec(tokens);
return;
case END_OF_TOKENS:
illegalAddress("Missing ';'", token);
}
token = tokens.nextRealToken();
}
}
/**
* Utility method for throwing an AddressException caused by an
* unexpected primitive token.
*
* @param token The token causing the problem (must not be a value type token).
*
* @exception AddressException
*/
private void invalidToken(final AddressToken token) throws AddressException {
illegalAddress("Unexpected '" + token.type + "'", token);
}
/**
* Raise an error about illegal syntax.
*
* @param message The message used in the thrown exception.
* @param position The parsing position within the string.
*
* @exception AddressException
*/
private void syntaxError(final String message, final int position) throws AddressException
{
throw new AddressException(message, addresses, position);
}
/**
* Throw an exception based on the position of an invalid token.
*
* @param message The exception message.
* @param token The token causing the error. This tokens position is used
* in the exception information.
*/
private void illegalAddress(final String message, final AddressToken token) throws AddressException {
throw new AddressException(message, addresses, token.position);
}
/**
* Validate that a required phrase exists.
*
* @param tokens The set of tokens to validate. positioned at the phrase start.
* @param required A flag indicating whether the phrase is optional or required.
*
* @exception AddressException
*/
private void validatePhrase(final TokenStream tokens, final boolean required) throws AddressException {
// we need to have at least one WORD token in the phrase...everything is optional
// after that.
AddressToken token = tokens.nextRealToken();
if (token.type != ATOM && token.type != QUOTED_LITERAL) {
if (required) {
illegalAddress("Missing group phrase", token);
}
}
// now scan forward to the end of the phrase
token = tokens.nextRealToken();
while (token.type == ATOM || token.type == QUOTED_LITERAL) {
token = tokens.nextRealToken();
}
}
/**
* validate a routeaddr specification
*
* @param tokens The tokens representing the address portion (personal information
* already removed).
* @param ingroup true indicates we're validating a route address inside a
* group list. false indicates we're validating a standalone
* address.
*
* @exception AddressException
*/
private void validateRouteAddr(final TokenStream tokens, final boolean ingroup) throws AddressException {
// get the next real token.
AddressToken token = tokens.nextRealToken();
// if this is an at sign, then we have a list of domains to parse.
if (token.type == AT_SIGN) {
// push the marker token back in for the route parser, and step past that part.
tokens.pushToken(token);
validateRoute(tokens);
}
else {
// we need to push this back on to validate the local part.
tokens.pushToken(token);
}
// now we expect to see an address spec.
validateAddressSpec(tokens);
token = tokens.nextRealToken();
if (ingroup) {
// if we're validating within a group specification, the angle brackets are still there (and
// required).
if (token.type != RIGHT_ANGLE) {
illegalAddress("Missing '>'", token);
}
}
else {
// the angle brackets were removed to make this an address, so we should be done. Make sure we
// have a terminator here.
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal Address", token);
}
}
}
/**
* Validate a simple address in the form "user@domain".
*
* @param tokens The stream of tokens representing the address.
*/
private void validateSimpleAddress(final TokenStream tokens) throws AddressException {
// the validation routines occur after addresses have been split into
// personal and address forms. Therefore, our validation begins directly
// with the first token.
validateAddressSpec(tokens);
// get the next token and see if there is something here...anything but the terminator is an error
final AddressToken token = tokens.nextRealToken();
if (token.type != END_OF_TOKENS) {
illegalAddress("Illegal Address", token);
}
}
/**
* Validate the addr-spec portion of an address. RFC822 requires
* this be of the form "local-part@domain". However, javamail also
* allows simple address of the form "local-part". We only require
* the domain if an '@' is encountered.
*
* @param tokens
*/
private void validateAddressSpec(final TokenStream tokens) throws AddressException {
// all addresses, even the simple ones, must have at least a local part.
validateLocalPart(tokens);
// now see if we have a domain portion to look at.
final AddressToken token = tokens.nextRealToken();
if (token.type == AT_SIGN) {
validateDomain(tokens);
}
else {
// put this back for termination
tokens.pushToken(token);
}
}
/**
* Validate the route portion of a route-addr. This is a list
* of domain values in the form 1#("@" domain) ":".
*
* @param tokens The token stream holding the address information.
*/
private void validateRoute(final TokenStream tokens) throws AddressException {
while (true) {
final AddressToken token = tokens.nextRealToken();
// if this is the first part of the list, go parse off a domain
if (token.type == AT_SIGN) {
validateDomain(tokens);
}
// another element in the list? Go around again
else if (token.type == COMMA) {
continue;
}
// the list is terminated by a colon...stop this part of the validation once we hit one.
else if (token.type == COLON) {
return;
}
// the list is terminated by a colon. If this isn't one of those, we have an error.
else {
illegalAddress("Missing ':'", token);
}
}
}
/**
* Parse the local part of an address spec. The local part
* is a series of "words" separated by ".".
*/
private void validateLocalPart(final TokenStream tokens) throws AddressException {
while (true) {
// get the token.
AddressToken token = tokens.nextRealToken();
// this must be either an atom or a literal.
if (token.type != ATOM && token.type != QUOTED_LITERAL) {
illegalAddress("Invalid local part", token);
}
// get the next token (white space and comments ignored)
token = tokens.nextRealToken();
// if this is a period, we continue parsing
if (token.type != PERIOD) {
tokens.pushToken(token);
// return the token
return;
}
}
}
/**
* Parse a domain name of the form sub-domain *("." sub-domain).
* a sub-domain is either an atom or a domain-literal.
*/
private void validateDomain(final TokenStream tokens) throws AddressException {
while (true) {
// get the token.
AddressToken token = tokens.nextRealToken();
// this must be either an atom or a domain literal.
if (token.type != ATOM && token.type != DOMAIN_LITERAL) {
illegalAddress("Invalid domain", token);
}
// get the next token (white space is ignored)
token = tokens.nextRealToken();
// if this is a period, we continue parsing
if (token.type != PERIOD) {
// return the token
tokens.pushToken(token);
return;
}
}
}
/**
* Convert a list of word tokens into a phrase string. The
* rules for this are a little hard to puzzle out, but there
* is a logic to it. If the list is empty, the phrase is
* just a null value.
*
* If we have a phrase, then the quoted strings need to
* handled appropriately. In multi-token phrases, the
* quoted literals are concatenated with the quotes intact,
* regardless of content. Thus a phrase that comes in like this:
*
* "Geronimo" Apache
*
* gets converted back to the same string.
*
* If there is just a single token in the phrase, AND the token
* is a quoted string AND the string does not contain embedded
* special characters ("\.,@<>()[]:;), then the phrase
* is expressed as an atom. Thus the literal
*
* "Geronimo"
*
* becomes
*
* Geronimo
*
* but
*
* "(Geronimo)"
*
* remains
*
* "(Geronimo)"
*
* Note that we're generating a canonical form of the phrase,
* which removes comments and reduces linear whitespace down
* to a single separator token.
*
* @param phrase An array list of phrase tokens (which may be empty).
*/
private String personalToString(final TokenStream tokens) {
// no tokens in the stream? This is a null value.
AddressToken token = tokens.nextToken();
if (token.type == END_OF_TOKENS) {
return null;
}
final AddressToken next = tokens.nextToken();
// single element phrases get special treatment.
if (next.type == END_OF_TOKENS) {
// this can be used directly...if it contains special characters, quoting will be
// performed when it's converted to a string value.
return token.value;
}
// reset to the beginning
tokens.pushToken(token);
// have at least two tokens,
final StringBuffer buffer = new StringBuffer();
// get the first token. After the first, we add these as blank delimited values.
token = tokens.nextToken();
addTokenValue(token, buffer);
token = tokens.nextToken();
while (token.type != END_OF_TOKENS) {
// add a blank separator
buffer.append(' ');
// now add the next tokens value
addTokenValue(token, buffer);
token = tokens.nextToken();
}
// and return the canonicalized value
return buffer.toString();
}
/**
* take a canonicalized set of address tokens and reformat it back into a string value,
* inserting whitespace where appropriate.
*
* @param tokens The set of tokens representing the address.
*
* @return The string value of the tokens.
*/
private String addressToString(final TokenStream tokens) {
final StringBuffer buffer = new StringBuffer();
// this flag controls whether we insert a blank delimiter between tokens as
// we advance through the list. Blanks are only inserted between consequtive value tokens.
// Initially, this is false, then we flip it to true whenever we add a value token, and
// back to false for any special character token.
boolean spaceRequired = false;
// we use nextToken rather than nextRealToken(), since we need to process the comments also.
AddressToken token = tokens.nextToken();
// now add each of the tokens
while (token.type != END_OF_TOKENS) {
switch (token.type) {
// the word tokens are the only ones where we need to worry about adding
// whitespace delimiters.
case ATOM:
case QUOTED_LITERAL:
// was the last token also a word? Insert a blank first.
if (spaceRequired) {
buffer.append(' ');
}
addTokenValue(token, buffer);
// let the next iteration know we just added a word to the list.
spaceRequired = true;
break;
// these special characters are just added in. The constants for the character types
// were carefully selected to be the character value in question. This allows us to
// just append the value.
case LEFT_ANGLE:
case RIGHT_ANGLE:
case COMMA:
case COLON:
case AT_SIGN:
case SEMICOLON:
case PERIOD:
buffer.append((char)token.type);
// no spaces around specials
spaceRequired = false;
break;
// Domain literals self delimiting...we can just append them and turn off the space flag.
case DOMAIN_LITERAL:
addTokenValue(token, buffer);
spaceRequired = false;
break;
// Comments are also self delimitin.
case COMMENT:
addTokenValue(token, buffer);
spaceRequired = false;
break;
}
token = tokens.nextToken();
}
return buffer.toString();
}
/**
* Append a value token on to a string buffer used to create
* the canonicalized string value.
*
* @param token The token we're adding.
* @param buffer The target string buffer.
*/
private void addTokenValue(final AddressToken token, final StringBuffer buffer) {
// atom values can be added directly.
if (token.type == ATOM) {
buffer.append(token.value);
}
// a literal value? Add this as a quoted string
else if (token.type == QUOTED_LITERAL) {
buffer.append(formatQuotedString(token.value));
}
// could be a domain literal of the form "[value]"
else if (token.type == DOMAIN_LITERAL) {
buffer.append('[');
buffer.append(token.value);
buffer.append(']');
}
// comments also have values
else if (token.type == COMMENT) {
buffer.append('(');
buffer.append(token.value);
buffer.append(')');
}
}
private static final byte[] CHARMAP = {
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x06, 0x02, 0x06, 0x02, 0x02, 0x06, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
};
private static final byte FLG_SPECIAL = 1;
private static final byte FLG_CONTROL = 2;
/**
* Quick test to see if a character is an allowed atom character
* or not.
*
* @param ch The test character.
*
* @return true if this character is allowed in atoms, false for any
* control characters, special characters, or blanks.
*/
public static boolean isAtom(final char ch) {
if (ch > '\u007f') {
return false;
}
else if (ch == ' ') {
return false;
}
else {
return (CHARMAP[ch] & (FLG_SPECIAL | FLG_CONTROL)) == 0;
}
}
/**
* Tests one string to determine if it contains any of the
* characters in a supplied test string.
*
* @param s The string we're testing.
* @param chars The set of characters we're testing against.
*
* @return true if any of the characters is found, false otherwise.
*/
public static boolean containsCharacters(final String s, final String chars)
{
for (int i = 0; i < s.length(); i++) {
if (chars.indexOf(s.charAt(i)) >= 0) {
return true;
}
}
return false;
}
/**
* Tests if a string contains any non-special characters that
* would require encoding the value as a quoted string rather
* than a simple atom value.
*
* @param s The test string.
*
* @return True if the string contains only blanks or allowed atom
* characters.
*/
public static boolean containsSpecials(final String s)
{
for (int i = 0; i < s.length(); i++) {
final char ch = s.charAt(i);
// must be either a blank or an allowed atom char.
if (ch == ' ' || isAtom(ch)) {
continue;
}
else {
return true;
}
}
return false;
}
/**
* Tests if a string contains any non-special characters that
* would require encoding the value as a quoted string rather
* than a simple atom value.
*
* @param s The test string.
*
* @return True if the string contains only blanks or allowed atom
* characters.
*/
public static boolean isAtom(final String s)
{
for (int i = 0; i < s.length(); i++) {
final char ch = s.charAt(i);
// must be an allowed atom character
if (!isAtom(ch)) {
return false;
}
}
return true;
}
/**
* Apply RFC822 quoting rules to a literal string value. This
* will search the string to see if there are any characters that
* require special escaping, and apply the escapes. If the
* string is just a string of blank-delimited atoms, the string
* value is returned without quotes.
*
* @param s The source string.
*
* @return A version of the string as a valid RFC822 quoted literal.
*/
public static String quoteString(final String s) {
// only backslash and double quote require escaping. If the string does not
// contain any of these, then we can just slap on some quotes and go.
if (s.indexOf('\\') == -1 && s.indexOf('"') == -1) {
// if the string is an atom (or a series of blank-delimited atoms), we can just return it directly.
if (!containsSpecials(s)) {
return s;
}
final StringBuffer buffer = new StringBuffer(s.length() + 2);
buffer.append('"');
buffer.append(s);
buffer.append('"');
return buffer.toString();
}
// get a buffer sufficiently large for the string, two quote characters, and a "reasonable"
// number of escaped values.
final StringBuffer buffer = new StringBuffer(s.length() + 10);
buffer.append('"');
// now check all of the characters.
for (int i = 0; i < s.length(); i++) {
final char ch = s.charAt(i);
// character requiring escaping?
if (ch == '\\' || ch == '"') {
// add an extra backslash
buffer.append('\\');
}
// and add on the character
buffer.append(ch);
}
buffer.append('"');
return buffer.toString();
}
/**
* Apply RFC822 quoting rules to a literal string value. This
* will search the string to see if there are any characters that
* require special escaping, and apply the escapes. The returned
* value is enclosed in quotes.
*
* @param s The source string.
*
* @return A version of the string as a valid RFC822 quoted literal.
*/
public static String formatQuotedString(final String s) {
// only backslash and double quote require escaping. If the string does not
// contain any of these, then we can just slap on some quotes and go.
if (s.indexOf('\\') == -1 && s.indexOf('"') == -1) {
final StringBuffer buffer = new StringBuffer(s.length() + 2);
buffer.append('"');
buffer.append(s);
buffer.append('"');
return buffer.toString();
}
// get a buffer sufficiently large for the string, two quote characters, and a "reasonable"
// number of escaped values.
final StringBuffer buffer = new StringBuffer(s.length() + 10);
buffer.append('"');
// now check all of the characters.
for (int i = 0; i < s.length(); i++) {
final char ch = s.charAt(i);
// character requiring escaping?
if (ch == '\\' || ch == '"') {
// add an extra backslash
buffer.append('\\');
}
// and add on the character
buffer.append(ch);
}
buffer.append('"');
return buffer.toString();
}
public class TokenStream {
// the set of tokens in the parsed address list, as determined by RFC822 syntax rules.
private final List tokens;
// the current token position
int currentToken = 0;
/**
* Default constructor for a TokenStream. This creates an
* empty TokenStream for purposes of tokenizing an address.
* It is the creator's responsibility to terminate the stream
* with a terminator token.
*/
public TokenStream() {
tokens = new ArrayList();
}
/**
* Construct a TokenStream from a list of tokens. A terminator
* token is added to the end.
*
* @param tokens An existing token list.
*/
public TokenStream(final List tokens) {
this.tokens = tokens;
tokens.add(new AddressToken(END_OF_TOKENS, -1));
}
/**
* Add an address token to the token list.
*
* @param t The new token to add to the list.
*/
public void addToken(final AddressToken token) {
tokens.add(token);
}
/**
* Get the next token at the cursor position, advancing the
* position accordingly.
*
* @return The token at the current token position.
*/
public AddressToken nextToken() {
AddressToken token = (AddressToken)tokens.get(currentToken++);
// we skip over white space tokens when operating in this mode, so
// check the token and iterate until we get a non-white space.
while (token.type == WHITESPACE) {
token = (AddressToken)tokens.get(currentToken++);
}
return token;
}
/**
* Get the next token at the cursor position, without advancing the
* position.
*
* @return The token at the current token position.
*/
public AddressToken currentToken() {
// return the current token and step the cursor
return (AddressToken)tokens.get(currentToken);
}
/**
* Get the next non-comment token from the string. Comments are ignored, except as personal information
* for very simple address specifications.
*
* @return A token guaranteed not to be a whitespace token.
*/
public AddressToken nextRealToken()
{
AddressToken token = nextToken();
if (token.type == COMMENT) {
token = nextToken();
}
return token;
}
/**
* Push a token back on to the queue, making the index of this
* token the current cursor position.
*
* @param token The token to push.
*/
public void pushToken(final AddressToken token) {
// just reset the cursor to the token's index position.
currentToken = tokenIndex(token);
}
/**
* Get the next token after a given token, without advancing the
* token position.
*
* @param token The token we're retrieving a token relative to.
*
* @return The next token in the list.
*/
public AddressToken nextToken(final AddressToken token) {
return (AddressToken)tokens.get(tokenIndex(token) + 1);
}
/**
* Return the token prior to a given token.
*
* @param token The token used for the index.
*
* @return The token prior to the index token in the list.
*/
public AddressToken previousToken(final AddressToken token) {
return (AddressToken)tokens.get(tokenIndex(token) - 1);
}
/**
* Retrieve a token at a given index position.
*
* @param index The target index.
*/
public AddressToken getToken(final int index)
{
return (AddressToken)tokens.get(index);
}
/**
* Retrieve the index of a particular token in the stream.
*
* @param token The target token.
*
* @return The index of the token within the stream. Returns -1 if this
* token is somehow not in the stream.
*/
public int tokenIndex(final AddressToken token) {
return tokens.indexOf(token);
}
/**
* Extract a new TokenStream running from the start token to the
* token preceeding the end token.
*
* @param start The starting token of the section.
* @param end The last token (+1) for the target section.
*
* @return A new TokenStream object for processing this section of tokens.
*/
public TokenStream section(final AddressToken start, final AddressToken end) {
final int startIndex = tokenIndex(start);
final int endIndex = tokenIndex(end);
// List.subList() returns a list backed by the original list. Since we need to add a
// terminator token to this list when we take the sublist, we need to manually copy the
// references so we don't end up munging the original list.
final ArrayList list = new ArrayList(endIndex - startIndex + 2);
for (int i = startIndex; i <= endIndex; i++) {
list.add(tokens.get(i));
}
return new TokenStream(list);
}
/**
* Reset the token position back to the beginning of the
* stream.
*/
public void reset() {
currentToken = 0;
}
/**
* Scan forward looking for a non-blank token.
*
* @return The first non-blank token in the stream.
*/
public AddressToken getNonBlank()
{
AddressToken token = currentToken();
while (token.type == WHITESPACE) {
currentToken++;
token = currentToken();
}
return token;
}
/**
* Extract a blank delimited token from a TokenStream. A blank
* delimited token is the set of tokens up to the next real whitespace
* token (comments not included).
*
* @return A TokenStream object with the new set of tokens.
*/
public TokenStream getBlankDelimitedToken()
{
// get the next non-whitespace token.
final AddressToken first = getNonBlank();
// if this is the end, we return null.
if (first.type == END_OF_TOKENS) {
return null;
}
AddressToken last = first;
// the methods for retrieving tokens skip over whitespace, so we're going to process this
// by index.
currentToken++;
AddressToken token = currentToken();
while (true) {
// if this is our marker, then pluck out the section and return it.
if (token.type == END_OF_TOKENS || token.type == WHITESPACE) {
return section(first, last);
}
last = token;
currentToken++;
// we accept any and all tokens here.
token = currentToken();
}
}
/**
* Return the index of the current cursor position.
*
* @return The integer index of the current token.
*/
public int currentIndex() {
return currentToken;
}
public void dumpTokens()
{
System.out.println(">>>>>>>>> Start dumping TokenStream tokens");
for (int i = 0; i < tokens.size(); i++) {
System.out.println("-------- Token: " + tokens.get(i));
}
System.out.println("++++++++ cursor position=" + currentToken);
System.out.println(">>>>>>>>> End dumping TokenStream tokens");
}
}
/**
* Simple utility class for representing address tokens.
*/
public class AddressToken {
// the token type
int type;
// string value of the token (can be null)
String value;
// position of the token within the address string.
int position;
AddressToken(final int type, final int position)
{
this.type = type;
this.value = null;
this.position = position;
}
AddressToken(final String value, final int type, final int position)
{
this.type = type;
this.value = value;
this.position = position;
}
@Override
public String toString()
{
if (type == END_OF_TOKENS) {
return "AddressToken: type=END_OF_TOKENS";
}
if (value == null) {
return "AddressToken: type=" + (char)type;
}
else {
return "AddressToken: type=" + (char)type + " value=" + value;
}
}
}
}
| 2,016 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/MessageCountListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface MessageCountListener extends EventListener {
public abstract void messagesAdded(MessageCountEvent event);
public abstract void messagesRemoved(MessageCountEvent event);
}
| 2,017 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/ConnectionAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
/**
* An adaptor that receives connection events.
* This is a default implementation where the handlers perform no action.
*
* @version $Rev$ $Date$
*/
public abstract class ConnectionAdapter implements ConnectionListener {
public void closed(final ConnectionEvent event) {
}
public void disconnected(final ConnectionEvent event) {
}
public void opened(final ConnectionEvent event) {
}
}
| 2,018 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/StoreListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface StoreListener extends EventListener {
public abstract void notification(StoreEvent event);
}
| 2,019 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/MessageChangedListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface MessageChangedListener extends EventListener {
public abstract void messageChanged(MessageChangedEvent event);
}
| 2,020 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/FolderEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import javax.mail.Folder;
/**
* @version $Rev$ $Date$
*/
public class FolderEvent extends MailEvent {
private static final long serialVersionUID = 5278131310563694307L;
public static final int CREATED = 1;
public static final int DELETED = 2;
public static final int RENAMED = 3;
protected transient Folder folder;
protected transient Folder newFolder;
protected int type;
/**
* Constructor used for RENAMED events.
*
* @param source the source of the event
* @param oldFolder the folder that was renamed
* @param newFolder the folder with the new name
* @param type the event type
*/
public FolderEvent(final Object source, final Folder oldFolder, final Folder newFolder, final int type) {
super(source);
folder = oldFolder;
this.newFolder = newFolder;
this.type = type;
}
/**
* Constructor other events.
*
* @param source the source of the event
* @param folder the folder affected
* @param type the event type
*/
public FolderEvent(final Object source, final Folder folder, final int type) {
this(source, folder, null, type);
}
@Override
public void dispatch(final Object listener) {
final FolderListener l = (FolderListener) listener;
switch (type) {
case CREATED:
l.folderCreated(this);
break;
case DELETED:
l.folderDeleted(this);
break;
case RENAMED:
l.folderRenamed(this);
break;
default:
throw new IllegalArgumentException("Invalid type " + type);
}
}
/**
* Return the affected folder.
* @return the affected folder
*/
public Folder getFolder() {
return folder;
}
/**
* Return the new folder; only applicable to RENAMED events.
* @return the new folder
*/
public Folder getNewFolder() {
return newFolder;
}
/**
* Return the event type.
* @return the event type
*/
public int getType() {
return type;
}
}
| 2,021 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/FolderAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
/**
* An adaptor that receives connection events.
* This is a default implementation where the handlers perform no action.
*
* @version $Rev$ $Date$
*/
public abstract class FolderAdapter implements FolderListener {
public void folderCreated(final FolderEvent event) {
}
public void folderDeleted(final FolderEvent event) {
}
public void folderRenamed(final FolderEvent event) {
}
}
| 2,022 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/ConnectionListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import java.util.EventListener;
/**
* Listener for handling connection events.
*
* @version $Rev$ $Date$
*/
public interface ConnectionListener extends EventListener {
/**
* Called when a connection is opened.
*/
public abstract void opened(ConnectionEvent event);
/**
* Called when a connection is disconnected.
*/
public abstract void disconnected(ConnectionEvent event);
/**
* Called when a connection is closed.
*/
public abstract void closed(ConnectionEvent event);
}
| 2,023 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/TransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface TransportListener extends EventListener {
public abstract void messageDelivered(TransportEvent event);
public abstract void messageNotDelivered(TransportEvent event);
public abstract void messagePartiallyDelivered(TransportEvent event);
}
| 2,024 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/MessageChangedEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import javax.mail.Message;
/**
* @version $Rev$ $Date$
*/
public class MessageChangedEvent extends MailEvent {
private static final long serialVersionUID = -4974972972105535108L;
/**
* The message's flags changed.
*/
public static final int FLAGS_CHANGED = 1;
/**
* The messages envelope changed.
*/
public static final int ENVELOPE_CHANGED = 2;
protected transient Message msg;
protected int type;
/**
* Constructor.
*
* @param source the folder that owns the message
* @param type the event type
* @param message the affected message
*/
public MessageChangedEvent(final Object source, final int type, final Message message) {
super(source);
msg = message;
this.type = type;
}
@Override
public void dispatch(final Object listener) {
final MessageChangedListener l = (MessageChangedListener) listener;
l.messageChanged(this);
}
/**
* Return the affected message.
* @return the affected message
*/
public Message getMessage() {
return msg;
}
/**
* Return the type of change.
* @return the event type
*/
public int getMessageChangeType() {
return type;
}
}
| 2,025 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/MessageCountAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
/**
* An adaptor that receives message count events.
* This is a default implementation where the handlers perform no action.
*
* @version $Rev$ $Date$
*/
public abstract class MessageCountAdapter implements MessageCountListener {
public void messagesAdded(final MessageCountEvent event) {
}
public void messagesRemoved(final MessageCountEvent event) {
}
}
| 2,026 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/TransportAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
/**
* An adaptor that receives transport events.
* This is a default implementation where the handlers perform no action.
*
* @version $Rev$ $Date$
*/
public abstract class TransportAdapter implements TransportListener {
public void messageDelivered(final TransportEvent event) {
}
public void messageNotDelivered(final TransportEvent event) {
}
public void messagePartiallyDelivered(final TransportEvent event) {
}
}
| 2,027 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/FolderListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface FolderListener extends EventListener {
public abstract void folderCreated(FolderEvent event);
public abstract void folderDeleted(FolderEvent event);
public abstract void folderRenamed(FolderEvent event);
}
| 2,028 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/MailEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import java.util.EventObject;
/**
* Common base class for mail events.
*
* @version $Rev$ $Date$
*/
public abstract class MailEvent extends EventObject {
private static final long serialVersionUID = 1846275636325456631L;
public MailEvent(final Object source) {
super(source);
}
public abstract void dispatch(Object listener);
}
| 2,029 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/MessageCountEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import javax.mail.Folder;
import javax.mail.Message;
/**
* Event indicating a change in the number of messages in a folder.
*
* @version $Rev$ $Date$
*/
public class MessageCountEvent extends MailEvent {
private static final long serialVersionUID = -7447022340837897369L;
/**
* Messages were added to the folder.
*/
public static final int ADDED = 1;
/**
* Messages were removed from the folder.
*/
public static final int REMOVED = 2;
/**
* The affected messages.
*/
protected transient Message msgs[];
/**
* The event type.
*/
protected int type;
/**
* If true, then messages were expunged from the folder by this client
* and message numbers reflect the deletion; if false, then the change
* was the result of an expunge by a different client.
*/
protected boolean removed;
/**
* Construct a new event.
*
* @param folder the folder containing the messages
* @param type the event type
* @param removed indicator of whether messages were expunged by this client
* @param messages the affected messages
*/
public MessageCountEvent(final Folder folder, final int type, final boolean removed, final Message messages[]) {
super(folder);
this.msgs = messages;
this.type = type;
this.removed = removed;
}
/**
* Return the event type.
*
* @return the event type
*/
public int getType() {
return type;
}
/**
* @return whether this event was the result of an expunge by this client
* @see MessageCountEvent#removed
*/
public boolean isRemoved() {
return removed;
}
/**
* Return the affected messages.
*
* @return the affected messages
*/
public Message[] getMessages() {
return msgs;
}
@Override
public void dispatch(final Object listener) {
final MessageCountListener l = (MessageCountListener) listener;
switch (type) {
case ADDED:
l.messagesAdded(this);
break;
case REMOVED:
l.messagesRemoved(this);
break;
default:
throw new IllegalArgumentException("Invalid type " + type);
}
}
}
| 2,030 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/StoreEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import javax.mail.Store;
/**
* Event representing motifications from the Store connection.
*
* @version $Rev$ $Date$
*/
public class StoreEvent extends MailEvent {
private static final long serialVersionUID = 1938704919992515330L;
/**
* Indicates that this message is an alert.
*/
public static final int ALERT = 1;
/**
* Indicates that this message is a notice.
*/
public static final int NOTICE = 2;
/**
* The message type.
*/
protected int type;
/**
* The text to be presented to the user.
*/
protected String message;
/**
* Construct a new event.
*
* @param store the Store that initiated the notification
* @param type the message type
* @param message the text to be presented to the user
*/
public StoreEvent(final Store store, final int type, final String message) {
super(store);
this.type = type;
this.message = message;
}
/**
* Return the message type.
*
* @return the message type
*/
public int getMessageType() {
return type;
}
/**
* Return the text to be displayed to the user.
*
* @return the text to be displayed to the user
*/
public String getMessage() {
return message;
}
@Override
public void dispatch(final Object listener) {
((StoreListener) listener).notification(this);
}
}
| 2,031 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/TransportEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Transport;
/**
* @version $Rev$ $Date$
*/
public class TransportEvent extends MailEvent {
private static final long serialVersionUID = -4729852364684273073L;
/**
* Indicates that the message has successfully been delivered to all
* recipients.
*/
public static final int MESSAGE_DELIVERED = 1;
/**
* Indicates that no messages could be delivered.
*/
public static final int MESSAGE_NOT_DELIVERED = 2;
/**
* Indicates that some of the messages were successfully delivered
* but that some failed.
*/
public static final int MESSAGE_PARTIALLY_DELIVERED = 3;
/**
* The event type.
*/
protected int type;
/**
* Addresses to which the message was successfully delivered.
*/
protected transient Address[] validSent;
/**
* Addresses which are valid but to which the message was not sent.
*/
protected transient Address[] validUnsent;
/**
* Addresses that are invalid.
*/
protected transient Address[] invalid;
/**
* The message associated with this event.
*/
protected transient Message msg;
/**
* Construct a new event,
*
* @param transport the transport attempting to deliver the message
* @param type the event type
* @param validSent addresses to which the message was successfully delivered
* @param validUnsent addresses which are valid but to which the message was not sent
* @param invalid invalid addresses
* @param message the associated message
*/
public TransportEvent(final Transport transport, final int type, final Address[] validSent, final Address[] validUnsent, final Address[] invalid, final Message message) {
super(transport);
this.type = type;
this.validSent = validSent;
this.validUnsent = validUnsent;
this.invalid = invalid;
this.msg = message;
}
public Address[] getValidSentAddresses() {
return validSent;
}
public Address[] getValidUnsentAddresses() {
return validUnsent;
}
public Address[] getInvalidAddresses() {
return invalid;
}
public Message getMessage() {
return msg;
}
public int getType() {
return type;
}
@Override
public void dispatch(final Object listener) {
final TransportListener l = (TransportListener) listener;
switch (type) {
case MESSAGE_DELIVERED:
l.messageDelivered(this);
break;
case MESSAGE_NOT_DELIVERED:
l.messageNotDelivered(this);
break;
case MESSAGE_PARTIALLY_DELIVERED:
l.messagePartiallyDelivered(this);
break;
default:
throw new IllegalArgumentException("Invalid type " + type);
}
}
}
| 2,032 |
0 | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail | Create_ds/geronimo-specs/geronimo-javamail_1.5_spec/src/main/java/javax/mail/event/ConnectionEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.event;
/**
* @version $Rev$ $Date$
*/
public class ConnectionEvent extends MailEvent {
private static final long serialVersionUID = -1855480171284792957L;
/**
* A connection was opened.
*/
public static final int OPENED = 1;
/**
* A connection was disconnected.
*/
public static final int DISCONNECTED = 2;
/**
* A connection was closed.
*/
public static final int CLOSED = 3;
protected int type;
public ConnectionEvent(final Object source, final int type) {
super(source);
this.type = type;
}
public int getType() {
return type;
}
@Override
public void dispatch(final Object listener) {
// assume that it is the right listener type
final ConnectionListener l = (ConnectionListener) listener;
switch (type) {
case OPENED:
l.opened(this);
break;
case DISCONNECTED:
l.disconnected(this);
break;
case CLOSED:
l.closed(this);
break;
default:
throw new IllegalArgumentException("Invalid type " + type);
}
}
}
| 2,033 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/PostConstruct.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PostConstruct {
}
| 2,034 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/Resource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Resource {
public enum AuthenticationType {
CONTAINER,
APPLICATION
}
String name() default "";
Class type() default Object.class;
AuthenticationType authenticationType()
default AuthenticationType.CONTAINER;
boolean shareable() default true;
String mappedName() default "";
String description() default "";
String lookup() default "";
}
| 2,035 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/ManagedBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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.annotation;
/**
* @version $Rev$ $Date$
*/
@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface ManagedBean {
java.lang.String value() default "";
}
| 2,036 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/Resources.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Resources {
Resource[] value();
}
| 2,037 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/PreDestroy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PreDestroy {
}
| 2,038 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/Generated.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @version $Rev$ $Date$
*/
@Target({
ElementType.PACKAGE,
ElementType.TYPE,
ElementType.ANNOTATION_TYPE,
ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.LOCAL_VARIABLE,
ElementType.PARAMETER
})
@Retention(RetentionPolicy.SOURCE)
@Documented
public @interface Generated {
String[] value();
String date() default "";
String comments() default "";
}
| 2,039 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/security/RunAs.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation.security;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface RunAs {
String value();
}
| 2,040 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/security/DeclareRoles.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation.security;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DeclareRoles {
String[] value();
}
| 2,041 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/security/DenyAll.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation.security;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DenyAll {
}
| 2,042 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/security/PermitAll.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation.security;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PermitAll {
}
| 2,043 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/security/RolesAllowed.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.annotation.security;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Documented;
/**
* @version $Rev$ $Date$
*/
@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RolesAllowed {
String[] value();
}
| 2,044 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/sql/DataSourceDefinitions.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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.annotation.sql;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* @version $Revision$ $Date$
*/
@Retention(RUNTIME)
@Target({TYPE})
public @interface DataSourceDefinitions {
DataSourceDefinition[] value();
} | 2,045 |
0 | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation | Create_ds/geronimo-specs/geronimo-annotation_1.1_spec/src/main/java/javax/annotation/sql/DataSourceDefinition.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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.annotation.sql;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* @version $Revision$ $Date$
*/
@Retention(RUNTIME)
@Target({TYPE})
public @interface DataSourceDefinition {
boolean transactional() default true;
int initialPoolSize() default -1;
int isolationLevel() default -1;
int loginTimeout() default 0;
int maxIdleTime() default -1;
int maxPoolSize() default -1;
int maxStatements() default -1;
int minPoolSize() default -1;
int portNumber() default -1;
String databaseName() default "";
String description() default "";
String password() default "";
String serverName() default "localhost";
String url() default "";
String user() default "";
String[] properties() default {};
String className();
String name();
}
| 2,046 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/TestBlobDeserializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import com.google.common.base.Charsets;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.serialization.EventDeserializer;
import org.apache.flume.serialization.EventDeserializerFactory;
import org.apache.flume.serialization.ResettableInputStream;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class TestBlobDeserializer extends Assert {
private String mini;
@Before
public void setup() {
StringBuilder sb = new StringBuilder();
sb.append("line 1\n");
sb.append("line 2\n");
mini = sb.toString();
}
@Test
public void testSimple() throws IOException {
ResettableInputStream in = new ResettableTestStringInputStream(mini);
EventDeserializer des = new BlobDeserializer(new Context(), in);
validateMiniParse(des);
}
@Test
public void testSimpleViaBuilder() throws IOException {
ResettableInputStream in = new ResettableTestStringInputStream(mini);
EventDeserializer.Builder builder = new BlobDeserializer.Builder();
EventDeserializer des = builder.build(new Context(), in);
validateMiniParse(des);
}
@Test
public void testSimpleViaFactory() throws IOException {
ResettableInputStream in = new ResettableTestStringInputStream(mini);
EventDeserializer des;
des = EventDeserializerFactory.getInstance(BlobDeserializer.Builder.class.getName(),
new Context(), in);
validateMiniParse(des);
}
@Test
public void testBatch() throws IOException {
ResettableInputStream in = new ResettableTestStringInputStream(mini);
EventDeserializer des = new BlobDeserializer(new Context(), in);
List<Event> events;
events = des.readEvents(10); // try to read more than we should have
assertEquals(1, events.size());
assertEventBodyEquals(mini, events.get(0));
des.mark();
des.close();
}
// truncation occurs at maxLineLength boundaries
@Test
public void testMaxLineLength() throws IOException {
String longLine = "abcdefghijklmnopqrstuvwxyz\n";
Context ctx = new Context();
ctx.put(BlobDeserializer.MAX_BLOB_LENGTH_KEY, "10");
ResettableInputStream in = new ResettableTestStringInputStream(longLine);
EventDeserializer des = new BlobDeserializer(ctx, in);
assertEventBodyEquals("abcdefghij", des.readEvent());
assertEventBodyEquals("klmnopqrst", des.readEvent());
assertEventBodyEquals("uvwxyz\n", des.readEvent());
assertNull(des.readEvent());
}
private void assertEventBodyEquals(String expected, Event event) {
String bodyStr = new String(event.getBody(), Charsets.UTF_8);
assertEquals(expected, bodyStr);
}
private void validateMiniParse(EventDeserializer des) throws IOException {
Event evt;
des.mark();
evt = des.readEvent();
assertEquals(new String(evt.getBody()), mini);
des.reset(); // reset!
evt = des.readEvent();
assertEquals("data should be repeated, " +
"because we reset() the stream", new String(evt.getBody()), mini);
evt = des.readEvent();
assertNull("Event should be null because there are no lines " +
"left to read", evt);
des.mark();
des.close();
}
}
| 2,047 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/TestUUIDInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.event.SimpleEvent;
import org.junit.Assert;
import org.junit.Test;
public class TestUUIDInterceptor extends Assert {
private static final String ID = "id";
@Test
public void testBasic() throws Exception {
Context context = new Context();
context.put(UUIDInterceptor.HEADER_NAME, ID);
context.put(UUIDInterceptor.PRESERVE_EXISTING_NAME, "true");
Event event = new SimpleEvent();
assertTrue(build(context).intercept(event).getHeaders().get(ID).length() > 0);
}
@Test
public void testPreserveExisting() throws Exception {
Context context = new Context();
context.put(UUIDInterceptor.HEADER_NAME, ID);
context.put(UUIDInterceptor.PRESERVE_EXISTING_NAME, "true");
Event event = new SimpleEvent();
event.getHeaders().put(ID, "foo");
assertEquals("foo", build(context).intercept(event).getHeaders().get(ID));
}
@Test
public void testPrefix() throws Exception {
Context context = new Context();
context.put(UUIDInterceptor.HEADER_NAME, ID);
context.put(UUIDInterceptor.PREFIX_NAME, "bar#");
Event event = new SimpleEvent();
assertTrue(build(context).intercept(event).getHeaders().get(ID).startsWith("bar#"));
}
private UUIDInterceptor build(Context context) {
UUIDInterceptor.Builder builder = new UUIDInterceptor.Builder();
builder.configure(context);
return builder.build();
}
}
| 2,048 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/TestBlobHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.flume.Event;
import org.apache.flume.source.http.HTTPSourceHandler;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestBlobHandler extends Assert {
private HTTPSourceHandler handler;
@Before
public void setUp() {
handler = new BlobHandler();
}
@Test
public void testSingleEvent() throws Exception {
byte[] json = "foo".getBytes("UTF-8");
HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
List<Event> deserialized = handler.getEvents(req);
assertEquals(1, deserialized.size());
Event e = deserialized.get(0);
assertEquals(0, e.getHeaders().size());
assertEquals("foo", new String(e.getBody(),"UTF-8"));
}
@Test
public void testEmptyEvent() throws Exception {
byte[] json = "".getBytes("UTF-8");
HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
List<Event> deserialized = handler.getEvents(req);
assertEquals(1, deserialized.size());
Event e = deserialized.get(0);
assertEquals(0, e.getHeaders().size());
assertEquals("", new String(e.getBody(),"UTF-8"));
}
}
| 2,049 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/FlumeHttpServletRequestWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.ReadListener;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.Part;
class FlumeHttpServletRequestWrapper implements HttpServletRequest {
private ServletInputStream stream;
private String charset;
public FlumeHttpServletRequestWrapper(final byte[] data) {
stream = new ServletInputStream() {
@Override
public boolean isFinished() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isReady() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setReadListener(ReadListener readListener) {
throw new UnsupportedOperationException("Not supported yet.");
}
private final InputStream in = new ByteArrayInputStream(data);
@Override
public int read() throws IOException {
return in.read();
}
};
}
@Override
public String getAuthType() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Cookie[] getCookies() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getDateHeader(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getHeader(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Enumeration getHeaders(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Enumeration getHeaderNames() {
return Collections.enumeration(Collections.EMPTY_LIST);
}
@Override
public int getIntHeader(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getMethod() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getPathInfo() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getPathTranslated() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getContextPath() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getQueryString() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getRemoteUser() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isUserInRole(String role) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Principal getUserPrincipal() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getRequestedSessionId() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getRequestURI() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public StringBuffer getRequestURL() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getServletPath() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public HttpSession getSession(boolean create) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public HttpSession getSession() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String changeSessionId() {
return null;
}
@Override
public boolean isRequestedSessionIdValid() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isRequestedSessionIdFromCookie() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isRequestedSessionIdFromURL() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isRequestedSessionIdFromUrl() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void login(String username, String password) throws ServletException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void logout() throws ServletException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Collection<Part> getParts() throws IOException, ServletException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Part getPart(String name) throws IOException, ServletException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass)
throws IOException, ServletException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object getAttribute(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Enumeration<String> getAttributeNames() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getCharacterEncoding() {
return charset;
}
@Override
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
this.charset = env;
}
@Override
public int getContentLength() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getContentLengthLong() {
return 0;
}
@Override
public String getContentType() {
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException {
return stream;
}
@Override
public String getParameter(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Enumeration getParameterNames() {
return Collections.enumeration(Collections.EMPTY_LIST);
}
@Override
public String[] getParameterValues(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Map getParameterMap() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getProtocol() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getScheme() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getServerName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getServerPort() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public BufferedReader getReader() throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getRemoteAddr() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getRemoteHost() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setAttribute(String name, Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void removeAttribute(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Locale getLocale() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Enumeration<Locale> getLocales() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isSecure() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getRealPath(String path) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getRemotePort() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getLocalName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getLocalAddr() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getLocalPort() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ServletContext getServletContext() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isAsyncStarted() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isAsyncSupported() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public AsyncContext getAsyncContext() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public DispatcherType getDispatcherType() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| 2,050 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/TestEnvironment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.net.UnknownHostException;
import org.junit.Test;
import org.kitesdk.morphline.solr.EnvironmentTest;
/** Print and verify some info about the environment in which the unit tests are running */
public class TestEnvironment extends EnvironmentTest {
@Test
public void testEnvironment() throws UnknownHostException {
super.testEnvironment();
}
}
| 2,051 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/TestMorphlineSolrSink.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.flume.Channel;
import org.apache.flume.ChannelException;
import org.apache.flume.ChannelSelector;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.Transaction;
import org.apache.flume.channel.BasicTransactionSemantics;
import org.apache.flume.channel.ChannelProcessor;
import org.apache.flume.channel.MemoryChannel;
import org.apache.flume.channel.ReplicatingChannelSelector;
import org.apache.flume.conf.Configurables;
import org.apache.flume.event.EventBuilder;
import org.apache.flume.instrumentation.SinkCounter;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.kitesdk.morphline.api.MorphlineContext;
import org.kitesdk.morphline.api.Record;
import org.kitesdk.morphline.base.FaultTolerance;
import org.kitesdk.morphline.base.Fields;
import org.kitesdk.morphline.solr.DocumentLoader;
import org.kitesdk.morphline.solr.SolrLocator;
import org.kitesdk.morphline.solr.SolrMorphlineContext;
import org.kitesdk.morphline.solr.SolrServerDocumentLoader;
import org.kitesdk.morphline.solr.TestEmbeddedSolrServer;
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.io.Files;
public class TestMorphlineSolrSink extends SolrTestCaseJ4 {
private EmbeddedSource source;
private SolrServer solrServer;
private MorphlineSink sink;
private Map<String,Integer> expectedRecords;
private File tmpFile;
private static final boolean TEST_WITH_EMBEDDED_SOLR_SERVER = true;
private static final String EXTERNAL_SOLR_SERVER_URL = System.getProperty("externalSolrServer");
//private static final String EXTERNAL_SOLR_SERVER_URL = "http://127.0.0.1:8983/solr";
private static final String RESOURCES_DIR = "target/test-classes";
//private static final String RESOURCES_DIR = "src/test/resources";
private static final AtomicInteger SEQ_NUM = new AtomicInteger();
private static final AtomicInteger SEQ_NUM2 = new AtomicInteger();
private static final Logger LOGGER = LoggerFactory.getLogger(TestMorphlineSolrSink.class);
@BeforeClass
public static void beforeClass() throws Exception {
initCore(
RESOURCES_DIR + "/solr/collection1/conf/solrconfig.xml",
RESOURCES_DIR + "/solr/collection1/conf/schema.xml",
RESOURCES_DIR + "/solr");
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
String path = RESOURCES_DIR + "/test-documents";
expectedRecords = new HashMap();
expectedRecords.put(path + "/sample-statuses-20120906-141433.avro", 2);
expectedRecords.put(path + "/sample-statuses-20120906-141433", 2);
expectedRecords.put(path + "/sample-statuses-20120906-141433.gz", 2);
expectedRecords.put(path + "/sample-statuses-20120906-141433.bz2", 2);
expectedRecords.put(path + "/cars.csv", 5);
expectedRecords.put(path + "/cars.csv.gz", 5);
expectedRecords.put(path + "/cars.tar.gz", 4);
expectedRecords.put(path + "/cars.tsv", 5);
expectedRecords.put(path + "/cars.ssv", 5);
final Map<String, String> context = new HashMap();
if (EXTERNAL_SOLR_SERVER_URL != null) {
throw new UnsupportedOperationException();
//solrServer = new ConcurrentUpdateSolrServer(EXTERNAL_SOLR_SERVER_URL, 2, 2);
//solrServer = new SafeConcurrentUpdateSolrServer(EXTERNAL_SOLR_SERVER_URL, 2, 2);
//solrServer = new HttpSolrServer(EXTERNAL_SOLR_SERVER_URL);
} else {
if (TEST_WITH_EMBEDDED_SOLR_SERVER) {
solrServer = new TestEmbeddedSolrServer(h.getCoreContainer(), "");
} else {
throw new RuntimeException("Not yet implemented");
//solrServer = new TestSolrServer(getSolrServer());
}
}
Map<String, String> channelContext = new HashMap();
channelContext.put("capacity", "1000000");
channelContext.put("keep-alive", "0"); // for faster tests
Channel channel = new MemoryChannel();
channel.setName(channel.getClass().getName() + SEQ_NUM.getAndIncrement());
Configurables.configure(channel, new Context(channelContext));
class MySolrSink extends MorphlineSolrSink {
public MySolrSink(MorphlineHandlerImpl indexer) {
super(indexer);
}
}
int batchSize = SEQ_NUM2.incrementAndGet() % 2 == 0 ? 100 : 1;
DocumentLoader testServer = new SolrServerDocumentLoader(solrServer, batchSize);
MorphlineContext solrMorphlineContext = new SolrMorphlineContext.Builder()
.setDocumentLoader(testServer)
.setExceptionHandler(new FaultTolerance(false, false, SolrServerException.class.getName()))
.setMetricRegistry(new MetricRegistry()).build();
MorphlineHandlerImpl impl = new MorphlineHandlerImpl();
impl.setMorphlineContext(solrMorphlineContext);
class MySolrLocator extends SolrLocator { // trick to access protected ctor
public MySolrLocator(MorphlineContext indexer) {
super(indexer);
}
}
SolrLocator locator = new MySolrLocator(solrMorphlineContext);
locator.setSolrHomeDir(testSolrHome + "/collection1");
String str1 = "SOLR_LOCATOR : " + locator.toString();
//File solrLocatorFile = new File("target/test-classes/test-morphlines/solrLocator.conf");
//String str1 = Files.toString(solrLocatorFile, Charsets.UTF_8);
File morphlineFile = new File("target/test-classes/test-morphlines/solrCellDocumentTypes.conf");
String str2 = Files.toString(morphlineFile, Charsets.UTF_8);
tmpFile = File.createTempFile("morphline", ".conf");
tmpFile.deleteOnExit();
Files.write(str1 + "\n" + str2, tmpFile, Charsets.UTF_8);
context.put("morphlineFile", tmpFile.getPath());
impl.configure(new Context(context));
sink = new MySolrSink(impl);
sink.setName(sink.getClass().getName() + SEQ_NUM.getAndIncrement());
sink.configure(new Context(context));
sink.setChannel(channel);
sink.start();
source = new EmbeddedSource(sink);
ChannelSelector rcs = new ReplicatingChannelSelector();
rcs.setChannels(Collections.singletonList(channel));
ChannelProcessor chp = new ChannelProcessor(rcs);
Context chpContext = new Context();
chpContext.put("interceptors", "uuidinterceptor");
chpContext.put("interceptors.uuidinterceptor.type", UUIDInterceptor.Builder.class.getName());
chp.configure(chpContext);
source.setChannelProcessor(chp);
deleteAllDocuments();
}
private void deleteAllDocuments() throws SolrServerException, IOException {
SolrServer s = solrServer;
s.deleteByQuery("*:*"); // delete everything!
s.commit();
}
@After
@Override
public void tearDown() throws Exception {
try {
if (source != null) {
source.stop();
source = null;
}
if (sink != null) {
sink.stop();
sink = null;
}
if (tmpFile != null) {
tmpFile.delete();
}
} finally {
solrServer = null;
expectedRecords = null;
super.tearDown();
}
}
@Test
public void testDocumentTypes() throws Exception {
String path = RESOURCES_DIR + "/test-documents";
String[] files = new String[] {
path + "/testBMPfp.txt",
path + "/boilerplate.html",
path + "/NullHeader.docx",
path + "/testWORD_various.doc",
path + "/testPDF.pdf",
path + "/testJPEG_EXIF.jpg",
path + "/testXML.xml",
// path + "/cars.csv",
// path + "/cars.tsv",
// path + "/cars.ssv",
// path + "/cars.csv.gz",
// path + "/cars.tar.gz",
path + "/sample-statuses-20120906-141433.avro",
path + "/sample-statuses-20120906-141433",
path + "/sample-statuses-20120906-141433.gz",
path + "/sample-statuses-20120906-141433.bz2",
};
testDocumentTypesInternal(files);
}
@Test
public void testDocumentTypes2() throws Exception {
String path = RESOURCES_DIR + "/test-documents";
String[] files = new String[] {
path + "/testPPT_various.ppt",
path + "/testPPT_various.pptx",
path + "/testEXCEL.xlsx",
path + "/testEXCEL.xls",
path + "/testPages.pages",
path + "/testNumbers.numbers",
path + "/testKeynote.key",
path + "/testRTFVarious.rtf",
path + "/complex.mbox",
path + "/test-outlook.msg",
path + "/testEMLX.emlx",
// path + "/testRFC822",
path + "/rsstest.rss",
// path + "/testDITA.dita",
path + "/testMP3i18n.mp3",
path + "/testAIFF.aif",
path + "/testFLAC.flac",
// path + "/testFLAC.oga",
// path + "/testVORBIS.ogg",
path + "/testMP4.m4a",
path + "/testWAV.wav",
// path + "/testWMA.wma",
path + "/testFLV.flv",
// path + "/testWMV.wmv",
path + "/testBMP.bmp",
path + "/testPNG.png",
path + "/testPSD.psd",
path + "/testSVG.svg",
path + "/testTIFF.tif",
// path + "/test-documents.7z",
// path + "/test-documents.cpio",
// path + "/test-documents.tar",
// path + "/test-documents.tbz2",
// path + "/test-documents.tgz",
// path + "/test-documents.zip",
// path + "/test-zip-of-zip.zip",
// path + "/testJAR.jar",
// path + "/testKML.kml",
// path + "/testRDF.rdf",
path + "/testTrueType.ttf",
path + "/testVISIO.vsd",
// path + "/testWAR.war",
// path + "/testWindows-x86-32.exe",
// path + "/testWINMAIL.dat",
// path + "/testWMF.wmf",
};
testDocumentTypesInternal(files);
}
@Test
public void testErrorCounters() throws Exception {
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.take()).thenThrow(new ChannelException("dummy"));
Transaction transaction = Mockito.mock(BasicTransactionSemantics.class);
Mockito.when(channel.getTransaction()).thenReturn(transaction);
sink.setChannel(channel);
sink.process();
SinkCounter sinkCounter = (SinkCounter) Whitebox.getInternalState(sink, "sinkCounter");
assertEquals(1, sinkCounter.getChannelReadFail());
}
@Test
public void testAvroRoundTrip() throws Exception {
String file = RESOURCES_DIR + "/test-documents" + "/sample-statuses-20120906-141433.avro";
testDocumentTypesInternal(file);
QueryResponse rsp = query("*:*");
Iterator<SolrDocument> iter = rsp.getResults().iterator();
ListMultimap<String, String> expectedFieldValues;
expectedFieldValues = ImmutableListMultimap.of("id", "1234567890", "text", "sample tweet one",
"user_screen_name", "fake_user1");
assertEquals(expectedFieldValues, next(iter));
expectedFieldValues = ImmutableListMultimap.of("id", "2345678901", "text", "sample tweet two",
"user_screen_name", "fake_user2");
assertEquals(expectedFieldValues, next(iter));
assertFalse(iter.hasNext());
}
private ListMultimap<String, Object> next(Iterator<SolrDocument> iter) {
SolrDocument doc = iter.next();
Record record = toRecord(doc);
record.removeAll("_version_"); // the values of this field are unknown and internal to solr
return record.getFields();
}
private Record toRecord(SolrDocument doc) {
Record record = new Record();
for (String key : doc.keySet()) {
record.getFields().replaceValues(key, doc.getFieldValues(key));
}
return record;
}
private void testDocumentTypesInternal(String... files) throws Exception {
int numDocs = 0;
long startTime = System.currentTimeMillis();
assertEquals(numDocs, queryResultSetSize("*:*"));
// assertQ(req("*:*"), "//*[@numFound='0']");
for (int i = 0; i < 1; i++) {
for (String file : files) {
File f = new File(file);
byte[] body = Files.toByteArray(f);
Event event = EventBuilder.withBody(body);
event.getHeaders().put(Fields.ATTACHMENT_NAME, f.getName());
load(event);
Integer count = expectedRecords.get(file);
if (count != null) {
numDocs += count;
} else {
numDocs++;
}
assertEquals(numDocs, queryResultSetSize("*:*"));
}
LOGGER.trace("iter: {}", i);
}
LOGGER.trace("all done with put at {}", System.currentTimeMillis() - startTime);
assertEquals(numDocs, queryResultSetSize("*:*"));
LOGGER.trace("sink: ", sink);
}
// @Test
public void benchmarkDocumentTypes() throws Exception {
int iters = 200;
// LogManager.getLogger(getClass().getPackage().getName()).setLevel(Level.INFO);
assertEquals(0, queryResultSetSize("*:*"));
String path = RESOURCES_DIR + "/test-documents";
String[] files = new String[] {
// path + "/testBMPfp.txt",
// path + "/boilerplate.html",
// path + "/NullHeader.docx",
// path + "/testWORD_various.doc",
// path + "/testPDF.pdf",
// path + "/testJPEG_EXIF.jpg",
// path + "/testXML.xml",
// path + "/cars.csv",
// path + "/cars.csv.gz",
// path + "/cars.tar.gz",
// path + "/sample-statuses-20120906-141433.avro",
path + "/sample-statuses-20120906-141433-medium.avro",
};
List<Event> events = new ArrayList();
for (String file : files) {
File f = new File(file);
byte[] body = Files.toByteArray(f);
Event event = EventBuilder.withBody(body);
// event.getHeaders().put(Metadata.RESOURCE_NAME_KEY, f.getName());
events.add(event);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < iters; i++) {
if (i % 10000 == 0) {
LOGGER.info("iter: {}", i);
}
for (Event event : events) {
event = EventBuilder.withBody(event.getBody(), new HashMap(event.getHeaders()));
event.getHeaders().put("id", UUID.randomUUID().toString());
load(event);
}
}
float secs = (System.currentTimeMillis() - startTime) / 1000.0f;
long numDocs = queryResultSetSize("*:*");
LOGGER.info("Took secs: " + secs + ", iters/sec: " + (iters / secs));
LOGGER.info("Took secs: " + secs + ", docs/sec: " + (numDocs / secs));
LOGGER.info("Iterations: " + iters + ", numDocs: " + numDocs);
LOGGER.info("sink: ", sink);
}
private void load(Event event) throws EventDeliveryException {
source.load(event);
}
private void commit() throws SolrServerException, IOException {
solrServer.commit(false, true, true);
}
private int queryResultSetSize(String query) throws SolrServerException, IOException {
commit();
QueryResponse rsp = query(query);
LOGGER.debug("rsp: {}", rsp);
int size = rsp.getResults().size();
return size;
}
private QueryResponse query(String query) throws SolrServerException, IOException {
commit();
QueryResponse rsp = solrServer.query(new SolrQuery(query).setRows(Integer.MAX_VALUE));
LOGGER.debug("rsp: {}", rsp);
return rsp;
}
}
| 2,052 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/TestMorphlineInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.event.EventBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.kitesdk.morphline.base.Fields;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestMorphlineInterceptor extends Assert {
private static final String RESOURCES_DIR = "target/test-classes";
@Test
public void testNoOperation() throws Exception {
Context context = new Context();
context.put(MorphlineHandlerImpl.MORPHLINE_FILE_PARAM,
RESOURCES_DIR + "/test-morphlines/noOperation.conf");
Event input = EventBuilder.withBody("foo", Charsets.UTF_8);
input.getHeaders().put("name", "nadja");
MorphlineInterceptor interceptor = build(context);
Event actual = interceptor.intercept(input);
interceptor.close();
Event expected = EventBuilder.withBody("foo".getBytes("UTF-8"),
ImmutableMap.of("name", "nadja"));
assertEqualsEvent(expected, actual);
List<Event> actualList = build(context).intercept(Collections.singletonList(input));
List<Event> expectedList = Collections.singletonList(expected);
assertEqualsEventList(expectedList, actualList);
}
@Test
public void testReadClob() throws Exception {
Context context = new Context();
context.put(MorphlineHandlerImpl.MORPHLINE_FILE_PARAM,
RESOURCES_DIR + "/test-morphlines/readClob.conf");
Event input = EventBuilder.withBody("foo", Charsets.UTF_8);
input.getHeaders().put("name", "nadja");
Event actual = build(context).intercept(input);
Event expected = EventBuilder.withBody(null,
ImmutableMap.of("name", "nadja", Fields.MESSAGE, "foo"));
assertEqualsEvent(expected, actual);
List<Event> actualList = build(context).intercept(Collections.singletonList(input));
List<Event> expectedList = Collections.singletonList(expected);
assertEqualsEventList(expectedList, actualList);
}
@Test
public void testGrokIfNotMatchDropEventRetain() throws Exception {
Context context = new Context();
context.put(MorphlineHandlerImpl.MORPHLINE_FILE_PARAM,
RESOURCES_DIR + "/test-morphlines/grokIfNotMatchDropRecord.conf");
String msg = "<164>Feb 4 10:46:14 syslog sshd[607]: Server listening on 0.0.0.0 port 22.";
Event input = EventBuilder.withBody(null, ImmutableMap.of(Fields.MESSAGE, msg));
Event actual = build(context).intercept(input);
Map<String, String> expected = new HashMap();
expected.put(Fields.MESSAGE, msg);
expected.put("syslog_pri", "164");
expected.put("syslog_timestamp", "Feb 4 10:46:14");
expected.put("syslog_hostname", "syslog");
expected.put("syslog_program", "sshd");
expected.put("syslog_pid", "607");
expected.put("syslog_message", "Server listening on 0.0.0.0 port 22.");
Event expectedEvent = EventBuilder.withBody(null, expected);
assertEqualsEvent(expectedEvent, actual);
}
@Test
/* leading XXXXX does not match regex, thus we expect the event to be dropped */
public void testGrokIfNotMatchDropEventDrop() throws Exception {
Context context = new Context();
context.put(MorphlineHandlerImpl.MORPHLINE_FILE_PARAM,
RESOURCES_DIR + "/test-morphlines/grokIfNotMatchDropRecord.conf");
String msg = "<XXXXXXXXXXXXX164>Feb 4 10:46:14 syslog sshd[607]: Server listening on 0.0.0.0" +
" port 22.";
Event input = EventBuilder.withBody(null, ImmutableMap.of(Fields.MESSAGE, msg));
Event actual = build(context).intercept(input);
assertNull(actual);
}
@Test
/** morphline says route to southpole if it's an avro file, otherwise route to northpole */
public void testIfDetectMimeTypeRouteToSouthPole() throws Exception {
Context context = new Context();
context.put(MorphlineHandlerImpl.MORPHLINE_FILE_PARAM,
RESOURCES_DIR + "/test-morphlines/ifDetectMimeType.conf");
context.put(MorphlineHandlerImpl.MORPHLINE_VARIABLE_PARAM + ".MY.MIME_TYPE", "avro/binary");
Event input = EventBuilder.withBody(Files.toByteArray(
new File(RESOURCES_DIR + "/test-documents/sample-statuses-20120906-141433.avro")));
Event actual = build(context).intercept(input);
Map<String, String> expected = new HashMap();
expected.put(Fields.ATTACHMENT_MIME_TYPE, "avro/binary");
expected.put("flume.selector.header", "goToSouthPole");
Event expectedEvent = EventBuilder.withBody(input.getBody(), expected);
assertEqualsEvent(expectedEvent, actual);
}
@Test
/** morphline says route to southpole if it's an avro file, otherwise route to northpole */
public void testIfDetectMimeTypeRouteToNorthPole() throws Exception {
Context context = new Context();
context.put(MorphlineHandlerImpl.MORPHLINE_FILE_PARAM,
RESOURCES_DIR + "/test-morphlines/ifDetectMimeType.conf");
context.put(MorphlineHandlerImpl.MORPHLINE_VARIABLE_PARAM + ".MY.MIME_TYPE", "avro/binary");
Event input = EventBuilder.withBody(
Files.toByteArray(new File(RESOURCES_DIR + "/test-documents/testPDF.pdf")));
Event actual = build(context).intercept(input);
Map<String, String> expected = new HashMap();
expected.put(Fields.ATTACHMENT_MIME_TYPE, "application/pdf");
expected.put("flume.selector.header", "goToNorthPole");
Event expectedEvent = EventBuilder.withBody(input.getBody(), expected);
assertEqualsEvent(expectedEvent, actual);
}
private MorphlineInterceptor build(Context context) {
MorphlineInterceptor.Builder builder = new MorphlineInterceptor.Builder();
builder.configure(context);
return builder.build();
}
// b/c SimpleEvent doesn't implement equals() method :-(
private void assertEqualsEvent(Event x, Event y) {
assertEquals(x.getHeaders(), y.getHeaders());
assertArrayEquals(x.getBody(), y.getBody());
}
private void assertEqualsEventList(List<Event> x, List<Event> y) {
assertEquals(x.size(), y.size());
for (int i = 0; i < x.size(); i++) {
assertEqualsEvent(x.get(i), y.get(i));
}
}
}
| 2,053 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/ResettableTestStringInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.io.IOException;
import org.apache.flume.serialization.ResettableInputStream;
class ResettableTestStringInputStream extends ResettableInputStream {
private String str;
private int markPos = 0;
private int curPos = 0;
/**
* Warning: This test class does not handle character/byte conversion at all!
* @param str String to use for testing
*/
public ResettableTestStringInputStream(String str) {
this.str = str;
}
@Override
public int readChar() throws IOException {
throw new UnsupportedOperationException("This test class doesn't return " +
"strings!");
}
@Override
public void mark() throws IOException {
markPos = curPos;
}
@Override
public void reset() throws IOException {
curPos = markPos;
}
@Override
public void seek(long position) throws IOException {
throw new UnsupportedOperationException("Unimplemented in test class");
}
@Override
public long tell() throws IOException {
throw new UnsupportedOperationException("Unimplemented in test class");
}
@Override
public int read() throws IOException {
if (curPos >= str.length()) {
return -1;
}
return str.charAt(curPos++);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (curPos >= str.length()) {
return -1;
}
int n = 0;
while (len > 0 && curPos < str.length()) {
b[off++] = (byte) str.charAt(curPos++);
n++;
len--;
}
return n;
}
@Override
public void close() throws IOException {
// no-op
}
}
| 2,054 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/test/java/org/apache/flume/sink/solr/morphline/EmbeddedSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.util.List;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.EventDrivenSource;
import org.apache.flume.Sink;
import org.apache.flume.source.AbstractSource;
class EmbeddedSource extends AbstractSource implements EventDrivenSource {
private Sink sink;
public EmbeddedSource(Sink sink) {
this.sink = sink;
}
public void load(Event event) throws EventDeliveryException {
getChannelProcessor().processEvent(event);
sink.process();
}
public void load(List<Event> events) throws EventDeliveryException {
getChannelProcessor().processEventBatch(events);
sink.process();
}
}
| 2,055 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr/morphline/MorphlineHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.io.IOException;
import org.apache.flume.Event;
import org.apache.flume.conf.Configurable;
/**
* Interface to load Flume events into Solr
*/
public interface MorphlineHandler extends Configurable {
/** Begins a transaction */
public void beginTransaction();
/** Loads the given event into Solr */
public void process(Event event);
/**
* Sends any outstanding documents to Solr and waits for a positive
* or negative ack (i.e. exception). Depending on the outcome the caller
* should then commit or rollback the current flume transaction
* correspondingly.
*
* @throws IOException
* If there is a low-level I/O error.
*/
public void commitTransaction();
/**
* Performs a rollback of all non-committed documents pending.
* <p>
* Note that this is not a true rollback as in databases. Content you have previously added to
* Solr may have already been committed due to autoCommit, buffer full, other client performing a
* commit etc. So this is only a best-effort rollback.
*
* @throws IOException
* If there is a low-level I/O error.
*/
public void rollbackTransaction();
/** Releases allocated resources */
public void stop();
}
| 2,056 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr/morphline/BlobHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.io.InputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.conf.ConfigurationException;
import org.apache.flume.conf.LogPrivacyUtil;
import org.apache.flume.event.EventBuilder;
import org.apache.flume.source.http.HTTPSourceHandler;
import org.apache.tika.metadata.Metadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* BlobHandler for HTTPSource that returns event that contains the request
* parameters as well as the Binary Large Object (BLOB) uploaded with this
* request.
* <p>
* Note that this approach is not suitable for very large objects because it
* buffers up the entire BLOB.
* <p>
* Example client usage:
* <pre>
* curl --data-binary @sample-statuses-20120906-141433-medium.avro 'http://127.0.0.1:5140?resourceName=sample-statuses-20120906-141433-medium.avro' --header 'Content-Type:application/octet-stream' --verbose
* </pre>
*/
public class BlobHandler implements HTTPSourceHandler {
private int maxBlobLength = MAX_BLOB_LENGTH_DEFAULT;
public static final String MAX_BLOB_LENGTH_KEY = "maxBlobLength";
public static final int MAX_BLOB_LENGTH_DEFAULT = 100 * 1000 * 1000;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 8;
private static final Logger LOGGER = LoggerFactory.getLogger(BlobHandler.class);
public BlobHandler() {
}
@Override
public void configure(Context context) {
this.maxBlobLength = context.getInteger(MAX_BLOB_LENGTH_KEY, MAX_BLOB_LENGTH_DEFAULT);
if (this.maxBlobLength <= 0) {
throw new ConfigurationException("Configuration parameter " + MAX_BLOB_LENGTH_KEY
+ " must be greater than zero: " + maxBlobLength);
}
}
@SuppressWarnings("resource")
@Override
public List<Event> getEvents(HttpServletRequest request) throws Exception {
Map<String, String> headers = getHeaders(request);
InputStream in = request.getInputStream();
try {
ByteArrayOutputStream blob = null;
byte[] buf = new byte[Math.min(maxBlobLength, DEFAULT_BUFFER_SIZE)];
int blobLength = 0;
int n = 0;
while ((n = in.read(buf, 0, Math.min(buf.length, maxBlobLength - blobLength))) != -1) {
if (blob == null) {
blob = new ByteArrayOutputStream(n);
}
blob.write(buf, 0, n);
blobLength += n;
if (blobLength >= maxBlobLength) {
LOGGER.warn("Request length exceeds maxBlobLength ({}), truncating BLOB event!",
maxBlobLength);
break;
}
}
byte[] array = blob != null ? blob.toByteArray() : new byte[0];
Event event = EventBuilder.withBody(array, headers);
if (LOGGER.isDebugEnabled() && LogPrivacyUtil.allowLogRawData()) {
LOGGER.debug("blobEvent: {}", event);
}
return Collections.singletonList(event);
} finally {
in.close();
}
}
private Map<String, String> getHeaders(HttpServletRequest request) {
if (LOGGER.isDebugEnabled() && LogPrivacyUtil.allowLogRawData()) {
Map requestHeaders = new HashMap();
Enumeration iter = request.getHeaderNames();
while (iter.hasMoreElements()) {
String name = (String) iter.nextElement();
requestHeaders.put(name, request.getHeader(name));
}
LOGGER.debug("requestHeaders: {}", requestHeaders);
}
Map<String, String> headers = new HashMap();
if (request.getContentType() != null) {
headers.put(Metadata.CONTENT_TYPE, request.getContentType());
}
Enumeration iter = request.getParameterNames();
while (iter.hasMoreElements()) {
String name = (String) iter.nextElement();
headers.put(name, request.getParameter(name));
}
return headers;
}
}
| 2,057 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr/morphline/MorphlineSink.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import org.apache.flume.Channel;
import org.apache.flume.ChannelException;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.Transaction;
import org.apache.flume.conf.BatchSizeSupported;
import org.apache.flume.conf.Configurable;
import org.apache.flume.conf.ConfigurationException;
import org.apache.flume.conf.LogPrivacyUtil;
import org.apache.flume.instrumentation.SinkCounter;
import org.apache.flume.sink.AbstractSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.kitesdk.morphline.api.Command;
/**
* Flume sink that extracts search documents from Flume events and processes them using a morphline
* {@link Command} chain.
*/
public class MorphlineSink extends AbstractSink implements Configurable, BatchSizeSupported {
private int maxBatchSize = 1000;
private long maxBatchDurationMillis = 1000;
private String handlerClass;
private MorphlineHandler handler;
private Context context;
private SinkCounter sinkCounter;
public static final String BATCH_SIZE = "batchSize";
public static final String BATCH_DURATION_MILLIS = "batchDurationMillis";
public static final String HANDLER_CLASS = "handlerClass";
private static final Logger LOGGER = LoggerFactory.getLogger(MorphlineSink.class);
public MorphlineSink() {
this(null);
}
/** For testing only */
protected MorphlineSink(MorphlineHandler handler) {
this.handler = handler;
}
@Override
public void configure(Context context) {
this.context = context;
maxBatchSize = context.getInteger(BATCH_SIZE, maxBatchSize);
maxBatchDurationMillis = context.getLong(BATCH_DURATION_MILLIS, maxBatchDurationMillis);
handlerClass = context.getString(HANDLER_CLASS, MorphlineHandlerImpl.class.getName());
if (sinkCounter == null) {
sinkCounter = new SinkCounter(getName());
}
}
/**
* Returns the maximum number of events to take per flume transaction;
* override to customize
*/
private int getMaxBatchSize() {
return maxBatchSize;
}
/** Returns the maximum duration per flume transaction; override to customize */
private long getMaxBatchDurationMillis() {
return maxBatchDurationMillis;
}
@Override
public synchronized void start() {
LOGGER.info("Starting Morphline Sink {} ...", this);
sinkCounter.start();
if (handler == null) {
MorphlineHandler tmpHandler;
try {
tmpHandler = (MorphlineHandler) Class.forName(handlerClass).newInstance();
} catch (Exception e) {
throw new ConfigurationException(e);
}
tmpHandler.configure(context);
handler = tmpHandler;
}
super.start();
LOGGER.info("Morphline Sink {} started.", getName());
}
@Override
public synchronized void stop() {
LOGGER.info("Morphline Sink {} stopping...", getName());
try {
if (handler != null) {
handler.stop();
}
sinkCounter.stop();
LOGGER.info("Morphline Sink {} stopped. Metrics: {}", getName(), sinkCounter);
} finally {
super.stop();
}
}
@Override
public Status process() throws EventDeliveryException {
int batchSize = getMaxBatchSize();
long batchEndTime = System.currentTimeMillis() + getMaxBatchDurationMillis();
Channel myChannel = getChannel();
Transaction txn = myChannel.getTransaction();
txn.begin();
boolean isMorphlineTransactionCommitted = true;
try {
int numEventsTaken = 0;
handler.beginTransaction();
isMorphlineTransactionCommitted = false;
// repeatedly take and process events from the Flume queue
for (int i = 0; i < batchSize; i++) {
Event event = myChannel.take();
if (event == null) {
break;
}
sinkCounter.incrementEventDrainAttemptCount();
numEventsTaken++;
if (LOGGER.isTraceEnabled() && LogPrivacyUtil.allowLogRawData()) {
LOGGER.trace("Flume event arrived {}", event);
}
//StreamEvent streamEvent = createStreamEvent(event);
handler.process(event);
if (System.currentTimeMillis() >= batchEndTime) {
break;
}
}
// update metrics
if (numEventsTaken == 0) {
sinkCounter.incrementBatchEmptyCount();
}
if (numEventsTaken < batchSize) {
sinkCounter.incrementBatchUnderflowCount();
} else {
sinkCounter.incrementBatchCompleteCount();
}
handler.commitTransaction();
isMorphlineTransactionCommitted = true;
txn.commit();
sinkCounter.addToEventDrainSuccessCount(numEventsTaken);
return numEventsTaken == 0 ? Status.BACKOFF : Status.READY;
} catch (Throwable t) {
// Ooops - need to rollback and back off
LOGGER.error("Morphline Sink " + getName() + ": Unable to process event from channel " +
myChannel.getName() + ". Exception follows.", t);
sinkCounter.incrementEventWriteOrChannelFail(t);
try {
if (!isMorphlineTransactionCommitted) {
handler.rollbackTransaction();
}
} catch (Throwable t2) {
LOGGER.error("Morphline Sink " + getName() +
": Unable to rollback morphline transaction. Exception follows.", t2);
} finally {
try {
txn.rollback();
} catch (Throwable t4) {
LOGGER.error("Morphline Sink " + getName() + ": Unable to rollback Flume transaction. " +
"Exception follows.", t4);
}
}
if (t instanceof Error) {
throw (Error) t; // rethrow original exception
} else if (t instanceof ChannelException) {
return Status.BACKOFF;
} else {
throw new EventDeliveryException("Failed to send events", t); // rethrow and backoff
}
} finally {
txn.close();
}
}
@Override
public long getBatchSize() {
return getMaxBatchSize();
}
@Override
public String toString() {
int i = getClass().getName().lastIndexOf('.') + 1;
String shortClassName = getClass().getName().substring(i);
return getName() + " (" + shortClassName + ")";
}
}
| 2,058 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr/morphline/BlobDeserializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.annotations.InterfaceAudience;
import org.apache.flume.annotations.InterfaceStability;
import org.apache.flume.conf.ConfigurationException;
import org.apache.flume.event.EventBuilder;
import org.apache.flume.serialization.EventDeserializer;
import org.apache.flume.serialization.ResettableInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
/**
* A deserializer that reads a Binary Large Object (BLOB) per event, typically
* one BLOB per file; To be used in conjunction with Flume SpoolDirectorySource.
* <p>
* Note that this approach is not suitable for very large objects because it
* buffers up the entire BLOB.
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class BlobDeserializer implements EventDeserializer {
private ResettableInputStream in;
private final int maxBlobLength;
private volatile boolean isOpen;
public static final String MAX_BLOB_LENGTH_KEY = "maxBlobLength";
public static final int MAX_BLOB_LENGTH_DEFAULT = 100 * 1000 * 1000;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 8;
private static final Logger LOGGER = LoggerFactory.getLogger(BlobDeserializer.class);
protected BlobDeserializer(Context context, ResettableInputStream in) {
this.in = in;
this.maxBlobLength = context.getInteger(MAX_BLOB_LENGTH_KEY, MAX_BLOB_LENGTH_DEFAULT);
if (this.maxBlobLength <= 0) {
throw new ConfigurationException("Configuration parameter " + MAX_BLOB_LENGTH_KEY
+ " must be greater than zero: " + maxBlobLength);
}
this.isOpen = true;
}
/**
* Reads a BLOB from a file and returns an event
* @return Event containing a BLOB
* @throws IOException
*/
@SuppressWarnings("resource")
@Override
public Event readEvent() throws IOException {
ensureOpen();
ByteArrayOutputStream blob = null;
byte[] buf = new byte[Math.min(maxBlobLength, DEFAULT_BUFFER_SIZE)];
int blobLength = 0;
int n = 0;
while ((n = in.read(buf, 0, Math.min(buf.length, maxBlobLength - blobLength))) != -1) {
if (blob == null) {
blob = new ByteArrayOutputStream(n);
}
blob.write(buf, 0, n);
blobLength += n;
if (blobLength >= maxBlobLength) {
LOGGER.warn("File length exceeds maxBlobLength ({}), truncating BLOB event!",
maxBlobLength);
break;
}
}
if (blob == null) {
return null;
} else {
return EventBuilder.withBody(blob.toByteArray());
}
}
/**
* Batch BLOB read
* @param numEvents Maximum number of events to return.
* @return List of events containing read BLOBs
* @throws IOException
*/
@Override
public List<Event> readEvents(int numEvents) throws IOException {
ensureOpen();
List<Event> events = Lists.newLinkedList();
for (int i = 0; i < numEvents; i++) {
Event event = readEvent();
if (event != null) {
events.add(event);
} else {
break;
}
}
return events;
}
@Override
public void mark() throws IOException {
ensureOpen();
in.mark();
}
@Override
public void reset() throws IOException {
ensureOpen();
in.reset();
}
@Override
public void close() throws IOException {
if (isOpen) {
reset();
in.close();
isOpen = false;
}
}
private void ensureOpen() {
if (!isOpen) {
throw new IllegalStateException("Serializer has been closed");
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
/** Builder implementations MUST have a public no-arg constructor */
public static class Builder implements EventDeserializer.Builder {
@Override
public BlobDeserializer build(Context context, ResettableInputStream in) {
return new BlobDeserializer(context, in);
}
}
}
| 2,059 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr/morphline/UUIDInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;
/**
* Flume Interceptor that sets a universally unique identifier on all events
* that are intercepted. By default this event header is named "id".
*/
public class UUIDInterceptor implements Interceptor {
private String headerName;
private boolean preserveExisting;
private String prefix;
public static final String HEADER_NAME = "headerName";
public static final String PRESERVE_EXISTING_NAME = "preserveExisting";
public static final String PREFIX_NAME = "prefix";
protected UUIDInterceptor(Context context) {
headerName = context.getString(HEADER_NAME, "id");
preserveExisting = context.getBoolean(PRESERVE_EXISTING_NAME, true);
prefix = context.getString(PREFIX_NAME, "");
}
@Override
public void initialize() {
}
protected String getPrefix() {
return prefix;
}
protected String generateUUID() {
return getPrefix() + UUID.randomUUID().toString();
}
protected boolean isMatch(Event event) {
return true;
}
@Override
public Event intercept(Event event) {
Map<String, String> headers = event.getHeaders();
if (preserveExisting && headers.containsKey(headerName)) {
// we must preserve the existing id
} else if (isMatch(event)) {
headers.put(headerName, generateUUID());
}
return event;
}
@Override
public List<Event> intercept(List<Event> events) {
List results = new ArrayList(events.size());
for (Event event : events) {
event = intercept(event);
if (event != null) {
results.add(event);
}
}
return results;
}
@Override
public void close() {
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
/** Builder implementations MUST have a public no-arg constructor */
public static class Builder implements Interceptor.Builder {
private Context context;
public Builder() {
}
@Override
public UUIDInterceptor build() {
return new UUIDInterceptor(context);
}
@Override
public void configure(Context context) {
this.context = context;
}
}
}
| 2,060 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr/morphline/MorphlineHandlerImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.io.File;
import java.util.Map.Entry;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.kitesdk.morphline.api.Command;
import org.kitesdk.morphline.api.MorphlineCompilationException;
import org.kitesdk.morphline.api.MorphlineContext;
import org.kitesdk.morphline.api.Record;
import org.kitesdk.morphline.base.Compiler;
import org.kitesdk.morphline.base.FaultTolerance;
import org.kitesdk.morphline.base.Fields;
import org.kitesdk.morphline.base.Metrics;
import org.kitesdk.morphline.base.Notifications;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import com.codahale.metrics.Timer;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
/**
* A {@link MorphlineHandler} that processes it's events using a morphline {@link Command} chain.
*/
public class MorphlineHandlerImpl implements MorphlineHandler {
private MorphlineContext morphlineContext;
private Command morphline;
private Command finalChild;
private String morphlineFileAndId;
private Timer mappingTimer;
private Meter numRecords;
private Meter numFailedRecords;
private Meter numExceptionRecords;
public static final String MORPHLINE_FILE_PARAM = "morphlineFile";
public static final String MORPHLINE_ID_PARAM = "morphlineId";
/**
* Morphline variables can be passed from flume.conf to the morphline, e.g.:
* agent.sinks.solrSink.morphlineVariable.zkHost=127.0.0.1:2181/solr
*/
public static final String MORPHLINE_VARIABLE_PARAM = "morphlineVariable";
private static final Logger LOG = LoggerFactory.getLogger(MorphlineHandlerImpl.class);
// For test injection
void setMorphlineContext(MorphlineContext morphlineContext) {
this.morphlineContext = morphlineContext;
}
// for interceptor
void setFinalChild(Command finalChild) {
this.finalChild = finalChild;
}
@Override
public void configure(Context context) {
String morphlineFile = context.getString(MORPHLINE_FILE_PARAM);
String morphlineId = context.getString(MORPHLINE_ID_PARAM);
if (morphlineFile == null || morphlineFile.trim().length() == 0) {
throw new MorphlineCompilationException("Missing parameter: " + MORPHLINE_FILE_PARAM, null);
}
morphlineFileAndId = morphlineFile + "@" + morphlineId;
if (morphlineContext == null) {
FaultTolerance faultTolerance = new FaultTolerance(
context.getBoolean(FaultTolerance.IS_PRODUCTION_MODE, false),
context.getBoolean(FaultTolerance.IS_IGNORING_RECOVERABLE_EXCEPTIONS, false),
context.getString(FaultTolerance.RECOVERABLE_EXCEPTION_CLASSES));
morphlineContext = new MorphlineContext.Builder()
.setExceptionHandler(faultTolerance)
.setMetricRegistry(SharedMetricRegistries.getOrCreate(morphlineFileAndId))
.build();
}
Config override = ConfigFactory.parseMap(
context.getSubProperties(MORPHLINE_VARIABLE_PARAM + "."));
morphline = new Compiler().compile(
new File(morphlineFile), morphlineId, morphlineContext, finalChild, override);
this.mappingTimer = morphlineContext.getMetricRegistry().timer(
MetricRegistry.name("morphline.app", Metrics.ELAPSED_TIME));
this.numRecords = morphlineContext.getMetricRegistry().meter(
MetricRegistry.name("morphline.app", Metrics.NUM_RECORDS));
this.numFailedRecords = morphlineContext.getMetricRegistry().meter(
MetricRegistry.name("morphline.app", "numFailedRecords"));
this.numExceptionRecords = morphlineContext.getMetricRegistry().meter(
MetricRegistry.name("morphline.app", "numExceptionRecords"));
}
@Override
public void process(Event event) {
numRecords.mark();
Timer.Context timerContext = mappingTimer.time();
try {
Record record = new Record();
for (Entry<String, String> entry : event.getHeaders().entrySet()) {
record.put(entry.getKey(), entry.getValue());
}
byte[] bytes = event.getBody();
if (bytes != null && bytes.length > 0) {
record.put(Fields.ATTACHMENT_BODY, bytes);
}
try {
Notifications.notifyStartSession(morphline);
if (!morphline.process(record)) {
numFailedRecords.mark();
LOG.warn("Morphline {} failed to process record: {}", morphlineFileAndId, record);
}
} catch (RuntimeException t) {
numExceptionRecords.mark();
morphlineContext.getExceptionHandler().handleException(t, record);
}
} finally {
timerContext.stop();
}
}
@Override
public void beginTransaction() {
Notifications.notifyBeginTransaction(morphline);
}
@Override
public void commitTransaction() {
Notifications.notifyCommitTransaction(morphline);
}
@Override
public void rollbackTransaction() {
Notifications.notifyRollbackTransaction(morphline);
}
@Override
public void stop() {
Notifications.notifyShutdown(morphline);
}
}
| 2,061 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr/morphline/MorphlineSolrSink.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import org.apache.flume.Context;
import org.kitesdk.morphline.api.Command;
import org.kitesdk.morphline.base.FaultTolerance;
/**
* Flume sink that extracts search documents from Flume events, processes them using a morphline
* {@link Command} chain, and loads them into Apache Solr.
*/
public class MorphlineSolrSink extends MorphlineSink {
public MorphlineSolrSink() {
super();
}
/** For testing only */
protected MorphlineSolrSink(MorphlineHandler handler) {
super(handler);
}
@Override
public void configure(Context context) {
if (context.getString(FaultTolerance.RECOVERABLE_EXCEPTION_CLASSES) == null) {
context.put(FaultTolerance.RECOVERABLE_EXCEPTION_CLASSES,
"org.apache.solr.client.solrj.SolrServerException");
}
super.configure(context);
}
}
| 2,062 |
0 | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr | Create_ds/flume-morphline/flume-morphline-solr-sink/src/main/java/org/apache/flume/sink/solr/morphline/MorphlineInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flume.sink.solr.morphline;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.FlumeException;
import org.apache.flume.event.EventBuilder;
import org.apache.flume.interceptor.Interceptor;
import org.kitesdk.morphline.api.Command;
import org.kitesdk.morphline.api.Record;
import org.kitesdk.morphline.base.Fields;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
/**
* Flume Interceptor that executes a morphline on events that are intercepted.
*
* Currently, there is a restriction in that the morphline must not generate more than one output
* record for each input event.
*/
public class MorphlineInterceptor implements Interceptor {
private final Context context;
private final Queue<LocalMorphlineInterceptor> pool = new ConcurrentLinkedQueue<>();
protected MorphlineInterceptor(Context context) {
Preconditions.checkNotNull(context);
this.context = context;
// fail fast on morphline compilation exception
returnToPool(new LocalMorphlineInterceptor(context));
}
@Override
public void initialize() {
}
@Override
public void close() {
LocalMorphlineInterceptor interceptor;
while ((interceptor = pool.poll()) != null) {
interceptor.close();
}
}
@Override
public List<Event> intercept(List<Event> events) {
LocalMorphlineInterceptor interceptor = borrowFromPool();
List<Event> results = interceptor.intercept(events);
returnToPool(interceptor);
return results;
}
@Override
public Event intercept(Event event) {
LocalMorphlineInterceptor interceptor = borrowFromPool();
Event result = interceptor.intercept(event);
returnToPool(interceptor);
return result;
}
private void returnToPool(LocalMorphlineInterceptor interceptor) {
pool.add(interceptor);
}
private LocalMorphlineInterceptor borrowFromPool() {
LocalMorphlineInterceptor interceptor = pool.poll();
if (interceptor == null) {
interceptor = new LocalMorphlineInterceptor(context);
}
return interceptor;
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
/** Builder implementations MUST have a public no-arg constructor */
public static class Builder implements Interceptor.Builder {
private Context context;
public Builder() {
}
@Override
public MorphlineInterceptor build() {
return new MorphlineInterceptor(context);
}
@Override
public void configure(Context context) {
this.context = context;
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
private static final class LocalMorphlineInterceptor implements Interceptor {
private final MorphlineHandlerImpl morphline;
private final Collector collector;
protected LocalMorphlineInterceptor(Context context) {
this.morphline = new MorphlineHandlerImpl();
this.collector = new Collector();
this.morphline.setFinalChild(collector);
this.morphline.configure(context);
}
@Override
public void initialize() {
}
@Override
public void close() {
morphline.stop();
}
@Override
public List<Event> intercept(List<Event> events) {
List results = new ArrayList(events.size());
for (Event event : events) {
event = intercept(event);
if (event != null) {
results.add(event);
}
}
return results;
}
@Override
public Event intercept(Event event) {
collector.reset();
morphline.process(event);
List<Record> results = collector.getRecords();
if (results.size() == 0) {
return null;
}
if (results.size() > 1) {
throw new FlumeException(getClass().getName() +
" must not generate more than one output record per input event");
}
Event result = toEvent(results.get(0));
return result;
}
private Event toEvent(Record record) {
Map<String, String> headers = new HashMap();
Map<String, Collection<Object>> recordMap = record.getFields().asMap();
byte[] body = null;
for (Map.Entry<String, Collection<Object>> entry : recordMap.entrySet()) {
if (entry.getValue().size() > 1) {
throw new FlumeException(getClass().getName()
+ " must not generate more than one output value per record field");
}
assert entry.getValue().size() != 0; // guava guarantees that
Object firstValue = entry.getValue().iterator().next();
if (Fields.ATTACHMENT_BODY.equals(entry.getKey())) {
if (firstValue instanceof byte[]) {
body = (byte[]) firstValue;
} else if (firstValue instanceof InputStream) {
try {
body = ByteStreams.toByteArray((InputStream) firstValue);
} catch (IOException e) {
throw new FlumeException(e);
}
} else {
throw new FlumeException(getClass().getName()
+ " must non generate attachments that are not a byte[] or InputStream");
}
} else {
headers.put(entry.getKey(), firstValue.toString());
}
}
return EventBuilder.withBody(body, headers);
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
private static final class Collector implements Command {
private final List<Record> results = new ArrayList();
public List<Record> getRecords() {
return results;
}
public void reset() {
results.clear();
}
@Override
public Command getParent() {
return null;
}
@Override
public void notify(Record notification) {
}
@Override
public boolean process(Record record) {
Preconditions.checkNotNull(record);
results.add(record);
return true;
}
}
}
| 2,063 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestAuthentication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static org.apache.fineract.cn.identity.api.v1.events.EventConstants.OPERATION_POST_PERMITTABLE_GROUP;
import static org.apache.fineract.cn.identity.api.v1.events.EventConstants.OPERATION_POST_ROLE;
import static org.apache.fineract.cn.identity.api.v1.events.EventConstants.OPERATION_POST_USER;
import static org.apache.fineract.cn.identity.api.v1.events.EventConstants.OPERATION_PUT_USER_PASSWORD;
import com.google.common.collect.Sets;
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import org.apache.fineract.cn.identity.api.v1.domain.Password;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
import org.apache.fineract.cn.identity.api.v1.domain.UserWithPassword;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.fineract.cn.anubis.api.v1.client.Anubis;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.anubis.api.v1.domain.TokenContent;
import org.apache.fineract.cn.anubis.api.v1.domain.TokenPermission;
import org.apache.fineract.cn.anubis.test.v1.SystemSecurityEnvironment;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.InvalidTokenException;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.apache.fineract.cn.lang.AutoTenantContext;
import org.apache.fineract.cn.lang.security.RsaPublicKeyBuilder;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Myrle Krantz
*/
public class TestAuthentication extends AbstractIdentityTest {
@Test
//@Repeat(25)
public void testAdminLogin() throws InterruptedException {
//noinspection EmptyTryBlock
try (final AutoUserContext ignore = loginAdmin()) {
}
}
@Test
public void testAdminLogout() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
getTestSubject().logout();
try {
getTestSubject().refresh();
Assert.fail("Refresh should fail after logout has occurred.");
}
catch (final InvalidTokenException ignored)
{
//Expected.
}
}
}
@Test(expected = NotFoundException.class)
public void testAdminIncorrectLogin() throws InterruptedException {
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword("set"));
Assert.fail("login with wrong password should fail with not found exception.");
}
@Test(expected = IllegalArgumentException.class)
public void testAdminMissingTenantHeader() throws InterruptedException {
try (final AutoUserContext ignored = tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
try (final AutoTenantContext ignored2 = new AutoTenantContext())
{
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
}
}
Assert.fail("login without tenant header set should fail with bad request.");
}
@Test()
public void testPermissionsCorrectInAdminToken() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final Authentication adminAuthentication =
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
Assert.assertNotNull(adminAuthentication);
final TokenContent tokenContent = SystemSecurityEnvironment.getTokenContent(adminAuthentication.getAccessToken(), getPublicKey());
final Set<TokenPermission> tokenPermissions = new HashSet<>(tokenContent.getTokenPermissions());
final Set<TokenPermission> expectedTokenPermissions = new HashSet<>();
Collections.addAll(expectedTokenPermissions,
new TokenPermission("identity-v1/permittablegroups/*", Sets.newHashSet(AllowedOperation.CHANGE, AllowedOperation.DELETE, AllowedOperation.READ)),
new TokenPermission("identity-v1/roles/*", Sets.newHashSet(AllowedOperation.CHANGE, AllowedOperation.DELETE, AllowedOperation.READ)),
new TokenPermission("identity-v1/users/*", Sets.newHashSet(AllowedOperation.CHANGE, AllowedOperation.DELETE, AllowedOperation.READ)));
//This is not a complete list. This is a spot check.
Assert.assertTrue("Expected: " + expectedTokenPermissions + "\nActual: " + tokenPermissions,
tokenPermissions.containsAll(expectedTokenPermissions));
}
}
@Test()
public void testPermissionsCorrectInTokenWhenMultiplePermittableGroupsInRole() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final PermittableEndpoint horusEndpoint = buildPermittableEndpoint("horus");
final PermittableGroup horusGroup = buildPermittableGroup("horus_Group", horusEndpoint);
getTestSubject().createPermittableGroup(horusGroup);
final PermittableEndpoint maatEndpoint = buildPermittableEndpoint("maat");
final PermittableGroup maatGroup = buildPermittableGroup("maat_Group", maatEndpoint);
getTestSubject().createPermittableGroup(maatGroup);
Assert.assertTrue(eventRecorder.wait(OPERATION_POST_PERMITTABLE_GROUP, horusGroup.getIdentifier()));
Assert.assertTrue(eventRecorder.wait(OPERATION_POST_PERMITTABLE_GROUP, maatGroup.getIdentifier()));
final Permission horusGroupPermission = new Permission(horusGroup.getIdentifier(), Collections.singleton(AllowedOperation.READ));
final Permission maatGroupPermission = new Permission(maatGroup.getIdentifier(), AllowedOperation.ALL);
final Role compositeRole = new Role("composite_role", Arrays.asList(horusGroupPermission, maatGroupPermission));
getTestSubject().createRole(compositeRole);
Assert.assertTrue(eventRecorder.wait(OPERATION_POST_ROLE, compositeRole.getIdentifier()));
final UserWithPassword user = new UserWithPassword("user_with_composite_role", compositeRole.getIdentifier(), "asdfasdfasdf");
getTestSubject().createUser(user);
Assert.assertTrue(eventRecorder.wait(OPERATION_POST_USER, user.getIdentifier()));
final Authentication passwordChangeOnlyAuthentication = getTestSubject().login(user.getIdentifier(), user.getPassword());
try (final AutoUserContext ignore2 = new AutoUserContext(user.getIdentifier(), passwordChangeOnlyAuthentication.getAccessToken()))
{
getTestSubject().changeUserPassword(user.getIdentifier(), new Password(user.getPassword()));
Assert.assertTrue(eventRecorder.wait(OPERATION_PUT_USER_PASSWORD, user.getIdentifier()));
}
final Authentication authentication = getTestSubject().login(user.getIdentifier(), user.getPassword());
final TokenContent tokenContent = SystemSecurityEnvironment
.getTokenContent(authentication.getAccessToken(), getPublicKey());
final Set<TokenPermission> tokenPermissions = new HashSet<>(tokenContent.getTokenPermissions());
final Set<TokenPermission> expectedTokenPermissions= new HashSet<>();
Collections.addAll(expectedTokenPermissions,
new TokenPermission(horusEndpoint.getPath(), Collections.singleton(AllowedOperation.READ)),
new TokenPermission(maatEndpoint.getPath(), Collections.singleton(AllowedOperation.READ)),
new TokenPermission("identity-v1/users/{useridentifier}/password",
Sets.newHashSet(AllowedOperation.READ, AllowedOperation.CHANGE, AllowedOperation.DELETE)),
new TokenPermission("identity-v1/users/{useridentifier}/permissions", Sets.newHashSet(AllowedOperation.READ)),
new TokenPermission("identity-v1/token/_current", Collections.singleton(AllowedOperation.DELETE)));
Assert.assertTrue("Expected: " + expectedTokenPermissions + "\nActual: " + tokenPermissions,
tokenPermissions.containsAll(expectedTokenPermissions));
}
}
private PermittableGroup buildPermittableGroup(final String identifier, final PermittableEndpoint... permittableEndpoint) {
final PermittableGroup ret = new PermittableGroup();
ret.setIdentifier(identifier);
ret.setPermittables(Arrays.asList(permittableEndpoint));
return ret;
}
private PermittableEndpoint buildPermittableEndpoint(final String group) {
final PermittableEndpoint ret = new PermittableEndpoint();
ret.setPath(group + "/v1/x/y/z");
ret.setMethod("GET");
ret.setGroupId(group);
return ret;
}
public PublicKey getPublicKey() {
try (final AutoUserContext ignored = tenantApplicationSecurityEnvironment.createAutoSeshatContext())
{
final Anubis anubis = tenantApplicationSecurityEnvironment.getAnubis();
final List<String> signatureKeyTimestamps = anubis.getAllSignatureSets();
Assert.assertTrue(!signatureKeyTimestamps.isEmpty());
final Signature sig = anubis.getApplicationSignature(signatureKeyTimestamps.get(0));
return new RsaPublicKeyBuilder()
.setPublicKeyMod(sig.getPublicKeyMod())
.setPublicKeyExp(sig.getPublicKeyExp())
.build();
}
}
}
| 2,064 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/Helpers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.springframework.util.Base64Utils;
import java.util.List;
import java.util.Random;
import java.util.function.Function;
/**
* @author Myrle Krantz
*/
class Helpers {
static <T> boolean instancePresent(final List<T> users, Function<T, String> getIdentifier,
final String identifier) {
return users.stream().map(getIdentifier).filter(i -> i.equals(identifier)).findAny().isPresent();
}
}
| 2,065 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/SuiteTestEnvironment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.apache.fineract.cn.test.fixture.cassandra.CassandraInitializer;
import org.junit.ClassRule;
import org.junit.rules.RuleChain;
import org.junit.rules.RunExternalResourceOnce;
import org.junit.rules.TestRule;
/**
* @author Myrle Krantz
*/
public class SuiteTestEnvironment {
static final String APP_NAME = "identity-v1";
final static TestEnvironment testEnvironment = new TestEnvironment(APP_NAME);
final static CassandraInitializer cassandraInitializer = new CassandraInitializer();
@ClassRule
public static TestRule orderClassRules = RuleChain
.outerRule(new RunExternalResourceOnce(testEnvironment))
.around(new RunExternalResourceOnce(cassandraInitializer));
}
| 2,066 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestKeyRotation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.fineract.cn.anubis.api.v1.client.Anubis;
import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.api.context.AutoGuest;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Myrle Krantz
*/
public class TestKeyRotation extends AbstractIdentityTest {
@Test
public void testKeyRotation() throws InterruptedException {
final Anubis anubis = tenantApplicationSecurityEnvironment.getAnubis();
//noinspection EmptyTryBlock
try (final AutoUserContext ignored = loginAdmin())
{
//Don't do anything yet.
}
final String systemToken = tenantApplicationSecurityEnvironment.getSystemSecurityEnvironment().systemToken(APP_NAME);
try (final AutoUserContext ignored1 = new AutoSeshat(systemToken)) {
//Create a signature set then test that it is listed.
final String timestamp = getTestSubject().createSignatureSet().getTimestamp();
{
final List<String> signatureSets = anubis.getAllSignatureSets();
Assert.assertTrue(signatureSets.contains(timestamp));
}
final Authentication adminAuthenticationOnFirstKeyset;
try (final AutoUserContext ignored2 = new AutoGuest()) {
adminAuthenticationOnFirstKeyset = getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
}
Assert.assertTrue(canAccessResources(adminAuthenticationOnFirstKeyset));
//For identity, application signature and identity manager signature should be identical.
final ApplicationSignatureSet signatureSet = anubis.getSignatureSet(timestamp);
Assert.assertEquals(signatureSet.getApplicationSignature(), signatureSet.getIdentityManagerSignature());
final Signature applicationSignature = anubis.getApplicationSignature(timestamp);
Assert.assertEquals(signatureSet.getApplicationSignature(), applicationSignature);
TimeUnit.SECONDS.sleep(2); //Timestamp has resolution at seconds level -- Make sure that second signature set has different timestamp from the first one.
//Create a second signature set and test that it and the previous signature set are listed.
final String timestamp2 = getTestSubject().createSignatureSet().getTimestamp();
{
final List<String> signatureSets = anubis.getAllSignatureSets();
Assert.assertTrue(signatureSets.contains(timestamp));
Assert.assertTrue(signatureSets.contains(timestamp2));
}
final Authentication adminAuthenticationOnSecondKeyset;
try (final AutoUserContext ignored2 = new AutoGuest()) {
adminAuthenticationOnSecondKeyset = getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment
.encodePassword(ADMIN_PASSWORD));
}
Assert.assertTrue(canAccessResources(adminAuthenticationOnFirstKeyset));
Assert.assertTrue(canAccessResources(adminAuthenticationOnSecondKeyset));
//Get the newly created signature set, and test that its contents are correct.
final ApplicationSignatureSet signatureSet2 = anubis.getSignatureSet(timestamp2);
Assert.assertEquals(signatureSet2.getApplicationSignature(), signatureSet2.getIdentityManagerSignature());
//Delete one of the signature sets and test that it is no longer listed.
anubis.deleteSignatureSet(timestamp);
{
final List<String> signatureSets = anubis.getAllSignatureSets();
Assert.assertFalse(signatureSets.contains(timestamp));
Assert.assertTrue(signatureSets.contains(timestamp2));
}
Assert.assertTrue(canAccessResources(adminAuthenticationOnSecondKeyset));
Assert.assertFalse(canAccessResources(adminAuthenticationOnFirstKeyset));
//Getting the newly deleted signature set should fail.
try {
anubis.getSignatureSet(timestamp);
Assert.fail("Not found exception should be thrown.");
} catch (final NotFoundException ignored) {
}
//Getting the newly deleted application signature set should likewise fail.
try {
anubis.getApplicationSignature(timestamp);
Assert.fail("Not found exception should be thrown.");
} catch (final NotFoundException ignored) {
}
}
}
private boolean canAccessResources(final Authentication adminAuthentication) {
try (final AutoUserContext ignored = new AutoUserContext(ADMIN_IDENTIFIER, adminAuthentication.getAccessToken())) {
getTestSubject().getUsers();
return true;
}
catch (Throwable ignored) {
return false;
}
}
}
| 2,067 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestRoles.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static org.apache.fineract.cn.identity.internal.util.IdentityConstants.SU_ROLE;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Myrle Krantz
*/
public class TestRoles extends AbstractIdentityTest {
@Test
public void testRolesSortedAlphabetically() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final Permission rolePermission = buildRolePermission();
final Role role1 = buildRole(testEnvironment.generateUniqueIdentifier("abba"), rolePermission);
final Role role2 = buildRole(testEnvironment.generateUniqueIdentifier("bubba"), rolePermission);
final Role role3 = buildRole(testEnvironment.generateUniqueIdentifier("c1"), rolePermission);
final Role role4 = buildRole(testEnvironment.generateUniqueIdentifier("calla"), rolePermission);
final Role role5 = buildRole(testEnvironment.generateUniqueIdentifier("uelf"), rolePermission);
final Role role6 = buildRole(testEnvironment.generateUniqueIdentifier("ulf"), rolePermission);
getTestSubject().createRole(role2);
getTestSubject().createRole(role1);
getTestSubject().createRole(role6);
getTestSubject().createRole(role4);
getTestSubject().createRole(role3);
getTestSubject().createRole(role5);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, role1.getIdentifier()));
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, role2.getIdentifier()));
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, role3.getIdentifier()));
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, role4.getIdentifier()));
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, role5.getIdentifier()));
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, role6.getIdentifier()));
final List<Role> roles = getTestSubject().getRoles();
final List<String> idList = roles.stream().map(Role::getIdentifier).collect(Collectors.toList());
final List<String> sortedList = Arrays.asList(
role1.getIdentifier(),
role2.getIdentifier(),
role3.getIdentifier(),
role4.getIdentifier(),
role5.getIdentifier(),
role6.getIdentifier());
final List<String> filterOutIdsFromOtherTests = idList.stream().filter(sortedList::contains).collect(Collectors.toList());
Assert.assertEquals(sortedList, filterOutIdsFromOtherTests);
}
}
@Test
public void testCreateRole() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String roleIdentifier = generateRoleIdentifier();
final Permission rolePermission = buildRolePermission();
final Role scribe = buildRole(roleIdentifier, rolePermission);
getTestSubject().createRole(scribe);
{
final boolean found = eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, scribe.getIdentifier());
Assert.assertTrue(found);
}
final List<Role> roles = getTestSubject().getRoles();
Assert.assertTrue(Helpers.instancePresent(roles, Role::getIdentifier, roleIdentifier));
final Role role = getTestSubject().getRole(roleIdentifier);
Assert.assertNotNull(role);
Assert.assertEquals(roleIdentifier, role.getIdentifier());
Assert.assertEquals(Collections.singletonList(rolePermission), role.getPermissions());
}
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotBeAbleToCreateRoleNamedDeactivated() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final Permission rolePermission = buildRolePermission();
final Role deactivated = buildRole("deactivated", rolePermission);
getTestSubject().createRole(deactivated);
}
}
@Test
public void deleteRole() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String roleIdentifier = createRoleManagementRole();
final Role role = getTestSubject().getRole(roleIdentifier);
Assert.assertNotNull(role);
getTestSubject().deleteRole(role.getIdentifier());
{
final boolean found = eventRecorder.wait(EventConstants.OPERATION_DELETE_ROLE, roleIdentifier);
Assert.assertTrue(found);
}
final List<Role> roles = getTestSubject().getRoles();
Assert.assertFalse(Helpers.instancePresent(roles, Role::getIdentifier, roleIdentifier));
}
}
@Test(expected= NotFoundException.class)
public void deleteRoleThatDoesntExist() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String randomIdentifier = generateRoleIdentifier();
getTestSubject().deleteRole(randomIdentifier);
}
}
@Test()
public void changeRole() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String roleIdentifier = createRoleManagementRole();
final Role role = getTestSubject().getRole(roleIdentifier);
role.getPermissions().add(buildUserPermission());
getTestSubject().changeRole(roleIdentifier, role);
{
final boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_ROLE, role.getIdentifier());
Assert.assertTrue(found);
}
final Role changedRole = getTestSubject().getRole(roleIdentifier);
Assert.assertEquals(role, changedRole);
}
}
@Test
public void testChangePharaohRoleFails() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final Role referenceRole = getTestSubject().getRole(SU_ROLE);
final Role roleChangeRequest = buildRole(SU_ROLE, buildSelfPermission());
try {
getTestSubject().changeRole(SU_ROLE, roleChangeRequest);
Assert.fail("Should not be able to change the pharaoh role.");
}
catch (final IllegalArgumentException expected) {
//noinspection EmptyCatchBlock
}
final Role unChangedRole = getTestSubject().getRole(SU_ROLE);
Assert.assertEquals(referenceRole, unChangedRole);
}
}
@Test
public void testDeletePharaohRoleFails() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final Role adminRole = getTestSubject().getRole(ADMIN_ROLE);
try {
getTestSubject().deleteRole(ADMIN_ROLE);
Assert.fail("It should not be possible to delete the admin role.");
}
catch (final IllegalArgumentException expected) {
//noinspection EmptyCatchBlock
}
final Role adminRoleStillThere = getTestSubject().getRole(ADMIN_ROLE);
Assert.assertEquals(adminRole, adminRoleStillThere);
}
}
} | 2,068 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestProvisioning.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.fineract.cn.identity.api.v1.client.IdentityManager;
import org.apache.fineract.cn.anubis.api.v1.RoleConstants;
import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.anubis.token.SystemAccessTokenSerializer;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.InvalidTokenException;
import org.apache.fineract.cn.lang.AutoTenantContext;
import org.apache.fineract.cn.lang.TenantContextHolder;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.util.concurrent.TimeUnit;
/**
* @author Myrle Krantz
*/
public class TestProvisioning extends AbstractIdentityTest {
@Test
public void testBoundaryInitializeCases() throws InterruptedException {
final IdentityManager testSubject = getTestSubject();
final ApplicationSignatureSet firstTenantSignatureSet;
final Signature firstTenantIdentityManagerSignature;
//Create tenant keyspaces.
final String tenant1 = TestEnvironment.getRandomTenantName();
final String tenant2 = TestEnvironment.getRandomTenantName();
cassandraInitializer.initializeTenant(tenant1);
cassandraInitializer.initializeTenant(tenant2);
TimeUnit.SECONDS.sleep(1);
// This gives cassandra a chance to complete saving the new keyspaces.
// Theoretically, the creation of keyspaces is synchronous, but I've
// found that the cassandra driver needs just a little bit longer
// To show up in the request for metadata for that keyspace.
try (final AutoTenantContext ignored = new AutoTenantContext(tenant1)) {
final String invalidSeshatToken = "notBearer";
try (final AutoSeshat ignored2 = new AutoSeshat(invalidSeshatToken)){
testSubject.initialize(TestEnvironment.encodePassword(ADMIN_PASSWORD));
Assert.fail("The key had the wrong format. This should've failed.");
}
catch (final InvalidTokenException ignored2)
{
}
final String wrongSystemToken = systemTokenFromWrongKey();
try (final AutoSeshat ignored2 = new AutoSeshat(wrongSystemToken)){
testSubject.initialize(TestEnvironment.encodePassword(ADMIN_PASSWORD));
Assert.fail("The key was signed by the wrong source. This should've failed.");
}
catch (final Exception e)
{
Assert.assertTrue("The exception should be 'invalid token'", (e instanceof InvalidTokenException));
}
try (final AutoUserContext ignored2 = tenantApplicationSecurityEnvironment.createAutoSeshatContext("goober")) {
testSubject.initialize(TestEnvironment.encodePassword(ADMIN_PASSWORD));
Assert.fail("The key was intended for a different tenant. This should've failed.");
}
catch (final Exception e)
{
Assert.assertTrue("The exception should be 'not found'", (e instanceof InvalidTokenException));
}
// The second otherwise valid call to initialize for the same tenant should
// not fail even though the tenant is now already initialized.
try (final AutoUserContext ignored2 = tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
firstTenantSignatureSet = testSubject.initialize(TestEnvironment.encodePassword(ADMIN_PASSWORD));
final Signature applicationSignature = tenantApplicationSecurityEnvironment.getAnubis().getApplicationSignature(firstTenantSignatureSet.getTimestamp());
firstTenantIdentityManagerSignature = tenantApplicationSecurityEnvironment.getAnubis().getSignatureSet(firstTenantSignatureSet.getTimestamp()).getIdentityManagerSignature();
Assert.assertEquals(applicationSignature, firstTenantIdentityManagerSignature);
testSubject.initialize("golden_osiris");
}
}
final ApplicationSignatureSet secondTenantSignatureSet;
try (final AutoTenantContext ignored = new AutoTenantContext(tenant2)) {
try (final AutoUserContext ignored2
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
secondTenantSignatureSet = testSubject.initialize(TestEnvironment.encodePassword(ADMIN_PASSWORD));
final Signature secondTenantIdentityManagerSignature = tenantApplicationSecurityEnvironment.getAnubis().getApplicationSignature(secondTenantSignatureSet.getTimestamp());
Assert.assertNotEquals(firstTenantIdentityManagerSignature, secondTenantIdentityManagerSignature);
}
}
catch (final Exception e)
{
Assert.fail("Call to initialize for a second tenant should succeed. "
+ "The exception was " + e
);
throw e;
}
TenantContextHolder.clear();
}
private String systemTokenFromWrongKey()
{
final SystemAccessTokenSerializer.Specification tokenSpecification
= new SystemAccessTokenSerializer.Specification();
tokenSpecification.setKeyTimestamp("rando");
tokenSpecification.setPrivateKey(getWrongPrivateKey());
tokenSpecification.setRole(RoleConstants.SYSTEM_ADMIN_ROLE_IDENTIFIER);
tokenSpecification.setSecondsToLive(TimeUnit.HOURS.toSeconds(12L));
tokenSpecification.setTargetApplicationName(APP_NAME);
tokenSpecification.setTenant(TenantContextHolder.checkedGetIdentifier());
return new SystemAccessTokenSerializer().build(tokenSpecification).getToken();
}
private PrivateKey getWrongPrivateKey() {
try {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final BigInteger privateKeyMod = new BigInteger("17492023076590407419772677529630320569634203626210733433914657600705550392421401008213478702016995697617177968917710500448063776244435761300358170637857566629780506514059676334317863416316403254208652514809444684705031748559737773841335114470369449872988726825545007588731959817361831095583721775522968972071928027030514641182819255368960492742269021132488312466659639538013906582095129294788911611410130509557024329936361580892139238423117992298190557606490543083859770282260174239092737213765902825945545746379786237952115129023474946280230282545899883335448866567923667432417504919606306921621754480829178419392063");
final BigInteger privateKeyExp = new BigInteger("3836197074627064495542864246660307880240969356539464297200899853440665208817504565223497099105700278649491111086168927826113808321425686210385705579717210204462139251515628239821027066889171978771395739740240603830895850009141569242130546108040040023566336125601696661013541334741315567340965150672011734372736240827969821590544366269533567400051316301569296349329670063250330460924547069022975441956699127698164632663315582302411984903513839691646332895582584509587803859003388718326640891827257180737700763719907116123118603418352134643169731657061459925351503055596019271348089711003706283690698717182672701958953");
final RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateKeyMod, privateKeyExp);
return keyFactory.generatePrivate(privateKeySpec);
} catch (final InvalidKeySpecException | NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
| 2,069 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/AbstractIdentityTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.client.IdentityManager;
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import org.apache.fineract.cn.identity.api.v1.domain.Password;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
import org.apache.fineract.cn.identity.api.v1.domain.UserWithPassword;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationSignatureEvent;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.anubis.test.v1.TenantApplicationSecurityEnvironmentTestRule;
import org.apache.fineract.cn.api.config.EnableApiFactory;
import org.apache.fineract.cn.api.context.AutoGuest;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.ApiFactory;
import org.apache.fineract.cn.api.util.UserContextHolder;
import org.apache.fineract.cn.identity.config.IdentityServiceConfig;
import org.apache.fineract.cn.lang.security.RsaKeyPairFactory;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.apache.fineract.cn.test.fixture.TenantDataStoreContextTestRule;
import org.apache.fineract.cn.test.listener.EnableEventRecording;
import org.apache.fineract.cn.test.listener.EventRecorder;
import org.junit.After;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
classes = {AbstractIdentityTest.TestConfiguration.class})
@TestPropertySource(properties = {"cassandra.cl.read = LOCAL_QUORUM", "cassandra.cl.write = LOCAL_QUORUM", "cassandra.cl.delete = LOCAL_QUORUM", "identity.token.refresh.secureCookie = false", "identity.passwordExpiresInDays = 93"})
public class AbstractIdentityTest extends SuiteTestEnvironment {
@Configuration
@EnableApiFactory
@EnableEventRecording
@Import({IdentityServiceConfig.class})
@ComponentScan("listener")
public static class TestConfiguration {
public TestConfiguration ( ) {
super();
}
}
static final String ADMIN_PASSWORD = "golden_osiris";
static final String ADMIN_ROLE = "pharaoh";
static final String ADMIN_IDENTIFIER = "antony";
static final String AHMES_PASSWORD = "fractions";
static final String AHMES_FRIENDS_PASSWORD = "sekhem";
@ClassRule
public final static TenantDataStoreContextTestRule tenantDataStoreContext = TenantDataStoreContextTestRule.forRandomTenantName(cassandraInitializer);
//Not using this as a rule because initialize in identityManager is different.
static final TenantApplicationSecurityEnvironmentTestRule tenantApplicationSecurityEnvironment = new TenantApplicationSecurityEnvironmentTestRule(testEnvironment);
@Autowired
ApiFactory apiFactory;
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
EventRecorder eventRecorder;
private IdentityManager identityManager;
@PostConstruct
public void provision ( ) throws Exception {
identityManager = apiFactory.create(IdentityManager.class, testEnvironment.serverURI());
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
identityManager.initialize(TestEnvironment.encodePassword(ADMIN_PASSWORD));
}
}
@After
public void after ( ) {
UserContextHolder.clear();
eventRecorder.clear();
}
IdentityManager getTestSubject ( ) {
return identityManager;
}
AutoUserContext loginAdmin ( ) throws InterruptedException {
final Authentication adminAuthentication =
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
Assert.assertNotNull(adminAuthentication);
{
final boolean found = eventRecorder
.wait(EventConstants.OPERATION_AUTHENTICATE, ADMIN_IDENTIFIER);
Assert.assertTrue(found);
}
return new AutoUserContext(ADMIN_IDENTIFIER, adminAuthentication.getAccessToken());
}
/**
* In identityManager, the user is created with an expired password. The user must change the password him- or herself
* to access any other endpoint.
*/
String createUserWithNonexpiredPassword (final String password, final String role) throws InterruptedException {
final String username = testEnvironment.generateUniqueIdentifier("Ahmes");
try (final AutoUserContext ignore = loginAdmin()) {
getTestSubject().createUser(new UserWithPassword(username, role, TestEnvironment.encodePassword(password)));
{
final boolean found = eventRecorder.wait(EventConstants.OPERATION_POST_USER, username);
Assert.assertTrue(found);
}
final Authentication passwordOnlyAuthentication = getTestSubject().login(username, TestEnvironment.encodePassword(password));
try (final AutoUserContext ignore2 = new AutoUserContext(username, passwordOnlyAuthentication.getAccessToken())) {
getTestSubject().changeUserPassword(username, new Password(TestEnvironment.encodePassword(password)));
final boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_USER_PASSWORD, username);
Assert.assertTrue(found);
}
}
return username;
}
String generateRoleIdentifier ( ) {
return testEnvironment.generateUniqueIdentifier("scribe");
}
Role buildRole (final String identifier, final Permission... permission) {
final Role scribe = new Role();
scribe.setIdentifier(identifier);
scribe.setPermissions(Arrays.asList(permission));
return scribe;
}
Permission buildRolePermission ( ) {
final Permission permission = new Permission();
permission.setAllowedOperations(AllowedOperation.ALL);
permission.setPermittableEndpointGroupIdentifier(PermittableGroupIds.ROLE_MANAGEMENT);
return permission;
}
Permission buildUserPermission ( ) {
final Permission permission = new Permission();
permission.setAllowedOperations(AllowedOperation.ALL);
permission.setPermittableEndpointGroupIdentifier(PermittableGroupIds.IDENTITY_MANAGEMENT);
return permission;
}
Permission buildSelfPermission ( ) {
final Permission permission = new Permission();
permission.setAllowedOperations(AllowedOperation.ALL);
permission.setPermittableEndpointGroupIdentifier(PermittableGroupIds.SELF_MANAGEMENT);
return permission;
}
Permission buildApplicationSelfPermission ( ) {
final Permission permission = new Permission();
permission.setAllowedOperations(AllowedOperation.ALL);
permission.setPermittableEndpointGroupIdentifier(PermittableGroupIds.APPLICATION_SELF_MANAGEMENT);
return permission;
}
String createRoleManagementRole ( ) throws InterruptedException {
return createRole(buildRolePermission());
}
String createSelfManagementRole ( ) throws InterruptedException {
return createRole(buildSelfPermission());
}
String createApplicationSelfManagementRole ( ) throws InterruptedException {
return createRole(buildApplicationSelfPermission());
}
String createRole (final Permission... permission) throws InterruptedException {
final String roleIdentifier = generateRoleIdentifier();
final Role role = buildRole(roleIdentifier, permission);
getTestSubject().createRole(role);
eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, roleIdentifier);
return roleIdentifier;
}
AutoUserContext loginUser (final String userId, final String password) {
final Authentication authentication;
try (AutoUserContext ignored = new AutoGuest()) {
authentication = getTestSubject().login(userId, TestEnvironment.encodePassword(password));
}
return new AutoUserContext(userId, authentication.getAccessToken());
}
private String createTestApplicationName ( ) {
return "test" + RandomStringUtils.randomNumeric(3) + "-v1";
}
static class ApplicationSignatureTestData {
private final String applicationIdentifier;
private final RsaKeyPairFactory.KeyPairHolder keyPair;
ApplicationSignatureTestData (final String applicationIdentifier, final RsaKeyPairFactory.KeyPairHolder keyPair) {
this.applicationIdentifier = applicationIdentifier;
this.keyPair = keyPair;
}
String getApplicationIdentifier ( ) {
return applicationIdentifier;
}
RsaKeyPairFactory.KeyPairHolder getKeyPair ( ) {
return keyPair;
}
String getKeyTimestamp ( ) {
return keyPair.getTimestamp();
}
}
ApplicationSignatureTestData setApplicationSignature ( ) throws InterruptedException {
final String testApplicationName = createTestApplicationName();
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final Signature signature = new Signature(keyPair.getPublicKeyMod(), keyPair.getPublicKeyExp());
getTestSubject().setApplicationSignature(testApplicationName, keyPair.getTimestamp(), signature);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE, new ApplicationSignatureEvent(testApplicationName, keyPair.getTimestamp())));
return new ApplicationSignatureTestData(testApplicationName, keyPair);
}
void createApplicationPermission (final String applicationIdentifier, final Permission permission) throws InterruptedException {
getTestSubject().createApplicationPermission(applicationIdentifier, permission);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_APPLICATION_PERMISSION,
new ApplicationPermissionEvent(applicationIdentifier,
permission.getPermittableEndpointGroupIdentifier())));
}
}
| 2,070 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestPermittableGroups.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import java.util.Collections;
import java.util.List;
import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Myrle Krantz
*/
public class TestPermittableGroups extends AbstractIdentityTest {
@Test
public void getPermittableGroups() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final PermittableGroup identityManagementPermittableGroup
= getTestSubject().getPermittableGroup(PermittableGroupIds.IDENTITY_MANAGEMENT);
Assert.assertNotNull(identityManagementPermittableGroup);
Assert.assertEquals(PermittableGroupIds.IDENTITY_MANAGEMENT, identityManagementPermittableGroup.getIdentifier());
final PermittableGroup roleManagementPermittableGroup
= getTestSubject().getPermittableGroup(PermittableGroupIds.ROLE_MANAGEMENT);
Assert.assertNotNull(roleManagementPermittableGroup);
Assert.assertEquals(PermittableGroupIds.ROLE_MANAGEMENT, roleManagementPermittableGroup.getIdentifier());
final PermittableGroup selfManagementPermittableGroup
= getTestSubject().getPermittableGroup(PermittableGroupIds.SELF_MANAGEMENT);
Assert.assertNotNull(selfManagementPermittableGroup);
Assert.assertEquals(PermittableGroupIds.SELF_MANAGEMENT, selfManagementPermittableGroup.getIdentifier());
}
}
@Test(expected = IllegalArgumentException.class)
public void createWithIllegalMethodThrows() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String identifier = testEnvironment.generateUniqueIdentifier("group");
final PermittableEndpoint permittableEndpoint = buildPermittableEndpoint();
permittableEndpoint.setMethod("blah");
final PermittableGroup group = buildPermittableGroup(identifier, permittableEndpoint);
getTestSubject().createPermittableGroup(group);
Assert.assertFalse("create should throw because 'blah' is an illegal method name.", true);
}
}
@Test
public void create() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String identifier = testEnvironment.generateUniqueIdentifier("group");
final PermittableEndpoint permittableEndpoint = buildPermittableEndpoint();
final PermittableGroup group = buildPermittableGroup(identifier, permittableEndpoint);
getTestSubject().createPermittableGroup(group);
{
final boolean found = eventRecorder.wait(EventConstants.OPERATION_POST_PERMITTABLE_GROUP, group.getIdentifier());
Assert.assertTrue(found);
}
final List<PermittableGroup> permittableGroups = getTestSubject().getPermittableGroups();
Assert.assertTrue(Helpers.instancePresent(permittableGroups, PermittableGroup::getIdentifier, identifier));
final PermittableGroup createdGroup = getTestSubject().getPermittableGroup(identifier);
Assert.assertNotNull(createdGroup);
Assert.assertEquals(createdGroup, group);
Assert.assertEquals(Collections.singletonList(permittableEndpoint), createdGroup.getPermittables());
}
}
private PermittableGroup buildPermittableGroup(final String identifier, final PermittableEndpoint permittableEndpoint) {
final PermittableGroup ret = new PermittableGroup();
ret.setIdentifier(identifier);
ret.setPermittables(Collections.singletonList(permittableEndpoint));
return ret;
}
private PermittableEndpoint buildPermittableEndpoint() {
final PermittableEndpoint ret = new PermittableEndpoint();
ret.setPath("/x/y/z");
ret.setMethod("POST");
return ret;
}
}
| 2,071 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestApplications.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.User;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationCallEndpointSetEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionUserEvent;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.anubis.token.TenantRefreshTokenSerializer;
import org.apache.fineract.cn.anubis.token.TokenSerializationResult;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author Myrle Krantz
*/
public class TestApplications extends AbstractIdentityTest {
private static final String CALL_ENDPOINT_SET_IDENTIFIER = "doughboy";
@Test
public void testSetApplicationSignature() throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData appPlusSig = setApplicationSignature();
final List<String> foundApplications = getTestSubject().getApplications();
Assert.assertTrue(foundApplications.contains(appPlusSig.getApplicationIdentifier()));
getTestSubject().getApplicationSignature(
appPlusSig.getApplicationIdentifier(),
appPlusSig.getKeyTimestamp());
}
}
@Test
public void testCreateAndDeleteApplicationPermission() throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData appPlusSig = setApplicationSignature();
final Permission identityManagementPermission = new Permission();
identityManagementPermission.setPermittableEndpointGroupIdentifier(PermittableGroupIds.IDENTITY_MANAGEMENT);
identityManagementPermission.setAllowedOperations(Collections.singleton(AllowedOperation.READ));
createApplicationPermission(appPlusSig.getApplicationIdentifier(), identityManagementPermission);
{
final List<Permission> applicationPermissions = getTestSubject().getApplicationPermissions(appPlusSig.getApplicationIdentifier());
Assert.assertTrue(applicationPermissions.contains(identityManagementPermission));
final Permission applicationPermission = getTestSubject().getApplicationPermission(appPlusSig.getApplicationIdentifier(), PermittableGroupIds.IDENTITY_MANAGEMENT);
Assert.assertEquals(identityManagementPermission, applicationPermission);
}
final Permission roleManagementPermission = new Permission();
roleManagementPermission.setPermittableEndpointGroupIdentifier(PermittableGroupIds.ROLE_MANAGEMENT);
roleManagementPermission.setAllowedOperations(Collections.singleton(AllowedOperation.READ));
createApplicationPermission(appPlusSig.getApplicationIdentifier(), roleManagementPermission);
{
final List<Permission> applicationPermissions = getTestSubject().getApplicationPermissions(appPlusSig.getApplicationIdentifier());
Assert.assertTrue(applicationPermissions.contains(identityManagementPermission));
Assert.assertTrue(applicationPermissions.contains(roleManagementPermission));
}
getTestSubject().deleteApplicationPermission(appPlusSig.getApplicationIdentifier(), identityManagementPermission.getPermittableEndpointGroupIdentifier());
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_DELETE_APPLICATION_PERMISSION,
new ApplicationPermissionEvent(appPlusSig.getApplicationIdentifier(), PermittableGroupIds.IDENTITY_MANAGEMENT)));
{
final List<Permission> applicationPermissions = getTestSubject().getApplicationPermissions(appPlusSig.getApplicationIdentifier());
Assert.assertFalse(applicationPermissions.contains(identityManagementPermission));
Assert.assertTrue(applicationPermissions.contains(roleManagementPermission));
}
}
}
@Test
public void testDeleteApplication() throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData appPlusSig = setApplicationSignature();
getTestSubject().deleteApplication(appPlusSig.getApplicationIdentifier());
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_DELETE_APPLICATION, appPlusSig.getApplicationIdentifier()));
final List<String> foundApplications = getTestSubject().getApplications();
Assert.assertFalse(foundApplications.contains(appPlusSig.getApplicationIdentifier()));
try {
getTestSubject().getApplicationSignature(
appPlusSig.getApplicationIdentifier(),
appPlusSig.getKeyTimestamp());
Assert.fail("Shouldn't find app sig after app was deleted.");
}
catch (final NotFoundException ignored2) {
}
}
}
@Test
public void testApplicationPermissionUserApprovalProvisioning() throws InterruptedException {
final ApplicationSignatureTestData appPlusSig;
final Permission identityManagementPermission;
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
appPlusSig = setApplicationSignature();
identityManagementPermission = new Permission(
PermittableGroupIds.ROLE_MANAGEMENT,
Collections.singleton(AllowedOperation.READ));
createApplicationPermission(appPlusSig.getApplicationIdentifier(), identityManagementPermission);
}
final String user1Password;
final String user1id;
final String user2Password;
final String user2id;
try (final AutoUserContext ignored = loginAdmin()) {
final String selfManagementRoleId = createSelfManagementRole();
final String roleManagementRoleId = createRoleManagementRole();
user1Password = RandomStringUtils.randomAlphanumeric(5);
user1id = createUserWithNonexpiredPassword(user1Password, selfManagementRoleId);
user2Password = RandomStringUtils.randomAlphanumeric(5);
user2id = createUserWithNonexpiredPassword(user2Password, roleManagementRoleId);
}
try (final AutoUserContext ignored = loginUser(user1id, user1Password)) {
Assert.assertFalse(getTestSubject().getApplicationPermissionEnabledForUser(
appPlusSig.getApplicationIdentifier(),
identityManagementPermission.getPermittableEndpointGroupIdentifier(),
user1id));
getTestSubject().setApplicationPermissionEnabledForUser(
appPlusSig.getApplicationIdentifier(),
identityManagementPermission.getPermittableEndpointGroupIdentifier(),
user1id,
true);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_PERMISSION_USER_ENABLED,
new ApplicationPermissionUserEvent(
appPlusSig.getApplicationIdentifier(),
identityManagementPermission.getPermittableEndpointGroupIdentifier(),
user1id)));
Assert.assertTrue(getTestSubject().getApplicationPermissionEnabledForUser(
appPlusSig.getApplicationIdentifier(),
identityManagementPermission.getPermittableEndpointGroupIdentifier(),
user1id));
}
try (final AutoUserContext ignored = loginUser(user2id, user2Password)) {
Assert.assertFalse(getTestSubject().getApplicationPermissionEnabledForUser(
appPlusSig.getApplicationIdentifier(),
identityManagementPermission.getPermittableEndpointGroupIdentifier(),
user2id));
}
try (final AutoUserContext ignored = loginUser(user1id, user1Password)) {
getTestSubject().setApplicationPermissionEnabledForUser(
appPlusSig.getApplicationIdentifier(),
identityManagementPermission.getPermittableEndpointGroupIdentifier(),
user1id,
false);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_PERMISSION_USER_ENABLED,
new ApplicationPermissionUserEvent(
appPlusSig.getApplicationIdentifier(),
identityManagementPermission.getPermittableEndpointGroupIdentifier(),
user1id)));
}
//Note that at this point, our imaginary application still cannot do anything in the name of any user,
//because neither of the users has the permission the user enabled for the application.
}
@Test
public void manageApplicationEndpointSet() throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData appPlusSig = setApplicationSignature();
final String endpointSetIdentifier = testEnvironment.generateUniqueIdentifier("epset");
final CallEndpointSet endpointSet = new CallEndpointSet();
endpointSet.setIdentifier(endpointSetIdentifier);
endpointSet.setPermittableEndpointGroupIdentifiers(Collections.emptyList());
getTestSubject().createApplicationCallEndpointSet(appPlusSig.getApplicationIdentifier(), endpointSet);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(appPlusSig.getApplicationIdentifier(), endpointSetIdentifier)));
final List<CallEndpointSet> applicationEndpointSets = getTestSubject().getApplicationCallEndpointSets(appPlusSig.getApplicationIdentifier());
Assert.assertTrue(applicationEndpointSets.contains(endpointSet));
final CallEndpointSet storedEndpointSet = getTestSubject().getApplicationCallEndpointSet(
appPlusSig.getApplicationIdentifier(),
endpointSetIdentifier);
Assert.assertEquals(endpointSet, storedEndpointSet);
endpointSet.setPermittableEndpointGroupIdentifiers(Collections.singletonList(PermittableGroupIds.ROLE_MANAGEMENT));
getTestSubject().changeApplicationCallEndpointSet(
appPlusSig.getApplicationIdentifier(),
endpointSetIdentifier,
endpointSet);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(appPlusSig.getApplicationIdentifier(), endpointSetIdentifier)));
final CallEndpointSet storedEndpointSet2 = getTestSubject().getApplicationCallEndpointSet(
appPlusSig.getApplicationIdentifier(),
endpointSetIdentifier);
Assert.assertEquals(endpointSet, storedEndpointSet2);
final List<CallEndpointSet> applicationEndpointSets2 = getTestSubject().getApplicationCallEndpointSets(appPlusSig.getApplicationIdentifier());
Assert.assertTrue(applicationEndpointSets2.size() == 1);
getTestSubject().deleteApplicationCallEndpointSet(appPlusSig.getApplicationIdentifier(), endpointSetIdentifier);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_DELETE_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(appPlusSig.getApplicationIdentifier(), endpointSetIdentifier)));
final List<CallEndpointSet> applicationEndpointSets3 = getTestSubject().getApplicationCallEndpointSets(appPlusSig.getApplicationIdentifier());
Assert.assertTrue(applicationEndpointSets3.isEmpty());
}
}
@Test
public void applicationIssuedRefreshTokenHappyCase() throws InterruptedException {
final ApplicationSignatureTestData appPlusSig;
final Permission rolePermission = buildRolePermission();
final Permission userPermission = buildUserPermission();
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
appPlusSig = setApplicationSignature();
createApplicationPermission(appPlusSig.getApplicationIdentifier(), rolePermission);
createApplicationPermission(appPlusSig.getApplicationIdentifier(), userPermission);
getTestSubject().createApplicationCallEndpointSet(
appPlusSig.getApplicationIdentifier(),
new CallEndpointSet(CALL_ENDPOINT_SET_IDENTIFIER,
Arrays.asList(rolePermission.getPermittableEndpointGroupIdentifier(),
userPermission.getPermittableEndpointGroupIdentifier())));
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(appPlusSig.getApplicationIdentifier(),
CALL_ENDPOINT_SET_IDENTIFIER)));
}
final String userid;
final String userPassword;
try (final AutoUserContext ignored = loginAdmin()) {
final String selfManagementRoleId = createRole(rolePermission, userPermission);
userPassword = RandomStringUtils.randomAlphanumeric(5);
userid = createUserWithNonexpiredPassword(userPassword, selfManagementRoleId);
}
try (final AutoUserContext ignored = loginUser(userid, userPassword)) {
getTestSubject().setApplicationPermissionEnabledForUser(
appPlusSig.getApplicationIdentifier(),
userPermission.getPermittableEndpointGroupIdentifier(),
userid,
true);
getTestSubject().setApplicationPermissionEnabledForUser(
appPlusSig.getApplicationIdentifier(),
rolePermission.getPermittableEndpointGroupIdentifier(),
userid,
true);
}
final TokenSerializationResult tokenSerializationResult =
new TenantRefreshTokenSerializer().build(new TenantRefreshTokenSerializer.Specification()
.setUser(userid)
.setEndpointSet(CALL_ENDPOINT_SET_IDENTIFIER)
.setSecondsToLive(30)
.setKeyTimestamp(appPlusSig.getKeyTimestamp())
.setPrivateKey(appPlusSig.getKeyPair().privateKey())
.setSourceApplication(appPlusSig.getApplicationIdentifier()));
final Authentication applicationAuthentication = getTestSubject().refresh(tokenSerializationResult.getToken());
try (final AutoUserContext ignored = new AutoUserContext(userid, applicationAuthentication.getAccessToken())) {
final List<User> users = getTestSubject().getUsers();
Assert.assertFalse(users.isEmpty());
}
}
@Test
public void applicationIssuedRefreshTokenToCreatePermissionRequest() throws InterruptedException {
final ApplicationSignatureTestData appPlusSig;
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
appPlusSig = setApplicationSignature();
createApplicationPermission(appPlusSig.getApplicationIdentifier(), buildApplicationSelfPermission());
}
final String userid;
final String userid2;
final String userPassword;
try (final AutoUserContext ignored = loginAdmin()) {
final String roleId = createApplicationSelfManagementRole();
userPassword = RandomStringUtils.randomAlphanumeric(5);
userid = createUserWithNonexpiredPassword(userPassword, roleId);
userid2 = createUserWithNonexpiredPassword(userPassword, roleId);
}
try (final AutoUserContext ignored = loginUser(userid, userPassword)) {
getTestSubject().setApplicationPermissionEnabledForUser(appPlusSig.getApplicationIdentifier(), PermittableGroupIds.APPLICATION_SELF_MANAGEMENT, userid, true);
}
final TokenSerializationResult tokenSerializationResult =
new TenantRefreshTokenSerializer().build(new TenantRefreshTokenSerializer.Specification()
.setUser(userid)
.setSecondsToLive(30)
.setKeyTimestamp(appPlusSig.getKeyTimestamp())
.setPrivateKey(appPlusSig.getKeyPair().privateKey())
.setSourceApplication(appPlusSig.getApplicationIdentifier()));
final Authentication applicationAuthentication = getTestSubject().refresh(tokenSerializationResult.getToken());
try (final AutoUserContext ignored = new AutoUserContext(userid, applicationAuthentication.getAccessToken())) {
final Permission rolePermission = buildRolePermission();
createApplicationPermission(appPlusSig.getApplicationIdentifier(), rolePermission);
final List<Permission> appPermissions = getTestSubject().getApplicationPermissions(
appPlusSig.getApplicationIdentifier());
Assert.assertTrue(appPermissions.contains(rolePermission));
try {
getTestSubject().setApplicationPermissionEnabledForUser(appPlusSig.getApplicationIdentifier(), rolePermission.getPermittableEndpointGroupIdentifier(), userid2, true);
Assert.fail("This call to create enable permission for another user should've failed.");
}
catch (final NotFoundException ignored2) {
}
try {
createApplicationPermission("madeupname-v1", rolePermission);
Assert.fail("This call to create application permission should've failed.");
}
catch (final NotFoundException ignored2) {
}
}
}
}
| 2,072 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/IdentityApiDocumentation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.domain.*;
import org.apache.fineract.cn.identity.api.v1.events.*;
import org.apache.fineract.cn.lang.security.RsaKeyPairFactory;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.Collections;
import java.util.List;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
public class IdentityApiDocumentation extends AbstractIdentityTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("build/doc/generated-snippets/test-identity");
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp ( ) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
@Test
public void documentCreateRole ( ) throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String roleIdentifier = generateRoleIdentifier();
final Permission rolePermission = buildRolePermission();
final Role copyist = buildRole(roleIdentifier, rolePermission);
Gson serializer = new Gson();
this.mockMvc.perform(post("/roles")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serializer.toJson(copyist)))
.andExpect(status().isAccepted())
.andDo(document("document-create-role", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("identifier").description("Identifier"),
fieldWithPath("permissions[].permittableEndpointGroupIdentifier").description("permittable endpoints"),
fieldWithPath("permissions[].allowedOperations").type("Set<AllowedOperation>").description("Set of allowed operations")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void documentDeleteRole ( ) throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String roleIdentifier = generateRoleIdentifier();
final Permission rolePermission = buildRolePermission();
final Role scribe = buildRole(roleIdentifier, rolePermission);
getTestSubject().createRole(scribe);
super.eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, scribe.getIdentifier());
try {
this.mockMvc.perform(delete("/roles/" + scribe.getIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isAccepted())
.andDo(document("document-delete-role", preprocessRequest(prettyPrint())));
} catch (Exception e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void documentUpdateRole ( ) throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String roleIdentifier = createRoleManagementRole();
final Role role = getTestSubject().getRole(roleIdentifier);
role.getPermissions().add(buildUserPermission());
Gson gson = new Gson();
role.getPermissions().remove(0);
try {
this.mockMvc.perform(put("/roles/" + role.getIdentifier())
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(gson.toJson(role)))
.andExpect(status().isAccepted())
.andDo(document("document-update-role", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("identifier").description("Identifier"),
fieldWithPath("permissions[].permittableEndpointGroupIdentifier").description("permittable endpoints"),
fieldWithPath("permissions[].allowedOperations").type("Set<AllowedOperation>").description("Set of allowed operations")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentGetRole ( ) throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String roleIdentifier = generateRoleIdentifier();
final Permission rolePermission = buildRolePermission();
final Role scribe = buildRole(roleIdentifier, rolePermission);
getTestSubject().createRole(scribe);
super.eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, scribe.getIdentifier());
try {
this.mockMvc.perform(get("/roles/" + scribe.getIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-get-role", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("identifier").description("Identifier"),
fieldWithPath("permissions[].permittableEndpointGroupIdentifier").description("permittable endpoints"),
fieldWithPath("permissions[].allowedOperations").type("Set<AllowedOperation>").description("Set of allowed operations")
)));
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void documentFindRoles ( ) throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String roleIdentifierOne = generateRoleIdentifier();
final Permission rolePermission = buildRolePermission();
final Role scribeOne = buildRole(roleIdentifierOne, rolePermission);
getTestSubject().createRole(scribeOne);
super.eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, scribeOne.getIdentifier());
final String roleIdentifierTwo = generateRoleIdentifier();
final Permission userPermission = buildUserPermission();
final Role scribeTwo = buildRole(roleIdentifierTwo, userPermission);
List <Role> roles = Lists.newArrayList(scribeOne, scribeTwo);
roles.stream()
.forEach(scribe -> {
try {
super.eventRecorder.wait(EventConstants.OPERATION_POST_ROLE, scribe.getIdentifier());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
try {
this.mockMvc.perform(get("/roles")
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-find-roles", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].identifier").description("first role's identifier"),
fieldWithPath("[].permissions[].permittableEndpointGroupIdentifier").description("first role's roles permittable"),
fieldWithPath("[].permissions[].allowedOperations").type("Set<AllowedOperation>").description("Set of first role's allowed operations"),
fieldWithPath("[].permissions[1].permittableEndpointGroupIdentifier").description("first role's users permittable"),
fieldWithPath("[].permissions[1].allowedOperations").type("Set<AllowedOperation>").description("Set of first role's allowed operations"),
fieldWithPath("[].permissions[2].permittableEndpointGroupIdentifier").description("first role's self permittable"),
fieldWithPath("[].permissions[2].allowedOperations").type("Set<AllowedOperation>").description("Set of first role's allowed operations"),
fieldWithPath("[].permissions[3].permittableEndpointGroupIdentifier").description("first role's app_self permittable"),
fieldWithPath("[].permissions[3].allowedOperations").type("Set<AllowedOperation>").description("Set of first role's allowed operations"),
fieldWithPath("[1].identifier").description("second role's identifier"),
fieldWithPath("[1].permissions[].permittableEndpointGroupIdentifier").description("second role's roles permittable"),
fieldWithPath("[1].permissions[].allowedOperations").type("Set<AllowedOperation>").description("Set of second role's allowed operations")
)));
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void documentCreatePGroup ( ) throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String identifier = testEnvironment.generateUniqueIdentifier("group");
final PermittableEndpoint permittableEndpoint = buildPermittableEndpoint();
final PermittableGroup pgroup = buildPermittableGroup(identifier, permittableEndpoint);
Gson serializer = new Gson();
try {
this.mockMvc.perform(post("/permittablegroups")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serializer.toJson(pgroup)))
.andExpect(status().isAccepted())
.andDo(document("document-create-p-group", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("identifier").description("Permittable group identifier"),
fieldWithPath("permittables[].path").description("RequestMapping value"),
fieldWithPath("permittables[].method").type("RequestMethod").description("HTTP Request Method"),
fieldWithPath("permittables[].groupId").type("String").description("permittable identifier"),
fieldWithPath("permittables[].acceptTokenIntendedForForeignApplication").type(Boolean.TYPE).description("Accept token for foreign application")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentFindPGroup ( ) throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String identifier = testEnvironment.generateUniqueIdentifier("pgroup");
final PermittableEndpoint permittableEndpoint = buildPermittableEndpoint();
final PermittableGroup pgroup = buildPermittableGroup(identifier, permittableEndpoint);
getTestSubject().createPermittableGroup(pgroup);
{
final boolean found = eventRecorder.wait(EventConstants.OPERATION_POST_PERMITTABLE_GROUP, pgroup.getIdentifier());
Assert.assertTrue(found);
}
try {
this.mockMvc.perform(get("/permittablegroups/" + pgroup.getIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-find-p-group", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("identifier").description("Permittable group identifier"),
fieldWithPath("permittables[].path").description("RequestMapping value"),
fieldWithPath("permittables[].method").type("RequestMethod").description("HTTP Request Method"),
fieldWithPath("permittables[].groupId").type("String").description("permittable identifier"),
fieldWithPath("permittables[].acceptTokenIntendedForForeignApplication").type(Boolean.TYPE).description("Accept token for foreign application ?")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentFindAllPGroups ( ) throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String firstIdentifier = testEnvironment.generateUniqueIdentifier("pgroup");
final String secondIdentifier = testEnvironment.generateUniqueIdentifier("pgroup");
final List <String> identifierstrings = Lists.newArrayList(firstIdentifier, secondIdentifier);
identifierstrings.stream()
.forEach(string -> {
final PermittableEndpoint permittableEndpoint = buildPermittableEndpoint();
final PermittableGroup pGroup = buildPermittableGroup(string, permittableEndpoint);
getTestSubject().createPermittableGroup(pGroup);
{
final boolean found;
try {
found = eventRecorder.wait(EventConstants.OPERATION_POST_PERMITTABLE_GROUP, pGroup.getIdentifier());
Assert.assertTrue(found);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
try {
this.mockMvc.perform(get("/permittablegroups")
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-find-all-p-groups", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].identifier").description("Permittable group identifier"),
fieldWithPath("[].permittables[].path").description("RequestMapping value"),
fieldWithPath("[].permittables[].method").type("RequestMethod").description("HTTP Request Method"),
fieldWithPath("[].permittables[].groupId").type("String").description("permittable identifier"),
fieldWithPath("[].permittables[].acceptTokenIntendedForForeignApplication").type(Boolean.TYPE).description("Accept token for foreign application ?"),
fieldWithPath("[1].identifier").description("Permittable group identifier"),
fieldWithPath("[1].permittables[].path").description("RequestMapping value"),
fieldWithPath("[1].permittables[].method").type("RequestMethod").description("HTTP Request Method"),
fieldWithPath("[1].permittables[].groupId").type("String").description("permittable identifier"),
fieldWithPath("[1].permittables[].acceptTokenIntendedForForeignApplication").type(Boolean.TYPE).description("Accept token for foreign application ?")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentCreateUser ( ) throws InterruptedException {
final String username = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
final Authentication userAuthentication =
getTestSubject().login(username, TestEnvironment.encodePassword(AHMES_PASSWORD));
try (final AutoUserContext ignored = new AutoUserContext(username, userAuthentication.getAccessToken())) {
UserWithPassword newUser = new UserWithPassword("Ahmes_friend_zero", "scribe_zero",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD));
Gson serializer = new Gson();
try {
this.mockMvc.perform(post("/users")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serializer.toJson(newUser)))
.andExpect(status().isAccepted())
.andDo(document("document-create-user", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("identifier").description("user's identifier"),
fieldWithPath("role").description("user's role"),
fieldWithPath("password").description("user's password")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentFindUser ( ) throws InterruptedException {
final String username = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
final Authentication userAuthentication =
getTestSubject().login(username, TestEnvironment.encodePassword(AHMES_PASSWORD));
try (final AutoUserContext ignored = new AutoUserContext(username, userAuthentication.getAccessToken())) {
UserWithPassword newUser = new UserWithPassword("Ahmes_friend_three", "scribe_three",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD));
getTestSubject().createUser(newUser);
final boolean found = eventRecorder.wait(EventConstants.OPERATION_POST_USER, newUser.getIdentifier());
Assert.assertTrue(found);
try {
this.mockMvc.perform(get("/users/" + newUser.getIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-find-user", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("identifier").description("user's identifier"),
fieldWithPath("role").description("user's role")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentFindAllUsers ( ) throws InterruptedException {
final String username = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
final Authentication userAuthentication =
getTestSubject().login(username, TestEnvironment.encodePassword(AHMES_PASSWORD));
try (final AutoUserContext ignored = new AutoUserContext(username, userAuthentication.getAccessToken())) {
UserWithPassword ahmesFriend = new UserWithPassword("Ahmes_friend", "scribe",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD));
getTestSubject().createUser(ahmesFriend);
final boolean found = eventRecorder.wait(EventConstants.OPERATION_POST_USER, ahmesFriend.getIdentifier());
Assert.assertTrue(found);
UserWithPassword ahmesOtherFriend = new UserWithPassword("Ahmes_Other_friend", "cobbler",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD + "Other"));
getTestSubject().createUser(ahmesOtherFriend);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_USER, ahmesOtherFriend.getIdentifier()));
try {
this.mockMvc.perform(get("/users")
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-find-all-users", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].identifier").description("first user's identifier"),
fieldWithPath("[].role").description("first user's role"),
fieldWithPath("[1].identifier").description("second user's identifier"),
fieldWithPath("[1].role").description("second user's role"),
fieldWithPath("[2].identifier").description("third user's identifier"),
fieldWithPath("[2].role").description("third user's role"),
fieldWithPath("[3].identifier").description("fourth user's identifier"),
fieldWithPath("[3].role").description("fourth user's role")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentChangeUserRole ( ) throws InterruptedException {
final String userName = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
final Authentication userAuthentication =
getTestSubject().login(userName, TestEnvironment.encodePassword(AHMES_PASSWORD));
try (final AutoUserContext ignored = new AutoUserContext(userName, userAuthentication.getAccessToken())) {
UserWithPassword user = new UserWithPassword("Ahmes_friend_One", "scribe_one",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD));
getTestSubject().createUser(user);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_USER, user.getIdentifier()));
RoleIdentifier newRole = new RoleIdentifier("cobbler");
Gson serializer = new Gson();
try {
this.mockMvc.perform(put("/users/" + user.getIdentifier() + "/roleIdentifier")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serializer.toJson(newRole)))
.andExpect(status().isAccepted())
.andDo(document("document-change-user-role", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("identifier").description(" updated role identifier")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentGetUserPermissions ( ) throws InterruptedException {
final String userName = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
final Authentication userAuthentication =
getTestSubject().login(userName, TestEnvironment.encodePassword(AHMES_PASSWORD));
try (final AutoUserContext ignored = new AutoUserContext(userName, userAuthentication.getAccessToken())) {
UserWithPassword user = new UserWithPassword("Ahmes_friend_Two", "scribe_two",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD));
getTestSubject().createUser(user);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_USER, user.getIdentifier()));
try {
this.mockMvc.perform(get("/users/" + user.getIdentifier() + "/permissions")
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-get-user-permissions", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].permittableEndpointGroupIdentifier").description(" permittable endpoint group identifier"),
fieldWithPath("[].allowedOperations").type("Set<AllowedOperation>").description("Set of allowed operations")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentChangeUserPassword ( ) throws InterruptedException {
final String userName = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
final Authentication userAuthentication =
getTestSubject().login(userName, TestEnvironment.encodePassword(AHMES_PASSWORD));
try (final AutoUserContext ignored = new AutoUserContext(userName, userAuthentication.getAccessToken())) {
UserWithPassword user = new UserWithPassword("Daddy", "bearer",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD));
getTestSubject().createUser(user);
Assert.assertTrue(eventRecorder.wait(EventConstants.OPERATION_POST_USER, user.getIdentifier()));
Password passw = new Password(TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD + "Daddy"));
user.setPassword(passw.getPassword());
Gson serializer = new Gson();
try {
this.mockMvc.perform(put("/users/" + user.getIdentifier() + "/password")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serializer.toJson(passw)))
.andExpect(status().isAccepted())
.andDo(document("document-change-user-password", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("password").description("updated password")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentGetApplications ( ) throws InterruptedException {
try (final AutoUserContext ignored = tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData firstApplication = setApplicationSignature();
final ApplicationSignatureTestData secondApplication = setApplicationSignature();
try {
this.mockMvc.perform(get("/applications")
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-get-applications", preprocessResponse(prettyPrint())));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentDeleteApplication ( ) throws InterruptedException {
try (final AutoUserContext ignored = tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData firstApplication = setApplicationSignature();
try {
this.mockMvc.perform(delete("/applications/" + firstApplication.getApplicationIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isAccepted())
.andDo(document("document-delete-application", preprocessResponse(prettyPrint())));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentSetApplicationSignature ( ) throws InterruptedException {
final String appIdentifier = "testApp" + RandomStringUtils.randomNumeric(3) + "-v1";
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final String appTimeStamp = keyPair.getTimestamp();
final Signature signature = new Signature(keyPair.getPublicKeyMod(), keyPair.getPublicKeyExp());
Gson serializer = new Gson();
try {
this.mockMvc.perform(put("/applications/" + appIdentifier + "/signatures/" + appTimeStamp)
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serializer.toJson(signature)))
.andExpect(status().isAccepted())
.andDo(document("document-set-application-signature", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("publicKeyMod").type("BigInteger").description(" public key mod"),
fieldWithPath("publicKeyExp").type("BigInteger").description(" public key exp")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void documentGetApplicationSignature ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final String appIdentifier = "testApp" + RandomStringUtils.randomNumeric(3) + "-v1";
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final String appTimeStamp = keyPair.getTimestamp();
final Signature signature = new Signature(keyPair.getPublicKeyMod(), keyPair.getPublicKeyExp());
getTestSubject().setApplicationSignature(appIdentifier, appTimeStamp, signature);
this.eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE, new ApplicationSignatureEvent(appIdentifier, keyPair.getTimestamp()));
try {
this.mockMvc.perform(get("/applications/" + appIdentifier + "/signatures/" + appTimeStamp)
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.ALL_VALUE))
.andExpect(status().isOk())
.andDo(document("document-get-application-signature", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("publicKeyMod").type("BigInteger").description("public key mod"),
fieldWithPath("publicKeyExp").type("BigInteger").description("public key exp")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentCreateApplicationPermission ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final String appIdentifier = "testApp" + RandomStringUtils.randomNumeric(3) + "-v1";
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final String appTimeStamp = keyPair.getTimestamp();
final Signature signature = new Signature(keyPair.getPublicKeyMod(), keyPair.getPublicKeyExp());
getTestSubject().setApplicationSignature(appIdentifier, appTimeStamp, signature);
this.eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE, new ApplicationSignatureEvent(appIdentifier, keyPair.getTimestamp()));
final Permission newPermission = new Permission(PermittableGroupIds.IDENTITY_MANAGEMENT, Sets.newHashSet(AllowedOperation.READ));
Gson serializer = new Gson();
try {
this.mockMvc.perform(post("/applications/" + appIdentifier + "/permissions")
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serializer.toJson(newPermission)))
.andExpect(status().isAccepted())
.andDo(document("document-create-application-permission", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("permittableEndpointGroupIdentifier").description("permittable group endpoint identifier"),
fieldWithPath("allowedOperations").type("Set<AllowedOperation>").description("Set of Allowed Operations")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentGetApplicationPermission ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final String appIdentifier = "testApp" + RandomStringUtils.randomNumeric(3) + "-v1";
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final String appTimeStamp = keyPair.getTimestamp();
final Signature signature = new Signature(keyPair.getPublicKeyMod(), keyPair.getPublicKeyExp());
getTestSubject().setApplicationSignature(appIdentifier, appTimeStamp, signature);
this.eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE, new ApplicationSignatureEvent(appIdentifier, keyPair.getTimestamp()));
final Permission newPermission = new Permission(PermittableGroupIds.IDENTITY_MANAGEMENT, Sets.newHashSet(AllowedOperation.CHANGE));
createApplicationPermission(appIdentifier, newPermission);
Gson serializer = new Gson();
try {
this.mockMvc.perform(get("/applications/" + appIdentifier + "/permissions/" + newPermission.getPermittableEndpointGroupIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-get-application-permission", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("permittableEndpointGroupIdentifier").description("permittable group endpoint identifier"),
fieldWithPath("allowedOperations").type("Set<AllowedOperation>").description("Set of Allowed Operations")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentGetApplicationPermissions ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final String appIdentifier = "testApp" + RandomStringUtils.randomNumeric(3) + "-v1";
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final String appTimeStamp = keyPair.getTimestamp();
final Signature signature = new Signature(keyPair.getPublicKeyMod(), keyPair.getPublicKeyExp());
getTestSubject().setApplicationSignature(appIdentifier, appTimeStamp, signature);
this.eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE, new ApplicationSignatureEvent(appIdentifier, keyPair.getTimestamp()));
final Permission firstPermission = new Permission(PermittableGroupIds.IDENTITY_MANAGEMENT, Sets.newHashSet(AllowedOperation.CHANGE));
createApplicationPermission(appIdentifier, firstPermission);
final Permission secondPermission = new Permission(PermittableGroupIds.ROLE_MANAGEMENT, Sets.newHashSet(AllowedOperation.DELETE));
createApplicationPermission(appIdentifier, secondPermission);
try {
this.mockMvc.perform(get("/applications/" + appIdentifier + "/permissions")
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-get-application-permissions", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].permittableEndpointGroupIdentifier").description("first permittable group endpoint identifier"),
fieldWithPath("[].allowedOperations").type("Set<AllowedOperation>").description("Set of Allowed Operations"),
fieldWithPath("[1].permittableEndpointGroupIdentifier").description("second permittable group endpoint identifier"),
fieldWithPath("[1].allowedOperations").type("Set<AllowedOperation>").description("Set of Allowed Operations")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentDeleteApplicationPermission ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final String appIdentifier = "testApp" + RandomStringUtils.randomNumeric(3) + "-v1";
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final String appTimeStamp = keyPair.getTimestamp();
final Signature signature = new Signature(keyPair.getPublicKeyMod(), keyPair.getPublicKeyExp());
getTestSubject().setApplicationSignature(appIdentifier, appTimeStamp, signature);
this.eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE, new ApplicationSignatureEvent(appIdentifier, keyPair.getTimestamp()));
final Permission newPermission = new Permission(PermittableGroupIds.IDENTITY_MANAGEMENT, Sets.newHashSet(AllowedOperation.CHANGE));
createApplicationPermission(appIdentifier, newPermission);
try {
this.mockMvc.perform(delete("/applications/" + appIdentifier + "/permissions/" + newPermission.getPermittableEndpointGroupIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isAccepted())
.andDo(document("document-delete-application-permission", preprocessResponse(prettyPrint())));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentCreateApplicationCallEndpointSet ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData application = setApplicationSignature();
final String endpointSetIdentifier = testEnvironment.generateUniqueIdentifier("end_pt_set");
final CallEndpointSet endpointSet = new CallEndpointSet();
endpointSet.setIdentifier(endpointSetIdentifier);
endpointSet.setPermittableEndpointGroupIdentifiers(Collections.emptyList());
Gson serial = new Gson();
try {
this.mockMvc.perform(post("/applications/" + application.getApplicationIdentifier() + "/callendpointset")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serial.toJson(endpointSet)))
.andExpect(status().isAccepted())
.andDo(document("document-create-application-call-endpoint-set", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("identifier").description("call endpoint set identifier"),
fieldWithPath("permittableEndpointGroupIdentifiers").type("List<String>").description("permittable group endpoint identifier")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentChangeApplicationCallEndpointSet ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData application = setApplicationSignature();
final String endpointSetIdentifier = testEnvironment.generateUniqueIdentifier("end_pt_set");
PermittableEndpoint pEndPointOne = buildPermittableEndpoint();
PermittableEndpoint pEndPointTwo = buildPermittableEndpoint();
PermittableGroup pgroup1 = buildPermittableGroup("ideeOne", pEndPointOne);
PermittableGroup pgroup2 = buildPermittableGroup("ideeTwo", pEndPointTwo);
List enlist = Lists.newArrayList(pgroup1.getIdentifier(), pgroup2.getIdentifier());
final CallEndpointSet endpointSet = new CallEndpointSet();
endpointSet.setIdentifier(endpointSetIdentifier);
endpointSet.setPermittableEndpointGroupIdentifiers(enlist);
getTestSubject().createApplicationCallEndpointSet(application.getApplicationIdentifier(), endpointSet);
super.eventRecorder.wait(EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(application.getApplicationIdentifier(), endpointSetIdentifier));
Gson serial = new Gson();
try {
this.mockMvc.perform(put("/applications/" + application.getApplicationIdentifier() + "/callendpointset/" + endpointSet.getIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(serial.toJson(endpointSet)))
.andExpect(status().isAccepted())
.andDo(document("document-change-application-call-endpoint-set", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("identifier").description("call endpoint set identifier"),
fieldWithPath("permittableEndpointGroupIdentifiers").type("List<String>").description("permittable group endpoint identifier")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentGetApplicationCallEndpointSets ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData application = setApplicationSignature();
final String endpointSetIdentifierOne = testEnvironment.generateUniqueIdentifier("end_pt_set");
final String endpointSetIdentifierTwo = testEnvironment.generateUniqueIdentifier("endptset");
PermittableEndpoint pEndPointZero = buildPermittableEndpoint();
PermittableEndpoint pEndPointOne = buildPermittableEndpoint();
PermittableEndpoint pEndPointTwo = buildPermittableEndpoint();
PermittableGroup pgroup = buildPermittableGroup("ideeZero", pEndPointZero);
PermittableGroup pgroup1 = buildPermittableGroup("ideeOne", pEndPointOne);
PermittableGroup pgroup2 = buildPermittableGroup("ideeTwo", pEndPointTwo);
List enlist1 = Lists.newArrayList(pgroup1.getIdentifier(), pgroup2.getIdentifier());
final CallEndpointSet endpointSetOne = new CallEndpointSet();
endpointSetOne.setIdentifier(endpointSetIdentifierOne);
endpointSetOne.setPermittableEndpointGroupIdentifiers(enlist1);
getTestSubject().createApplicationCallEndpointSet(application.getApplicationIdentifier(), endpointSetOne);
super.eventRecorder.wait(EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(application.getApplicationIdentifier(), endpointSetIdentifierOne));
List enlist2 = Lists.newArrayList(pgroup.getIdentifier());
final CallEndpointSet endpointSetTwo = new CallEndpointSet();
endpointSetTwo.setIdentifier(endpointSetIdentifierTwo);
endpointSetTwo.setPermittableEndpointGroupIdentifiers(enlist2);
getTestSubject().createApplicationCallEndpointSet(application.getApplicationIdentifier(), endpointSetTwo);
super.eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(application.getApplicationIdentifier(), endpointSetIdentifierTwo));
Assert.assertTrue(getTestSubject().getApplicationCallEndpointSets(application.getApplicationIdentifier()).size() == 2);
try {
this.mockMvc.perform(get("/applications/" + application.getApplicationIdentifier() + "/callendpointset")
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-get-application-call-endpoint-sets", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].identifier").description("first call endpoint call set identifier"),
fieldWithPath("[].permittableEndpointGroupIdentifiers").type("List<String>").description("first permittable group endpoint identifier"),
fieldWithPath("[2].identifier").description("second call endpoint call set identifier"),
fieldWithPath("[2].permittableEndpointGroupIdentifiers").type("List<String>").description("second permittable group endpoint identifier")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentGetApplicationCallEndpointSet ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData application = setApplicationSignature();
final String endpointSetIdentifierOne = testEnvironment.generateUniqueIdentifier("end_pt_set");
final String endpointSetIdentifierTwo = testEnvironment.generateUniqueIdentifier("endptset");
PermittableEndpoint pEndPointZero = buildPermittableEndpoint();
PermittableEndpoint pEndPointOne = buildPermittableEndpoint();
PermittableEndpoint pEndPointTwo = buildPermittableEndpoint();
PermittableGroup pgroup = buildPermittableGroup("ideeZero", pEndPointZero);
PermittableGroup pgroup1 = buildPermittableGroup("ideeOne", pEndPointOne);
PermittableGroup pgroup2 = buildPermittableGroup("ideeTwo", pEndPointTwo);
List enlist1 = Lists.newArrayList(pgroup1.getIdentifier(), pgroup2.getIdentifier());
final CallEndpointSet endpointSetOne = new CallEndpointSet();
endpointSetOne.setIdentifier(endpointSetIdentifierOne);
endpointSetOne.setPermittableEndpointGroupIdentifiers(enlist1);
getTestSubject().createApplicationCallEndpointSet(application.getApplicationIdentifier(), endpointSetOne);
super.eventRecorder.wait(EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(application.getApplicationIdentifier(), endpointSetIdentifierOne));
List enlist2 = Lists.newArrayList(pgroup.getIdentifier());
final CallEndpointSet endpointSetTwo = new CallEndpointSet();
endpointSetTwo.setIdentifier(endpointSetIdentifierTwo);
endpointSetTwo.setPermittableEndpointGroupIdentifiers(enlist2);
getTestSubject().createApplicationCallEndpointSet(application.getApplicationIdentifier(), endpointSetTwo);
super.eventRecorder.wait(EventConstants.OPERATION_PUT_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(application.getApplicationIdentifier(), endpointSetIdentifierTwo));
Assert.assertTrue(getTestSubject().getApplicationCallEndpointSets(application.getApplicationIdentifier()).size() == 2);
try {
this.mockMvc.perform(get("/applications/" + application.getApplicationIdentifier() + "/callendpointset/" + endpointSetOne.getIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-get-application-call-endpoint-set", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("identifier").description("call endpoint call set identifier"),
fieldWithPath("permittableEndpointGroupIdentifiers").type("List<String>").description("permittable group endpoint identifier")
)
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void documentDeleteApplicationCallEndpointSet ( ) throws InterruptedException {
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
final ApplicationSignatureTestData application = setApplicationSignature();
final String endpointSetIdentifier = testEnvironment.generateUniqueIdentifier("end_pt_set");
PermittableEndpoint pEndPointOne = buildPermittableEndpoint();
PermittableEndpoint pEndPointTwo = buildPermittableEndpoint();
PermittableGroup pgroup1 = buildPermittableGroup("yepue", pEndPointOne);
PermittableGroup pgroup2 = buildPermittableGroup("yetah", pEndPointTwo);
List enlist = Lists.newArrayList(pgroup1.getIdentifier(), pgroup2.getIdentifier());
final CallEndpointSet endpointSet = new CallEndpointSet();
endpointSet.setIdentifier(endpointSetIdentifier);
endpointSet.setPermittableEndpointGroupIdentifiers(enlist);
getTestSubject().createApplicationCallEndpointSet(application.getApplicationIdentifier(), endpointSet);
super.eventRecorder.wait(EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET,
new ApplicationCallEndpointSetEvent(application.getApplicationIdentifier(), endpointSetIdentifier));
try {
this.mockMvc.perform(delete("/applications/" + application.getApplicationIdentifier() + "/callendpointset/" + endpointSet.getIdentifier())
.accept(MediaType.ALL_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isAccepted())
.andDo(document("document-delete-application-call-endpoint-set", preprocessRequest(prettyPrint())));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private PermittableGroup buildPermittableGroup (final String identifier, final PermittableEndpoint permittableEndpoint) {
final PermittableGroup ret = new PermittableGroup();
ret.setIdentifier(identifier);
ret.setPermittables(Collections.singletonList(permittableEndpoint));
return ret;
}
private PermittableEndpoint buildPermittableEndpoint ( ) {
final PermittableEndpoint ret = new PermittableEndpoint();
ret.setPath("/exx/eyy/eze");
ret.setMethod("POST");
ret.setGroupId("id");
return ret;
}
}
| 2,073 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestPasswords.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import org.apache.fineract.cn.identity.api.v1.domain.Password;
import org.apache.fineract.cn.identity.api.v1.domain.UserWithPassword;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.apache.fineract.cn.test.domain.TimeStampChecker;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.junit.Assert;
import org.junit.Test;
import java.time.Duration;
/**
* @author Myrle Krantz
*/
public class TestPasswords extends AbstractIdentityTest {
@Test
public void testAdminChangeUserPassword() throws InterruptedException {
final String username = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
try (final AutoUserContext ignore = loginAdmin()) {
final String newPassword = TestEnvironment.encodePassword(
AHMES_PASSWORD + "make_it_a_little_longer");
{
//Important here is that we are changing the password *as*the*admin*.
getTestSubject().changeUserPassword(username, new Password(newPassword));
boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_USER_PASSWORD, username);
Assert.assertTrue(found);
}
final Authentication newPasswordAuthentication = getTestSubject().login(username, newPassword);
try (final AutoUserContext ignore2 = new AutoUserContext(username, newPasswordAuthentication.getAccessToken()))
{
getTestSubject().createUser(new UserWithPassword("Ahmes_friend", "scribe",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD)));
Assert.fail("createUser should've thrown an exception because the password is admin reset.");
}
catch (final NotFoundException ex)
{
//Should throw because under the new password, the user has only the right to change the password.
}
try (final AutoUserContext ignore3 = new AutoUserContext(username, newPasswordAuthentication.getAccessToken()))
{
getTestSubject().changeUserPassword(username, new Password(newPassword));
boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_USER_PASSWORD, username);
Assert.assertTrue(found);
}
final Authentication newPasswordAuthenticationAsFullyPermissionedUser = getTestSubject().login(username, newPassword);
try (final AutoUserContext ignore4 = new AutoUserContext(username, newPasswordAuthenticationAsFullyPermissionedUser.getAccessToken()))
{
//Now it should be possible to create a user since the user changed the password herself.
getTestSubject().createUser(new UserWithPassword("Ahmes_friend", "scribe",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD)));
}
}
}
@Test
public void testAdminChangeAdminPassword() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final String newPassword = TestEnvironment.encodePassword(
ADMIN_PASSWORD + "make_it_a_little_longer");
{
getTestSubject().changeUserPassword(ADMIN_IDENTIFIER, new Password(newPassword));
final boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_USER_PASSWORD, ADMIN_IDENTIFIER);
Assert.assertTrue(found);
}
try {
final String oldPassword = TestEnvironment.encodePassword(ADMIN_PASSWORD);
getTestSubject().login(ADMIN_IDENTIFIER, oldPassword);
Assert.fail("Login with the old password should not succeed.");
} catch (final NotFoundException ignored) {
}
getTestSubject().login(ADMIN_IDENTIFIER, newPassword);
{
//Change the password back so the tests after this don't fail.
getTestSubject().changeUserPassword(ADMIN_IDENTIFIER, new Password(TestEnvironment.encodePassword(ADMIN_PASSWORD)));
boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_USER_PASSWORD, ADMIN_IDENTIFIER);
Assert.assertTrue(found);
}
}
}
@Test
public void testUserChangeOwnPasswordButNotAdminPassword() throws InterruptedException {
final String username = createUserWithNonexpiredPassword(AHMES_PASSWORD, "scribe");
try (final AutoUserContext ignored = loginUser(username, AHMES_PASSWORD))
{
final String newPassword = "new password";
{
getTestSubject().changeUserPassword(username, new Password(TestEnvironment.encodePassword(newPassword)));
boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_USER_PASSWORD, username);
Assert.assertTrue(found);
}
final TimeStampChecker passwordExpirationChecker = TimeStampChecker.inTheFutureWithWiggleRoom(Duration.ofDays(93), Duration.ofHours(24));
final Authentication userAuthenticationAfterPasswordChange = getTestSubject().login(username, TestEnvironment.encodePassword(newPassword));
final String passwordExpiration = userAuthenticationAfterPasswordChange.getPasswordExpiration();
passwordExpirationChecker.assertCorrect(passwordExpiration);
//noinspection EmptyCatchBlock
try {
getTestSubject().changeUserPassword(ADMIN_IDENTIFIER, new Password(TestEnvironment.encodePassword(newPassword)));
Assert.fail("trying to change the admins password should fail.");
}
catch (final NotFoundException ex) {
boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_USER_PASSWORD, ADMIN_IDENTIFIER);
Assert.assertFalse(found);
}
try {
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(newPassword));
Assert.fail("logging into admin with the new password should likewise fail.");
}
catch (final NotFoundException ex) {
//Not found is expected.
}
//noinspection EmptyTryBlock
try (final AutoUserContext ignored2 = loginAdmin()) { //logging into admin with the old password should *not* fail.
}
}
}
@Test(expected = IllegalArgumentException.class)
public void loginWithUnencodedPasswordShouldThrowIllegalArgumentException() throws InterruptedException {
try (final AutoUserContext ignored = loginAdmin()) {
final String selfManagementRoleId = createSelfManagementRole();
final String userPassword = RandomStringUtils.randomAlphanumeric(5);
final String userid = createUserWithNonexpiredPassword(userPassword, selfManagementRoleId);
getTestSubject().login(userid, userPassword);
}
}
@Test
public void activatedAntonyPasswordDoesntExpire() throws InterruptedException {
try (final AutoUserContext ignored = loginAdmin()) {
final Authentication adminAuthentication =
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
Assert.assertEquals(null, adminAuthentication.getPasswordExpiration());
}
}
@Test
public void onlyAntonyCanSetAntonyPassword() throws InterruptedException {
try (final AutoUserContext ignored = loginAdmin()) {
final String roleIdentifier = createRole(buildUserPermission(), buildSelfPermission(), buildRolePermission());
final String username = createUserWithNonexpiredPassword(AHMES_PASSWORD, roleIdentifier);
try (final AutoUserContext ignored2 = loginUser(username, AHMES_PASSWORD)) {
getTestSubject().changeUserPassword(ADMIN_IDENTIFIER, new Password(TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD)));
Assert.fail("Should not be able to change antony's password from any account other than antony's.");
}
catch (final IllegalArgumentException expected) {
//noinspection EmptyCatchBlock
}
}
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
}
}
| 2,074 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestRefreshToken.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.fineract.cn.identity.api.v1.client.IdentityManager;
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import org.apache.fineract.cn.identity.api.v1.domain.Password;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.User;
import org.apache.fineract.cn.anubis.api.v1.TokenConstants;
import org.apache.fineract.cn.anubis.token.TenantRefreshTokenSerializer;
import org.apache.fineract.cn.anubis.token.TokenSerializationResult;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.FeignTargetWithCookieJar;
import org.apache.fineract.cn.api.util.InvalidTokenException;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.apache.fineract.cn.test.domain.TimeStampChecker;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.apache.fineract.cn.test.fixture.TenantDataStoreTestContext;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author Myrle Krantz
*/
public class TestRefreshToken extends AbstractIdentityTest {
private static final int ACCESS_TOKEN_TIME_TO_LIVE = 5;
private static final int REFRESH_TOKEN_TIME_TO_LIVE = 10;
@BeforeClass
public static void setup() throws Exception {
//Shorten access time to 5 seconds for test purposes.;
System.getProperties().setProperty("identity.token.access.ttl", String.valueOf(ACCESS_TOKEN_TIME_TO_LIVE));
System.getProperties().setProperty("identity.token.refresh.ttl", String.valueOf(REFRESH_TOKEN_TIME_TO_LIVE));
}
@Test(expected = InvalidTokenException.class)
public void adminLoginAccessTokenShouldTimeOut() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
Thread.sleep(TimeUnit.SECONDS.toMillis(ACCESS_TOKEN_TIME_TO_LIVE + 1));
getTestSubject().getUser(ADMIN_IDENTIFIER);
}
}
@Test(expected = InvalidTokenException.class)
public void adminLoginRefreshTokenShouldTimeOut() throws InterruptedException {
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
Thread.sleep(TimeUnit.SECONDS.toMillis(REFRESH_TOKEN_TIME_TO_LIVE + 1));
getTestSubject().refresh();
}
@Test
public void afterAccessTokenExpiresRefreshTokenShouldAcquireNewAccessToken() throws InterruptedException {
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
Thread.sleep(TimeUnit.SECONDS.toMillis(ACCESS_TOKEN_TIME_TO_LIVE + 1));
final Authentication refreshAccessTokenAuthentication =
getTestSubject().refresh();
try (final AutoUserContext ignored = new AutoUserContext(ADMIN_IDENTIFIER, refreshAccessTokenAuthentication.getAccessToken())) {
getTestSubject().changeUserPassword(ADMIN_IDENTIFIER, new Password(TestEnvironment.encodePassword(ADMIN_PASSWORD)));
}
}
@Test(expected = InvalidTokenException.class)
public void refreshTokenShouldGrantAccessOnlyToOneTenant()
{
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
try (final TenantDataStoreTestContext ignored = TenantDataStoreTestContext.forRandomTenantName(cassandraInitializer)) {
try (final AutoUserContext ignored2
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
getTestSubject().initialize(TestEnvironment.encodePassword(ADMIN_PASSWORD));
}
getTestSubject().refresh();
}
}
@Test
public void expirationDatesShouldBeCorrectIsoDateTimes() throws InterruptedException {
final Authentication authentication =
getTestSubject().login(ADMIN_IDENTIFIER, TestEnvironment.encodePassword(ADMIN_PASSWORD));
final TimeStampChecker preRefreshAccessTokenTimeStampChecker = TimeStampChecker.inTheFuture(Duration.ofSeconds(ACCESS_TOKEN_TIME_TO_LIVE));
final TimeStampChecker refreshTokenTimeStampChecker = TimeStampChecker.inTheFuture(Duration.ofSeconds(REFRESH_TOKEN_TIME_TO_LIVE));
Assert.assertNotNull(authentication);
preRefreshAccessTokenTimeStampChecker.assertCorrect(authentication.getAccessTokenExpiration());
refreshTokenTimeStampChecker.assertCorrect(authentication.getRefreshTokenExpiration());
TimeUnit.SECONDS.sleep(3);
final TimeStampChecker postRefreshAccessTokenTimeStampChecker = TimeStampChecker.inTheFuture(Duration.ofSeconds(ACCESS_TOKEN_TIME_TO_LIVE));
final Authentication refreshedAuthentication = getTestSubject().refresh();
postRefreshAccessTokenTimeStampChecker.assertCorrect(refreshedAuthentication.getAccessTokenExpiration());
refreshTokenTimeStampChecker.assertCorrect(refreshedAuthentication.getRefreshTokenExpiration());
}
@Test
public void bothRefreshMethodsShouldProduceSamePermissions() throws InterruptedException {
final Permission userPermission = buildUserPermission();
final ApplicationSignatureTestData appPlusSig;
try (final AutoUserContext ignored
= tenantApplicationSecurityEnvironment.createAutoSeshatContext()) {
appPlusSig = setApplicationSignature();
createApplicationPermission(appPlusSig.getApplicationIdentifier(), userPermission);
}
try (final AutoUserContext ignored = loginAdmin()) {
getTestSubject().setApplicationPermissionEnabledForUser(
appPlusSig.getApplicationIdentifier(),
userPermission.getPermittableEndpointGroupIdentifier(),
ADMIN_IDENTIFIER,
true);
}
final TenantRefreshTokenSerializer refreshTokenSerializer = new TenantRefreshTokenSerializer();
final TokenSerializationResult tokenSerializationResult =
refreshTokenSerializer.build(new TenantRefreshTokenSerializer.Specification()
.setUser(ADMIN_IDENTIFIER)
.setSecondsToLive(30)
.setKeyTimestamp(appPlusSig.getKeyTimestamp())
.setPrivateKey(appPlusSig.getKeyPair().privateKey())
.setSourceApplication(appPlusSig.getApplicationIdentifier()));
final FeignTargetWithCookieJar<IdentityManager> identityManagerWithCookieJar
= apiFactory.createWithCookieJar(IdentityManager.class, testEnvironment.serverURI());
identityManagerWithCookieJar.putCookie("/token", TokenConstants.REFRESH_TOKEN_COOKIE_NAME, tokenSerializationResult.getToken());
final Authentication applicationAuthenticationViaCookie = identityManagerWithCookieJar.getFeignTarget().refresh();
final Authentication applicationAuthenticationViaParam = getTestSubject().refresh(tokenSerializationResult.getToken());
try (final AutoUserContext ignored = new AutoUserContext(ADMIN_IDENTIFIER, applicationAuthenticationViaCookie.getAccessToken()))
{
checkAccessToUsersAndOnlyUsers();
}
try (final AutoUserContext ignored = new AutoUserContext(ADMIN_IDENTIFIER, applicationAuthenticationViaParam.getAccessToken()))
{
checkAccessToUsersAndOnlyUsers();
}
}
private void checkAccessToUsersAndOnlyUsers() {
final List<User> users = getTestSubject().getUsers();
Assert.assertFalse(users.isEmpty());
try {
getTestSubject().getRoles();
Assert.fail("Shouldn't be able to get roles with token for application for which roles are not permitted.");
}
catch (final NotFoundException ignored2) { }
}
}
| 2,075 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestUsers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static org.apache.fineract.cn.identity.internal.util.IdentityConstants.SU_NAME;
import static org.apache.fineract.cn.identity.internal.util.IdentityConstants.SU_ROLE;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
import org.apache.fineract.cn.identity.api.v1.domain.RoleIdentifier;
import org.apache.fineract.cn.identity.api.v1.domain.User;
import org.apache.fineract.cn.identity.api.v1.domain.UserWithPassword;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Myrle Krantz
*/
public class TestUsers extends AbstractIdentityTest {
@Test
public void testAddLogin() throws InterruptedException {
final String username = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
try (final AutoUserContext ignore = loginAdmin()) {
final User user = getTestSubject().getUser(username);
Assert.assertNotNull(user);
Assert.assertEquals("Correct user identifier?", username, user.getIdentifier());
Assert.assertEquals("Correct role?", ADMIN_ROLE, user.getRole());
}
final Authentication userAuthentication =
getTestSubject().login(username, TestEnvironment.encodePassword(AHMES_PASSWORD));
Assert.assertNotNull(userAuthentication);
try (final AutoUserContext ignored = new AutoUserContext(username, userAuthentication.getAccessToken())) {
getTestSubject().createUser(new UserWithPassword("Ahmes_friend", "scribe",
TestEnvironment.encodePassword(AHMES_FRIENDS_PASSWORD)));
final boolean found = eventRecorder.wait(EventConstants.OPERATION_POST_USER, "Ahmes_friend");
Assert.assertTrue(found);
}
try (final AutoUserContext ignore = loginAdmin()) {
final List<User> users = getTestSubject().getUsers();
Assert.assertTrue(Helpers.instancePresent(users, User::getIdentifier, username));
Assert.assertTrue(Helpers.instancePresent(users, User::getIdentifier, "Ahmes_friend"));
}
}
@Test
public void testChangeUserRole() throws InterruptedException {
final String userIdentifier = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
final Authentication ahmesAuthentication =
getTestSubject().login(userIdentifier, TestEnvironment.encodePassword(AHMES_PASSWORD));
try (final AutoUserContext ignored = new AutoUserContext(userIdentifier, ahmesAuthentication.getAccessToken())) {
List<User> users = getTestSubject().getUsers();
Assert.assertEquals(2, users.size());
getTestSubject().changeUserRole(userIdentifier, new RoleIdentifier("scribe"));
final boolean found = eventRecorder.wait(EventConstants.OPERATION_PUT_USER_ROLEIDENTIFIER, userIdentifier);
Assert.assertTrue(found);
final User ahmes = getTestSubject().getUser(userIdentifier);
Assert.assertEquals("scribe", ahmes.getRole());
final Set<Permission> userPermittableGroups = getTestSubject().getUserPermissions(userIdentifier);
Assert.assertTrue(userPermittableGroups.contains(new Permission(PermittableGroupIds.SELF_MANAGEMENT, AllowedOperation.ALL)));
users = getTestSubject().getUsers();
Assert.assertEquals(2, users.size());
}
}
@Test
public void testChangeAntonyRoleFails() throws InterruptedException {
final String userIdentifier = createUserWithNonexpiredPassword(AHMES_PASSWORD, ADMIN_ROLE);
final Authentication ahmesAuthentication =
getTestSubject().login(userIdentifier, TestEnvironment.encodePassword(AHMES_PASSWORD));
try (final AutoUserContext ignored = new AutoUserContext(userIdentifier, ahmesAuthentication.getAccessToken())) {
try {
getTestSubject().changeUserRole(SU_NAME, new RoleIdentifier("scribe"));
Assert.fail("Should not be able to change the role set for antony.");
}
catch (final IllegalArgumentException expected) {
//noinspection EmptyCatchBlock
}
final User antony = getTestSubject().getUser(SU_NAME);
Assert.assertEquals(SU_ROLE, antony.getRole());
}
}
@Test
public void testAdminProvisioning() throws InterruptedException {
try (final AutoUserContext ignore = loginAdmin()) {
final List<Role> roleIdentifiers = getTestSubject().getRoles();
Assert.assertTrue(Helpers.instancePresent(roleIdentifiers, Role::getIdentifier, ADMIN_ROLE));
final Role role = getTestSubject().getRole(ADMIN_ROLE);
Assert.assertNotNull(role);
Assert.assertTrue(role.getPermissions().contains(constructFullAccessPermission(PermittableGroupIds.IDENTITY_MANAGEMENT)));
Assert.assertTrue(role.getPermissions().contains(constructFullAccessPermission(PermittableGroupIds.ROLE_MANAGEMENT)));
final List<User> userIdentifiers = getTestSubject().getUsers();
Assert.assertTrue(Helpers.instancePresent(userIdentifiers, User::getIdentifier, ADMIN_IDENTIFIER));
final User user = getTestSubject().getUser(ADMIN_IDENTIFIER);
Assert.assertNotNull(user);
Assert.assertEquals(ADMIN_IDENTIFIER, user.getIdentifier());
Assert.assertEquals(ADMIN_ROLE, user.getRole());
final Set<Permission> adminPermittableGroups = getTestSubject().getUserPermissions(ADMIN_IDENTIFIER);
Assert.assertTrue(adminPermittableGroups.contains(new Permission(PermittableGroupIds.SELF_MANAGEMENT, AllowedOperation.ALL)));
Assert.assertTrue(adminPermittableGroups.contains(new Permission(PermittableGroupIds.IDENTITY_MANAGEMENT, AllowedOperation.ALL)));
Assert.assertTrue(adminPermittableGroups.contains(new Permission(PermittableGroupIds.ROLE_MANAGEMENT, AllowedOperation.ALL)));
}
}
private Permission constructFullAccessPermission(final String permittableGroupId) {
final HashSet<AllowedOperation> allowedOperations = new HashSet<>();
allowedOperations.add(AllowedOperation.CHANGE);
allowedOperations.add(AllowedOperation.DELETE);
allowedOperations.add(AllowedOperation.READ);
return new Permission(permittableGroupId, allowedOperations);
}
}
| 2,076 |
0 | Create_ds/fineract-cn-identity/component-test/src/main | Create_ds/fineract-cn-identity/component-test/src/main/java/TestSuite.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* @author Myrle Krantz
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestApplications.class,
TestAuthentication.class,
TestKeyRotation.class,
//TestPasswords.class,
TestPermittableGroups.class,
TestProvisioning.class,
//TestRefreshToken.class,
TestRoles.class,
TestUsers.class,
})
public class TestSuite extends SuiteTestEnvironment {
//TODO: Add TestPasswords and TestRefreshToken back in.
// For some reason, they fail in the test suite even though
// they succeed when run individually.
}
| 2,077 |
0 | Create_ds/fineract-cn-identity/component-test/src/main/java | Create_ds/fineract-cn-identity/component-test/src/main/java/listener/AuthenticationEventListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package listener;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.lang.config.TenantHeaderFilter;
import org.apache.fineract.cn.test.listener.EventRecorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Component
public class AuthenticationEventListener {
private final EventRecorder eventRecorder;
@Autowired
public AuthenticationEventListener(@SuppressWarnings("SpringJavaAutowiringInspection") final EventRecorder eventRecorder)
{
this.eventRecorder = eventRecorder;
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_AUTHENTICATE
)
public void onAuthentication(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_AUTHENTICATE, payload, String.class);
}
}
| 2,078 |
0 | Create_ds/fineract-cn-identity/component-test/src/main/java | Create_ds/fineract-cn-identity/component-test/src/main/java/listener/RoleEventListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package listener;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.lang.config.TenantHeaderFilter;
import org.apache.fineract.cn.test.listener.EventRecorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Component
public class RoleEventListener {
private final EventRecorder eventRecorder;
@Autowired
public RoleEventListener(@SuppressWarnings("SpringJavaAutowiringInspection") final EventRecorder eventRecorder)
{
this.eventRecorder = eventRecorder;
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_POST_ROLE
)
public void onCreateRole(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_POST_ROLE, payload, String.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_PUT_ROLE
)
public void onChangeRole(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_PUT_ROLE, payload, String.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_DELETE_ROLE
)
public void onDeleteRole(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_DELETE_ROLE, payload, String.class);
}
}
| 2,079 |
0 | Create_ds/fineract-cn-identity/component-test/src/main/java | Create_ds/fineract-cn-identity/component-test/src/main/java/listener/PermittableGroupEventListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package listener;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.lang.config.TenantHeaderFilter;
import org.apache.fineract.cn.test.listener.EventRecorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Component
public class PermittableGroupEventListener {
private final EventRecorder eventRecorder;
@Autowired
public PermittableGroupEventListener(@SuppressWarnings("SpringJavaAutowiringInspection") final EventRecorder eventRecorder)
{
this.eventRecorder = eventRecorder;
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_POST_PERMITTABLE_GROUP
)
public void onCreatePermittableGroup(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_POST_PERMITTABLE_GROUP, payload, String.class);
}
}
| 2,080 |
0 | Create_ds/fineract-cn-identity/component-test/src/main/java | Create_ds/fineract-cn-identity/component-test/src/main/java/listener/UserEventListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package listener;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.lang.config.TenantHeaderFilter;
import org.apache.fineract.cn.test.listener.EventRecorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Component
public class UserEventListener {
private final EventRecorder eventRecorder;
@Autowired
public UserEventListener(@SuppressWarnings("SpringJavaAutowiringInspection") final EventRecorder eventRecorder)
{
this.eventRecorder = eventRecorder;
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_POST_USER
)
public void onCreateUser(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_POST_USER, payload, String.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_PUT_USER_ROLEIDENTIFIER
)
public void onChangeUserRole(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_PUT_USER_ROLEIDENTIFIER, payload, String.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_PUT_USER_PASSWORD
)
public void onChangeUserPassword(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_PUT_USER_PASSWORD, payload, String.class);
}
}
| 2,081 |
0 | Create_ds/fineract-cn-identity/component-test/src/main/java | Create_ds/fineract-cn-identity/component-test/src/main/java/listener/ApplicationEventListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package listener;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationCallEndpointSetEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionUserEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationSignatureEvent;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.lang.config.TenantHeaderFilter;
import org.apache.fineract.cn.test.listener.EventRecorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Component
public class ApplicationEventListener {
private final EventRecorder eventRecorder;
@Autowired
public ApplicationEventListener(@SuppressWarnings("SpringJavaAutowiringInspection") final EventRecorder eventRecorder)
{
this.eventRecorder = eventRecorder;
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_PUT_APPLICATION_SIGNATURE
)
public void onSetApplicationSignature(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE, payload, ApplicationSignatureEvent.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_DELETE_APPLICATION
)
public void onDeleteApplication(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_DELETE_APPLICATION, payload, String.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_POST_APPLICATION_PERMISSION
)
public void onCreateApplicationPermission(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_POST_APPLICATION_PERMISSION, payload, ApplicationPermissionEvent.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_DELETE_APPLICATION_PERMISSION
)
public void onDeleteApplicationPermission(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_DELETE_APPLICATION_PERMISSION, payload, ApplicationPermissionEvent.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_PUT_APPLICATION_PERMISSION_USER_ENABLED
)
public void onPutApplicationPermissionEnabledForUser(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_PUT_APPLICATION_PERMISSION_USER_ENABLED, payload, ApplicationPermissionUserEvent.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_POST_APPLICATION_CALLENDPOINTSET
)
public void onCreateApplicationEndpointSet(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET, payload, ApplicationCallEndpointSetEvent.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_PUT_APPLICATION_CALLENDPOINTSET
)
public void onSetApplicationEndpointSet(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_PUT_APPLICATION_CALLENDPOINTSET, payload, ApplicationCallEndpointSetEvent.class);
}
@JmsListener(
subscription = EventConstants.DESTINATION,
destination = EventConstants.DESTINATION,
selector = EventConstants.SELECTOR_DELETE_APPLICATION_CALLENDPOINTSET
)
public void onDeleteApplicationEndpointSet(
@Header(TenantHeaderFilter.TENANT_HEADER)final String tenant,
final String payload) throws Exception {
eventRecorder.event(tenant, EventConstants.OPERATION_DELETE_APPLICATION_CALLENDPOINTSET, payload, ApplicationCallEndpointSetEvent.class);
}
} | 2,082 |
0 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1/domain/RoleIdentifierTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.fineract.cn.test.domain.ValidationTestCase;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* @author Myrle Krantz
*/
@RunWith(Parameterized.class)
public class RoleIdentifierTest {
@Parameterized.Parameters
public static Collection testCases() {
final Collection<ValidationTestCase> ret = new ArrayList<>();
ret.add(new ValidationTestCase<RoleIdentifier>("validCase")
.adjustment(x -> {})
.valid(true));
ret.add(new ValidationTestCase<RoleIdentifier>("spaceyIdentifier")
.adjustment(x -> x.setIdentifier(" "))
.valid(false));
ret.add(new ValidationTestCase<RoleIdentifier>("deactivated")
.adjustment(x -> x.setIdentifier("deactivated"))
.valid(true));
ret.add(new ValidationTestCase<RoleIdentifier>("pharaoh")
.adjustment(x -> x.setIdentifier("pharaoh"))
.valid(false));
return ret;
}
private final ValidationTestCase<RoleIdentifier> testCase;
public RoleIdentifierTest(final ValidationTestCase<RoleIdentifier> testCase)
{
this.testCase = testCase;
}
private RoleIdentifier createValidTestSubject()
{
return new RoleIdentifier("scribe");
}
@Test()
public void test(){
final RoleIdentifier testSubject = createValidTestSubject();
testCase.getAdjustment().accept(testSubject);
Assert.assertTrue(testCase.toString(), testCase.check(testSubject));
}
} | 2,083 |
0 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1/domain/UserWithPasswordTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.apache.fineract.cn.test.domain.ValidationTestCase;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* @author Myrle Krantz
*/
@RunWith(Parameterized.class)
public class UserWithPasswordTest {
@Parameterized.Parameters
public static Collection testCases() {
final Collection<ValidationTestCase> ret = new ArrayList<>();
ret.add(new ValidationTestCase<UserWithPassword>("validCase")
.adjustment(x -> {})
.valid(true));
ret.add(new ValidationTestCase<UserWithPassword>("tooShortPassword")
.adjustment(x -> x.setPassword("1234567"))
.valid(false));
ret.add(new ValidationTestCase<UserWithPassword>("illegalUserIdentifierSeshat")
.adjustment(x -> x.setIdentifier("seshat"))
.valid(false));
ret.add(new ValidationTestCase<UserWithPassword>("illegalUserIdentifierSystem")
.adjustment(x -> x.setIdentifier("system"))
.valid(false));
ret.add(new ValidationTestCase<UserWithPassword>("illegalUserIdentifierSU")
.adjustment(x -> x.setIdentifier(ApiConstants.SYSTEM_SU))
.valid(false));
return ret;
}
private final ValidationTestCase<UserWithPassword> testCase;
public UserWithPasswordTest(final ValidationTestCase<UserWithPassword> testCase)
{
this.testCase = testCase;
}
private UserWithPassword createValidTestSubject()
{
return new UserWithPassword("Ahmes", "pharaoh", "fractions");
}
@Test()
public void test(){
final UserWithPassword testSubject = createValidTestSubject();
testCase.getAdjustment().accept(testSubject);
Assert.assertTrue(testCase.toString(), testCase.check(testSubject));
}
} | 2,084 |
0 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1/domain/RoleTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.apache.fineract.cn.test.domain.ValidationTest;
import org.apache.fineract.cn.test.domain.ValidationTestCase;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* @author Myrle Krantz
*/
@RunWith(Parameterized.class)
public class RoleTest extends ValidationTest<Role> {
public RoleTest(final ValidationTestCase<Role> testCase) {
super(testCase);
}
@Parameterized.Parameters
public static Collection testCases() {
final Collection<ValidationTestCase> ret = new ArrayList<>();
ret.add(new ValidationTestCase<Role>("validCase")
.adjustment(x -> {})
.valid(true));
ret.add(new ValidationTestCase<Role>("deactivated")
.adjustment(x -> x.setIdentifier("deactivated"))
.valid(false));
ret.add(new ValidationTestCase<Role>("pharaoh")
.adjustment(x -> x.setIdentifier("pharaoh"))
.valid(false));
return ret;
}
@Override
protected Role createValidTestSubject() {
final Role ret = new Role();
ret.setIdentifier("blah");
ret.setPermissions(Collections.emptyList());
return ret;
}
}
| 2,085 |
0 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1/domain/PasswordTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.fineract.cn.test.domain.ValidationTestCase;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* @author Myrle Krantz
*/
@RunWith(Parameterized.class)
public class PasswordTest {
@Parameterized.Parameters
public static Collection testCases() {
final Collection<ValidationTestCase> ret = new ArrayList<>();
ret.add(new ValidationTestCase<Password>("validCase")
.adjustment(x -> {})
.valid(true));
ret.add(new ValidationTestCase<Password>("spacesInPassword")
.adjustment(x -> x.setPassword(" "))
.valid(false));
ret.add(new ValidationTestCase<Password>("tooShortPassword")
.adjustment(x -> x.setPassword("1234567"))
.valid(false));
return ret;
}
private final ValidationTestCase<Password> testCase;
public PasswordTest(final ValidationTestCase<Password> testCase)
{
this.testCase = testCase;
}
private Password createValidTestSubject()
{
return new Password("golden_osiris");
}
@Test()
public void test(){
final Password testSubject = createValidTestSubject();
testCase.getAdjustment().accept(testSubject);
Assert.assertTrue(testCase.toString(), testCase.check(testSubject));
}
} | 2,086 |
0 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/test/java/org/apache/fineract/cn/identity/api/v1/domain/CallEndpointSetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.apache.fineract.cn.test.domain.ValidationTest;
import org.apache.fineract.cn.test.domain.ValidationTestCase;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* @author Myrle Krantz
*/
@RunWith(Parameterized.class)
public class CallEndpointSetTest extends ValidationTest<CallEndpointSet> {
public CallEndpointSetTest(final ValidationTestCase<CallEndpointSet> testCase) {
super(testCase);
}
@Parameterized.Parameters
public static Collection testCases() {
final Collection<ValidationTestCase> ret = new ArrayList<>();
ret.add(new ValidationTestCase<CallEndpointSet>("validCase")
.adjustment(x -> {})
.valid(true));
ret.add(new ValidationTestCase<CallEndpointSet>("invalid identifier")
.adjustment(x -> x.setIdentifier(null))
.valid(false));
ret.add(new ValidationTestCase<CallEndpointSet>("null list")
.adjustment(x -> x.setPermittableEndpointGroupIdentifiers(null))
.valid(false));
return ret;
}
@Override
protected CallEndpointSet createValidTestSubject() {
final CallEndpointSet ret = new CallEndpointSet();
ret.setIdentifier("blah");
ret.setPermittableEndpointGroupIdentifiers(Collections.emptyList());
return ret;
}
} | 2,087 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/PermittableGroupIds.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public interface PermittableGroupIds {
String IDENTITY_MANAGEMENT = "identity__v1__users";
String ROLE_MANAGEMENT = "identity__v1__roles";
String SELF_MANAGEMENT = "identity__v1__self";
String APPLICATION_SELF_MANAGEMENT = "identity__v1__app_self";
} | 2,088 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/events/ApplicationPermissionUserEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.events;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class ApplicationPermissionUserEvent {
private String applicationIdentifier;
private String permittableGroupIdentifier;
private String userIdentifier;
public ApplicationPermissionUserEvent() {
}
public ApplicationPermissionUserEvent(String applicationIdentifier, String permittableGroupIdentifier, String userIdentifier) {
this.applicationIdentifier = applicationIdentifier;
this.permittableGroupIdentifier = permittableGroupIdentifier;
this.userIdentifier = userIdentifier;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getPermittableGroupIdentifier() {
return permittableGroupIdentifier;
}
public void setPermittableGroupIdentifier(String permittableGroupIdentifier) {
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
public String getUserIdentifier() {
return userIdentifier;
}
public void setUserIdentifier(String userIdentifier) {
this.userIdentifier = userIdentifier;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ApplicationPermissionUserEvent that = (ApplicationPermissionUserEvent) o;
return Objects.equals(applicationIdentifier, that.applicationIdentifier) &&
Objects.equals(permittableGroupIdentifier, that.permittableGroupIdentifier) &&
Objects.equals(userIdentifier, that.userIdentifier);
}
@Override
public int hashCode() {
return Objects.hash(applicationIdentifier, permittableGroupIdentifier, userIdentifier);
}
@Override
public String toString() {
return "ApplicationPermissionUserEvent{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", permittableGroupIdentifier='" + permittableGroupIdentifier + '\'' +
", userIdentifier='" + userIdentifier + '\'' +
'}';
}
}
| 2,089 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/events/ApplicationCallEndpointSetEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.events;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class ApplicationCallEndpointSetEvent {
private String applicationIdentifier;
private String callEndpointSetIdentifier;
public ApplicationCallEndpointSetEvent() {
}
public ApplicationCallEndpointSetEvent(String applicationIdentifier, String callEndpointSetIdentifier) {
this.applicationIdentifier = applicationIdentifier;
this.callEndpointSetIdentifier = callEndpointSetIdentifier;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getCallEndpointSetIdentifier() {
return callEndpointSetIdentifier;
}
public void setCallEndpointSetIdentifier(String callEndpointSetIdentifier) {
this.callEndpointSetIdentifier = callEndpointSetIdentifier;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ApplicationCallEndpointSetEvent that = (ApplicationCallEndpointSetEvent) o;
return Objects.equals(applicationIdentifier, that.applicationIdentifier) &&
Objects.equals(callEndpointSetIdentifier, that.callEndpointSetIdentifier);
}
@Override
public int hashCode() {
return Objects.hash(applicationIdentifier, callEndpointSetIdentifier);
}
@Override
public String toString() {
return "ApplicationCallEndpointSetEvent{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", callEndpointSetIdentifier='" + callEndpointSetIdentifier + '\'' +
'}';
}
}
| 2,090 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/events/EventConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.events;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public interface EventConstants {
String DESTINATION = "identity-v1";
String OPERATION_HEADER = "operation";
String OPERATION_AUTHENTICATE = "auth";
String OPERATION_POST_PERMITTABLE_GROUP = "post-permittablegroup";
String OPERATION_POST_ROLE = "post-role";
String OPERATION_PUT_ROLE = "put-role";
String OPERATION_DELETE_ROLE = "delete-role";
String OPERATION_POST_USER = "post-user";
String OPERATION_PUT_USER_ROLEIDENTIFIER = "put-user-roleidentifier";
String OPERATION_PUT_USER_PASSWORD = "put-user-password";
String OPERATION_PUT_APPLICATION_SIGNATURE = "put-application-signature";
String OPERATION_DELETE_APPLICATION = "delete-application";
String OPERATION_POST_APPLICATION_CALLENDPOINTSET = "post-application-callendpointset";
String OPERATION_PUT_APPLICATION_CALLENDPOINTSET = "put-application-callendpointset";
String OPERATION_DELETE_APPLICATION_CALLENDPOINTSET = "delete-application-callendpointset";
String OPERATION_POST_APPLICATION_PERMISSION = "post-application-permission";
String OPERATION_DELETE_APPLICATION_PERMISSION = "delete-application-permission";
String OPERATION_PUT_APPLICATION_PERMISSION_USER_ENABLED = "put-application-permission-user-enabled";
String SELECTOR_AUTHENTICATE = OPERATION_HEADER + " = '" + OPERATION_AUTHENTICATE + "'";
String SELECTOR_POST_PERMITTABLE_GROUP = OPERATION_HEADER + " = '" + OPERATION_POST_PERMITTABLE_GROUP + "'";
String SELECTOR_POST_ROLE = OPERATION_HEADER + " = '" + OPERATION_POST_ROLE + "'";
String SELECTOR_PUT_ROLE = OPERATION_HEADER + " = '" + OPERATION_PUT_ROLE + "'";
String SELECTOR_DELETE_ROLE = OPERATION_HEADER + " = '" + OPERATION_DELETE_ROLE + "'";
String SELECTOR_POST_USER = OPERATION_HEADER + " = '" + OPERATION_POST_USER + "'";
String SELECTOR_PUT_USER_ROLEIDENTIFIER = OPERATION_HEADER + " = '" + OPERATION_PUT_USER_ROLEIDENTIFIER + "'";
String SELECTOR_PUT_USER_PASSWORD = OPERATION_HEADER + " = '" + OPERATION_PUT_USER_PASSWORD + "'";
String SELECTOR_PUT_APPLICATION_SIGNATURE = OPERATION_HEADER + " = '" + OPERATION_PUT_APPLICATION_SIGNATURE + "'";
String SELECTOR_DELETE_APPLICATION = OPERATION_HEADER + " = '" + OPERATION_DELETE_APPLICATION + "'";
String SELECTOR_POST_APPLICATION_CALLENDPOINTSET = OPERATION_HEADER + " = '" + OPERATION_POST_APPLICATION_CALLENDPOINTSET + "'";
String SELECTOR_PUT_APPLICATION_CALLENDPOINTSET = OPERATION_HEADER + " = '" + OPERATION_PUT_APPLICATION_CALLENDPOINTSET + "'";
String SELECTOR_DELETE_APPLICATION_CALLENDPOINTSET = OPERATION_HEADER + " = '" + OPERATION_DELETE_APPLICATION_CALLENDPOINTSET + "'";
String SELECTOR_POST_APPLICATION_PERMISSION = OPERATION_HEADER + " = '" + OPERATION_POST_APPLICATION_PERMISSION + "'";
String SELECTOR_DELETE_APPLICATION_PERMISSION = OPERATION_HEADER + " = '" + OPERATION_DELETE_APPLICATION_PERMISSION + "'";
String SELECTOR_PUT_APPLICATION_PERMISSION_USER_ENABLED = OPERATION_HEADER + " = '" + OPERATION_PUT_APPLICATION_PERMISSION_USER_ENABLED + "'";
}
| 2,091 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/events/ApplicationSignatureEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.events;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class ApplicationSignatureEvent {
private String applicationIdentifier;
private String keyTimestamp;
public ApplicationSignatureEvent() {
}
public ApplicationSignatureEvent(String applicationIdentifier, String keyTimestamp) {
this.applicationIdentifier = applicationIdentifier;
this.keyTimestamp = keyTimestamp;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getKeyTimestamp() {
return keyTimestamp;
}
public void setKeyTimestamp(String keyTimestamp) {
this.keyTimestamp = keyTimestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ApplicationSignatureEvent that = (ApplicationSignatureEvent) o;
return Objects.equals(applicationIdentifier, that.applicationIdentifier) &&
Objects.equals(keyTimestamp, that.keyTimestamp);
}
@Override
public int hashCode() {
return Objects.hash(applicationIdentifier, keyTimestamp);
}
@Override
public String toString() {
return "ApplicationSignatureEvent{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", keyTimestamp='" + keyTimestamp + '\'' +
'}';
}
}
| 2,092 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/events/ApplicationPermissionEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.events;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class ApplicationPermissionEvent {
private String applicationIdentifier;
private String permittableGroupIdentifier;
public ApplicationPermissionEvent() {
}
public ApplicationPermissionEvent(String applicationIdentifier, String permittableGroupIdentifier) {
this.applicationIdentifier = applicationIdentifier;
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getPermittableGroupIdentifier() {
return permittableGroupIdentifier;
}
public void setPermittableGroupIdentifier(String permittableGroupIdentifier) {
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ApplicationPermissionEvent that = (ApplicationPermissionEvent) o;
return Objects.equals(applicationIdentifier, that.applicationIdentifier) &&
Objects.equals(permittableGroupIdentifier, that.permittableGroupIdentifier);
}
@Override
public int hashCode() {
return Objects.hash(applicationIdentifier, permittableGroupIdentifier);
}
@Override
public String toString() {
return "ApplicationPermissionEvent{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", permittableGroupIdentifier='" + permittableGroupIdentifier + '\'' +
'}';
}
} | 2,093 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/RoleIdentifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import org.apache.fineract.cn.identity.api.v1.validation.NotRootRole;
import org.hibernate.validator.constraints.NotBlank;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class RoleIdentifier {
@NotBlank
@NotRootRole
private String identifier;
public RoleIdentifier() {
}
public RoleIdentifier(String identifier) {
this.identifier = identifier;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof RoleIdentifier))
return false;
RoleIdentifier that = (RoleIdentifier) o;
return Objects.equals(identifier, that.identifier);
}
@Override public int hashCode() {
return Objects.hash(identifier);
}
@Override public String toString() {
return "RoleIdentifier{" +
"identifier='" + identifier + '\'' +
'}';
}
}
| 2,094 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/CallEndpointSet.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifier;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class CallEndpointSet {
@ValidIdentifier
private String identifier;
@NotNull
private List<String> permittableEndpointGroupIdentifiers;
public CallEndpointSet() {
}
public CallEndpointSet(String identifier, List<String> permittableEndpointGroupIdentifiers) {
this.identifier = identifier;
this.permittableEndpointGroupIdentifiers = permittableEndpointGroupIdentifiers;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public List<String> getPermittableEndpointGroupIdentifiers() {
return permittableEndpointGroupIdentifiers;
}
public void setPermittableEndpointGroupIdentifiers(List<String> permittableEndpointGroupIdentifiers) {
this.permittableEndpointGroupIdentifiers = permittableEndpointGroupIdentifiers;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CallEndpointSet that = (CallEndpointSet) o;
return Objects.equals(identifier, that.identifier) &&
Objects.equals(permittableEndpointGroupIdentifiers, that.permittableEndpointGroupIdentifiers);
}
@Override
public int hashCode() {
return Objects.hash(identifier, permittableEndpointGroupIdentifiers);
}
@Override
public String toString() {
return "CallEndpointSet{" +
"identifier='" + identifier + '\'' +
", permittableEndpointGroupIdentifiers=" + permittableEndpointGroupIdentifiers +
'}';
}
}
| 2,095 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/User.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.ScriptAssert;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess", "unused"})
@ScriptAssert(lang = "javascript", script = "_this.identifier !== \"guest\" && _this.identifier !== \"seshat\" && _this.identifier !== \"system\" && _this.identifier !== \"wepemnefret\"" )
public class User {
@NotBlank
@Length(min = 4, max = 32)
private String identifier;
@NotBlank
private String role;
public User() { }
public User(final String identifier, final String role) {
this.identifier = identifier;
this.role = role;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof User))
return false;
User user = (User) o;
return Objects.equals(identifier, user.identifier) && Objects.equals(role, user.role);
}
@Override public int hashCode() {
return Objects.hash(identifier, role);
}
@Override public String toString() {
return "User{" +
"identifier='" + identifier + '\'' +
", role='" + role + '\'' +
'}';
}
}
| 2,096 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/UserWithPassword.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifier;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.ScriptAssert;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@ScriptAssert(lang = "javascript", script = "_this.identifier !== \"guest\" && _this.identifier !== \"seshat\" && _this.identifier !== \"system\" && _this.identifier !== \"wepemnefret\"" )
public class UserWithPassword {
@ValidIdentifier
private String identifier;
@ValidIdentifier
private String role;
@NotBlank
@Length(min = 8)
private String password;
public UserWithPassword()
{
super();
}
public UserWithPassword(final String identifier, final String role, final String password) {
this.identifier = identifier;
this.role = role;
this.password = password;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof UserWithPassword))
return false;
UserWithPassword that = (UserWithPassword) o;
return Objects.equals(identifier, that.identifier) &&
Objects.equals(role, that.role) &&
Objects.equals(password, that.password);
}
@Override public int hashCode() {
return Objects.hash(identifier, role, password);
}
@Override public String toString() {
return "UserWithPassword{" +
"identifier='" + identifier + '\'' +
", role='" + role + '\'' +
", password='" + password + '\'' +
'}';
}
}
| 2,097 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/PermittableGroup.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import java.util.List;
import java.util.Objects;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifier;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class PermittableGroup {
@ValidIdentifier
private String identifier;
@NotNull
@Valid
private List<PermittableEndpoint> permittables;
public PermittableGroup() {
}
public PermittableGroup(String identifier, List<PermittableEndpoint> permittables) {
this.identifier = identifier;
this.permittables = permittables;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public List<PermittableEndpoint> getPermittables() {
return permittables;
}
public void setPermittables(List<PermittableEndpoint> permittables) {
this.permittables = permittables;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PermittableGroup that = (PermittableGroup) o;
return Objects.equals(identifier, that.identifier) &&
Objects.equals(permittables, that.permittables);
}
@Override
public int hashCode() {
return Objects.hash(identifier, permittables);
}
@Override
public String toString() {
return "PermittableGroup{" +
"identifier='" + identifier + '\'' +
", permittables=" + permittables +
'}';
}
}
| 2,098 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/Authentication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.fineract.cn.identity.api.v1.domain;
import org.hibernate.validator.constraints.NotBlank;
import javax.annotation.Nullable;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class Authentication {
@NotBlank
private String tokenType;
@NotBlank
private String accessToken;
@NotBlank
private String accessTokenExpiration;
@NotBlank
private String refreshTokenExpiration;
/**
* If password expiration is in the past, then the tokens provided only allow the user to change his/her password.
* If password expiration is null then password will never expire.
*/
@Nullable
private String passwordExpiration;
public Authentication()
{
}
public Authentication(
final String accessToken,
final String accessTokenExpiration,
final String refreshTokenExpiration,
final String passwordExpiration) {
this.tokenType = "bearer";
this.accessToken = accessToken;
this.accessTokenExpiration = accessTokenExpiration;
this.refreshTokenExpiration = refreshTokenExpiration;
this.passwordExpiration = passwordExpiration;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getAccessTokenExpiration() {
return accessTokenExpiration;
}
public void setAccessTokenExpiration(String accessTokenExpiration) {
this.accessTokenExpiration = accessTokenExpiration;
}
public String getRefreshTokenExpiration() {
return refreshTokenExpiration;
}
public void setRefreshTokenExpiration(String refreshTokenExpiration) {
this.refreshTokenExpiration = refreshTokenExpiration;
}
public String getPasswordExpiration() {
return passwordExpiration;
}
public void setPasswordExpiration(String passwordExpiration) {
this.passwordExpiration = passwordExpiration;
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Authentication))
return false;
Authentication that = (Authentication) o;
return Objects.equals(tokenType, that.tokenType) &&
Objects.equals(accessToken, that.accessToken) &&
Objects.equals(accessTokenExpiration, that.accessTokenExpiration) &&
Objects.equals(refreshTokenExpiration, that.refreshTokenExpiration) &&
Objects.equals(passwordExpiration, that.passwordExpiration);
}
@Override public int hashCode() {
return Objects
.hash(tokenType, accessToken, accessTokenExpiration, refreshTokenExpiration,
passwordExpiration);
}
@Override public String toString() {
return "Authentication{" +
"tokenType='" + tokenType + '\'' +
", accessToken='" + accessToken + '\'' +
", accessTokenExpiration='" + accessTokenExpiration + '\'' +
", refreshTokenExpiration='" + refreshTokenExpiration + '\'' +
", passwordExpiration='" + passwordExpiration + '\'' +
'}';
}
}
| 2,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.