repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
HonzaKral/elasticsearch | server/src/main/java/org/joda/time/format/StrictISODateTimeFormat.java | 79822 | package org.joda.time.format;
/*
* Copyright 2001-2009 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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.joda.time.DateTimeFieldType;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/*
* Elasticsearch Note: This class has been copied almost identically from joda, where the
* class is named ISODatetimeFormat
*
* However there has been done one huge modification in several methods, which forces the date
* year to be exactly n digits, so that a year like "5" is invalid and must be "0005"
*
* All methods have been marked with an "// ES change" commentary
*
* In case you compare this with the original ISODateTimeFormat, make sure you use a diff
* call, that ignores whitespaces/tabs/indentations like 'diff -b'
*/
/**
* Factory that creates instances of DateTimeFormatter based on the ISO8601 standard.
* <p>
* Date-time formatting is performed by the {@link DateTimeFormatter} class.
* Three classes provide factory methods to create formatters, and this is one.
* The others are {@link DateTimeFormat} and {@link DateTimeFormatterBuilder}.
* <p>
* ISO8601 is the international standard for data interchange. It defines a
* framework, rather than an absolute standard. As a result this provider has a
* number of methods that represent common uses of the framework. The most common
* formats are {@link #date() date}, {@link #time() time}, and {@link #dateTime() dateTime}.
* <p>
* For example, to format a date time in ISO format:
* <pre>
* DateTime dt = new DateTime();
* DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
* String str = fmt.print(dt);
* </pre>
* <p>
* Note that these formatters mostly follow the ISO8601 standard for printing.
* For parsing, the formatters are more lenient and allow formats that are not
* in strict compliance with the standard.
* <p>
* It is important to understand that these formatters are not linked to
* the <code>ISOChronology</code>. These formatters may be used with any
* chronology, however there may be certain side effects with more unusual
* chronologies. For example, the ISO formatters rely on dayOfWeek being
* single digit, dayOfMonth being two digit and dayOfYear being three digit.
* A chronology with a ten day week would thus cause issues. However, in
* general, it is safe to use these formatters with other chronologies.
* <p>
* ISODateTimeFormat is thread-safe and immutable, and the formatters it
* returns are as well.
*
* @author Brian S O'Neill
* @since 1.0
* @see DateTimeFormat
* @see DateTimeFormatterBuilder
*/
public class StrictISODateTimeFormat {
/**
* Constructor.
*
* @since 1.1 (previously private)
*/
protected StrictISODateTimeFormat() {
super();
}
//-----------------------------------------------------------------------
/**
* Returns a formatter that outputs only those fields specified.
* <p>
* This method examines the fields provided and returns an ISO-style
* formatter that best fits. This can be useful for outputting
* less-common ISO styles, such as YearMonth (YYYY-MM) or MonthDay (--MM-DD).
* <p>
* The list provided may have overlapping fields, such as dayOfWeek and
* dayOfMonth. In this case, the style is chosen based on the following
* list, thus in the example, the calendar style is chosen as dayOfMonth
* is higher in priority than dayOfWeek:
* <ul>
* <li>monthOfYear - calendar date style
* <li>dayOfYear - ordinal date style
* <li>weekOfWeekYear - week date style
* <li>dayOfMonth - calendar date style
* <li>dayOfWeek - week date style
* <li>year
* <li>weekyear
* </ul>
* The supported formats are:
* <pre>
* Extended Basic Fields
* 2005-03-25 20050325 year/monthOfYear/dayOfMonth
* 2005-03 2005-03 year/monthOfYear
* 2005--25 2005--25 year/dayOfMonth *
* 2005 2005 year
* --03-25 --0325 monthOfYear/dayOfMonth
* --03 --03 monthOfYear
* ---03 ---03 dayOfMonth
* 2005-084 2005084 year/dayOfYear
* -084 -084 dayOfYear
* 2005-W12-5 2005W125 weekyear/weekOfWeekyear/dayOfWeek
* 2005-W-5 2005W-5 weekyear/dayOfWeek *
* 2005-W12 2005W12 weekyear/weekOfWeekyear
* -W12-5 -W125 weekOfWeekyear/dayOfWeek
* -W12 -W12 weekOfWeekyear
* -W-5 -W-5 dayOfWeek
* 10:20:30.040 102030.040 hour/minute/second/milli
* 10:20:30 102030 hour/minute/second
* 10:20 1020 hour/minute
* 10 10 hour
* -20:30.040 -2030.040 minute/second/milli
* -20:30 -2030 minute/second
* -20 -20 minute
* --30.040 --30.040 second/milli
* --30 --30 second
* ---.040 ---.040 milli *
* 10-30.040 10-30.040 hour/second/milli *
* 10:20-.040 1020-.040 hour/minute/milli *
* 10-30 10-30 hour/second *
* 10--.040 10--.040 hour/milli *
* -20-.040 -20-.040 minute/milli *
* plus datetime formats like {date}T{time}
* </pre>
* * indicates that this is not an official ISO format and can be excluded
* by passing in <code>strictISO</code> as <code>true</code>.
* <p>
* This method can side effect the input collection of fields.
* If the input collection is modifiable, then each field that was added to
* the formatter will be removed from the collection, including any duplicates.
* If the input collection is unmodifiable then no side effect occurs.
* <p>
* This side effect processing is useful if you need to know whether all
* the fields were converted into the formatter or not. To achieve this,
* pass in a modifiable list, and check that it is empty on exit.
*
* @param fields the fields to get a formatter for, not null,
* updated by the method call unless unmodifiable,
* removing those fields built in the formatter
* @param extended true to use the extended format (with separators)
* @param strictISO true to stick exactly to ISO8601, false to include additional formats
* @return a suitable formatter
* @throws IllegalArgumentException if there is no format for the fields
* @since 1.1
*/
public static DateTimeFormatter forFields(
Collection<DateTimeFieldType> fields,
boolean extended,
boolean strictISO) {
if (fields == null || fields.size() == 0) {
throw new IllegalArgumentException("The fields must not be null or empty");
}
Set<DateTimeFieldType> workingFields = new HashSet<>(fields);
int inputSize = workingFields.size();
boolean reducedPrec = false;
DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder();
// date
if (workingFields.contains(DateTimeFieldType.monthOfYear())) {
reducedPrec = dateByMonth(bld, workingFields, extended, strictISO);
} else if (workingFields.contains(DateTimeFieldType.dayOfYear())) {
reducedPrec = dateByOrdinal(bld, workingFields, extended);
} else if (workingFields.contains(DateTimeFieldType.weekOfWeekyear())) {
reducedPrec = dateByWeek(bld, workingFields, extended, strictISO);
} else if (workingFields.contains(DateTimeFieldType.dayOfMonth())) {
reducedPrec = dateByMonth(bld, workingFields, extended, strictISO);
} else if (workingFields.contains(DateTimeFieldType.dayOfWeek())) {
reducedPrec = dateByWeek(bld, workingFields, extended, strictISO);
} else if (workingFields.remove(DateTimeFieldType.year())) {
bld.append(Constants.ye);
reducedPrec = true;
} else if (workingFields.remove(DateTimeFieldType.weekyear())) {
bld.append(Constants.we);
reducedPrec = true;
}
boolean datePresent = (workingFields.size() < inputSize);
// time
time(bld, workingFields, extended, strictISO, reducedPrec, datePresent);
// result
if (bld.canBuildFormatter() == false) {
throw new IllegalArgumentException("No valid format for fields: " + fields);
}
// side effect the input collection to indicate the processed fields
// handling unmodifiable collections with no side effect
try {
fields.retainAll(workingFields);
} catch (UnsupportedOperationException ex) {
// ignore, so we can handle unmodifiable collections
}
return bld.toFormatter();
}
//-----------------------------------------------------------------------
/**
* Creates a date using the calendar date format.
* Specification reference: 5.2.1.
*
* @param bld the builder
* @param fields the fields
* @param extended true to use extended format
* @param strictISO true to only allow ISO formats
* @return true if reduced precision
* @since 1.1
*/
private static boolean dateByMonth(
DateTimeFormatterBuilder bld,
Collection<DateTimeFieldType> fields,
boolean extended,
boolean strictISO) {
boolean reducedPrec = false;
if (fields.remove(DateTimeFieldType.year())) {
bld.append(Constants.ye);
if (fields.remove(DateTimeFieldType.monthOfYear())) {
if (fields.remove(DateTimeFieldType.dayOfMonth())) {
// YYYY-MM-DD/YYYYMMDD
appendSeparator(bld, extended);
bld.appendMonthOfYear(2);
appendSeparator(bld, extended);
bld.appendDayOfMonth(2);
} else {
// YYYY-MM/YYYY-MM
bld.appendLiteral('-');
bld.appendMonthOfYear(2);
reducedPrec = true;
}
} else {
if (fields.remove(DateTimeFieldType.dayOfMonth())) {
// YYYY--DD/YYYY--DD (non-iso)
checkNotStrictISO(fields, strictISO);
bld.appendLiteral('-');
bld.appendLiteral('-');
bld.appendDayOfMonth(2);
} else {
// YYYY/YYYY
reducedPrec = true;
}
}
} else if (fields.remove(DateTimeFieldType.monthOfYear())) {
bld.appendLiteral('-');
bld.appendLiteral('-');
bld.appendMonthOfYear(2);
if (fields.remove(DateTimeFieldType.dayOfMonth())) {
// --MM-DD/--MMDD
appendSeparator(bld, extended);
bld.appendDayOfMonth(2);
} else {
// --MM/--MM
reducedPrec = true;
}
} else if (fields.remove(DateTimeFieldType.dayOfMonth())) {
// ---DD/---DD
bld.appendLiteral('-');
bld.appendLiteral('-');
bld.appendLiteral('-');
bld.appendDayOfMonth(2);
}
return reducedPrec;
}
//-----------------------------------------------------------------------
/**
* Creates a date using the ordinal date format.
* Specification reference: 5.2.2.
*
* @param bld the builder
* @param fields the fields
* @param extended true to use extended format
* @since 1.1
*/
private static boolean dateByOrdinal(
DateTimeFormatterBuilder bld,
Collection<DateTimeFieldType> fields,
boolean extended) {
boolean reducedPrec = false;
if (fields.remove(DateTimeFieldType.year())) {
bld.append(Constants.ye);
if (fields.remove(DateTimeFieldType.dayOfYear())) {
// YYYY-DDD/YYYYDDD
appendSeparator(bld, extended);
bld.appendDayOfYear(3);
} else {
// YYYY/YYYY
reducedPrec = true;
}
} else if (fields.remove(DateTimeFieldType.dayOfYear())) {
// -DDD/-DDD
bld.appendLiteral('-');
bld.appendDayOfYear(3);
}
return reducedPrec;
}
//-----------------------------------------------------------------------
/**
* Creates a date using the calendar date format.
* Specification reference: 5.2.3.
*
* @param bld the builder
* @param fields the fields
* @param extended true to use extended format
* @param strictISO true to only allow ISO formats
* @since 1.1
*/
private static boolean dateByWeek(
DateTimeFormatterBuilder bld,
Collection<DateTimeFieldType> fields,
boolean extended,
boolean strictISO) {
boolean reducedPrec = false;
if (fields.remove(DateTimeFieldType.weekyear())) {
bld.append(Constants.we);
if (fields.remove(DateTimeFieldType.weekOfWeekyear())) {
appendSeparator(bld, extended);
bld.appendLiteral('W');
bld.appendWeekOfWeekyear(2);
if (fields.remove(DateTimeFieldType.dayOfWeek())) {
// YYYY-WWW-D/YYYYWWWD
appendSeparator(bld, extended);
bld.appendDayOfWeek(1);
} else {
// YYYY-WWW/YYYY-WWW
reducedPrec = true;
}
} else {
if (fields.remove(DateTimeFieldType.dayOfWeek())) {
// YYYY-W-D/YYYYW-D (non-iso)
checkNotStrictISO(fields, strictISO);
appendSeparator(bld, extended);
bld.appendLiteral('W');
bld.appendLiteral('-');
bld.appendDayOfWeek(1);
} else {
// YYYY/YYYY
reducedPrec = true;
}
}
} else if (fields.remove(DateTimeFieldType.weekOfWeekyear())) {
bld.appendLiteral('-');
bld.appendLiteral('W');
bld.appendWeekOfWeekyear(2);
if (fields.remove(DateTimeFieldType.dayOfWeek())) {
// -WWW-D/-WWWD
appendSeparator(bld, extended);
bld.appendDayOfWeek(1);
} else {
// -WWW/-WWW
reducedPrec = true;
}
} else if (fields.remove(DateTimeFieldType.dayOfWeek())) {
// -W-D/-W-D
bld.appendLiteral('-');
bld.appendLiteral('W');
bld.appendLiteral('-');
bld.appendDayOfWeek(1);
}
return reducedPrec;
}
//-----------------------------------------------------------------------
/**
* Adds the time fields to the builder.
* Specification reference: 5.3.1.
*
* @param bld the builder
* @param fields the fields
* @param extended whether to use the extended format
* @param strictISO whether to be strict
* @param reducedPrec whether the date was reduced precision
* @param datePresent whether there was a date
* @since 1.1
*/
private static void time(
DateTimeFormatterBuilder bld,
Collection<DateTimeFieldType> fields,
boolean extended,
boolean strictISO,
boolean reducedPrec,
boolean datePresent) {
boolean hour = fields.remove(DateTimeFieldType.hourOfDay());
boolean minute = fields.remove(DateTimeFieldType.minuteOfHour());
boolean second = fields.remove(DateTimeFieldType.secondOfMinute());
boolean milli = fields.remove(DateTimeFieldType.millisOfSecond());
if (!hour && !minute && !second && !milli) {
return;
}
if (hour || minute || second || milli) {
if (strictISO && reducedPrec) {
throw new IllegalArgumentException("No valid ISO8601 format for fields because Date was reduced precision: " + fields);
}
if (datePresent) {
bld.appendLiteral('T');
}
}
if (hour && minute && second || (hour && !second && !milli)) {
// OK - HMSm/HMS/HM/H - valid in combination with date
} else {
if (strictISO && datePresent) {
throw new IllegalArgumentException("No valid ISO8601 format for fields because Time was truncated: " + fields);
}
if (!hour && (minute && second || (minute && !milli) || second)) {
// OK - MSm/MS/M/Sm/S - valid ISO formats
} else {
if (strictISO) {
throw new IllegalArgumentException("No valid ISO8601 format for fields: " + fields);
}
}
}
if (hour) {
bld.appendHourOfDay(2);
} else if (minute || second || milli) {
bld.appendLiteral('-');
}
if (extended && hour && minute) {
bld.appendLiteral(':');
}
if (minute) {
bld.appendMinuteOfHour(2);
} else if (second || milli) {
bld.appendLiteral('-');
}
if (extended && minute && second) {
bld.appendLiteral(':');
}
if (second) {
bld.appendSecondOfMinute(2);
} else if (milli) {
bld.appendLiteral('-');
}
if (milli) {
bld.appendLiteral('.');
bld.appendMillisOfSecond(3);
}
}
//-----------------------------------------------------------------------
/**
* Checks that the iso only flag is not set, throwing an exception if it is.
*
* @param fields the fields
* @param strictISO true if only ISO formats allowed
* @since 1.1
*/
private static void checkNotStrictISO(Collection<DateTimeFieldType> fields, boolean strictISO) {
if (strictISO) {
throw new IllegalArgumentException("No valid ISO8601 format for fields: " + fields);
}
}
/**
* Appends the separator if necessary.
*
* @param bld the builder
* @param extended whether to append the separator
* @since 1.1
*/
private static void appendSeparator(DateTimeFormatterBuilder bld, boolean extended) {
if (extended) {
bld.appendLiteral('-');
}
}
//-----------------------------------------------------------------------
/**
* Returns a generic ISO date parser for parsing dates with a possible zone.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* date = date-element ['T' offset]
* date-element = std-date-element | ord-date-element | week-date-element
* std-date-element = yyyy ['-' MM ['-' dd]]
* ord-date-element = yyyy ['-' DDD]
* week-date-element = xxxx '-W' ww ['-' e]
* offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
* </pre>
*/
public static DateTimeFormatter dateParser() {
return Constants.dp;
}
/**
* Returns a generic ISO date parser for parsing local dates.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* This parser is initialised with the local (UTC) time zone.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* date-element = std-date-element | ord-date-element | week-date-element
* std-date-element = yyyy ['-' MM ['-' dd]]
* ord-date-element = yyyy ['-' DDD]
* week-date-element = xxxx '-W' ww ['-' e]
* </pre>
* @since 1.3
*/
public static DateTimeFormatter localDateParser() {
return Constants.ldp;
}
/**
* Returns a generic ISO date parser for parsing dates.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* date-element = std-date-element | ord-date-element | week-date-element
* std-date-element = yyyy ['-' MM ['-' dd]]
* ord-date-element = yyyy ['-' DDD]
* week-date-element = xxxx '-W' ww ['-' e]
* </pre>
*/
public static DateTimeFormatter dateElementParser() {
return Constants.dpe;
}
/**
* Returns a generic ISO time parser for parsing times with a possible zone.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* time = ['T'] time-element [offset]
* time-element = HH [minute-element] | [fraction]
* minute-element = ':' mm [second-element] | [fraction]
* second-element = ':' ss [fraction]
* fraction = ('.' | ',') digit+
* offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
* </pre>
*/
public static DateTimeFormatter timeParser() {
return Constants.tp;
}
/**
* Returns a generic ISO time parser for parsing local times.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* This parser is initialised with the local (UTC) time zone.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* time = ['T'] time-element
* time-element = HH [minute-element] | [fraction]
* minute-element = ':' mm [second-element] | [fraction]
* second-element = ':' ss [fraction]
* fraction = ('.' | ',') digit+
* </pre>
* @since 1.3
*/
public static DateTimeFormatter localTimeParser() {
return Constants.ltp;
}
/**
* Returns a generic ISO time parser.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* time-element = HH [minute-element] | [fraction]
* minute-element = ':' mm [second-element] | [fraction]
* second-element = ':' ss [fraction]
* fraction = ('.' | ',') digit+
* </pre>
*/
public static DateTimeFormatter timeElementParser() {
return Constants.tpe;
}
/**
* Returns a generic ISO datetime parser which parses either a date or a time or both.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* datetime = time | date-opt-time
* time = 'T' time-element [offset]
* date-opt-time = date-element ['T' [time-element] [offset]]
* date-element = std-date-element | ord-date-element | week-date-element
* std-date-element = yyyy ['-' MM ['-' dd]]
* ord-date-element = yyyy ['-' DDD]
* week-date-element = xxxx '-W' ww ['-' e]
* time-element = HH [minute-element] | [fraction]
* minute-element = ':' mm [second-element] | [fraction]
* second-element = ':' ss [fraction]
* fraction = ('.' | ',') digit+
* offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
* </pre>
*/
public static DateTimeFormatter dateTimeParser() {
return Constants.dtp;
}
/**
* Returns a generic ISO datetime parser where the date is mandatory and the time is optional.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* This parser can parse zoned datetimes.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* date-opt-time = date-element ['T' [time-element] [offset]]
* date-element = std-date-element | ord-date-element | week-date-element
* std-date-element = yyyy ['-' MM ['-' dd]]
* ord-date-element = yyyy ['-' DDD]
* week-date-element = xxxx '-W' ww ['-' e]
* time-element = HH [minute-element] | [fraction]
* minute-element = ':' mm [second-element] | [fraction]
* second-element = ':' ss [fraction]
* fraction = ('.' | ',') digit+
* </pre>
* @since 1.3
*/
public static DateTimeFormatter dateOptionalTimeParser() {
return Constants.dotp;
}
/**
* Returns a generic ISO datetime parser where the date is mandatory and the time is optional.
* <p>
* The returned formatter can only be used for parsing, printing is unsupported.
* <p>
* This parser only parses local datetimes.
* This parser is initialised with the local (UTC) time zone.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* It accepts formats described by the following syntax:
* <pre>
* datetime = date-element ['T' time-element]
* date-element = std-date-element | ord-date-element | week-date-element
* std-date-element = yyyy ['-' MM ['-' dd]]
* ord-date-element = yyyy ['-' DDD]
* week-date-element = xxxx '-W' ww ['-' e]
* time-element = HH [minute-element] | [fraction]
* minute-element = ':' mm [second-element] | [fraction]
* second-element = ':' ss [fraction]
* fraction = ('.' | ',') digit+
* </pre>
* @since 1.3
*/
public static DateTimeFormatter localDateOptionalTimeParser() {
return Constants.ldotp;
}
//-----------------------------------------------------------------------
/**
* Returns a formatter for a full date as four digit year, two digit month
* of year, and two digit day of month (yyyy-MM-dd).
* <p>
* The returned formatter prints and parses only this format.
* See {@link #dateParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for yyyy-MM-dd
*/
public static DateTimeFormatter date() {
return yearMonthDay();
}
/**
* Returns a formatter for a two digit hour of day, two digit minute of
* hour, two digit second of minute, three digit fraction of second, and
* time zone offset (HH:mm:ss.SSSZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
* See {@link #timeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for HH:mm:ss.SSSZZ
*/
public static DateTimeFormatter time() {
return Constants.t;
}
/**
* Returns a formatter for a two digit hour of day, two digit minute of
* hour, two digit second of minute, and time zone offset (HH:mm:ssZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
* See {@link #timeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for HH:mm:ssZZ
*/
public static DateTimeFormatter timeNoMillis() {
return Constants.tx;
}
/**
* Returns a formatter for a two digit hour of day, two digit minute of
* hour, two digit second of minute, three digit fraction of second, and
* time zone offset prefixed by 'T' ('T'HH:mm:ss.SSSZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
* See {@link #timeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for 'T'HH:mm:ss.SSSZZ
*/
public static DateTimeFormatter tTime() {
return Constants.tt;
}
/**
* Returns a formatter for a two digit hour of day, two digit minute of
* hour, two digit second of minute, and time zone offset prefixed
* by 'T' ('T'HH:mm:ssZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
* See {@link #timeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for 'T'HH:mm:ssZZ
*/
public static DateTimeFormatter tTimeNoMillis() {
return Constants.ttx;
}
/**
* Returns a formatter that combines a full date and time, separated by a 'T'
* (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
* See {@link #dateTimeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSSZZ
*/
public static DateTimeFormatter dateTime() {
return Constants.dt;
}
/**
* Returns a formatter that combines a full date and time without millis,
* separated by a 'T' (yyyy-MM-dd'T'HH:mm:ssZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
* See {@link #dateTimeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for yyyy-MM-dd'T'HH:mm:ssZZ
*/
public static DateTimeFormatter dateTimeNoMillis() {
return Constants.dtx;
}
/**
* Returns a formatter for a full ordinal date, using a four
* digit year and three digit dayOfYear (yyyy-DDD).
* <p>
* The returned formatter prints and parses only this format.
* See {@link #dateParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for yyyy-DDD
* @since 1.1
*/
public static DateTimeFormatter ordinalDate() {
return Constants.od;
}
/**
* Returns a formatter for a full ordinal date and time, using a four
* digit year and three digit dayOfYear (yyyy-DDD'T'HH:mm:ss.SSSZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
* See {@link #dateTimeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for yyyy-DDD'T'HH:mm:ss.SSSZZ
* @since 1.1
*/
public static DateTimeFormatter ordinalDateTime() {
return Constants.odt;
}
/**
* Returns a formatter for a full ordinal date and time without millis,
* using a four digit year and three digit dayOfYear (yyyy-DDD'T'HH:mm:ssZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
* See {@link #dateTimeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for yyyy-DDD'T'HH:mm:ssZZ
* @since 1.1
*/
public static DateTimeFormatter ordinalDateTimeNoMillis() {
return Constants.odtx;
}
/**
* Returns a formatter for a full date as four digit weekyear, two digit
* week of weekyear, and one digit day of week (xxxx-'W'ww-e).
* <p>
* The returned formatter prints and parses only this format.
* See {@link #dateParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for xxxx-'W'ww-e
*/
public static DateTimeFormatter weekDate() {
return Constants.wwd;
}
/**
* Returns a formatter that combines a full weekyear date and time,
* separated by a 'T' (xxxx-'W'ww-e'T'HH:mm:ss.SSSZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
* See {@link #dateTimeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for xxxx-'W'ww-e'T'HH:mm:ss.SSSZZ
*/
public static DateTimeFormatter weekDateTime() {
return Constants.wdt;
}
/**
* Returns a formatter that combines a full weekyear date and time without millis,
* separated by a 'T' (xxxx-'W'ww-e'T'HH:mm:ssZZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
* See {@link #dateTimeParser()} for a more flexible parser that accepts different formats.
*
* @return a formatter for xxxx-'W'ww-e'T'HH:mm:ssZZ
*/
public static DateTimeFormatter weekDateTimeNoMillis() {
return Constants.wdtx;
}
//-----------------------------------------------------------------------
/**
* Returns a basic formatter for a full date as four digit year, two digit
* month of year, and two digit day of month (yyyyMMdd).
* <p>
* The returned formatter prints and parses only this format.
*
* @return a formatter for yyyyMMdd
*/
public static DateTimeFormatter basicDate() {
return Constants.bd;
}
/**
* Returns a basic formatter for a two digit hour of day, two digit minute
* of hour, two digit second of minute, three digit millis, and time zone
* offset (HHmmss.SSSZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
*
* @return a formatter for HHmmss.SSSZ
*/
public static DateTimeFormatter basicTime() {
return Constants.bt;
}
/**
* Returns a basic formatter for a two digit hour of day, two digit minute
* of hour, two digit second of minute, and time zone offset (HHmmssZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
*
* @return a formatter for HHmmssZ
*/
public static DateTimeFormatter basicTimeNoMillis() {
return Constants.btx;
}
/**
* Returns a basic formatter for a two digit hour of day, two digit minute
* of hour, two digit second of minute, three digit millis, and time zone
* offset prefixed by 'T' ('T'HHmmss.SSSZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
*
* @return a formatter for 'T'HHmmss.SSSZ
*/
public static DateTimeFormatter basicTTime() {
return Constants.btt;
}
/**
* Returns a basic formatter for a two digit hour of day, two digit minute
* of hour, two digit second of minute, and time zone offset prefixed by 'T'
* ('T'HHmmssZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
*
* @return a formatter for 'T'HHmmssZ
*/
public static DateTimeFormatter basicTTimeNoMillis() {
return Constants.bttx;
}
/**
* Returns a basic formatter that combines a basic date and time, separated
* by a 'T' (yyyyMMdd'T'HHmmss.SSSZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
*
* @return a formatter for yyyyMMdd'T'HHmmss.SSSZ
*/
public static DateTimeFormatter basicDateTime() {
return Constants.bdt;
}
/**
* Returns a basic formatter that combines a basic date and time without millis,
* separated by a 'T' (yyyyMMdd'T'HHmmssZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
*
* @return a formatter for yyyyMMdd'T'HHmmssZ
*/
public static DateTimeFormatter basicDateTimeNoMillis() {
return Constants.bdtx;
}
/**
* Returns a formatter for a full ordinal date, using a four
* digit year and three digit dayOfYear (yyyyDDD).
* <p>
* The returned formatter prints and parses only this format.
*
* @return a formatter for yyyyDDD
* @since 1.1
*/
public static DateTimeFormatter basicOrdinalDate() {
return Constants.bod;
}
/**
* Returns a formatter for a full ordinal date and time, using a four
* digit year and three digit dayOfYear (yyyyDDD'T'HHmmss.SSSZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
*
* @return a formatter for yyyyDDD'T'HHmmss.SSSZ
* @since 1.1
*/
public static DateTimeFormatter basicOrdinalDateTime() {
return Constants.bodt;
}
/**
* Returns a formatter for a full ordinal date and time without millis,
* using a four digit year and three digit dayOfYear (yyyyDDD'T'HHmmssZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
*
* @return a formatter for yyyyDDD'T'HHmmssZ
* @since 1.1
*/
public static DateTimeFormatter basicOrdinalDateTimeNoMillis() {
return Constants.bodtx;
}
/**
* Returns a basic formatter for a full date as four digit weekyear, two
* digit week of weekyear, and one digit day of week (xxxx'W'wwe).
* <p>
* The returned formatter prints and parses only this format.
*
* @return a formatter for xxxx'W'wwe
*/
public static DateTimeFormatter basicWeekDate() {
return Constants.bwd;
}
/**
* Returns a basic formatter that combines a basic weekyear date and time,
* separated by a 'T' (xxxx'W'wwe'T'HHmmss.SSSZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which includes milliseconds.
*
* @return a formatter for xxxx'W'wwe'T'HHmmss.SSSZ
*/
public static DateTimeFormatter basicWeekDateTime() {
return Constants.bwdt;
}
/**
* Returns a basic formatter that combines a basic weekyear date and time
* without millis, separated by a 'T' (xxxx'W'wwe'T'HHmmssZ).
* <p>
* The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero.
* The parser is strict by default, thus time string {@code 24:00} cannot be parsed.
* <p>
* The returned formatter prints and parses only this format, which excludes milliseconds.
*
* @return a formatter for xxxx'W'wwe'T'HHmmssZ
*/
public static DateTimeFormatter basicWeekDateTimeNoMillis() {
return Constants.bwdtx;
}
//-----------------------------------------------------------------------
/**
* Returns a formatter for a four digit year. (yyyy)
*
* @return a formatter for yyyy
*/
public static DateTimeFormatter year() {
return Constants.ye;
}
/**
* Returns a formatter for a four digit year and two digit month of
* year. (yyyy-MM)
*
* @return a formatter for yyyy-MM
*/
public static DateTimeFormatter yearMonth() {
return Constants.ym;
}
/**
* Returns a formatter for a four digit year, two digit month of year, and
* two digit day of month. (yyyy-MM-dd)
*
* @return a formatter for yyyy-MM-dd
*/
public static DateTimeFormatter yearMonthDay() {
return Constants.ymd;
}
/**
* Returns a formatter for a four digit weekyear. (xxxx)
*
* @return a formatter for xxxx
*/
public static DateTimeFormatter weekyear() {
return Constants.we;
}
/**
* Returns a formatter for a four digit weekyear and two digit week of
* weekyear. (xxxx-'W'ww)
*
* @return a formatter for xxxx-'W'ww
*/
public static DateTimeFormatter weekyearWeek() {
return Constants.ww;
}
/**
* Returns a formatter for a four digit weekyear, two digit week of
* weekyear, and one digit day of week. (xxxx-'W'ww-e)
*
* @return a formatter for xxxx-'W'ww-e
*/
public static DateTimeFormatter weekyearWeekDay() {
return Constants.wwd;
}
/**
* Returns a formatter for a two digit hour of day. (HH)
*
* @return a formatter for HH
*/
public static DateTimeFormatter hour() {
return Constants.hde;
}
/**
* Returns a formatter for a two digit hour of day and two digit minute of
* hour. (HH:mm)
*
* @return a formatter for HH:mm
*/
public static DateTimeFormatter hourMinute() {
return Constants.hm;
}
/**
* Returns a formatter for a two digit hour of day, two digit minute of
* hour, and two digit second of minute. (HH:mm:ss)
*
* @return a formatter for HH:mm:ss
*/
public static DateTimeFormatter hourMinuteSecond() {
return Constants.hms;
}
/**
* Returns a formatter for a two digit hour of day, two digit minute of
* hour, two digit second of minute, and three digit fraction of
* second (HH:mm:ss.SSS). Parsing will parse up to 3 fractional second
* digits.
*
* @return a formatter for HH:mm:ss.SSS
*/
public static DateTimeFormatter hourMinuteSecondMillis() {
return Constants.hmsl;
}
/**
* Returns a formatter for a two digit hour of day, two digit minute of
* hour, two digit second of minute, and three digit fraction of
* second (HH:mm:ss.SSS). Parsing will parse up to 9 fractional second
* digits, throwing away all except the first three.
*
* @return a formatter for HH:mm:ss.SSS
*/
public static DateTimeFormatter hourMinuteSecondFraction() {
return Constants.hmsf;
}
/**
* Returns a formatter that combines a full date and two digit hour of
* day. (yyyy-MM-dd'T'HH)
*
* @return a formatter for yyyy-MM-dd'T'HH
*/
public static DateTimeFormatter dateHour() {
return Constants.dh;
}
/**
* Returns a formatter that combines a full date, two digit hour of day,
* and two digit minute of hour. (yyyy-MM-dd'T'HH:mm)
*
* @return a formatter for yyyy-MM-dd'T'HH:mm
*/
public static DateTimeFormatter dateHourMinute() {
return Constants.dhm;
}
/**
* Returns a formatter that combines a full date, two digit hour of day,
* two digit minute of hour, and two digit second of
* minute. (yyyy-MM-dd'T'HH:mm:ss)
*
* @return a formatter for yyyy-MM-dd'T'HH:mm:ss
*/
public static DateTimeFormatter dateHourMinuteSecond() {
return Constants.dhms;
}
/**
* Returns a formatter that combines a full date, two digit hour of day,
* two digit minute of hour, two digit second of minute, and three digit
* fraction of second (yyyy-MM-dd'T'HH:mm:ss.SSS). Parsing will parse up
* to 3 fractional second digits.
*
* @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSS
*/
public static DateTimeFormatter dateHourMinuteSecondMillis() {
return Constants.dhmsl;
}
/**
* Returns a formatter that combines a full date, two digit hour of day,
* two digit minute of hour, two digit second of minute, and three digit
* fraction of second (yyyy-MM-dd'T'HH:mm:ss.SSS). Parsing will parse up
* to 9 fractional second digits, throwing away all except the first three.
*
* @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSS
*/
public static DateTimeFormatter dateHourMinuteSecondFraction() {
return Constants.dhmsf;
}
//-----------------------------------------------------------------------
static final class Constants {
private static final DateTimeFormatter
ye = yearElement(), // year element (yyyy)
mye = monthElement(), // monthOfYear element (-MM)
dme = dayOfMonthElement(), // dayOfMonth element (-dd)
we = weekyearElement(), // weekyear element (xxxx)
wwe = weekElement(), // weekOfWeekyear element (-ww)
dwe = dayOfWeekElement(), // dayOfWeek element (-ee)
dye = dayOfYearElement(), // dayOfYear element (-DDD)
hde = hourElement(), // hourOfDay element (HH)
mhe = minuteElement(), // minuteOfHour element (:mm)
sme = secondElement(), // secondOfMinute element (:ss)
fse = fractionElement(), // fractionOfSecond element (.SSSSSSSSS)
ze = offsetElement(), // zone offset element
lte = literalTElement(), // literal 'T' element
//y, // year (same as year element)
ym = yearMonth(), // year month
ymd = yearMonthDay(), // year month day
//w, // weekyear (same as weekyear element)
ww = weekyearWeek(), // weekyear week
wwd = weekyearWeekDay(), // weekyear week day
//h, // hour (same as hour element)
hm = hourMinute(), // hour minute
hms = hourMinuteSecond(), // hour minute second
hmsl = hourMinuteSecondMillis(), // hour minute second millis
hmsf = hourMinuteSecondFraction(), // hour minute second fraction
dh = dateHour(), // date hour
dhm = dateHourMinute(), // date hour minute
dhms = dateHourMinuteSecond(), // date hour minute second
dhmsl = dateHourMinuteSecondMillis(), // date hour minute second millis
dhmsf = dateHourMinuteSecondFraction(), // date hour minute second fraction
//d, // date (same as ymd)
t = time(), // time
tx = timeNoMillis(), // time no millis
tt = tTime(), // Ttime
ttx = tTimeNoMillis(), // Ttime no millis
dt = dateTime(), // date time
dtx = dateTimeNoMillis(), // date time no millis
//wd, // week date (same as wwd)
wdt = weekDateTime(), // week date time
wdtx = weekDateTimeNoMillis(), // week date time no millis
od = ordinalDate(), // ordinal date (same as yd)
odt = ordinalDateTime(), // ordinal date time
odtx = ordinalDateTimeNoMillis(), // ordinal date time no millis
bd = basicDate(), // basic date
bt = basicTime(), // basic time
btx = basicTimeNoMillis(), // basic time no millis
btt = basicTTime(), // basic Ttime
bttx = basicTTimeNoMillis(), // basic Ttime no millis
bdt = basicDateTime(), // basic date time
bdtx = basicDateTimeNoMillis(), // basic date time no millis
bod = basicOrdinalDate(), // basic ordinal date
bodt = basicOrdinalDateTime(), // basic ordinal date time
bodtx = basicOrdinalDateTimeNoMillis(), // basic ordinal date time no millis
bwd = basicWeekDate(), // basic week date
bwdt = basicWeekDateTime(), // basic week date time
bwdtx = basicWeekDateTimeNoMillis(), // basic week date time no millis
dpe = dateElementParser(), // date parser element
tpe = timeElementParser(), // time parser element
dp = dateParser(), // date parser
ldp = localDateParser(), // local date parser
tp = timeParser(), // time parser
ltp = localTimeParser(), // local time parser
dtp = dateTimeParser(), // date time parser
dotp = dateOptionalTimeParser(), // date optional time parser
ldotp = localDateOptionalTimeParser(); // local date optional time parser
//-----------------------------------------------------------------------
private static DateTimeFormatter dateParser() {
if (dp == null) {
DateTimeParser tOffset = new DateTimeFormatterBuilder()
.appendLiteral('T')
.append(offsetElement()).toParser();
return new DateTimeFormatterBuilder()
.append(dateElementParser())
.appendOptional(tOffset)
.toFormatter();
}
return dp;
}
private static DateTimeFormatter localDateParser() {
if (ldp == null) {
return dateElementParser().withZoneUTC();
}
return ldp;
}
private static DateTimeFormatter dateElementParser() {
if (dpe == null) {
return new DateTimeFormatterBuilder()
.append(null, new DateTimeParser[] {
new DateTimeFormatterBuilder()
.append(yearElement())
.appendOptional
(new DateTimeFormatterBuilder()
.append(monthElement())
.appendOptional(dayOfMonthElement().getParser())
.toParser())
.toParser(),
new DateTimeFormatterBuilder()
.append(weekyearElement())
.append(weekElement())
.appendOptional(dayOfWeekElement().getParser())
.toParser(),
new DateTimeFormatterBuilder()
.append(yearElement())
.append(dayOfYearElement())
.toParser()
})
.toFormatter();
}
return dpe;
}
private static DateTimeFormatter timeParser() {
if (tp == null) {
return new DateTimeFormatterBuilder()
.appendOptional(literalTElement().getParser())
.append(timeElementParser())
.appendOptional(offsetElement().getParser())
.toFormatter();
}
return tp;
}
private static DateTimeFormatter localTimeParser() {
if (ltp == null) {
return new DateTimeFormatterBuilder()
.appendOptional(literalTElement().getParser())
.append(timeElementParser())
.toFormatter().withZoneUTC();
}
return ltp;
}
private static DateTimeFormatter timeElementParser() {
if (tpe == null) {
// Decimal point can be either '.' or ','
DateTimeParser decimalPoint = new DateTimeFormatterBuilder()
.append(null, new DateTimeParser[] {
new DateTimeFormatterBuilder()
.appendLiteral('.')
.toParser(),
new DateTimeFormatterBuilder()
.appendLiteral(',')
.toParser()
})
.toParser();
return new DateTimeFormatterBuilder()
// time-element
.append(hourElement())
.append
(null, new DateTimeParser[] {
new DateTimeFormatterBuilder()
// minute-element
.append(minuteElement())
.append
(null, new DateTimeParser[] {
new DateTimeFormatterBuilder()
// second-element
.append(secondElement())
// second fraction
.appendOptional(new DateTimeFormatterBuilder()
.append(decimalPoint)
.appendFractionOfSecond(1, 9)
.toParser())
.toParser(),
// minute fraction
new DateTimeFormatterBuilder()
.append(decimalPoint)
.appendFractionOfMinute(1, 9)
.toParser(),
null
})
.toParser(),
// hour fraction
new DateTimeFormatterBuilder()
.append(decimalPoint)
.appendFractionOfHour(1, 9)
.toParser(),
null
})
.toFormatter();
}
return tpe;
}
private static DateTimeFormatter dateTimeParser() {
if (dtp == null) {
// This is different from the general time parser in that the 'T'
// is required.
DateTimeParser time = new DateTimeFormatterBuilder()
.appendLiteral('T')
.append(timeElementParser())
.appendOptional(offsetElement().getParser())
.toParser();
return new DateTimeFormatterBuilder()
.append(null, new DateTimeParser[] {time, dateOptionalTimeParser().getParser()})
.toFormatter();
}
return dtp;
}
private static DateTimeFormatter dateOptionalTimeParser() {
if (dotp == null) {
DateTimeParser timeOrOffset = new DateTimeFormatterBuilder()
.appendLiteral('T')
.appendOptional(timeElementParser().getParser())
.appendOptional(offsetElement().getParser())
.toParser();
return new DateTimeFormatterBuilder()
.append(dateElementParser())
.appendOptional(timeOrOffset)
.toFormatter();
}
return dotp;
}
private static DateTimeFormatter localDateOptionalTimeParser() {
if (ldotp == null) {
DateTimeParser time = new DateTimeFormatterBuilder()
.appendLiteral('T')
.append(timeElementParser())
.toParser();
return new DateTimeFormatterBuilder()
.append(dateElementParser())
.appendOptional(time)
.toFormatter().withZoneUTC();
}
return ldotp;
}
//-----------------------------------------------------------------------
private static DateTimeFormatter time() {
if (t == null) {
return new DateTimeFormatterBuilder()
.append(hourMinuteSecondFraction())
.append(offsetElement())
.toFormatter();
}
return t;
}
private static DateTimeFormatter timeNoMillis() {
if (tx == null) {
return new DateTimeFormatterBuilder()
.append(hourMinuteSecond())
.append(offsetElement())
.toFormatter();
}
return tx;
}
private static DateTimeFormatter tTime() {
if (tt == null) {
return new DateTimeFormatterBuilder()
.append(literalTElement())
.append(time())
.toFormatter();
}
return tt;
}
private static DateTimeFormatter tTimeNoMillis() {
if (ttx == null) {
return new DateTimeFormatterBuilder()
.append(literalTElement())
.append(timeNoMillis())
.toFormatter();
}
return ttx;
}
private static DateTimeFormatter dateTime() {
if (dt == null) {
return new DateTimeFormatterBuilder()
.append(date())
.append(tTime())
.toFormatter();
}
return dt;
}
private static DateTimeFormatter dateTimeNoMillis() {
if (dtx == null) {
return new DateTimeFormatterBuilder()
.append(date())
.append(tTimeNoMillis())
.toFormatter();
}
return dtx;
}
private static DateTimeFormatter ordinalDate() {
if (od == null) {
return new DateTimeFormatterBuilder()
.append(yearElement())
.append(dayOfYearElement())
.toFormatter();
}
return od;
}
private static DateTimeFormatter ordinalDateTime() {
if (odt == null) {
return new DateTimeFormatterBuilder()
.append(ordinalDate())
.append(tTime())
.toFormatter();
}
return odt;
}
private static DateTimeFormatter ordinalDateTimeNoMillis() {
if (odtx == null) {
return new DateTimeFormatterBuilder()
.append(ordinalDate())
.append(tTimeNoMillis())
.toFormatter();
}
return odtx;
}
private static DateTimeFormatter weekDateTime() {
if (wdt == null) {
return new DateTimeFormatterBuilder()
.append(weekDate())
.append(tTime())
.toFormatter();
}
return wdt;
}
private static DateTimeFormatter weekDateTimeNoMillis() {
if (wdtx == null) {
return new DateTimeFormatterBuilder()
.append(weekDate())
.append(tTimeNoMillis())
.toFormatter();
}
return wdtx;
}
//-----------------------------------------------------------------------
private static DateTimeFormatter basicDate() {
if (bd == null) {
return new DateTimeFormatterBuilder()
.appendYear(4, 4)
.appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2)
.appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2)
.toFormatter();
}
return bd;
}
private static DateTimeFormatter basicTime() {
if (bt == null) {
return new DateTimeFormatterBuilder()
.appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2)
.appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2)
.appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2)
.appendLiteral('.')
.appendFractionOfSecond(3, 9)
.appendTimeZoneOffset("Z", false, 2, 2)
.toFormatter();
}
return bt;
}
private static DateTimeFormatter basicTimeNoMillis() {
if (btx == null) {
return new DateTimeFormatterBuilder()
.appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2)
.appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2)
.appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2)
.appendTimeZoneOffset("Z", false, 2, 2)
.toFormatter();
}
return btx;
}
private static DateTimeFormatter basicTTime() {
if (btt == null) {
return new DateTimeFormatterBuilder()
.append(literalTElement())
.append(basicTime())
.toFormatter();
}
return btt;
}
private static DateTimeFormatter basicTTimeNoMillis() {
if (bttx == null) {
return new DateTimeFormatterBuilder()
.append(literalTElement())
.append(basicTimeNoMillis())
.toFormatter();
}
return bttx;
}
private static DateTimeFormatter basicDateTime() {
if (bdt == null) {
return new DateTimeFormatterBuilder()
.append(basicDate())
.append(basicTTime())
.toFormatter();
}
return bdt;
}
private static DateTimeFormatter basicDateTimeNoMillis() {
if (bdtx == null) {
return new DateTimeFormatterBuilder()
.append(basicDate())
.append(basicTTimeNoMillis())
.toFormatter();
}
return bdtx;
}
private static DateTimeFormatter basicOrdinalDate() {
if (bod == null) {
return new DateTimeFormatterBuilder()
.appendYear(4, 4)
.appendFixedDecimal(DateTimeFieldType.dayOfYear(), 3)
.toFormatter();
}
return bod;
}
private static DateTimeFormatter basicOrdinalDateTime() {
if (bodt == null) {
return new DateTimeFormatterBuilder()
.append(basicOrdinalDate())
.append(basicTTime())
.toFormatter();
}
return bodt;
}
private static DateTimeFormatter basicOrdinalDateTimeNoMillis() {
if (bodtx == null) {
return new DateTimeFormatterBuilder()
.append(basicOrdinalDate())
.append(basicTTimeNoMillis())
.toFormatter();
}
return bodtx;
}
private static DateTimeFormatter basicWeekDate() {
if (bwd == null) {
return new DateTimeFormatterBuilder()
// ES change, was .appendWeekyear(4, 4)
.appendFixedSignedDecimal(DateTimeFieldType.weekyear(), 4)
.appendLiteral('W')
.appendFixedDecimal(DateTimeFieldType.weekOfWeekyear(), 2)
.appendFixedDecimal(DateTimeFieldType.dayOfWeek(), 1)
.toFormatter();
}
return bwd;
}
private static DateTimeFormatter basicWeekDateTime() {
if (bwdt == null) {
return new DateTimeFormatterBuilder()
.append(basicWeekDate())
.append(basicTTime())
.toFormatter();
}
return bwdt;
}
private static DateTimeFormatter basicWeekDateTimeNoMillis() {
if (bwdtx == null) {
return new DateTimeFormatterBuilder()
.append(basicWeekDate())
.append(basicTTimeNoMillis())
.toFormatter();
}
return bwdtx;
}
//-----------------------------------------------------------------------
private static DateTimeFormatter yearMonth() {
if (ym == null) {
return new DateTimeFormatterBuilder()
.append(yearElement())
.append(monthElement())
.toFormatter();
}
return ym;
}
private static DateTimeFormatter yearMonthDay() {
if (ymd == null) {
return new DateTimeFormatterBuilder()
.append(yearElement())
.append(monthElement())
.append(dayOfMonthElement())
.toFormatter();
}
return ymd;
}
private static DateTimeFormatter weekyearWeek() {
if (ww == null) {
return new DateTimeFormatterBuilder()
.append(weekyearElement())
.append(weekElement())
.toFormatter();
}
return ww;
}
private static DateTimeFormatter weekyearWeekDay() {
if (wwd == null) {
return new DateTimeFormatterBuilder()
.append(weekyearElement())
.append(weekElement())
.append(dayOfWeekElement())
.toFormatter();
}
return wwd;
}
private static DateTimeFormatter hourMinute() {
if (hm == null) {
return new DateTimeFormatterBuilder()
.append(hourElement())
.append(minuteElement())
.toFormatter();
}
return hm;
}
private static DateTimeFormatter hourMinuteSecond() {
if (hms == null) {
return new DateTimeFormatterBuilder()
.append(hourElement())
.append(minuteElement())
.append(secondElement())
.toFormatter();
}
return hms;
}
private static DateTimeFormatter hourMinuteSecondMillis() {
if (hmsl == null) {
return new DateTimeFormatterBuilder()
.append(hourElement())
.append(minuteElement())
.append(secondElement())
.appendLiteral('.')
.appendFractionOfSecond(3, 3)
.toFormatter();
}
return hmsl;
}
private static DateTimeFormatter hourMinuteSecondFraction() {
if (hmsf == null) {
return new DateTimeFormatterBuilder()
.append(hourElement())
.append(minuteElement())
.append(secondElement())
.append(fractionElement())
.toFormatter();
}
return hmsf;
}
private static DateTimeFormatter dateHour() {
if (dh == null) {
return new DateTimeFormatterBuilder()
.append(date())
.append(literalTElement())
.append(hour())
.toFormatter();
}
return dh;
}
private static DateTimeFormatter dateHourMinute() {
if (dhm == null) {
return new DateTimeFormatterBuilder()
.append(date())
.append(literalTElement())
.append(hourMinute())
.toFormatter();
}
return dhm;
}
private static DateTimeFormatter dateHourMinuteSecond() {
if (dhms == null) {
return new DateTimeFormatterBuilder()
.append(date())
.append(literalTElement())
.append(hourMinuteSecond())
.toFormatter();
}
return dhms;
}
private static DateTimeFormatter dateHourMinuteSecondMillis() {
if (dhmsl == null) {
return new DateTimeFormatterBuilder()
.append(date())
.append(literalTElement())
.append(hourMinuteSecondMillis())
.toFormatter();
}
return dhmsl;
}
private static DateTimeFormatter dateHourMinuteSecondFraction() {
if (dhmsf == null) {
return new DateTimeFormatterBuilder()
.append(date())
.append(literalTElement())
.append(hourMinuteSecondFraction())
.toFormatter();
}
return dhmsf;
}
//-----------------------------------------------------------------------
private static DateTimeFormatter yearElement() {
if (ye == null) {
return new DateTimeFormatterBuilder()
// ES change, was .appendYear(4, 9)
.appendFixedSignedDecimal(DateTimeFieldType.year(), 4)
.toFormatter();
}
return ye;
}
private static DateTimeFormatter monthElement() {
if (mye == null) {
return new DateTimeFormatterBuilder()
.appendLiteral('-')
// ES change, was .appendMonthOfYear(2)
.appendFixedSignedDecimal(DateTimeFieldType.monthOfYear(), 2)
.toFormatter();
}
return mye;
}
private static DateTimeFormatter dayOfMonthElement() {
if (dme == null) {
return new DateTimeFormatterBuilder()
.appendLiteral('-')
// ES change, was .appendDayOfMonth(2)
.appendFixedSignedDecimal(DateTimeFieldType.dayOfMonth(), 2)
.toFormatter();
}
return dme;
}
private static DateTimeFormatter weekyearElement() {
if (we == null) {
return new DateTimeFormatterBuilder()
// ES change, was .appendWeekyear(4, 9)
.appendFixedSignedDecimal(DateTimeFieldType.weekyear(), 4)
.toFormatter();
}
return we;
}
private static DateTimeFormatter weekElement() {
if (wwe == null) {
return new DateTimeFormatterBuilder()
.appendLiteral("-W")
// ES change, was .appendWeekOfWeekyear(2)
.appendFixedSignedDecimal(DateTimeFieldType.weekOfWeekyear(), 2)
.toFormatter();
}
return wwe;
}
private static DateTimeFormatter dayOfWeekElement() {
if (dwe == null) {
return new DateTimeFormatterBuilder()
.appendLiteral('-')
.appendDayOfWeek(1)
.toFormatter();
}
return dwe;
}
private static DateTimeFormatter dayOfYearElement() {
if (dye == null) {
return new DateTimeFormatterBuilder()
.appendLiteral('-')
// ES change, was .appendDayOfYear(3)
.appendFixedSignedDecimal(DateTimeFieldType.dayOfYear(), 3)
.toFormatter();
}
return dye;
}
private static DateTimeFormatter literalTElement() {
if (lte == null) {
return new DateTimeFormatterBuilder()
.appendLiteral('T')
.toFormatter();
}
return lte;
}
private static DateTimeFormatter hourElement() {
if (hde == null) {
return new DateTimeFormatterBuilder()
// ES change, was .appendHourOfDay(2)
.appendFixedSignedDecimal(DateTimeFieldType.hourOfDay(), 2)
.toFormatter();
}
return hde;
}
private static DateTimeFormatter minuteElement() {
if (mhe == null) {
return new DateTimeFormatterBuilder()
.appendLiteral(':')
// ES change, was .appendMinuteOfHour(2)
.appendFixedSignedDecimal(DateTimeFieldType.minuteOfHour(), 2)
.toFormatter();
}
return mhe;
}
private static DateTimeFormatter secondElement() {
if (sme == null) {
return new DateTimeFormatterBuilder()
.appendLiteral(':')
// ES change, was .appendSecondOfMinute(2)
.appendFixedSignedDecimal(DateTimeFieldType.secondOfMinute(), 2)
.toFormatter();
}
return sme;
}
private static DateTimeFormatter fractionElement() {
if (fse == null) {
return new DateTimeFormatterBuilder()
.appendLiteral('.')
// Support parsing up to nanosecond precision even though
// those extra digits will be dropped.
.appendFractionOfSecond(3, 9)
.toFormatter();
}
return fse;
}
private static DateTimeFormatter offsetElement() {
if (ze == null) {
return new DateTimeFormatterBuilder()
.appendTimeZoneOffset("Z", true, 2, 4)
.toFormatter();
}
return ze;
}
}
}
| apache-2.0 |
nmirasch/jbpm-console-ng | jbpm-wb-case-mgmt/jbpm-wb-case-mgmt-showcase/src/test/java/org/jbpm/workbench/cm/server/JGitFileSystemProviderTest.java | 2528 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.jbpm.workbench.cm.server;
import java.util.Properties;
import org.junit.Test;
import org.uberfire.commons.config.ConfigProperties;
import static org.uberfire.java.nio.fs.jgit.JGitFileSystemProviderConfiguration.*;
import static org.jbpm.workbench.cm.server.JGitFileSystemProvider.*;
import static org.junit.Assert.*;
public class JGitFileSystemProviderTest {
@Test
public void testDefaultProperties() {
final ConfigProperties gitPrefs = new ConfigProperties(new JGitFileSystemProvider.DefaultProperties());
assertEquals(false,
gitPrefs.get(GIT_DAEMON_ENABLED,
null).getBooleanValue());
assertEquals(false,
gitPrefs.get(GIT_SSH_ENABLED,
null).getBooleanValue());
assertEquals(NIOGIT_CASEAPP,
gitPrefs.get(GIT_NIO_DIR_NAME,
null).getValue());
}
@Test
public void testPropertiesOverride() {
final Properties configuredValues = new Properties();
configuredValues.put(GIT_DAEMON_ENABLED,
"true");
configuredValues.put(GIT_SSH_ENABLED,
"true");
configuredValues.put(GIT_NIO_DIR_NAME,
".niogit");
final ConfigProperties gitPrefs = new ConfigProperties(new JGitFileSystemProvider.DefaultProperties(configuredValues));
assertEquals(false,
gitPrefs.get(GIT_DAEMON_ENABLED,
null).getBooleanValue());
assertEquals(false,
gitPrefs.get(GIT_SSH_ENABLED,
null).getBooleanValue());
assertEquals(NIOGIT_CASEAPP,
gitPrefs.get(GIT_NIO_DIR_NAME,
null).getValue());
}
}
| apache-2.0 |
MicheleGuerriero/SeaCloudsPlatform | dashboard/src/test/java/eu/seaclouds/platform/dashboard/rest/SlaResourceTest.java | 2690 | /*
* Copyright 2014 SeaClouds
* Contact: SeaClouds
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.seaclouds.platform.dashboard.rest;
import eu.atos.sla.parser.data.GuaranteeTermsStatus;
import eu.atos.sla.parser.data.Violation;
import eu.atos.sla.parser.data.wsag.Agreement;
import eu.atos.sla.parser.data.wsag.GuaranteeTerm;
import eu.seaclouds.platform.dashboard.model.SeaCloudsApplicationData;
import eu.seaclouds.platform.dashboard.model.SeaCloudsApplicationDataStorage;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import static org.testng.Assert.assertNotNull;
public class SlaResourceTest extends AbstractResourceTest<SlaResource>{
SlaResource resource = new SlaResource(getSlaProxy());
SeaCloudsApplicationData applicationData;
@Override
@BeforeMethod
public void setUpMethod() throws Exception {
super.setUpMethod();
applicationData = new SeaCloudsApplicationData(getDam());
applicationData.setAgreementId(getAgreement());
SeaCloudsApplicationDataStorage.getInstance().addSeaCloudsApplicationData(applicationData);
}
@Test
public void testGetAgreement() throws Exception {
Agreement agreement = (Agreement) resource.getAgreement(applicationData.getSeaCloudsApplicationId()).getEntity();
assertNotNull(agreement);
}
@Test
public void testGetAgreementStatus() throws Exception {
GuaranteeTermsStatus entity = (GuaranteeTermsStatus) resource.getAgreementStatus(applicationData.getSeaCloudsApplicationId()).getEntity();
assertNotNull(entity);
}
@Test
public void testGetViolations() throws Exception {
Agreement agreement = (Agreement) resource.getAgreement(applicationData.getSeaCloudsApplicationId()).getEntity();
for(GuaranteeTerm term : agreement.getTerms().getAllTerms().getGuaranteeTerms()){
List<Violation> entity = (List<Violation>) resource.getViolations(applicationData.getSeaCloudsApplicationId(), term.getName()).getEntity();
assertNotNull(entity);
}
}
} | apache-2.0 |
OpenCollabZA/sakai | kernel/kernel-private/src/main/java/org/sakaiproject/hibernate/AssignableUUIDGenerator.java | 1692 | package org.sakaiproject.hibernate;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.UUIDGenerator;
import org.hibernate.type.Type;
import org.sakaiproject.component.api.ServerConfigurationService;
import lombok.Setter;
public class AssignableUUIDGenerator extends UUIDGenerator implements IdentifierGenerator, Configurable {
public static final String HIBERNATE_ASSIGNABLE_ID_CLASSES = "hibernate.assignable.id.classes";
@Setter
private static ServerConfigurationService serverConfigurationService;
@Override
public void configure(Type type, Properties params, Dialect d) throws MappingException {
super.configure(type, params, d);
}
@Override
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
if (serverConfigurationService != null) {
String[] classes = serverConfigurationService.getStrings(HIBERNATE_ASSIGNABLE_ID_CLASSES);
if (classes != null) {
String entityName = object.getClass().getName();
if (Arrays.asList(classes).contains(entityName)) {
final Serializable id = session.getEntityPersister(entityName, object).getIdentifier(object, session);
if (id != null) return id;
}
}
}
return super.generate(session, object);
}
}
| apache-2.0 |
yogidevendra/incubator-apex-malhar | examples/distributedistinct/src/main/java/org/apache/apex/examples/distributeddistinct/IntegerUniqueValueCountAppender.java | 3227 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.apex.examples.distributeddistinct;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;
import com.datatorrent.lib.algo.UniqueValueCount;
import com.datatorrent.lib.util.KeyValPair;
/**
* This operator demonstrates {@link UniqueValueCountAppender} given that the keys and values of the preceding {@link UniqueValueCount} operator
* are both integers. <br/>
* It will keep track of the number of all the unique values emitted per key since the application starts.
*
* @since 1.0.4
*/
public class IntegerUniqueValueCountAppender extends UniqueValueCountAppender<Integer>
{
@Override
public Object processResultSet(ResultSet resultSet)
{
Set<Integer> valSet = new HashSet<Integer>();
try {
while (resultSet.next()) {
valSet.add(resultSet.getInt(1));
}
return valSet;
} catch (SQLException e) {
throw new RuntimeException("while processing the result set", e);
}
}
@Override
protected void prepareGetStatement(PreparedStatement getStatement, Object key) throws SQLException
{
getStatement.setInt(1, (Integer)key);
}
@Override
protected void preparePutStatement(PreparedStatement putStatement, Object key, Object value) throws SQLException
{
@SuppressWarnings("unchecked")
Set<Integer> valueSet = (Set<Integer>)value;
for (Integer val : valueSet) {
@SuppressWarnings("unchecked")
Set<Integer> currentVals = (Set<Integer>)get(key);
if (!currentVals.contains(val)) {
batch = true;
putStatement.setInt(1, (Integer)key);
putStatement.setInt(2, val);
putStatement.setLong(3, windowID);
putStatement.addBatch();
}
}
}
@Override
public void endWindow()
{
try {
Statement stmt = store.getConnection().createStatement();
String keySetQuery = "SELECT DISTINCT col1 FROM " + tableName;
ResultSet resultSet = stmt.executeQuery(keySetQuery);
while (resultSet.next()) {
int val = resultSet.getInt(1);
@SuppressWarnings("unchecked")
Set<Integer> valSet = (Set<Integer>)cacheManager.get(val);
output.emit(new KeyValPair<Object, Object>(val, valSet.size()));
}
} catch (SQLException e) {
throw new RuntimeException("While emitting tuples", e);
}
}
}
| apache-2.0 |
danielmitterdorfer/elasticsearch | modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/SearchTemplateRequest.java | 5070 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.elasticsearch.action.search.template;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.script.ScriptService;
import java.io.IOException;
import java.util.Map;
import static org.elasticsearch.action.ValidateActions.addValidationError;
/**
* A request to execute a search based on a search template.
*/
public class SearchTemplateRequest extends ActionRequest<SearchTemplateRequest> implements IndicesRequest {
private SearchRequest request;
private boolean simulate = false;
private ScriptService.ScriptType scriptType;
private String script;
private Map<String, Object> scriptParams;
public SearchTemplateRequest() {
}
public SearchTemplateRequest(SearchRequest searchRequest) {
this.request = searchRequest;
}
public void setRequest(SearchRequest request) {
this.request = request;
}
public SearchRequest getRequest() {
return request;
}
public boolean isSimulate() {
return simulate;
}
public void setSimulate(boolean simulate) {
this.simulate = simulate;
}
public ScriptService.ScriptType getScriptType() {
return scriptType;
}
public void setScriptType(ScriptService.ScriptType scriptType) {
this.scriptType = scriptType;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public Map<String, Object> getScriptParams() {
return scriptParams;
}
public void setScriptParams(Map<String, Object> scriptParams) {
this.scriptParams = scriptParams;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (script == null || script.isEmpty()) {
validationException = addValidationError("template is missing", validationException);
}
if (scriptType == null) {
validationException = addValidationError("template's script type is missing", validationException);
}
if (simulate == false) {
if (request == null) {
validationException = addValidationError("search request is missing", validationException);
} else {
ActionRequestValidationException ex = request.validate();
if (ex != null) {
if (validationException == null) {
validationException = new ActionRequestValidationException();
}
validationException.addValidationErrors(ex.validationErrors());
}
}
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
request = in.readOptionalStreamable(SearchRequest::new);
simulate = in.readBoolean();
scriptType = ScriptService.ScriptType.readFrom(in);
script = in.readOptionalString();
if (in.readBoolean()) {
scriptParams = in.readMap();
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalStreamable(request);
out.writeBoolean(simulate);
ScriptService.ScriptType.writeTo(scriptType, out);
out.writeOptionalString(script);
boolean hasParams = scriptParams != null;
out.writeBoolean(hasParams);
if (hasParams) {
out.writeMap(scriptParams);
}
}
@Override
public String[] indices() {
return request != null ? request.indices() : Strings.EMPTY_ARRAY;
}
@Override
public IndicesOptions indicesOptions() {
return request != null ? request.indicesOptions() : SearchRequest.DEFAULT_INDICES_OPTIONS;
}
}
| apache-2.0 |
nutzam/nutz | src/org/nutz/dao/impl/sql/SqlTemplate.java | 18043 | package org.nutz.dao.impl.sql;
import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.nutz.castor.Castors;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.lang.Lang;
/**
* 仿照Spring JdbcTemplate实现nutz的SqlTemplate,方便sql的调用
*
* @author hzl7652(hzl7652@sina.com)
*/
public class SqlTemplate {
private Dao dao;
public SqlTemplate() {}
public SqlTemplate(Dao dao) {
setDao(dao);
}
public void setDao(Dao dao) {
this.dao = dao;
}
public Dao dao() {
return this.dao;
}
/**
* 执行一个SQL更新操作(如插入,更新或删除语句)。
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
*
* @return SQL 语句所影响的行数
*/
public int update(String sql, Map<String, Object> params) {
return update(sql, null, params);
}
/**
* 执行一个SQL更新操作(如插入,更新或删除语句)。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
*
* @return SQL 语句所影响的行数
*/
public int update(String sql, Map<String, Object> vars, Map<String, Object> params) {
Sql sqlObj = createSqlObj(sql, params);
execute(sqlObj, vars, params);
return sqlObj.getUpdateCount();
}
/**
* 执行SQL批量更新操作(如插入,更新或删除语句)。
*
* @param sql
* 包含变量占位符的SQL
* @param batchValues
* 批量更新参数集合
*
* @return SQL 语句所影响的行数
*/
public int batchUpdate(String sql, List<Map<String, Object>> batchValues) {
return batchUpdate(sql, null, batchValues);
}
/**
* 执行SQL批量更新操作(如插入,更新或删除语句)。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param batchValues
* 批量更新参数集合
*
* @return SQL 语句所影响的行数
*/
public int batchUpdate(String sql,
Map<String, Object> vars,
List<Map<String, Object>> batchValues) {
Sql sqlObj = null;
if (batchValues != null && batchValues.size() > 0) {
sqlObj = createSqlObj(sql, batchValues.get(0));
for (Map<String, Object> params : batchValues) {
Map<String, Object> newParams = paramProcess(params);
sqlObj.params().putAll(newParams);
sqlObj.addBatch();
}
dao.execute(sqlObj);
} else {
sqlObj = createSqlObj(sql, null);
execute(sqlObj, vars, null);
}
return sqlObj.getUpdateCount();
}
/**
* 执行一个SQL查询操作,结果为一个int形数值。
* <p>
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
*
* @return int数值,当查询为null时返回0
*/
public int queryForInt(String sql, Map<String, Object> params) {
return queryForInt(sql, null, params);
}
/**
* 执行一个SQL查询操作,结果为一个int形数值。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
*
* @return int数值,当查询为null时返回0
*/
public int queryForInt(String sql, Map<String, Object> vars, Map<String, Object> params) {
Sql sqlObj = createSqlObj(sql, params);
sqlObj.setCallback(Sqls.callback.integer());
execute(sqlObj, vars, params);
return sqlObj.getInt();
}
/**
* 执行一个SQL查询操作,结果为一个long形数值。
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
*
* @return long数值,当查询为null时返回0
*/
public long queryForLong(String sql, Map<String, Object> params) {
return queryForLong(sql, null, params);
}
/**
* 执行一个SQL查询操作,结果为一个long形数值。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
*
* @return long数值,当查询为null时返回0
*/
public long queryForLong(String sql, Map<String, Object> vars, Map<String, Object> params) {
Sql sqlObj = createSqlObj(sql, params);
sqlObj.setCallback(Sqls.callback.longValue());
execute(sqlObj, vars, params);
Long result = sqlObj.getObject(Long.class);
return result == null ? 0 : result;
}
/**
* 执行一个SQL查询操作,结果为给定对象类型的对象,适用于明确SQL查询结果的类型。
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map 无参数时,可为null
* @param classOfT
* 对象类型,SQL查询结果所对应的类型,如Date.class等
*
* @return 对象,无查询结果时返回null
*/
public <T> T queryForObject(String sql, Map<String, Object> params, Class<T> classOfT) {
return queryForObject(sql, null, params, classOfT);
}
/**
* 执行一个SQL查询操作,结果为给定对象类型的对象,适用于明确SQL查询结果的类型。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
* @param classOfT
* 对象类型,SQL查询结果所对应的类型,如Date.class等
*
* @return 对象,无查询结果时返回null
*/
public <T> T queryForObject(String sql,
Map<String, Object> vars,
Map<String, Object> params,
Class<T> classOfT) {
Sql sqlObj = createSqlObj(sql, params);
sqlObj.setCallback(new SqlCallback() {
public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
if (null != rs && rs.next())
return rs.getObject(1);
return null;
}
});
execute(sqlObj, vars, params);
return sqlObj.getObject(classOfT);
}
/**
* 执行一个SQL查询操作,结果为给定实体的对象。
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
* @param entity
* 实体类型,无参数时,可为null
*
* @return 对象,无查询结果时返回null
*/
public <T> T queryForObject(String sql, Map<String, Object> params, Entity<T> entity) {
return queryForObject(sql, null, params, entity);
}
/**
* 执行一个SQL查询操作,结果为给定实体的对象。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
* @param entity
* 实体类型
*
* @return 对象,无查询结果时返回null
*/
public <T> T queryForObject(String sql,
Map<String, Object> vars,
Map<String, Object> params,
Entity<T> entity) {
Sql sqlObj = createSqlObj(sql, params);
sqlObj.setCallback(Sqls.callback.entity());
sqlObj.setEntity(entity);
execute(sqlObj, vars, params);
return sqlObj.getObject(entity.getType());
}
/**
* 执行一个SQL查询操作,结果为Record的对象。
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
*
* @return Record对象,无查询结果时返回null
*/
public Record queryForRecord(String sql, Map<String, Object> params) {
return queryForRecord(sql, null, params);
}
/**
* 执行一个SQL查询操作,结果为Record的对象。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
* @return Record对象,无查询结果时返回null
*/
public Record queryForRecord(String sql, Map<String, Object> vars, Map<String, Object> params) {
Sql sqlObj = createSqlObj(sql, params);
sqlObj.setCallback(Sqls.callback.record());
execute(sqlObj, vars, params);
return sqlObj.getObject(Record.class);
}
/**
* 执行一个SQL查询操作,结果为一组对象。
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
* @param entity
* 对象类型,无参数时,可为null
*
* @return 对象列表,无查询结果时返回长度为0的List对象
*/
public <T> List<T> query(String sql, Map<String, Object> params, Entity<T> entity) {
return query(sql, null, params, entity);
}
/**
* 执行一个SQL查询操作,结果为一组对象。
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
* @param classOfT
* 对象类类
*
* @return 对象列表,无查询结果时返回长度为0的List对象
*/
public <T> List<T> query(String sql,
Map<String, Object> params,
Class<T> classOfT) {
return query(sql, null, params, dao.getEntity(classOfT));
}
/**
* 执行一个SQL查询操作,结果为一组对象。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
* @param entity
* 对象类型
*
* @return 对象列表,无查询结果时返回长度为0的List对象
*/
public <T> List<T> query(String sql,
Map<String, Object> vars,
Map<String, Object> params,
Entity<T> entity) {
Sql sqlObj = createSqlObj(sql, params);
sqlObj.setCallback(Sqls.callback.entities());
sqlObj.setEntity(entity);
execute(sqlObj, vars, params);
return sqlObj.getList(entity.getType());
}
/**
* 执行一个SQL查询操作,结果为一组对象。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
* @param classOfT
* 对象类型
*
* @return 对象列表,无查询结果时返回长度为0的List对象
*/
public <T> List<T> queryForList(String sql,
Map<String, Object> vars,
Map<String, Object> params,
final Class<T> classOfT) {
Sql sqlObj = createSqlObj(sql, params);
sqlObj.setCallback(new SqlCallback() {
public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
List<T> list = new ArrayList<T>();
while (rs.next()) {
T result = Castors.me().castTo(rs.getObject(1), classOfT);
list.add(result);
}
return list;
}
});
execute(sqlObj, vars, params);
return sqlObj.getList(classOfT);
}
/**
* 执行一个SQL查询操作,结果为Record对象列表。
*
* @param sql
* 包含变量占位符的SQL
* @param vars
* 变量map,无参数时,可为null
* @param params
* 参数map,无参数时,可为null
*
* @return Record列表,无查询结果时返回长度为0的List对象
*/
public List<Record> queryRecords(String sql,
Map<String, Object> vars,
Map<String, Object> params) {
Sql sqlObj = createSqlObj(sql, params);
sqlObj.setCallback(Sqls.callback.records());
execute(sqlObj, vars, params);
return sqlObj.getList(Record.class);
}
/**
* 设置sql参数并执行sql。
*/
private void execute(Sql sqlObj, Map<String, Object> vars, Map<String, Object> params) {
if (vars != null)
sqlObj.vars().putAll(vars);
if (params != null) {
Map<String, Object> newParams = paramProcess(params);
sqlObj.params().putAll(newParams);
}
dao().execute(sqlObj);
}
/**
* 创建Sql对象。
* <p>
* 在这里处理Array Collection类型参数,方便SQL IN 表达式的设置
*
* @param sql
* 包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
*
* @return Sql对象
*/
private Sql createSqlObj(String sql, Map<String, Object> params) {
if (params == null)
return Sqls.create(sql);
String newSql = sqlProcess(sql, params);
return Sqls.create(newSql);
}
/**
* 将Array Collection类型参数对应的sql占位符进行处理
*
* @param originSql
* 原包含变量占位符的SQL
* @param params
* 参数map,无参数时,可为null
*
* @return 包含处理IN表达式的sql
*/
private String sqlProcess(String originSql, Map<String, Object> params) {
if (params == null || params.size() == 0)
return originSql;
String newSql = originSql;
for (Entry<String, Object> entry : params.entrySet()) {
String paramName = entry.getKey();
Object paramObj = entry.getValue();
if (paramObj.getClass().isArray()) {
String inSqlExp = inSqlProcess(paramName, paramObj);
newSql = newSql.replaceAll("@" + paramName, inSqlExp);
}
if (paramObj instanceof Collection) {
Collection<?> collection = (Collection<?>) paramObj;
Object[] paramVals = Lang.collection2array(collection);
String inSqlExp = inSqlProcess(paramName, paramVals);
newSql = newSql.replaceAll("@" + paramName, inSqlExp);
}
}
return newSql;
}
/**
* sql参数处理,在这里处理Array Collection类型参数,方便SQL IN 表达式的设置
*
* @param params
* 参数map,无参数时,可为null
*
* @return 包含处理IN表达式的sql
*/
private Map<String, Object> paramProcess(Map<String, Object> params) {
if (params == null || params.size() == 0)
return null;
Map<String, Object> newParams = new HashMap<String, Object>(params);
for (Entry<String, Object> entry : params.entrySet()) {
String paramName = entry.getKey();
Object paramObj = entry.getValue();
if (paramObj.getClass().isArray()) {
inParamProcess(paramName, paramObj, newParams);
newParams.remove(paramName);
}
if (paramObj instanceof Collection) {
Collection<?> collection = (Collection<?>) paramObj;
Object[] paramVals = Lang.collection2array(collection);
inParamProcess(paramName, paramVals, newParams);
newParams.remove(paramName);
}
}
return newParams;
}
private static String inSqlProcess(String paramName, Object paramObj) {
int len = Array.getLength(paramObj);
StringBuilder inSqlExp = new StringBuilder();
for (int i = 0; i < len; i++) {
inSqlExp.append("@").append(paramName).append(i).append(",");
}
inSqlExp.deleteCharAt(inSqlExp.length() - 1);
return inSqlExp.toString();
}
private static void inParamProcess(String paramName, Object paramObj, Map<String, Object> newParams) {
int len = Array.getLength(paramObj);
for (int i = 0; i < len; i++) {
String inParamName = paramName + i;
newParams.put(inParamName, Array.get(paramObj, i));
}
}
}
| apache-2.0 |
fazerish/hibernate-validator | engine/src/test/java/org/hibernate/validator/test/internal/engine/valuehandling/model/Account.java | 444 | /*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.test.internal.engine.valuehandling.model;
import javax.validation.Valid;
/**
* @author Gunnar Morling
*/
public class Account {
@Valid
private final Customer customer = new Customer();
}
| apache-2.0 |
yush1ga/pulsar | pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongHashMapTest.java | 13097 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.pulsar.common.util.collections;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.LongFunction;
import org.apache.pulsar.common.util.collections.ConcurrentLongHashMap;
import org.testng.annotations.Test;
import com.google.common.collect.Lists;
public class ConcurrentLongHashMapTest {
@Test
public void testConstructor() {
try {
new ConcurrentLongHashMap<String>(0);
fail("should have thrown exception");
} catch (IllegalArgumentException e) {
// ok
}
try {
new ConcurrentLongHashMap<String>(16, 0);
fail("should have thrown exception");
} catch (IllegalArgumentException e) {
// ok
}
try {
new ConcurrentLongHashMap<String>(4, 8);
fail("should have thrown exception");
} catch (IllegalArgumentException e) {
// ok
}
}
@Test
public void simpleInsertions() {
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>(16);
assertTrue(map.isEmpty());
assertNull(map.put(1, "one"));
assertFalse(map.isEmpty());
assertNull(map.put(2, "two"));
assertNull(map.put(3, "three"));
assertEquals(map.size(), 3);
assertEquals(map.get(1), "one");
assertEquals(map.size(), 3);
assertEquals(map.remove(1), "one");
assertEquals(map.size(), 2);
assertEquals(map.get(1), null);
assertEquals(map.get(5), null);
assertEquals(map.size(), 2);
assertNull(map.put(1, "one"));
assertEquals(map.size(), 3);
assertEquals(map.put(1, "uno"), "one");
assertEquals(map.size(), 3);
}
@Test
public void testRemove() {
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>();
assertTrue(map.isEmpty());
assertNull(map.put(1, "one"));
assertFalse(map.isEmpty());
assertFalse(map.remove(0, "zero"));
assertFalse(map.remove(1, "uno"));
assertFalse(map.isEmpty());
assertTrue(map.remove(1, "one"));
assertTrue(map.isEmpty());
}
@Test
public void testNegativeUsedBucketCount() {
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>(16, 1);
map.put(0, "zero");
assertEquals(1, map.getUsedBucketCount());
map.put(0, "zero1");
assertEquals(1, map.getUsedBucketCount());
map.remove(0);
assertEquals(0, map.getUsedBucketCount());
map.remove(0);
assertEquals(0, map.getUsedBucketCount());
}
@Test
public void testRehashing() {
int n = 16;
ConcurrentLongHashMap<Integer> map = new ConcurrentLongHashMap<>(n / 2, 1);
assertEquals(map.capacity(), n);
assertEquals(map.size(), 0);
for (int i = 0; i < n; i++) {
map.put(i, i);
}
assertEquals(map.capacity(), 2 * n);
assertEquals(map.size(), n);
}
@Test
public void testRehashingWithDeletes() {
int n = 16;
ConcurrentLongHashMap<Integer> map = new ConcurrentLongHashMap<>(n / 2, 1);
assertEquals(map.capacity(), n);
assertEquals(map.size(), 0);
for (int i = 0; i < n / 2; i++) {
map.put(i, i);
}
for (int i = 0; i < n / 2; i++) {
map.remove(i);
}
for (int i = n; i < (2 * n); i++) {
map.put(i, i);
}
assertEquals(map.capacity(), 2 * n);
assertEquals(map.size(), n);
}
@Test
public void concurrentInsertions() throws Throwable {
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>();
ExecutorService executor = Executors.newCachedThreadPool();
final int nThreads = 16;
final int N = 100_000;
String value = "value";
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < nThreads; i++) {
final int threadIdx = i;
futures.add(executor.submit(() -> {
Random random = new Random();
for (int j = 0; j < N; j++) {
long key = random.nextLong();
// Ensure keys are uniques
key -= key % (threadIdx + 1);
map.put(key, value);
}
}));
}
for (Future<?> future : futures) {
future.get();
}
assertEquals(map.size(), N * nThreads);
executor.shutdown();
}
@Test
public void concurrentInsertionsAndReads() throws Throwable {
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>();
ExecutorService executor = Executors.newCachedThreadPool();
final int nThreads = 16;
final int N = 100_000;
String value = "value";
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < nThreads; i++) {
final int threadIdx = i;
futures.add(executor.submit(() -> {
Random random = new Random();
for (int j = 0; j < N; j++) {
long key = random.nextLong();
// Ensure keys are uniques
key -= key % (threadIdx + 1);
map.put(key, value);
}
}));
}
for (Future<?> future : futures) {
future.get();
}
assertEquals(map.size(), N * nThreads);
executor.shutdown();
}
@Test
public void testIteration() {
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>();
assertEquals(map.keys(), Collections.emptyList());
assertEquals(map.values(), Collections.emptyList());
map.put(0, "zero");
assertEquals(map.keys(), Lists.newArrayList(0l));
assertEquals(map.values(), Lists.newArrayList("zero"));
map.remove(0);
assertEquals(map.keys(), Collections.emptyList());
assertEquals(map.values(), Collections.emptyList());
map.put(0, "zero");
map.put(1, "one");
map.put(2, "two");
List<Long> keys = map.keys();
keys.sort(null);
assertEquals(keys, Lists.newArrayList(0l, 1l, 2l));
List<String> values = map.values();
values.sort(null);
assertEquals(values, Lists.newArrayList("one", "two", "zero"));
map.put(1, "uno");
keys = map.keys();
keys.sort(null);
assertEquals(keys, Lists.newArrayList(0l, 1l, 2l));
values = map.values();
values.sort(null);
assertEquals(values, Lists.newArrayList("two", "uno", "zero"));
map.clear();
assertTrue(map.isEmpty());
}
@Test
public void testHashConflictWithDeletion() {
final int Buckets = 16;
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>(Buckets, 1);
// Pick 2 keys that fall into the same bucket
long key1 = 1;
long key2 = 27;
int bucket1 = ConcurrentLongHashMap.signSafeMod(ConcurrentLongHashMap.hash(key1), Buckets);
int bucket2 = ConcurrentLongHashMap.signSafeMod(ConcurrentLongHashMap.hash(key2), Buckets);
assertEquals(bucket1, bucket2);
assertEquals(map.put(key1, "value-1"), null);
assertEquals(map.put(key2, "value-2"), null);
assertEquals(map.size(), 2);
assertEquals(map.remove(key1), "value-1");
assertEquals(map.size(), 1);
assertEquals(map.put(key1, "value-1-overwrite"), null);
assertEquals(map.size(), 2);
assertEquals(map.remove(key1), "value-1-overwrite");
assertEquals(map.size(), 1);
assertEquals(map.put(key2, "value-2-overwrite"), "value-2");
assertEquals(map.get(key2), "value-2-overwrite");
assertEquals(map.size(), 1);
assertEquals(map.remove(key2), "value-2-overwrite");
assertTrue(map.isEmpty());
}
@Test
public void testPutIfAbsent() {
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>();
assertEquals(map.putIfAbsent(1, "one"), null);
assertEquals(map.get(1), "one");
assertEquals(map.putIfAbsent(1, "uno"), "one");
assertEquals(map.get(1), "one");
}
@Test
public void testComputeIfAbsent() {
ConcurrentLongHashMap<Integer> map = new ConcurrentLongHashMap<>(16, 1);
AtomicInteger counter = new AtomicInteger();
LongFunction<Integer> provider = new LongFunction<Integer>() {
public Integer apply(long key) {
return counter.getAndIncrement();
}
};
assertEquals(map.computeIfAbsent(0, provider).intValue(), 0);
assertEquals(map.get(0).intValue(), 0);
assertEquals(map.computeIfAbsent(1, provider).intValue(), 1);
assertEquals(map.get(1).intValue(), 1);
assertEquals(map.computeIfAbsent(1, provider).intValue(), 1);
assertEquals(map.get(1).intValue(), 1);
assertEquals(map.computeIfAbsent(2, provider).intValue(), 2);
assertEquals(map.get(2).intValue(), 2);
}
final static int Iterations = 1;
final static int ReadIterations = 10000;
final static int N = 100_000;
public void benchConcurrentLongHashMap() throws Exception {
ConcurrentLongHashMap<String> map = new ConcurrentLongHashMap<>(N, 1);
for (long i = 0; i < Iterations; i++) {
for (int j = 0; j < N; j++) {
map.put(i, "value");
}
for (long h = 0; h < ReadIterations; h++) {
for (int j = 0; j < N; j++) {
map.get(i);
}
}
for (int j = 0; j < N; j++) {
map.remove(i);
}
}
}
public void benchConcurrentHashMap() throws Exception {
ConcurrentHashMap<Long, String> map = new ConcurrentHashMap<Long, String>(N, 0.66f, 1);
for (long i = 0; i < Iterations; i++) {
for (int j = 0; j < N; j++) {
map.put(i, "value");
}
for (long h = 0; h < ReadIterations; h++) {
for (int j = 0; j < N; j++) {
map.get(i);
}
}
for (int j = 0; j < N; j++) {
map.remove(i);
}
}
}
void benchHashMap() throws Exception {
HashMap<Long, String> map = new HashMap<Long, String>(N, 0.66f);
for (long i = 0; i < Iterations; i++) {
for (int j = 0; j < N; j++) {
map.put(i, "value");
}
for (long h = 0; h < ReadIterations; h++) {
for (int j = 0; j < N; j++) {
map.get(i);
}
}
for (int j = 0; j < N; j++) {
map.remove(i);
}
}
}
public static void main(String[] args) throws Exception {
ConcurrentLongHashMapTest t = new ConcurrentLongHashMapTest();
long start = System.nanoTime();
t.benchConcurrentLongHashMap();
long end = System.nanoTime();
System.out.println("CLHM: " + TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
start = System.nanoTime();
t.benchHashMap();
end = System.nanoTime();
System.out.println("HM: " + TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
start = System.nanoTime();
t.benchConcurrentHashMap();
end = System.nanoTime();
System.out.println("CHM: " + TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
}
}
| apache-2.0 |
lorban/terracotta-platform | management/cluster-topology/src/test/java/org/terracotta/management/model/cluster/AbstractTest.java | 5586 | /*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.terracotta.management.model.cluster;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.terracotta.management.model.capabilities.Capability;
import org.terracotta.management.model.capabilities.DefaultCapability;
import org.terracotta.management.model.capabilities.context.CapabilityContext;
import org.terracotta.management.model.context.ContextContainer;
import java.util.function.Supplier;
/**
* @author Mathieu Carbou
*/
@RunWith(JUnit4.class)
public abstract class AbstractTest {
protected Cluster cluster1;
protected Cluster cluster2;
protected ServerEntity ehcache_server_entity;
protected Capability action;
protected ContextContainer serverContextContainer;
protected ContextContainer clientContextContainer;
protected Client client;
@Before
public void createClusters() {
action = new DefaultCapability("ActionCapability", new CapabilityContext());
clientContextContainer = new ContextContainer("cacheManagerName", "cache-manager-1", new ContextContainer("cacheName", "my-cache"));
serverContextContainer = new ContextContainer("entityName", "ehcache-entity-name-1");
Supplier<ServerEntity> serverEntitySupplier = () -> {
ServerEntity s = ServerEntity.create("ehcache-entity-name-1", "org.ehcache.clustered.client.internal.EhcacheClientEntity");
s.setManagementRegistry(ManagementRegistry.create(serverContextContainer)
.addCapabilities(action));
return s;
};
Supplier<Client> clientSupplier = () -> {
Client c = Client.create("12345@127.0.0.1:ehcache:uid");
c.setManagementRegistry(ManagementRegistry.create(clientContextContainer)
.addCapability(action));
return c;
};
cluster1 = Cluster.create();
Stripe stripe11 = Stripe.create("stripe-1");
cluster1.addStripe(stripe11);
Server server111 = Server.create("server-1")
.setHostName("hostname-1")
.setBindAddress("0.0.0.0")
.setBindPort(8881)
.setState(Server.State.ACTIVE);
stripe11.addServer(server111);
server111.addServerEntity(ehcache_server_entity = serverEntitySupplier.get());
stripe11.addServer(Server.create("server-2")
.setHostName("hostname-2")
.setBindAddress("0.0.0.0")
.setBindPort(8881)
.setState(Server.State.PASSIVE));
Stripe stripe12 = Stripe.create("stripe-2");
cluster1.addStripe(stripe12);
Server server121 = Server.create("server-1")
.setHostName("hostname-3")
.setBindAddress("0.0.0.0")
.setBindPort(8881)
.setState(Server.State.ACTIVE);
stripe12.addServer(server121);
server121.addServerEntity(serverEntitySupplier.get());
stripe12.addServer(Server.create("server-2")
.setHostName("hostname-4")
.setBindAddress("0.0.0.0")
.setBindPort(8881)
.setState(Server.State.PASSIVE));
cluster1.addClient(client = clientSupplier.get());
client.addConnection(Connection.create(
"uid",
cluster1.getStripe("stripe-1").get().getServerByName("server-1").get(),
Endpoint.create("10.10.10.10", 3456)));
client.addConnection(Connection.create(
"uid",
cluster1.getStripe("stripe-2").get().getServerByName("server-1").get(),
Endpoint.create("10.10.10.10", 3457)));
cluster2 = Cluster.create();
Stripe stripe21 = Stripe.create("stripe-1");
cluster2.addStripe(stripe21);
Server server211 = Server.create("server-1")
.setHostName("hostname-1")
.setBindAddress("0.0.0.0")
.setBindPort(8881)
.setState(Server.State.ACTIVE);
stripe21.addServer(server211);
server211.addServerEntity(serverEntitySupplier.get());
stripe21.addServer(Server.create("server-2")
.setHostName("hostname-2")
.setBindAddress("0.0.0.0")
.setBindPort(8881)
.setState(Server.State.PASSIVE));
Stripe stripe22 = Stripe.create("stripe-2");
cluster2.addStripe(stripe22);
Server server221 = Server.create("server-1")
.setHostName("hostname-3")
.setBindAddress("0.0.0.0")
.setBindPort(8881)
.setState(Server.State.ACTIVE);
stripe22.addServer(server221);
server221.addServerEntity(serverEntitySupplier.get());
stripe22.addServer(Server.create("server-2")
.setHostName("hostname-4")
.setBindAddress("0.0.0.0")
.setBindPort(8881)
.setState(Server.State.PASSIVE));
cluster2.addClient(clientSupplier.get());
Client client2 = cluster2.getClient("12345@127.0.0.1:ehcache:uid").get();
client2.addConnection(Connection.create(
"uid",
cluster2.getStripe("stripe-1").get().getServerByName("server-1").get(),
Endpoint.create("10.10.10.10", 3456)));
client2.addConnection(Connection.create(
"uid",
cluster2.getStripe("stripe-2").get().getServerByName("server-1").get(),
Endpoint.create("10.10.10.10", 3457)));
}
}
| apache-2.0 |
goodwinnk/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/intention/AddExplicitTypeArgumentsIntentionTest.java | 4583 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInsight.intention;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
public class AddExplicitTypeArgumentsIntentionTest extends JavaCodeInsightFixtureTestCase {
public void testNoStaticQualifier() {
doTest("class Test {\n" +
" static {\n" +
" String s = fo<caret>o(\"\");\n" +
" }\n" +
" static <T> T foo(T t) {\n" +
" return t;\n" +
" }\n" +
"}",
"class Test {\n" +
" static {\n" +
" String s = Test.<String>foo(\"\");\n" +
" }\n" +
" static <T> T foo(T t) {\n" +
" return t;\n" +
" }\n" +
"}");
}
public void testNoThisQualifier() {
doTest("class Test {\n" +
" {\n" +
" String s = fo<caret>o(\"\");\n" +
" }\n" +
" <T> T foo(T t) {\n" +
" return t;\n" +
" }\n" +
"}",
"class Test {\n" +
" {\n" +
" String s = this.<String>foo(\"\");\n" +
" }\n" +
" <T> T foo(T t) {\n" +
" return t;\n" +
" }\n" +
"}");
}
public void testInferredCapturedWildcard() {
doTest("class Test {\n" +
" static void m(java.util.List<? extends String> l) {\n" +
" fo<caret>o(l.get(0));\n" +
" }\n" +
" static <T> void foo(T t) {\n" +
" }\n" +
"}",
"class Test {\n" +
" static void m(java.util.List<? extends String> l) {\n" +
" Test.<String>foo(l.get(0));\n" +
" }\n" +
" static <T> void foo(T t) {\n" +
" }\n" +
"}");
}
public void testNotAvailableWhenRawTypeInferred() {
myFixture.configureByText("a.java", "import java.util.List;\n" +
"class Foo {\n" +
" <T> List<T> getList() {return null;}\n" +
" {\n" +
" List l;\n" +
" l = get<caret>List();\n" +
" }\n" +
"}");
final IntentionAction intentionAction = myFixture.getAvailableIntention(CodeInsightBundle.message("intention.add.explicit.type.arguments.family"));
assertNull(intentionAction);
}
public void testNotAvailableWhenWildcardInferred() {
myFixture.configureByText("a.java", "import java.util.stream.*;\n" +
"\n" +
"public class JDbQueryElement {\n" +
"\n" +
" void m(final Stream<String> stringStream) {\n" +
" stringStream.c<caret>ollect(Collectors.joining(\", \"));\n" +
" }\n" +
"\n" +
"}");
final IntentionAction intentionAction = myFixture.getAvailableIntention(CodeInsightBundle.message("intention.add.explicit.type.arguments.family"));
assertNull(intentionAction);
}
private void doTest(String beforeText, String afterText) {
myFixture.configureByText("a.java", beforeText);
final IntentionAction intentionAction = myFixture.findSingleIntention(CodeInsightBundle.message("intention.add.explicit.type.arguments.family"));
assertNotNull(intentionAction);
myFixture.launchAction(intentionAction);
myFixture.checkResult(afterText);
}
}
| apache-2.0 |
rockmkd/datacollector | sso/src/main/java/com/streamsets/lib/security/http/PrincipalCache.java | 2301 | /*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.lib.security.http;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
public class PrincipalCache {
private static final Object DUMMY = new Object();
private final Cache<String, SSOPrincipal> principalsCache;
private final Cache<String, Object> invalidatedTokens;
public PrincipalCache(long principalCacheExpirationMillis, long invalidatedTokensCacheExpirationMillis) {
principalsCache =
CacheBuilder.newBuilder().expireAfterWrite(principalCacheExpirationMillis, TimeUnit.MILLISECONDS).build();
invalidatedTokens = CacheBuilder
.newBuilder()
.expireAfterWrite(invalidatedTokensCacheExpirationMillis, TimeUnit.MILLISECONDS)
.build();
}
public SSOPrincipal get(String autToken) {
return principalsCache.getIfPresent(autToken);
}
public boolean isInvalid(String authToken) {
return invalidatedTokens.getIfPresent(authToken) != null;
}
public synchronized boolean put(String authToken, SSOPrincipal principal) {
boolean cached = false;
if (invalidatedTokens.getIfPresent(authToken) == null && principalsCache.getIfPresent(authToken) == null) {
principalsCache.put(authToken, principal);
cached = true;
}
return cached;
}
public synchronized boolean invalidate(String authToken) {
boolean invalidate = false;
if (!isInvalid(authToken)) {
principalsCache.invalidate(authToken);
invalidatedTokens.put(authToken, DUMMY);
invalidate = true;
}
return invalidate;
}
public void clear (){
invalidatedTokens.invalidateAll();
principalsCache.invalidateAll();
}
}
| apache-2.0 |
hurricup/intellij-community | plugins/git4idea/src/git4idea/repo/GitRepositoryImpl.java | 7089 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.repo;
import com.intellij.dvcs.repo.RepositoryImpl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.GitLocalBranch;
import git4idea.GitUtil;
import git4idea.GitVcs;
import git4idea.branch.GitBranchesCollection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Collection;
import static com.intellij.util.ObjectUtils.assertNotNull;
public class GitRepositoryImpl extends RepositoryImpl implements GitRepository {
@NotNull private final GitVcs myVcs;
@NotNull private final GitRepositoryReader myReader;
@NotNull private final VirtualFile myGitDir;
@NotNull private final GitRepositoryFiles myRepositoryFiles;
@Nullable private final GitUntrackedFilesHolder myUntrackedFilesHolder;
@NotNull private volatile GitRepoInfo myInfo;
private GitRepositoryImpl(@NotNull VirtualFile rootDir,
@NotNull VirtualFile gitDir,
@NotNull Project project,
@NotNull Disposable parentDisposable,
final boolean light) {
super(project, rootDir, parentDisposable);
myVcs = assertNotNull(GitVcs.getInstance(project));
myGitDir = gitDir;
myRepositoryFiles = GitRepositoryFiles.getInstance(gitDir);
myReader = new GitRepositoryReader(myRepositoryFiles);
myInfo = readRepoInfo();
if (!light) {
myUntrackedFilesHolder = new GitUntrackedFilesHolder(this, myRepositoryFiles);
Disposer.register(this, myUntrackedFilesHolder);
}
else {
myUntrackedFilesHolder = null;
}
}
@NotNull
public static GitRepository getInstance(@NotNull VirtualFile root,
@NotNull Project project,
boolean listenToRepoChanges) {
return getInstance(root, assertNotNull(GitUtil.findGitDir(root)), project, listenToRepoChanges);
}
@NotNull
public static GitRepository getInstance(@NotNull VirtualFile root,
@NotNull VirtualFile gitDir,
@NotNull Project project,
boolean listenToRepoChanges) {
GitRepositoryImpl repository = new GitRepositoryImpl(root, gitDir, project, project, !listenToRepoChanges);
if (listenToRepoChanges) {
repository.getUntrackedFilesHolder().setupVfsListener(project);
repository.setupUpdater();
notifyListenersAsync(repository);
}
return repository;
}
private void setupUpdater() {
GitRepositoryUpdater updater = new GitRepositoryUpdater(this, myRepositoryFiles);
Disposer.register(this, updater);
}
@Deprecated
@NotNull
@Override
public VirtualFile getGitDir() {
return myGitDir;
}
@NotNull
@Override
public GitRepositoryFiles getRepositoryFiles() {
return myRepositoryFiles;
}
@Override
@NotNull
public GitUntrackedFilesHolder getUntrackedFilesHolder() {
if (myUntrackedFilesHolder == null) {
throw new IllegalStateException("Using untracked files holder with light git repository instance " + this);
}
return myUntrackedFilesHolder;
}
@Override
@NotNull
public GitRepoInfo getInfo() {
return myInfo;
}
@Override
@Nullable
public GitLocalBranch getCurrentBranch() {
return myInfo.getCurrentBranch();
}
@Nullable
@Override
public String getCurrentRevision() {
return myInfo.getCurrentRevision();
}
@NotNull
@Override
public State getState() {
return myInfo.getState();
}
@Nullable
@Override
public String getCurrentBranchName() {
GitLocalBranch currentBranch = getCurrentBranch();
return currentBranch == null ? null : currentBranch.getName();
}
@NotNull
@Override
public GitVcs getVcs() {
return myVcs;
}
/**
* @return local and remote branches in this repository.
*/
@Override
@NotNull
public GitBranchesCollection getBranches() {
GitRepoInfo info = myInfo;
return new GitBranchesCollection(info.getLocalBranchesWithHashes(), info.getRemoteBranchesWithHashes());
}
@Override
@NotNull
public Collection<GitRemote> getRemotes() {
return myInfo.getRemotes();
}
@Override
@NotNull
public Collection<GitBranchTrackInfo> getBranchTrackInfos() {
return myInfo.getBranchTrackInfos();
}
@Override
public boolean isRebaseInProgress() {
return getState() == State.REBASING;
}
@Override
public boolean isOnBranch() {
return getState() != State.DETACHED && getState() != State.REBASING;
}
@Override
public boolean isFresh() {
return getCurrentRevision() == null;
}
@Override
public void update() {
GitRepoInfo previousInfo = myInfo;
myInfo = readRepoInfo();
notifyIfRepoChanged(this, previousInfo, myInfo);
}
@NotNull
private GitRepoInfo readRepoInfo() {
File configFile = myRepositoryFiles.getConfigFile();
GitConfig config = GitConfig.read(configFile);
Collection<GitRemote> remotes = config.parseRemotes();
GitBranchState state = myReader.readState(remotes);
Collection<GitBranchTrackInfo> trackInfos = config.parseTrackInfos(state.getLocalBranches().keySet(), state.getRemoteBranches().keySet());
return new GitRepoInfo(state.getCurrentBranch(), state.getCurrentRevision(), state.getState(), remotes,
state.getLocalBranches(), state.getRemoteBranches(), trackInfos);
}
private static void notifyIfRepoChanged(@NotNull final GitRepository repository, @NotNull GitRepoInfo previousInfo, @NotNull GitRepoInfo info) {
if (!repository.getProject().isDisposed() && !info.equals(previousInfo)) {
notifyListenersAsync(repository);
}
}
private static void notifyListenersAsync(@NotNull final GitRepository repository) {
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
Project project = repository.getProject();
if (!project.isDisposed()) {
project.getMessageBus().syncPublisher(GIT_REPO_CHANGE).repositoryChanged(repository);
}
}
});
}
@NotNull
@Override
public String toLogString() {
return "GitRepository " + getRoot() + " : " + myInfo;
}
}
| apache-2.0 |
lgobinath/carbon-analytics-common | components/event-publisher/event-output-adapters/org.wso2.carbon.event.output.adapter.websocket.local/org.wso2.carbon.event.output.adapter.websocket.endpoint/src/main/java/SubscriptionEndpoint.java | 2747 | /*
* Copyright (c) 2005-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.event.output.adapter.websocket.local.WebsocketLocalOutputCallbackRegisterService;
import javax.websocket.CloseReason;
import javax.websocket.Session;
public class SubscriptionEndpoint {
protected WebsocketLocalOutputCallbackRegisterService websocketLocalOutputCallbackRegisterService;
private static final Log log = LogFactory.getLog(SubscriptionEndpoint.class);
public SubscriptionEndpoint() {
websocketLocalOutputCallbackRegisterService = (WebsocketLocalOutputCallbackRegisterService) PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getOSGiService(WebsocketLocalOutputCallbackRegisterService.class, null);
}
public void onClose (Session session, CloseReason reason, String adaptorName, int tenantId) {
if (log.isDebugEnabled()) {
log.debug("Closing a WebSocket due to "+reason.getReasonPhrase()+", for session ID:"+session.getId()+", for request URI - "+session.getRequestURI());
}
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
websocketLocalOutputCallbackRegisterService.unsubscribe(adaptorName, session);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
public void onError (Session session, Throwable throwable, String adaptorName, int tenantId) {
log.error("Error occurred in session ID: "+session.getId()+", for request URI - "+session.getRequestURI()+", "+throwable.getMessage(),throwable);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
websocketLocalOutputCallbackRegisterService.unsubscribe(adaptorName, session);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
| apache-2.0 |
baishuo/hbase-1.0.0-cdh5.4.7_baishuo | hbase-common/src/test/java/org/apache/hadoop/hbase/types/TestUnion2.java | 4281 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.hadoop.hbase.types;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Order;
import org.apache.hadoop.hbase.util.PositionedByteRange;
import org.apache.hadoop.hbase.util.SimplePositionedMutableByteRange;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(SmallTests.class)
public class TestUnion2 {
/**
* An example <code>Union</code>
*/
private static class SampleUnion1 extends Union2<Integer, String> {
private static final byte IS_INTEGER = 0x00;
private static final byte IS_STRING = 0x01;
public SampleUnion1() {
super(new RawInteger(), new RawStringTerminated(Order.DESCENDING, "."));
}
@Override
public int skip(PositionedByteRange src) {
switch (src.get()) {
case IS_INTEGER:
return 1 + typeA.skip(src);
case IS_STRING:
return 1 + typeB.skip(src);
default:
throw new IllegalArgumentException("Unrecognized encoding format.");
}
}
@Override
public Object decode(PositionedByteRange src) {
switch (src.get()) {
case IS_INTEGER:
return typeA.decode(src);
case IS_STRING:
return typeB.decode(src);
default:
throw new IllegalArgumentException("Unrecognized encoding format.");
}
}
@Override
public int encodedLength(Object val) {
Integer i = null;
String s = null;
try {
i = (Integer) val;
} catch (ClassCastException e) {}
try {
s = (String) val;
} catch (ClassCastException e) {}
if (null != i) return 1 + typeA.encodedLength(i);
if (null != s) return 1 + typeB.encodedLength(s);
throw new IllegalArgumentException("val is not a valid member of this union.");
}
@Override
public int encode(PositionedByteRange dst, Object val) {
Integer i = null;
String s = null;
try {
i = (Integer) val;
} catch (ClassCastException e) {}
try {
s = (String) val;
} catch (ClassCastException e) {}
if (null != i) {
dst.put(IS_INTEGER);
return 1 + typeA.encode(dst, i);
} else if (null != s) {
dst.put(IS_STRING);
return 1 + typeB.encode(dst, s);
}
else
throw new IllegalArgumentException("val is not of a supported type.");
}
}
@Test
public void testEncodeDecode() {
Integer intVal = Integer.valueOf(10);
String strVal = "hello";
PositionedByteRange buff = new SimplePositionedMutableByteRange(10);
SampleUnion1 type = new SampleUnion1();
type.encode(buff, intVal);
buff.setPosition(0);
assertTrue(0 == intVal.compareTo(type.decodeA(buff)));
buff.setPosition(0);
type.encode(buff, strVal);
buff.setPosition(0);
assertTrue(0 == strVal.compareTo(type.decodeB(buff)));
}
@Test
public void testSkip() {
Integer intVal = Integer.valueOf(10);
String strVal = "hello";
PositionedByteRange buff = new SimplePositionedMutableByteRange(10);
SampleUnion1 type = new SampleUnion1();
int len = type.encode(buff, intVal);
buff.setPosition(0);
assertEquals(len, type.skip(buff));
buff.setPosition(0);
len = type.encode(buff, strVal);
buff.setPosition(0);
assertEquals(len, type.skip(buff));
}
}
| apache-2.0 |
objectiser/camel | components/camel-netty/src/test/java/org/apache/camel/component/netty/LogCaptureTest.java | 1346 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.camel.component.netty;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Assert;
import org.junit.Test;
/**
* This test ensures LogCaptureAppender is configured properly
*/
public class LogCaptureTest {
@Test
public void testCapture() {
InternalLoggerFactory.getInstance(ResourceLeakDetector.class).error("testError");
Assert.assertFalse(LogCaptureAppender.getEvents().isEmpty());
LogCaptureAppender.reset();
}
}
| apache-2.0 |
broly-git/alien4cloud | alien4cloud-security/src/main/java/alien4cloud/security/groups/rest/CreateGroupRequest.java | 430 | package alien4cloud.security.groups.rest;
import java.util.Set;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.validator.constraints.NotBlank;
@Getter
@Setter
@NoArgsConstructor
public class CreateGroupRequest {
@NotBlank
private String name;
private String email;
private String description;
private Set<String> users;
private Set<String> roles;
}
| apache-2.0 |
objectiser/camel | components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfClientCallback.java | 5600 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.camel.component.cxf;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.camel.AsyncCallback;
import org.apache.camel.Exchange;
import org.apache.cxf.endpoint.ClientCallback;
import org.apache.cxf.endpoint.ConduitSelector;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.message.Message;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CxfClientCallback extends ClientCallback {
private static final Logger LOG = LoggerFactory.getLogger(CxfClientCallback.class);
private final AsyncCallback camelAsyncCallback;
private final Exchange camelExchange;
private final org.apache.cxf.message.Exchange cxfExchange;
private final BindingOperationInfo boi;
private final CxfEndpoint endpoint;
public CxfClientCallback(AsyncCallback callback,
Exchange camelExchange,
org.apache.cxf.message.Exchange cxfExchange,
BindingOperationInfo boi,
CxfEndpoint endpoint) {
this.camelAsyncCallback = callback;
this.camelExchange = camelExchange;
this.cxfExchange = cxfExchange;
this.boi = boi;
this.endpoint = endpoint;
}
@Override
public void handleResponse(Map<String, Object> ctx, Object[] res) {
try {
super.handleResponse(ctx, res);
} finally {
// add cookies to the cookie store
if (endpoint.getCookieHandler() != null && cxfExchange.getInMessage() != null) {
try {
Map<String, List<String>> cxfHeaders = CastUtils.cast((Map<?, ?>)cxfExchange.getInMessage().get(Message.PROTOCOL_HEADERS));
endpoint.getCookieHandler().storeCookies(camelExchange, endpoint.getRequestUri(camelExchange), cxfHeaders);
} catch (IOException e) {
LOG.error("Cannot store cookies", e);
}
}
// bind the CXF response to Camel exchange and
// call camel callback
// for one way messages callback is already called in
// process method of org.apache.camel.component.cxf.CxfProducer
if (!boi.getOperationInfo().isOneWay()) {
endpoint.getCxfBinding().populateExchangeFromCxfResponse(camelExchange, cxfExchange, ctx);
camelAsyncCallback.done(false);
}
if (LOG.isDebugEnabled()) {
LOG.debug("{} calling handleResponse", Thread.currentThread().getName());
}
}
}
@Override
public void handleException(Map<String, Object> ctx, Throwable ex) {
try {
super.handleException(ctx, ex);
// need to call the conduitSelector complete method to enable the fail over feature
ConduitSelector conduitSelector = cxfExchange.get(ConduitSelector.class);
if (conduitSelector != null) {
conduitSelector.complete(cxfExchange);
ex = cxfExchange.getOutMessage().getContent(Exception.class);
if (ex == null && cxfExchange.getInMessage() != null) {
ex = cxfExchange.getInMessage().getContent(Exception.class);
}
if (ex != null) {
camelExchange.setException(ex);
}
} else {
camelExchange.setException(ex);
}
} finally {
// add cookies to the cookie store
if (endpoint.getCookieHandler() != null && cxfExchange.getInMessage() != null) {
try {
Map<String, List<String>> cxfHeaders = CastUtils.cast((Map<?, ?>)cxfExchange.getInMessage().get(Message.PROTOCOL_HEADERS));
endpoint.getCookieHandler().storeCookies(camelExchange, endpoint.getRequestUri(camelExchange), cxfHeaders);
} catch (IOException e) {
LOG.error("Cannot store cookies", e);
}
}
// copy the context information and
// call camel callback
// for one way messages callback is already called in
// process method of org.apache.camel.component.cxf.CxfProducer
if (!boi.getOperationInfo().isOneWay()) {
endpoint.getCxfBinding().populateExchangeFromCxfResponse(camelExchange, cxfExchange, ctx);
camelAsyncCallback.done(false);
}
if (LOG.isDebugEnabled()) {
LOG.debug("{} calling handleException", Thread.currentThread().getName());
}
}
}
}
| apache-2.0 |
Diaosir/WeX5 | UI2/system/components/justep/select/server/dsrc/Select.java | 2219 | import java.util.List;
import java.util.Map;
import org.dom4j.Element;
import com.justep.ui.component.ComponentContext;
import com.justep.ui.component.ComponentTemplate;
import com.justep.ui2.system.component.data.BaseDataDef;
public class Select implements ComponentTemplate {
public void execute(Element bound, Map<String, String> dataItems, Map<String, Object> props, Map<String, String> events,
Map<String, Object> context) {
String optionLabel = bound.attributeValue("bind-optionsLabel");
if(null!=optionLabel && !"".equals(optionLabel)){
bound.addAttribute("bind-optionsText", "'"+optionLabel+"'");
bound.remove(bound.attribute("bind-optionsLabel"));
}
String optionValue = bound.attributeValue("bind-optionsValue");
if(null!=optionValue && !"".equals(optionValue)){
bound.addAttribute("bind-optionsValue", "'"+optionValue+"'");
}
String optionCaption = bound.attributeValue("bind-optionsCaption");
if(null!=optionCaption && !"".equals(optionCaption)){
bound.addAttribute("bind-optionsCaption", "'"+optionCaption+"'");
}
String options = bound.attributeValue("bind-options");
if(null!=options && !"".equals(options)){
String str = options.replaceAll("\\$model.", "").replaceAll("\\$parent.", "");
//支持data的特殊处理,支持直接写data的xid
Object dataDef = context.get("data." + str);
if(dataDef instanceof BaseDataDef) options = options+".datas";
bound.addAttribute("bind-options", options);
//生成select组件的selectOptionsAfterRender
@SuppressWarnings("unchecked")
List<String> init = (List<String>) context.get(ComponentContext.INIT);
String js = "var justep = require('$UI/system/lib/justep');"
+"if(!this['__justep__']) this['__justep__'] = {};"
+"if(!this['__justep__'].selectOptionsAfterRender)"
+" this['__justep__'].selectOptionsAfterRender = function($element) {"
+" var comp = justep.Component.getComponent($element);"
+" if(comp) comp._addDefaultOption();"
+" };";
init.add(js);
bound.addAttribute("bind-optionsAfterRender", "$model.__justep__.selectOptionsAfterRender.bind($model,$element)");
}
}
}
| apache-2.0 |
josh-mckenzie/cassandra | src/java/org/apache/cassandra/net/StartupClusterConnectivityChecker.java | 12447 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.cassandra.net;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.util.concurrent.Uninterruptibles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.gms.ApplicationState;
import org.apache.cassandra.gms.EndpointState;
import org.apache.cassandra.gms.Gossiper;
import org.apache.cassandra.gms.IEndpointStateChangeSubscriber;
import org.apache.cassandra.gms.VersionedValue;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.net.async.OutboundConnectionIdentifier.ConnectionType;
import org.apache.cassandra.utils.FBUtilities;
import static org.apache.cassandra.net.MessagingService.Verb.PING;
import static org.apache.cassandra.net.async.OutboundConnectionIdentifier.ConnectionType.LARGE_MESSAGE;
import static org.apache.cassandra.net.async.OutboundConnectionIdentifier.ConnectionType.SMALL_MESSAGE;
public class StartupClusterConnectivityChecker
{
private static final Logger logger = LoggerFactory.getLogger(StartupClusterConnectivityChecker.class);
private final boolean blockForRemoteDcs;
private final long timeoutNanos;
public static StartupClusterConnectivityChecker create(long timeoutSecs, boolean blockForRemoteDcs)
{
if (timeoutSecs > 100)
logger.warn("setting the block-for-peers timeout (in seconds) to {} might be a bit excessive, but using it nonetheless", timeoutSecs);
long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSecs);
return new StartupClusterConnectivityChecker(timeoutNanos, blockForRemoteDcs);
}
@VisibleForTesting
StartupClusterConnectivityChecker(long timeoutNanos, boolean blockForRemoteDcs)
{
this.blockForRemoteDcs = blockForRemoteDcs;
this.timeoutNanos = timeoutNanos;
}
/**
* @param peers The currently known peers in the cluster; argument is not modified.
* @param getDatacenterSource A function for mapping peers to their datacenter.
* @return true if the requested percentage of peers are marked ALIVE in gossip and have their connections opened;
* else false.
*/
public boolean execute(Set<InetAddressAndPort> peers, Function<InetAddressAndPort, String> getDatacenterSource)
{
if (peers == null || this.timeoutNanos < 0)
return true;
// make a copy of the set, to avoid mucking with the input (in case it's a sensitive collection)
peers = new HashSet<>(peers);
InetAddressAndPort localAddress = FBUtilities.getBroadcastAddressAndPort();
String localDc = getDatacenterSource.apply(localAddress);
peers.remove(localAddress);
if (peers.isEmpty())
return true;
// make a copy of the datacenter mapping (in case gossip updates happen during this method or some such)
Map<InetAddressAndPort, String> peerToDatacenter = new HashMap<>();
SetMultimap<String, InetAddressAndPort> datacenterToPeers = HashMultimap.create();
for (InetAddressAndPort peer : peers)
{
String datacenter = getDatacenterSource.apply(peer);
peerToDatacenter.put(peer, datacenter);
datacenterToPeers.put(datacenter, peer);
}
// In the case where we do not want to block startup on remote datacenters (e.g. because clients only use
// LOCAL_X consistency levels), we remove all other datacenter hosts from the mapping and we only wait
// on the remaining local datacenter.
if (!blockForRemoteDcs)
{
datacenterToPeers.keySet().retainAll(Collections.singleton(localDc));
logger.info("Blocking coordination until only a single peer is DOWN in the local datacenter, timeout={}s",
TimeUnit.NANOSECONDS.toSeconds(timeoutNanos));
}
else
{
logger.info("Blocking coordination until only a single peer is DOWN in each datacenter, timeout={}s",
TimeUnit.NANOSECONDS.toSeconds(timeoutNanos));
}
AckMap acks = new AckMap(3);
Map<String, CountDownLatch> dcToRemainingPeers = new HashMap<>(datacenterToPeers.size());
for (String datacenter: datacenterToPeers.keys())
{
dcToRemainingPeers.put(datacenter,
new CountDownLatch(Math.max(datacenterToPeers.get(datacenter).size() - 1, 0)));
}
long startNanos = System.nanoTime();
// set up a listener to react to new nodes becoming alive (in gossip), and account for all the nodes that are already alive
Set<InetAddressAndPort> alivePeers = Collections.newSetFromMap(new ConcurrentHashMap<>());
AliveListener listener = new AliveListener(alivePeers, dcToRemainingPeers, acks, peerToDatacenter::get);
Gossiper.instance.register(listener);
// send out a ping message to open up the non-gossip connections to all peers. Note that this sends the
// ping messages to _all_ peers, not just the ones we block for in dcToRemainingPeers.
sendPingMessages(peers, dcToRemainingPeers, acks, peerToDatacenter::get);
for (InetAddressAndPort peer : peers)
{
if (Gossiper.instance.isAlive(peer) && alivePeers.add(peer) && acks.incrementAndCheck(peer))
{
String datacenter = peerToDatacenter.get(peer);
// We have to check because we might only have the local DC in the map
if (dcToRemainingPeers.containsKey(datacenter))
dcToRemainingPeers.get(datacenter).countDown();
}
}
boolean succeeded = true;
for (String datacenter: dcToRemainingPeers.keySet())
{
long remainingNanos = Math.max(1, timeoutNanos - (System.nanoTime() - startNanos));
succeeded &= Uninterruptibles.awaitUninterruptibly(dcToRemainingPeers.get(datacenter),
remainingNanos, TimeUnit.NANOSECONDS);
}
Gossiper.instance.unregister(listener);
Map<String, Long> numDown = dcToRemainingPeers.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().getCount()));
if (succeeded)
{
logger.info("Ensured sufficient healthy connections with {} after {} milliseconds",
numDown.keySet(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos));
}
else
{
logger.warn("Timed out after {} milliseconds, was waiting for remaining peers to connect: {}",
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos), numDown);
}
return succeeded;
}
/**
* Sends a "connection warmup" message to each peer in the collection, on every {@link ConnectionType}
* used for internode messaging (that is not gossip).
*/
private void sendPingMessages(Set<InetAddressAndPort> peers, Map<String, CountDownLatch> dcToRemainingPeers,
AckMap acks, Function<InetAddressAndPort, String> getDatacenter)
{
IAsyncCallback responseHandler = new IAsyncCallback()
{
public boolean isLatencyForSnitch()
{
return false;
}
public void response(MessageIn msg)
{
if (acks.incrementAndCheck(msg.from))
{
String datacenter = getDatacenter.apply(msg.from);
// We have to check because we might only have the local DC in the map
if (dcToRemainingPeers.containsKey(datacenter))
dcToRemainingPeers.get(datacenter).countDown();
}
}
};
MessageOut<PingMessage> smallChannelMessageOut = new MessageOut<>(PING, PingMessage.smallChannelMessage,
PingMessage.serializer, SMALL_MESSAGE);
MessageOut<PingMessage> largeChannelMessageOut = new MessageOut<>(PING, PingMessage.largeChannelMessage,
PingMessage.serializer, LARGE_MESSAGE);
for (InetAddressAndPort peer : peers)
{
MessagingService.instance().sendRR(smallChannelMessageOut, peer, responseHandler);
MessagingService.instance().sendRR(largeChannelMessageOut, peer, responseHandler);
}
}
/**
* A trivial implementation of {@link IEndpointStateChangeSubscriber} that really only cares about
* {@link #onAlive(InetAddressAndPort, EndpointState)} invocations.
*/
private static final class AliveListener implements IEndpointStateChangeSubscriber
{
private final Map<String, CountDownLatch> dcToRemainingPeers;
private final Set<InetAddressAndPort> livePeers;
private final Function<InetAddressAndPort, String> getDatacenter;
private final AckMap acks;
AliveListener(Set<InetAddressAndPort> livePeers, Map<String, CountDownLatch> dcToRemainingPeers,
AckMap acks, Function<InetAddressAndPort, String> getDatacenter)
{
this.livePeers = livePeers;
this.dcToRemainingPeers = dcToRemainingPeers;
this.acks = acks;
this.getDatacenter = getDatacenter;
}
public void onJoin(InetAddressAndPort endpoint, EndpointState epState)
{
}
public void beforeChange(InetAddressAndPort endpoint, EndpointState currentState, ApplicationState newStateKey, VersionedValue newValue)
{
}
public void onChange(InetAddressAndPort endpoint, ApplicationState state, VersionedValue value)
{
}
public void onAlive(InetAddressAndPort endpoint, EndpointState state)
{
if (livePeers.add(endpoint) && acks.incrementAndCheck(endpoint))
{
String datacenter = getDatacenter.apply(endpoint);
if (dcToRemainingPeers.containsKey(datacenter))
dcToRemainingPeers.get(datacenter).countDown();
}
}
public void onDead(InetAddressAndPort endpoint, EndpointState state)
{
}
public void onRemove(InetAddressAndPort endpoint)
{
}
public void onRestart(InetAddressAndPort endpoint, EndpointState state)
{
}
}
private static final class AckMap
{
private final int threshold;
private final Map<InetAddressAndPort, AtomicInteger> acks;
AckMap(int threshold)
{
this.threshold = threshold;
acks = new ConcurrentHashMap<>();
}
boolean incrementAndCheck(InetAddressAndPort address)
{
return acks.computeIfAbsent(address, addr -> new AtomicInteger(0)).incrementAndGet() == threshold;
}
}
}
| apache-2.0 |
jpountz/elasticsearch | core/src/test/java/org/elasticsearch/search/aggregations/bucket/ChildrenIT.java | 26190 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.elasticsearch.search.aggregations.bucket;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.children.Children;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.ESIntegTestCase;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.elasticsearch.index.query.QueryBuilders.hasChildQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.children;
import static org.elasticsearch.search.aggregations.AggregationBuilders.sum;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
import static org.elasticsearch.search.aggregations.AggregationBuilders.topHits;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
/**
*/
@ESIntegTestCase.SuiteScopeTestCase
public class ChildrenIT extends ESIntegTestCase {
private final static Map<String, Control> categoryToControl = new HashMap<>();
@Override
public void setupSuiteScopeCluster() throws Exception {
assertAcked(
prepareCreate("test")
.addMapping("article")
.addMapping("comment", "_parent", "type=article")
);
List<IndexRequestBuilder> requests = new ArrayList<>();
String[] uniqueCategories = new String[randomIntBetween(1, 25)];
for (int i = 0; i < uniqueCategories.length; i++) {
uniqueCategories[i] = Integer.toString(i);
}
int catIndex = 0;
int numParentDocs = randomIntBetween(uniqueCategories.length, uniqueCategories.length * 5);
for (int i = 0; i < numParentDocs; i++) {
String id = Integer.toString(i);
// TODO: this array is always of length 1, and testChildrenAggs fails if this is changed
String[] categories = new String[randomIntBetween(1,1)];
for (int j = 0; j < categories.length; j++) {
String category = categories[j] = uniqueCategories[catIndex++ % uniqueCategories.length];
Control control = categoryToControl.get(category);
if (control == null) {
categoryToControl.put(category, control = new Control(category));
}
control.articleIds.add(id);
}
requests.add(client().prepareIndex("test", "article", id).setCreate(true).setSource("category", categories, "randomized", true));
}
String[] commenters = new String[randomIntBetween(5, 50)];
for (int i = 0; i < commenters.length; i++) {
commenters[i] = Integer.toString(i);
}
int id = 0;
for (Control control : categoryToControl.values()) {
for (String articleId : control.articleIds) {
int numChildDocsPerParent = randomIntBetween(0, 5);
for (int i = 0; i < numChildDocsPerParent; i++) {
String commenter = commenters[id % commenters.length];
String idValue = Integer.toString(id++);
control.commentIds.add(idValue);
Set<String> ids = control.commenterToCommentId.get(commenter);
if (ids == null) {
control.commenterToCommentId.put(commenter, ids = new HashSet<>());
}
ids.add(idValue);
requests.add(client().prepareIndex("test", "comment", idValue).setCreate(true).setParent(articleId).setSource("commenter", commenter));
}
}
}
requests.add(client().prepareIndex("test", "article", "a").setSource("category", new String[]{"a"}, "randomized", false));
requests.add(client().prepareIndex("test", "article", "b").setSource("category", new String[]{"a", "b"}, "randomized", false));
requests.add(client().prepareIndex("test", "article", "c").setSource("category", new String[]{"a", "b", "c"}, "randomized", false));
requests.add(client().prepareIndex("test", "article", "d").setSource("category", new String[]{"c"}, "randomized", false));
requests.add(client().prepareIndex("test", "comment", "a").setParent("a").setSource("{}"));
requests.add(client().prepareIndex("test", "comment", "c").setParent("c").setSource("{}"));
indexRandom(true, requests);
ensureSearchable("test");
}
public void testChildrenAggs() throws Exception {
SearchResponse searchResponse = client().prepareSearch("test")
.setQuery(matchQuery("randomized", true))
.addAggregation(
terms("category").field("category").size(0).subAggregation(
children("to_comment").childType("comment").subAggregation(
terms("commenters").field("commenter").size(0).subAggregation(
topHits("top_comments")
))
)
).get();
assertSearchResponse(searchResponse);
Terms categoryTerms = searchResponse.getAggregations().get("category");
assertThat(categoryTerms.getBuckets().size(), equalTo(categoryToControl.size()));
for (Map.Entry<String, Control> entry1 : categoryToControl.entrySet()) {
Terms.Bucket categoryBucket = categoryTerms.getBucketByKey(entry1.getKey());
assertThat(categoryBucket.getKeyAsString(), equalTo(entry1.getKey()));
assertThat(categoryBucket.getDocCount(), equalTo((long) entry1.getValue().articleIds.size()));
Children childrenBucket = categoryBucket.getAggregations().get("to_comment");
assertThat(childrenBucket.getName(), equalTo("to_comment"));
assertThat(childrenBucket.getDocCount(), equalTo((long) entry1.getValue().commentIds.size()));
assertThat((long) childrenBucket.getProperty("_count"), equalTo((long) entry1.getValue().commentIds.size()));
Terms commentersTerms = childrenBucket.getAggregations().get("commenters");
assertThat((Terms) childrenBucket.getProperty("commenters"), sameInstance(commentersTerms));
assertThat(commentersTerms.getBuckets().size(), equalTo(entry1.getValue().commenterToCommentId.size()));
for (Map.Entry<String, Set<String>> entry2 : entry1.getValue().commenterToCommentId.entrySet()) {
Terms.Bucket commentBucket = commentersTerms.getBucketByKey(entry2.getKey());
assertThat(commentBucket.getKeyAsString(), equalTo(entry2.getKey()));
assertThat(commentBucket.getDocCount(), equalTo((long) entry2.getValue().size()));
TopHits topHits = commentBucket.getAggregations().get("top_comments");
for (SearchHit searchHit : topHits.getHits().getHits()) {
assertThat(entry2.getValue().contains(searchHit.getId()), is(true));
}
}
}
}
public void testParentWithMultipleBuckets() throws Exception {
SearchResponse searchResponse = client().prepareSearch("test")
.setQuery(matchQuery("randomized", false))
.addAggregation(
terms("category").field("category").size(0).subAggregation(
children("to_comment").childType("comment").subAggregation(topHits("top_comments").addSort("_uid", SortOrder.ASC))
)
).get();
assertSearchResponse(searchResponse);
Terms categoryTerms = searchResponse.getAggregations().get("category");
assertThat(categoryTerms.getBuckets().size(), equalTo(3));
for (Terms.Bucket bucket : categoryTerms.getBuckets()) {
logger.info("bucket=" + bucket.getKey());
Children childrenBucket = bucket.getAggregations().get("to_comment");
TopHits topHits = childrenBucket.getAggregations().get("top_comments");
logger.info("total_hits={}", topHits.getHits().getTotalHits());
for (SearchHit searchHit : topHits.getHits()) {
logger.info("hit= {} {} {}", searchHit.sortValues()[0], searchHit.getType(), searchHit.getId());
}
}
Terms.Bucket categoryBucket = categoryTerms.getBucketByKey("a");
assertThat(categoryBucket.getKeyAsString(), equalTo("a"));
assertThat(categoryBucket.getDocCount(), equalTo(3l));
Children childrenBucket = categoryBucket.getAggregations().get("to_comment");
assertThat(childrenBucket.getName(), equalTo("to_comment"));
assertThat(childrenBucket.getDocCount(), equalTo(2l));
TopHits topHits = childrenBucket.getAggregations().get("top_comments");
assertThat(topHits.getHits().totalHits(), equalTo(2l));
assertThat(topHits.getHits().getAt(0).getId(), equalTo("a"));
assertThat(topHits.getHits().getAt(0).getType(), equalTo("comment"));
assertThat(topHits.getHits().getAt(1).getId(), equalTo("c"));
assertThat(topHits.getHits().getAt(1).getType(), equalTo("comment"));
categoryBucket = categoryTerms.getBucketByKey("b");
assertThat(categoryBucket.getKeyAsString(), equalTo("b"));
assertThat(categoryBucket.getDocCount(), equalTo(2l));
childrenBucket = categoryBucket.getAggregations().get("to_comment");
assertThat(childrenBucket.getName(), equalTo("to_comment"));
assertThat(childrenBucket.getDocCount(), equalTo(1l));
topHits = childrenBucket.getAggregations().get("top_comments");
assertThat(topHits.getHits().totalHits(), equalTo(1l));
assertThat(topHits.getHits().getAt(0).getId(), equalTo("c"));
assertThat(topHits.getHits().getAt(0).getType(), equalTo("comment"));
categoryBucket = categoryTerms.getBucketByKey("c");
assertThat(categoryBucket.getKeyAsString(), equalTo("c"));
assertThat(categoryBucket.getDocCount(), equalTo(2l));
childrenBucket = categoryBucket.getAggregations().get("to_comment");
assertThat(childrenBucket.getName(), equalTo("to_comment"));
assertThat(childrenBucket.getDocCount(), equalTo(1l));
topHits = childrenBucket.getAggregations().get("top_comments");
assertThat(topHits.getHits().totalHits(), equalTo(1l));
assertThat(topHits.getHits().getAt(0).getId(), equalTo("c"));
assertThat(topHits.getHits().getAt(0).getType(), equalTo("comment"));
}
public void testWithDeletes() throws Exception {
String indexName = "xyz";
assertAcked(
prepareCreate(indexName)
.addMapping("parent")
.addMapping("child", "_parent", "type=parent", "count", "type=long")
);
List<IndexRequestBuilder> requests = new ArrayList<>();
requests.add(client().prepareIndex(indexName, "parent", "1").setSource("{}"));
requests.add(client().prepareIndex(indexName, "child", "0").setParent("1").setSource("count", 1));
requests.add(client().prepareIndex(indexName, "child", "1").setParent("1").setSource("count", 1));
requests.add(client().prepareIndex(indexName, "child", "2").setParent("1").setSource("count", 1));
requests.add(client().prepareIndex(indexName, "child", "3").setParent("1").setSource("count", 1));
indexRandom(true, requests);
for (int i = 0; i < 10; i++) {
SearchResponse searchResponse = client().prepareSearch(indexName)
.addAggregation(children("children").childType("child").subAggregation(sum("counts").field("count")))
.get();
assertNoFailures(searchResponse);
Children children = searchResponse.getAggregations().get("children");
assertThat(children.getDocCount(), equalTo(4l));
Sum count = children.getAggregations().get("counts");
assertThat(count.getValue(), equalTo(4.));
String idToUpdate = Integer.toString(randomInt(3));
/*
* The whole point of this test is to test these things with deleted
* docs in the index so we turn off detect_noop to make sure that
* the updates cause that.
*/
UpdateResponse updateResponse = client().prepareUpdate(indexName, "child", idToUpdate)
.setParent("1")
.setDoc("count", 1)
.setDetectNoop(false)
.get();
assertThat(updateResponse.getVersion(), greaterThan(1l));
refresh();
}
}
public void testNonExistingChildType() throws Exception {
SearchResponse searchResponse = client().prepareSearch("test")
.addAggregation(
children("non-existing").childType("xyz")
).get();
assertSearchResponse(searchResponse);
Children children = searchResponse.getAggregations().get("non-existing");
assertThat(children.getName(), equalTo("non-existing"));
assertThat(children.getDocCount(), equalTo(0l));
}
public void testPostCollection() throws Exception {
String indexName = "prodcatalog";
String masterType = "masterprod";
String childType = "variantsku";
assertAcked(
prepareCreate(indexName)
.addMapping(masterType, "brand", "type=string", "name", "type=string", "material", "type=string")
.addMapping(childType, "_parent", "type=masterprod", "color", "type=string", "size", "type=string")
);
List<IndexRequestBuilder> requests = new ArrayList<>();
requests.add(client().prepareIndex(indexName, masterType, "1").setSource("brand", "Levis", "name", "Style 501", "material", "Denim"));
requests.add(client().prepareIndex(indexName, childType, "0").setParent("1").setSource("color", "blue", "size", "32"));
requests.add(client().prepareIndex(indexName, childType, "1").setParent("1").setSource("color", "blue", "size", "34"));
requests.add(client().prepareIndex(indexName, childType, "2").setParent("1").setSource("color", "blue", "size", "36"));
requests.add(client().prepareIndex(indexName, childType, "3").setParent("1").setSource("color", "black", "size", "38"));
requests.add(client().prepareIndex(indexName, childType, "4").setParent("1").setSource("color", "black", "size", "40"));
requests.add(client().prepareIndex(indexName, childType, "5").setParent("1").setSource("color", "gray", "size", "36"));
requests.add(client().prepareIndex(indexName, masterType, "2").setSource("brand", "Wrangler", "name", "Regular Cut", "material", "Leather"));
requests.add(client().prepareIndex(indexName, childType, "6").setParent("2").setSource("color", "blue", "size", "32"));
requests.add(client().prepareIndex(indexName, childType, "7").setParent("2").setSource("color", "blue", "size", "34"));
requests.add(client().prepareIndex(indexName, childType, "8").setParent("2").setSource("color", "black", "size", "36"));
requests.add(client().prepareIndex(indexName, childType, "9").setParent("2").setSource("color", "black", "size", "38"));
requests.add(client().prepareIndex(indexName, childType, "10").setParent("2").setSource("color", "black", "size", "40"));
requests.add(client().prepareIndex(indexName, childType, "11").setParent("2").setSource("color", "orange", "size", "36"));
requests.add(client().prepareIndex(indexName, childType, "12").setParent("2").setSource("color", "green", "size", "44"));
indexRandom(true, requests);
SearchResponse response = client().prepareSearch(indexName).setTypes(masterType)
.setQuery(hasChildQuery(childType, termQuery("color", "orange")))
.addAggregation(children("my-refinements")
.childType(childType)
.subAggregation(terms("my-colors").field("color"))
.subAggregation(terms("my-sizes").field("size"))
).get();
assertNoFailures(response);
assertHitCount(response, 1);
Children childrenAgg = response.getAggregations().get("my-refinements");
assertThat(childrenAgg.getDocCount(), equalTo(7l));
Terms termsAgg = childrenAgg.getAggregations().get("my-colors");
assertThat(termsAgg.getBuckets().size(), equalTo(4));
assertThat(termsAgg.getBucketByKey("black").getDocCount(), equalTo(3l));
assertThat(termsAgg.getBucketByKey("blue").getDocCount(), equalTo(2l));
assertThat(termsAgg.getBucketByKey("green").getDocCount(), equalTo(1l));
assertThat(termsAgg.getBucketByKey("orange").getDocCount(), equalTo(1l));
termsAgg = childrenAgg.getAggregations().get("my-sizes");
assertThat(termsAgg.getBuckets().size(), equalTo(6));
assertThat(termsAgg.getBucketByKey("36").getDocCount(), equalTo(2l));
assertThat(termsAgg.getBucketByKey("32").getDocCount(), equalTo(1l));
assertThat(termsAgg.getBucketByKey("34").getDocCount(), equalTo(1l));
assertThat(termsAgg.getBucketByKey("38").getDocCount(), equalTo(1l));
assertThat(termsAgg.getBucketByKey("40").getDocCount(), equalTo(1l));
assertThat(termsAgg.getBucketByKey("44").getDocCount(), equalTo(1l));
}
public void testHierarchicalChildrenAggs() {
String indexName = "geo";
String grandParentType = "continent";
String parentType = "country";
String childType = "city";
assertAcked(
prepareCreate(indexName)
.setSettings(Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
)
.addMapping(grandParentType)
.addMapping(parentType, "_parent", "type=" + grandParentType)
.addMapping(childType, "_parent", "type=" + parentType)
);
client().prepareIndex(indexName, grandParentType, "1").setSource("name", "europe").get();
client().prepareIndex(indexName, parentType, "2").setParent("1").setSource("name", "belgium").get();
client().prepareIndex(indexName, childType, "3").setParent("2").setRouting("1").setSource("name", "brussels").get();
refresh();
SearchResponse response = client().prepareSearch(indexName)
.setQuery(matchQuery("name", "europe"))
.addAggregation(
children(parentType).childType(parentType).subAggregation(
children(childType).childType(childType).subAggregation(
terms("name").field("name")
)
)
)
.get();
assertNoFailures(response);
assertHitCount(response, 1);
Children children = response.getAggregations().get(parentType);
assertThat(children.getName(), equalTo(parentType));
assertThat(children.getDocCount(), equalTo(1l));
children = children.getAggregations().get(childType);
assertThat(children.getName(), equalTo(childType));
assertThat(children.getDocCount(), equalTo(1l));
Terms terms = children.getAggregations().get("name");
assertThat(terms.getBuckets().size(), equalTo(1));
assertThat(terms.getBuckets().get(0).getKey().toString(), equalTo("brussels"));
assertThat(terms.getBuckets().get(0).getDocCount(), equalTo(1l));
}
public void testPostCollectAllLeafReaders() throws Exception {
// The 'towns' and 'parent_names' aggs operate on parent docs and if child docs are in different segments we need
// to ensure those segments which child docs are also evaluated to in the post collect phase.
// Before we only evaluated segments that yielded matches in 'towns' and 'parent_names' aggs, which caused
// us to miss to evaluate child docs in segments we didn't have parent matches for.
assertAcked(
prepareCreate("index")
.addMapping("parentType", "name", "type=string,index=not_analyzed", "town", "type=string,index=not_analyzed")
.addMapping("childType", "_parent", "type=parentType", "name", "type=string,index=not_analyzed", "age", "type=integer")
);
List<IndexRequestBuilder> requests = new ArrayList<>();
requests.add(client().prepareIndex("index", "parentType", "1").setSource("name", "Bob", "town", "Memphis"));
requests.add(client().prepareIndex("index", "parentType", "2").setSource("name", "Alice", "town", "Chicago"));
requests.add(client().prepareIndex("index", "parentType", "3").setSource("name", "Bill", "town", "Chicago"));
requests.add(client().prepareIndex("index", "childType", "1").setSource("name", "Jill", "age", 5).setParent("1"));
requests.add(client().prepareIndex("index", "childType", "2").setSource("name", "Joey", "age", 3).setParent("1"));
requests.add(client().prepareIndex("index", "childType", "3").setSource("name", "John", "age", 2).setParent("2"));
requests.add(client().prepareIndex("index", "childType", "4").setSource("name", "Betty", "age", 6).setParent("3"));
requests.add(client().prepareIndex("index", "childType", "5").setSource("name", "Dan", "age", 1).setParent("3"));
indexRandom(true, requests);
SearchResponse response = client().prepareSearch("index")
.setSize(0)
.addAggregation(AggregationBuilders.terms("towns").field("town")
.subAggregation(AggregationBuilders.terms("parent_names").field("name")
.subAggregation(AggregationBuilders.children("child_docs").childType("childType"))
)
)
.get();
Terms towns = response.getAggregations().get("towns");
assertThat(towns.getBuckets().size(), equalTo(2));
assertThat(towns.getBuckets().get(0).getKeyAsString(), equalTo("Chicago"));
assertThat(towns.getBuckets().get(0).getDocCount(), equalTo(2L));
Terms parents = towns.getBuckets().get(0).getAggregations().get("parent_names");
assertThat(parents.getBuckets().size(), equalTo(2));
assertThat(parents.getBuckets().get(0).getKeyAsString(), equalTo("Alice"));
assertThat(parents.getBuckets().get(0).getDocCount(), equalTo(1L));
Children children = parents.getBuckets().get(0).getAggregations().get("child_docs");
assertThat(children.getDocCount(), equalTo(1L));
assertThat(parents.getBuckets().get(1).getKeyAsString(), equalTo("Bill"));
assertThat(parents.getBuckets().get(1).getDocCount(), equalTo(1L));
children = parents.getBuckets().get(1).getAggregations().get("child_docs");
assertThat(children.getDocCount(), equalTo(2L));
assertThat(towns.getBuckets().get(1).getKeyAsString(), equalTo("Memphis"));
assertThat(towns.getBuckets().get(1).getDocCount(), equalTo(1L));
parents = towns.getBuckets().get(1).getAggregations().get("parent_names");
assertThat(parents.getBuckets().size(), equalTo(1));
assertThat(parents.getBuckets().get(0).getKeyAsString(), equalTo("Bob"));
assertThat(parents.getBuckets().get(0).getDocCount(), equalTo(1L));
children = parents.getBuckets().get(0).getAggregations().get("child_docs");
assertThat(children.getDocCount(), equalTo(2L));
}
private static final class Control {
final String category;
final Set<String> articleIds = new HashSet<>();
final Set<String> commentIds = new HashSet<>();
final Map<String, Set<String>> commenterToCommentId = new HashMap<>();
private Control(String category) {
this.category = category;
}
}
}
| apache-2.0 |
andyspan/pinpoint | plugins/jetty/src/main/java/com/navercorp/pinpoint/plugin/jetty/JettyDetector.java | 1654 | /*
* Copyright 2014 NAVER Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.plugin.jetty;
import com.navercorp.pinpoint.bootstrap.plugin.ApplicationTypeDetector;
import com.navercorp.pinpoint.bootstrap.resolver.ConditionProvider;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.util.CollectionUtils;
import java.util.Arrays;
import java.util.List;
public class JettyDetector implements ApplicationTypeDetector {
private static final String DEFAULT_BOOTSTRAP_MAIN = "org.eclipse.jetty.start.Main";
private final List<String> bootstrapMains;
public JettyDetector(List<String> bootstrapMains) {
if (CollectionUtils.isEmpty(bootstrapMains)) {
this.bootstrapMains = Arrays.asList(DEFAULT_BOOTSTRAP_MAIN);
} else {
this.bootstrapMains = bootstrapMains;
}
}
@Override
public ServiceType getApplicationType() {
return JettyConstants.JETTY;
}
@Override
public boolean detect(ConditionProvider provider) {
return provider.checkMainClass(bootstrapMains);
}
}
| apache-2.0 |
joansmith/bnd | biz.aQute.bndlib/src/aQute/bnd/osgi/BundleId.java | 853 | package aQute.bnd.osgi;
/**
* Holds the bundle bsn + version pair
*/
public class BundleId implements Comparable<BundleId> {
final String bsn;
final String version;
public BundleId(String bsn, String version) {
this.bsn = bsn.trim();
this.version = version.trim();
}
public String getVersion() {
return version;
}
public String getBsn() {
return bsn;
}
public boolean isValid() {
return Verifier.isVersion(version) && Verifier.isBsn(bsn);
}
@Override
public boolean equals(Object o) {
return this == o || ((o instanceof BundleId) && compareTo((BundleId) o) == 0);
}
@Override
public int hashCode() {
return bsn.hashCode() ^ version.hashCode();
}
public int compareTo(BundleId other) {
int result = bsn.compareTo(other.bsn);
if (result != 0)
return result;
return version.compareTo(other.version);
}
}
| apache-2.0 |
ravihansa3000/stratos | components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/message/receiver/domain/mapping/DomainMappingEventMessageDelegator.java | 3753 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.stratos.messaging.message.receiver.domain.mapping;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.messaging.domain.Message;
import org.apache.stratos.messaging.listener.EventListener;
import org.apache.stratos.messaging.message.processor.MessageProcessorChain;
import org.apache.stratos.messaging.message.processor.domain.mapping.DomainMappingMessageProcessorChain;
/**
* Domain mapping event message delegator.
*/
class DomainMappingEventMessageDelegator implements Runnable {
private static final Log log = LogFactory.getLog(DomainMappingEventMessageDelegator.class);
private MessageProcessorChain processorChain;
private DomainMappingEventMessageQueue messageQueue;
private boolean terminated;
public DomainMappingEventMessageDelegator(DomainMappingEventMessageQueue messageQueue) {
this.messageQueue = messageQueue;
this.processorChain = new DomainMappingMessageProcessorChain();
}
public void addEventListener(EventListener eventListener) {
processorChain.addEventListener(eventListener);
}
public void removeEventListener(EventListener eventListener) {
processorChain.removeEventListener(eventListener);
}
@Override
public void run() {
try {
if (log.isInfoEnabled()) {
log.info("Domain mapping event message delegator started");
}
while (!terminated) {
try {
Message message = messageQueue.take();
String type = message.getEventClassName();
// Retrieve the actual message
String json = message.getText();
if (log.isDebugEnabled()) {
log.debug(String.format("Domain mapping event message received from queue: [event-class-name] %s " +
"[message-queue] %s", type, messageQueue.getClass()));
}
if (log.isDebugEnabled()) {
log.debug(String.format("Delegating domain mapping event message: %s", type));
}
processorChain.process(type, json, DomainMappingManager.getInstance());
} catch (InterruptedException e) {
log.info("Shutting down domain mapping event message delegator...");
terminate();
} catch (Exception e) {
log.error("Failed to retrieve domain mapping event message", e);
}
}
} catch (Exception e) {
if (log.isErrorEnabled()) {
log.error("Domain mapping event message delegator failed", e);
}
}
}
/**
* Terminate topology event message delegator thread.
*/
public void terminate() {
terminated = true;
}
}
| apache-2.0 |
ra0077/jmeter | test/src/org/apache/jmeter/threads/TestUnmodifiableJMeterVariables.java | 4803 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.jmeter.threads;
import static org.junit.Assert.assertThat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;
public class TestUnmodifiableJMeterVariables {
private static final String MY_OBJECT_KEY = "my.objectKey";
private static final String MY_KEY = "my.key";
private JMeterVariables vars;
private UnmodifiableJMeterVariables unmodifiables;
@Before
public void setUp() {
vars = new JMeterVariables();
vars.put(MY_KEY, "something to test for");
vars.putObject(MY_OBJECT_KEY, new Object());
unmodifiables = new UnmodifiableJMeterVariables(vars);
}
@Test
public void testGetThreadName() {
assertThat(unmodifiables.getThreadName(), CoreMatchers.is(vars.getThreadName()));
}
@Test
public void testGetIteration() {
assertThat(unmodifiables.getIteration(), CoreMatchers.is(vars.getIteration()));
}
@Test(expected = UnsupportedOperationException.class)
public void testIncIteration() {
unmodifiables.incIteration();
}
@Test(expected = UnsupportedOperationException.class)
public void testRemove() {
unmodifiables.remove("some.key");
}
@Test(expected = UnsupportedOperationException.class)
public void testPut() {
unmodifiables.put("some.key", "anything");
}
@Test(expected = UnsupportedOperationException.class)
public void testPutObject() {
unmodifiables.putObject("some.key", new Object());
}
@Test(expected = UnsupportedOperationException.class)
public void testPutAllMapOfStringQ() {
unmodifiables.putAll(Collections.emptyMap());
}
@Test(expected = UnsupportedOperationException.class)
public void testPutAllJMeterVariables() {
unmodifiables.putAll(vars);
}
@Test
public void testGet() {
assertThat(unmodifiables.get(MY_KEY), CoreMatchers.is(vars.get(MY_KEY)));
}
@Test
public void testGetObject() {
assertThat(unmodifiables.getObject(MY_OBJECT_KEY), CoreMatchers.is(vars.getObject(MY_OBJECT_KEY)));
}
@Test(expected = UnsupportedOperationException.class)
public void testGetIteratorIsUnmodifable() {
Iterator<Entry<String, Object>> iterator = unmodifiables.getIterator();
assertThat(iterator.hasNext(), CoreMatchers.is(true));
iterator.next();
iterator.remove();
}
@Test
public void testGetIterator() {
assertThat(iteratorToMap(unmodifiables.getIterator()), CoreMatchers.is(iteratorToMap(vars.getIterator())));
}
private <K, V> Map<K, V> iteratorToMap(Iterator<Entry<K, V>> it) {
Map<K, V> result = new HashMap<>();
while (it.hasNext()) {
Entry<K, V> entry = it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
@Test
public void testEntrySet() {
assertThat(unmodifiables.entrySet(), CoreMatchers.is(vars.entrySet()));
}
@Test
public void testEqualsObjectSymmetry() {
UnmodifiableJMeterVariables otherUnmodifiables = new UnmodifiableJMeterVariables(vars);
assertThat(unmodifiables, CoreMatchers.is(otherUnmodifiables));
assertThat(otherUnmodifiables, CoreMatchers.is(unmodifiables));
}
@Test
public void testEqualsObjectReflexivity() {
assertThat(unmodifiables, CoreMatchers.is(unmodifiables));
}
@Test
public void testEqualsObjectWithJMeterVariables() {
assertThat(unmodifiables.equals(vars), CoreMatchers.is(vars.equals(unmodifiables)));
}
@Test
public void testHashCode() {
UnmodifiableJMeterVariables otherUnmodifiables = new UnmodifiableJMeterVariables(vars);
assertThat(unmodifiables.hashCode(), CoreMatchers.is(otherUnmodifiables.hashCode()));
}
}
| apache-2.0 |
jssenyange/traccar | src/main/java/org/traccar/protocol/WatchFrameDecoder.java | 2397 | /*
* Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.traccar.protocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.traccar.BaseFrameDecoder;
public class WatchFrameDecoder extends BaseFrameDecoder {
@Override
protected Object decode(
ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception {
int endIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ']') + 1;
if (endIndex > 0) {
ByteBuf frame = Unpooled.buffer();
while (buf.readerIndex() < endIndex) {
byte b1 = buf.readByte();
if (b1 == '}') {
byte b2 = buf.readByte();
switch (b2) {
case 0x01:
frame.writeByte('}');
break;
case 0x02:
frame.writeByte('[');
break;
case 0x03:
frame.writeByte(']');
break;
case 0x04:
frame.writeByte(',');
break;
case 0x05:
frame.writeByte('*');
break;
default:
throw new IllegalArgumentException(String.format(
"unexpected byte at %d: 0x%02x", buf.readerIndex() - 1, b2));
}
} else {
frame.writeByte(b1);
}
}
return frame;
}
return null;
}
}
| apache-2.0 |
idea4bsd/idea4bsd | platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitSession.java | 2124 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes;
import com.intellij.openapi.ui.ValidationInfo;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Collection;
/**
* @author max
*/
public interface CommitSession {
CommitSession VCS_COMMIT = new CommitSession() {
public JComponent getAdditionalConfigurationUI() {
return null;
}
public JComponent getAdditionalConfigurationUI(Collection<Change> changes, String commitMessage) {
return null;
}
public boolean canExecute(Collection<Change> changes, String commitMessage) {
return true;
}
public void execute(Collection<Change> changes, String commitMessage) {
}
public void executionCanceled() {
}
@Override
public String getHelpId() {
return null;
}
};
/**
* @deprecated Since version 7.0, {@link #getAdditionalConfigurationUI(java.util.Collection, String)} is called instead
*/
@Nullable
JComponent getAdditionalConfigurationUI();
@Nullable
JComponent getAdditionalConfigurationUI(Collection<Change> changes, String commitMessage);
boolean canExecute(Collection<Change> changes, String commitMessage);
void execute(Collection<Change> changes, String commitMessage);
void executionCanceled();
/**
* @return the ID of the help topic to show for the dialog
* @since 10.5
*/
String getHelpId();
@CalledInAwt
default ValidationInfo validateFields() {
return null;
}
}
| apache-2.0 |
732773358/cool | src/com/coolweather/app/model/County.java | 637 | package com.coolweather.app.model;
public class County {
private int id;
private String countyName;
private String countyCode;
private int cityId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public String getCountyCode() {
return countyCode;
}
public void setCountyCode(String countyCode) {
this.countyCode = countyCode;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
| apache-2.0 |
android-ia/platform_tools_idea | java/execution/openapi/src/com/intellij/execution/configurations/CommandLineBuilder.java | 4413 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.execution.configurations;
import com.intellij.execution.CantRunException;
import com.intellij.execution.ExecutionBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdkType;
import com.intellij.openapi.projectRoots.JdkUtil;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkTypeId;
import com.intellij.openapi.util.Computable;
public class CommandLineBuilder {
private CommandLineBuilder() { }
public static GeneralCommandLine createFromJavaParameters(final SimpleJavaParameters javaParameters) throws CantRunException {
return createFromJavaParameters(javaParameters, false);
}
/**
* In order to avoid too long cmd problem dynamic classpath can be used - if allowed by both {@code dynamicClasspath} parameter
* and project settings.
*
* @param javaParameters parameters.
* @param project a project to get a dynamic classpath setting from.
* @param dynamicClasspath whether system properties and project settings will be able to cause using dynamic classpath. If false,
* classpath will always be passed through the command line.
* @return a command line.
* @throws CantRunException if there are problems with JDK setup.
*/
public static GeneralCommandLine createFromJavaParameters(final SimpleJavaParameters javaParameters,
final Project project,
final boolean dynamicClasspath) throws CantRunException {
return createFromJavaParameters(javaParameters, dynamicClasspath && JdkUtil.useDynamicClasspath(project));
}
/**
* @param javaParameters parameters.
* @param forceDynamicClasspath whether dynamic classpath will be used for this execution, to prevent problems caused by too long command line.
* @return a command line.
* @throws CantRunException if there are problems with JDK setup.
*/
public static GeneralCommandLine createFromJavaParameters(final SimpleJavaParameters javaParameters,
final boolean forceDynamicClasspath) throws CantRunException {
try {
return ApplicationManager.getApplication().runReadAction(new Computable<GeneralCommandLine>() {
public GeneralCommandLine compute() {
try {
final Sdk jdk = javaParameters.getJdk();
if (jdk == null) {
throw new CantRunException(ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
}
final SdkTypeId sdkType = jdk.getSdkType();
if (!(sdkType instanceof JavaSdkType)) {
throw new CantRunException(ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
}
final String exePath = ((JavaSdkType)sdkType).getVMExecutablePath(jdk);
if (exePath == null) {
throw new CantRunException(ExecutionBundle.message("run.configuration.cannot.find.vm.executable"));
}
if (javaParameters.getMainClass() == null) {
throw new CantRunException(ExecutionBundle.message("main.class.is.not.specified.error.message"));
}
return JdkUtil.setupJVMCommandLine(exePath, javaParameters, forceDynamicClasspath);
}
catch (CantRunException e) {
throw new RuntimeException(e);
}
}
});
}
catch (RuntimeException e) {
if (e.getCause() instanceof CantRunException) {
throw (CantRunException)e.getCause();
}
else {
throw e;
}
}
}
}
| apache-2.0 |
divs1210/retrolambda | retrolambda/src/main/java/net/orfjackal/retrolambda/lambdas/LambdaReifier.java | 4749 | // Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
package net.orfjackal.retrolambda.lambdas;
import org.objectweb.asm.*;
import java.lang.invoke.*;
import java.lang.reflect.Constructor;
import java.util.*;
import java.util.concurrent.*;
public class LambdaReifier {
// These globals are used for communicating with the Java agent which
// is spying on the LambdaMetafactory's dynamically generated bytecode.
// We expect only one class being processed at a time, so it should
// be an error if these collections contain more than one element.
private static final BlockingDeque<Handle> currentLambdaImplMethod = new LinkedBlockingDeque<>(1);
private static final BlockingDeque<Handle> currentLambdaAccessMethod = new LinkedBlockingDeque<>(1);
private static final BlockingDeque<Class<?>> currentInvoker = new LinkedBlockingDeque<>(1);
private static final BlockingDeque<Type> currentInvokedType = new LinkedBlockingDeque<>(1);
private static final BlockingDeque<String> currentLambdaClass = new LinkedBlockingDeque<>(1);
public static LambdaFactoryMethod reifyLambdaClass(Handle lambdaImplMethod, Handle lambdaAccessMethod,
Class<?> invoker, String invokedName, Type invokedType, Handle bsm, Object[] bsmArgs) {
try {
setLambdaImplMethod(lambdaImplMethod);
setLambdaAccessMethod(lambdaAccessMethod);
setInvoker(invoker);
setInvokedType(invokedType);
// Causes the lambda class to be loaded. Retrolambda's Java agent
// will detect it, save it to a file and tell us (via the globals
// in this class) that what the name of the lambda class was.
callBootstrapMethod(invoker, invokedName, invokedType, bsm, bsmArgs);
return getLambdaFactoryMethod();
} catch (Throwable t) {
throw new RuntimeException(t);
} finally {
resetGlobals();
}
}
private static void setLambdaImplMethod(Handle lambdaImplMethod) {
currentLambdaImplMethod.push(lambdaImplMethod);
}
private static void setLambdaAccessMethod(Handle lambdaAccessMethod) {
currentLambdaAccessMethod.push(lambdaAccessMethod);
}
private static void setInvoker(Class<?> lambdaInvoker) {
currentInvoker.push(lambdaInvoker);
}
private static void setInvokedType(Type invokedType) {
currentInvokedType.push(invokedType);
}
public static void setLambdaClass(String lambdaClass) {
currentLambdaClass.push(lambdaClass);
}
public static boolean isLambdaClassToReify(String className) {
Class<?> invoker = currentInvoker.peekFirst();
return invoker != null
&& className.startsWith(Type.getInternalName(invoker))
&& LambdaNaming.LAMBDA_CLASS.matcher(className).matches();
}
public static Handle getLambdaImplMethod() {
return currentLambdaImplMethod.getFirst();
}
public static Handle getLambdaAccessMethod() {
return currentLambdaAccessMethod.getFirst();
}
public static LambdaFactoryMethod getLambdaFactoryMethod() {
String lambdaClass = currentLambdaClass.getFirst();
Type invokedType = currentInvokedType.getFirst();
return new LambdaFactoryMethod(lambdaClass, invokedType);
}
private static void resetGlobals() {
currentLambdaImplMethod.clear();
currentLambdaAccessMethod.clear();
currentInvoker.clear();
currentInvokedType.clear();
currentLambdaClass.clear();
}
private static CallSite callBootstrapMethod(Class<?> invoker, String invokedName, Type invokedType, Handle bsm, Object[] bsmArgs) throws Throwable {
ClassLoader cl = invoker.getClassLoader();
MethodHandles.Lookup caller = getLookup(invoker);
List<Object> args = new ArrayList<>();
args.add(caller);
args.add(invokedName);
args.add(Types.toMethodType(invokedType, cl));
for (Object arg : bsmArgs) {
args.add(Types.asmToJdkType(arg, cl, caller));
}
MethodHandle bootstrapMethod = Types.toMethodHandle(bsm, cl, caller);
return (CallSite) bootstrapMethod.invokeWithArguments(args);
}
private static MethodHandles.Lookup getLookup(Class<?> targetClass) throws Exception {
Constructor<MethodHandles.Lookup> ctor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class);
ctor.setAccessible(true);
return ctor.newInstance(targetClass);
}
}
| apache-2.0 |
UTSDataArena/examples | processing/sketchbook/libraries/minim/src/ddf/minim/AudioListener.java | 2720 | /*
* Copyright (c) 2007 - 2008 by Damien Di Fede <ddf@compartmental.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package ddf.minim;
/**
* An <code>AudioListener</code> can be used to monitor <code>Recordable</code>
* objects such as <code>AudioPlayer</code>, <code>AudioOutput</code>, and <code>AudioInput</code>.
* Each time a <code>Recordable</code> object receives a new sample buffer
* from the audio system, or generates a new sample buffer at the request of the
* audio system, it passes a copy of this buffer to its listeners. You can
* implement this interface if you want to receive samples in a callback fashion,
* rather than using an object's <code>AudioBuffer</code>s to access them. You
* add an <code>AudioListener</code> to a <code>Recordable</code> by calling
* the addListener method. When you want to stop receiving samples you call the
* removeListener method.
*
* @example Advanced/AddAndRemoveAudioListener
*
* @author Damien Di Fede
*
* @related AudioPlayer
* @related AudioInput
* @related AudioOutput
*/
public interface AudioListener
{
/**
* Called by the audio object this AudioListener is attached to
* when that object has new samples.
*
* @example Advanced/AddAndRemoveAudioListener
*
* @param samp
* a float[] buffer of samples from a MONO sound stream
*
* @related AudioListener
*/
void samples(float[] samp);
/**
* Called by the <code>Recordable</code> object this is attached to
* when that object has new samples.
*
* @param sampL
* a float[] buffer containing the left channel of a STEREO sound stream
* @param sampR
* a float[] buffer containing the right channel of a STEREO sound stream
*
* @related AudioListener
*/
void samples(float[] sampL, float[] sampR);
// TODO: consider replacing above two methods with this single one
// void samples( MultiChannelBuffer buffer );
}
| bsd-2-clause |
n4ybn/yavijava | src/main/java/com/vmware/vim25/ArrayOfIpPoolManagerIpAllocation.java | 2294 | /*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
public class ArrayOfIpPoolManagerIpAllocation {
public IpPoolManagerIpAllocation[] IpPoolManagerIpAllocation;
public IpPoolManagerIpAllocation[] getIpPoolManagerIpAllocation() {
return this.IpPoolManagerIpAllocation;
}
public IpPoolManagerIpAllocation getIpPoolManagerIpAllocation(int i) {
return this.IpPoolManagerIpAllocation[i];
}
public void setIpPoolManagerIpAllocation(IpPoolManagerIpAllocation[] IpPoolManagerIpAllocation) {
this.IpPoolManagerIpAllocation = IpPoolManagerIpAllocation;
}
} | bsd-3-clause |
eity0323/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/producers/SettableProducerContext.java | 5117 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.imagepipeline.producers;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import java.util.List;
import com.facebook.common.internal.Lists;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.internal.VisibleForTesting;
import com.facebook.imagepipeline.common.Priority;
import com.facebook.imagepipeline.request.ImageRequest;
/**
* ProducerContext that allows the client to cancel an image request in-flight.
*/
@ThreadSafe
public class SettableProducerContext implements ProducerContext {
private final ImageRequest mImageRequest;
private final String mId;
private final ProducerListener mProducerListener;
private final Object mCallerContext;
@GuardedBy("this")
private final List<ProducerContextCallbacks> mCallbacks;
@GuardedBy("this")
private boolean mIsCancelled;
@GuardedBy("this")
private boolean mIsPrefetch;
@GuardedBy("this")
private Priority mPriority;
@GuardedBy("this")
private boolean mIsIntermediateResultExpected;
public SettableProducerContext(
ImageRequest imageRequest,
String id,
ProducerListener producerListener,
Object callerContext,
boolean isPrefetch,
boolean isIntermediateResultExpected,
Priority priority) {
mImageRequest = Preconditions.checkNotNull(imageRequest);
mId = Preconditions.checkNotNull(id);
mProducerListener = Preconditions.checkNotNull(producerListener);
mCallerContext = callerContext;
mIsPrefetch = isPrefetch;
mIsIntermediateResultExpected = isIntermediateResultExpected;
mPriority = priority;
mIsCancelled = false;
mCallbacks = Lists.newArrayList();
}
@Override
public ImageRequest getImageRequest() {
return mImageRequest;
}
@Override
public String getId() {
return mId;
}
@Override
public ProducerListener getListener() {
return mProducerListener;
}
@Override
public Object getCallerContext() {
return mCallerContext;
}
@Override
public synchronized boolean isPrefetch() {
return mIsPrefetch;
}
@Override
public synchronized Priority getPriority() {
return mPriority;
}
@Override
public synchronized boolean isIntermediateResultExpected() {
return mIsIntermediateResultExpected;
}
@Override
public void addCallbacks(ProducerContextCallbacks callbacks) {
boolean cancelImmediately = false;
synchronized (this) {
mCallbacks.add(callbacks);
if (mIsCancelled) {
cancelImmediately = true;
}
}
if (cancelImmediately) {
callbacks.onCancellationRequested();
}
}
/**
* Cancels the request processing.
*/
public void cancel() {
List<ProducerContextCallbacks> callbacks = null;
synchronized (this) {
if (!mIsCancelled) {
mIsCancelled = true;
callbacks = Lists.newArrayList(mCallbacks);
}
}
if (callbacks != null) {
for (ProducerContextCallbacks callback : callbacks) {
callback.onCancellationRequested();
}
}
}
/**
* Set whether the request is a prefetch request or not.
* @param isPrefetch
*/
public void setIsPrefetch(boolean isPrefetch) {
List<ProducerContextCallbacks> callbacks = null;
synchronized (this) {
if (mIsPrefetch != isPrefetch) {
mIsPrefetch = isPrefetch;
callbacks = Lists.newArrayList(mCallbacks);
}
}
if (callbacks != null) {
for (ProducerContextCallbacks callback : callbacks) {
callback.onIsPrefetchChanged();
}
}
}
/**
* Set whether intermediate result is expected or not
* @param isIntermediateResultExpected
*/
public void setIsIntermediateResultExpected(boolean isIntermediateResultExpected) {
List<ProducerContextCallbacks> callbacks = null;
synchronized (this) {
if (mIsIntermediateResultExpected != isIntermediateResultExpected) {
mIsIntermediateResultExpected = isIntermediateResultExpected;
callbacks = Lists.newArrayList(mCallbacks);
}
}
if (callbacks != null) {
for (ProducerContextCallbacks callback : callbacks) {
callback.onIsIntermediateResultExpectedChanged();
}
}
}
/**
* Set the priority of the request
* @param priority
*/
public void setPriority(Priority priority) {
List<ProducerContextCallbacks> callbacks = null;
synchronized (this) {
if (mPriority != priority) {
mPriority = priority;
callbacks = Lists.newArrayList(mCallbacks);
}
}
if (callbacks != null) {
for (ProducerContextCallbacks callback : callbacks) {
callback.onPriorityChanged();
}
}
}
@VisibleForTesting
synchronized boolean isCancelled() {
return mIsCancelled;
}
}
| bsd-3-clause |
fregaham/KiWi | src/action/kiwi/service/reasoning/ClasspathRuleLoader.java | 4488 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the KiWi Project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Contributor(s):
*
*
*/
package kiwi.service.reasoning;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;
import kiwi.api.reasoning.RuleLoader;
/** Loads a file from classpath line by line.
*
*
* @author Jakub Kotowski
*
*/
public class ClasspathRuleLoader implements RuleLoader {
private static String RULES_FILE = "kiwi/service/reasoning/rules.txt";
//"($1 http://www.w3.org/1999/02/22-rdf-syntax-ns#type $2) -> ($1 http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/1999/02/22-rdf-syntax-ns#Resource)"
/*static String[] rules = {"($1 http://xmlns.com/foaf/0.1/firstName $2) -> (http://dummy.com/person/dummy http://xmlns.com/foaf/0.1/firstName $2)",
"($1 http://www.w3.org/1999/02/22-rdf-syntax-ns#subClass $2), ($2 http://www.w3.org/1999/02/22-rdf-syntax-ns#subClass $3) -> ($1 http://www.w3.org/1999/02/22-rdf-syntax-ns#subClass $3)",
"($1 http://ex.com/p $2), ($2 http://ex.com/p $1), ($1 http://ex.com/sc $3) -> ($1 http://ex.com/sc $3), (http://ex.com/u/u1 http://ex.com/p $2)",
"($1 http://xmlns.com/foaf/0.1/firstName $2) -> ($1 http://xmlns.com/foaf/0.1/firstName \"Inferred First Name\")"
}; */
private ArrayList<String> rules;
Log log = Logging.getLog(this.getClass());
public ClasspathRuleLoader() {
}
/** Loads rules from a file on classpath.
*
* Expects the file to contain one rule per line, ignores empty lines.
*/
private ArrayList<String> loadRulesFromClasspath() {
rules = new ArrayList<String>();
java.net.URL url = Thread.currentThread().getContextClassLoader().getResource(RULES_FILE); //ClassLoader.getSystemResource(RULES_FILE);
//log.info("Loading rules from #0", url);
try {
File f = new File(url.toURI());
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.equals(""))
rules.add(line);
}
} catch (URISyntaxException e) {
log.error("Error while loading rules from file "+RULES_FILE+". The error was: "+e.getMessage());
return null;
} catch (FileNotFoundException e) {
log.error("File "+RULES_FILE+" not found. The error was: "+e.getMessage());
return null;
} catch (IOException e) {
log.error("Error while reading from file "+RULES_FILE+". The error was: "+e.getMessage());
return null;
}
//log.info("Rules loaded.");
return rules;
}
public ArrayList<String> loadRules() {
return loadRulesFromClasspath();
}
}
| bsd-3-clause |
codeck/XChange | xchange-bitcoinde/src/test/java/com/xeiam/xchange/bitcoinde/dto/marketdata/BitcoindeRateTest.java | 1069 | package com.xeiam.xchange.bitcoinde.dto.marketdata;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author matthewdowney
*/
public class BitcoindeRateTest {
@Test
public void testBitcoindeRate() throws JsonParseException, JsonMappingException, IOException {
// Read in the JSON from the example resources
InputStream is = BitcoindeRateTest.class.getResourceAsStream("/rate.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
BitcoindeRate bitcoindeRate = mapper.readValue(is, BitcoindeRate.class);
// Make sure we get what we're expecting
assertEquals(bitcoindeRate.getRate_weighted(), "225.18347646");
assertEquals(bitcoindeRate.getRate_weighted_12h(), "224.91338164");
assertEquals(bitcoindeRate.getRate_weighted_3h(), "225.18347646");
}
}
| mit |
jonathan-major/Rapture | Libs/RaptureAddinCore/src/main/java/rapture/audit/AuditLog.java | 1975 | /**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package rapture.audit;
import java.util.List;
import java.util.Map;
import rapture.common.RaptureURI;
import rapture.common.model.AuditLogEntry;
/**
* An audit log is used to write log messages for audit purposes
*
* @author alan
*
*/
public interface AuditLog {
List<AuditLogEntry> getRecentEntries(int count);
void setConfig(String logId, Map<String, String> config);
void setInstanceName(String instanceName);
Boolean writeLog(String category, int level, String message, String user);
Boolean writeLogData(String category, int level, String message, String user, Map<String, Object> data);
List<AuditLogEntry> getEntriesSince(AuditLogEntry when);
void setContext(RaptureURI internalURI);
List<AuditLogEntry> getRecentUserActivity(String user, int count);
}
| mit |
fabitous/arquiteturadesoftware-master_ | asw.rpg1/src/com/github/awvalenti/arquiteturadesoftware/rpg1/versao5/arquiteturadefinida/logicajogo/Elemento.java | 425 | package com.github.awvalenti.arquiteturadesoftware.rpg1.versao5.arquiteturadefinida.logicajogo;
public enum Elemento {
AGUA("/agua.png"),
MACA("/maca.png"),
PERSONAGEM("/personagem.png"),
GRAMA("/grama.png"),
PORTAL("/passagem.png"),
;
private final String caminhoImagem;
Elemento(String caminhoImagem) {
this.caminhoImagem = caminhoImagem;
}
public String getCaminhoImagem() {
return caminhoImagem;
}
}
| mit |
scarabus/Rapture | Libs/Reflex/src/main/java/reflex/function/LibNode.java | 2424 | /**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reflex.function;
import reflex.IReflexHandler;
import reflex.Scope;
import reflex.debug.IReflexDebugger;
import reflex.node.BaseNode;
import reflex.node.ReflexNode;
import reflex.value.ReflexLibValue;
import reflex.value.ReflexValue;
import reflex.value.internal.ReflexVoidValue;
/**
* Try to instantiate an instance of the class provided by a class name. It must
* implement IReflexLibrary
*
* @author amkimian
*
*/
public class LibNode extends BaseNode {
private ReflexNode expression;
public LibNode(int lineNumber, IReflexHandler handler, Scope s, ReflexNode e) {
super(lineNumber, handler, s);
expression = e;
}
@Override
public ReflexValue evaluate(IReflexDebugger debugger, Scope scope) {
debugger.stepStart(this, scope);
ReflexValue value = expression.evaluate(debugger, scope);
ReflexValue retVal = new ReflexVoidValue(lineNumber);
if (value.isString()) {
retVal = new ReflexValue(new ReflexLibValue(value.asString(), handler));
}
debugger.stepEnd(this, retVal, scope);
return retVal;
}
@Override
public String toString() {
return super.toString() + " - " + String.format("lib(%s)", expression);
}
}
| mit |
richardissuperman/MiniWeChat-Server | src/server/ClientRequest_Dispatcher.java | 3570 | package server;
import exception.NoIpException;
import protocol.ProtoHead;
import tools.Debug;
/**
* 用switch进行请求分发
*
* @author Feng
*
*/
public class ClientRequest_Dispatcher {
// public static ClientRequest_Dispatcher instance = new
// ClientRequest_Dispatcher();
private Server_User server_User;
private Server_Friend server_Friend;
private Server_Chatting server_Chatting;
public Server_User getServer_User() {
return server_User;
}
public void setServer_User(Server_User server_User) {
this.server_User = server_User;
}
public Server_Friend getServer_Friend() {
return server_Friend;
}
public void setServer_Friend(Server_Friend server_Friend) {
this.server_Friend = server_Friend;
}
public Server_Chatting getServer_Chatting() {
return server_Chatting;
}
public void setServer_Chatting(Server_Chatting server_Chatting) {
this.server_Chatting = server_Chatting;
}
/**
* 根据请求的类型分配给不同的处理器
*
* @param networkMessage
* @author Feng
*/
public void dispatcher(NetworkPacket networkPacket) {
// System.out.println("IP" +
// networkMessage.ioSession.getRemoteAddress());
try {
Debug.log("ClientRequest_Dispatcher", "Client(" + ServerModel.getIoSessionKey(networkPacket.ioSession)
+ ")'s request type is : " + networkPacket.getMessageType().toString());
} catch (Exception e1) {
}
try {
switch (networkPacket.getMessageType().getNumber()) {
// Client回复心跳包
// case ProtoHead.ENetworkMessage.KEEP_ALIVE_SYNC_VALUE:
// server_User.keepAlive(networkPacket);
// break;
case ProtoHead.ENetworkMessage.REGISTER_REQ_VALUE:
server_User.register(networkPacket);
break;
case ProtoHead.ENetworkMessage.LOGIN_REQ_VALUE:
server_User.login(networkPacket);
break;
case ProtoHead.ENetworkMessage.PERSONALSETTINGS_REQ_VALUE:
server_User.personalSettings(networkPacket);
break;
case ProtoHead.ENetworkMessage.GET_USERINFO_REQ_VALUE:
server_Friend.getUserInfo(networkPacket);
break;
case ProtoHead.ENetworkMessage.ADD_FRIEND_REQ_VALUE:
server_Friend.addFriend(networkPacket);
break;
case ProtoHead.ENetworkMessage.DELETE_FRIEND_REQ_VALUE:
server_Friend.deleteFriend(networkPacket);
break;
// 另一个人登陆,本用户被踢下的通知的回复
// case ProtoHead.ENetworkMessage.OFFLINE_SYNC_VALUE:
// server_User.clientOfflineResponse(networkPacket);
// break;
case ProtoHead.ENetworkMessage.LOGOUT_REQ_VALUE:
server_User.logout(networkPacket);
break;
case ProtoHead.ENetworkMessage.GET_PERSONALINFO_REQ_VALUE:
server_User.getPersonalInfo(networkPacket);
break;
// client发送消息
case ProtoHead.ENetworkMessage.SEND_CHAT_REQ_VALUE:
server_Chatting.clientSendChatting(networkPacket);
break;
// 服务器向客户端发送未接收消息,客户端的回答
// case ProtoHead.ENetworkMessage.RECEIVE_CHAT_SYNC_VALUE:
// server_Chatting.clientReceiveChatting(networkPacket);
// break;
// 创建群聊
case ProtoHead.ENetworkMessage.CREATE_GROUP_CHAT_REQ_VALUE:
server_Chatting.createGroupChatting(networkPacket);
break;
// 修改群聊成员
case ProtoHead.ENetworkMessage.CHANGE_GROUP_REQ_VALUE:
server_Chatting.changeGroup(networkPacket);
break;
// 获取群资料
case ProtoHead.ENetworkMessage.GET_GROUP_INFO_REQ_VALUE:
server_Chatting.getGroupInfo(networkPacket);
break;
default:
break;
}
} catch (NoIpException e) {
e.printStackTrace();
}
}
}
| mit |
tjlee/at.info-knowledge-base | functional test automation/webdriver/methods-interceptor-via-aspectj-on-java/src/main/java/info/testing/automated/abstraction/WebDriver.java | 135 | package info.testing.automated.abstraction;
/**
* Author: Serhii Kuts
*/
public class WebDriver {
public void quit() {
}
}
| mit |
agoncal/core | ui/api/src/main/java/org/jboss/forge/addon/ui/result/NavigationResultEntry.java | 1027 | /**
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.ui.result;
import org.jboss.forge.addon.ui.command.UICommand;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.controller.CommandController;
import org.jboss.forge.furnace.addons.AddonRegistry;
/**
* Encapsulates the {@link UICommand} creation.
*
* This interface should only be used in {@link CommandController} implementations
*
* @author <a href="ggastald@redhat.com">George Gastaldi</a>
*/
public interface NavigationResultEntry
{
/**
* Returns a Command associated with this {@link NavigationResultEntry}
*
* @param addonRegistry the {@link AddonRegistry} instance of this
* @param context the current {@link UIContext}
* @return command instance, never null
*/
UICommand getCommand(AddonRegistry addonRegistry, UIContext context);
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/schemamodelgenerator/Employee.java | 1786 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* dmccann - Mar 2/2009 - 2.0 - Initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.oxm.schemamodelgenerator;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import javax.activation.DataHandler;
public class Employee {
public String name; // XMLDirectMapping - PK
public Address address; // XMLCompositeObjectMapping
public Address billingAddress; // XMLObjectReferenceMapping
public Collection<PhoneNumber> phoneNumbers; // XMLCompositeCollectionMapping
public Collection<Number> projectIDs; // XMLDirectCollectionMapping
public Collection<Object> stuff; // XMLAnyCollectionMapping
public Object choice; // XMLChoiceObjectMapping
public Collection<Object> choices; // XMLChoiceCollectionMapping
public DataHandler data; // XMLBinaryDataMapping
public List<byte[]> bytes; // XMLBinaryDataCollectionMapping
public URL aUrl;
public Employee() {}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/models/transparentindirection/IndirectContainerProject.java | 15554 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.transparentindirection;
import java.util.*;
import org.eclipse.persistence.descriptors.RelationalDescriptor;
/**
* override the generated methods with hand-modified methods;
* allow different container policies (Collection/Vector, Map/Hashtable)
*/
public abstract class IndirectContainerProject extends GeneratedIndirectContainerProject {
public IndirectContainerProject() {
super();
}
/**
* modifications are marked with "bjv"
*/
protected void buildOrderDescriptor() {
RelationalDescriptor descriptor = new RelationalDescriptor();
// SECTION: DESCRIPTOR
descriptor.setJavaClass(this.orderClass());// bjv
Vector vector = new Vector();
vector.addElement("ORD");
descriptor.setTableNames(vector);
descriptor.addPrimaryKeyFieldName("ORD.ID");
// SECTION: PROPERTIES
descriptor.setIdentityMapClass(org.eclipse.persistence.internal.identitymaps.FullIdentityMap.class);
descriptor.setSequenceNumberName("order_seq");
descriptor.setSequenceNumberFieldName("ID");
descriptor.setExistenceChecking("Check cache");
descriptor.setIdentityMapSize(100);
// SECTION: COPY POLICY
descriptor.createCopyPolicy("constructor");
// SECTION: INSTANTIATION POLICY
descriptor.createInstantiationPolicy("constructor");
// SECTION: DIRECTCOLLECTIONMAPPING
org.eclipse.persistence.mappings.DirectCollectionMapping directcollectionmapping = new org.eclipse.persistence.mappings.DirectCollectionMapping();
directcollectionmapping.setAttributeName("contacts");
directcollectionmapping.setIsReadOnly(false);
directcollectionmapping.setUsesIndirection(false);
directcollectionmapping.setIsPrivateOwned(true);
this.configureContactContainer(directcollectionmapping);// bjv
directcollectionmapping.setDirectFieldName("CONTACT.NAME");
directcollectionmapping.setReferenceTableName("CONTACT");
directcollectionmapping.addReferenceKeyFieldName("CONTACT.ORDER_ID", "ORD.ID");
descriptor.addMapping(directcollectionmapping);
// SECTION: DIRECTCOLLECTIONMAPPING
org.eclipse.persistence.mappings.DirectCollectionMapping directcollectionmapping1 = new org.eclipse.persistence.mappings.DirectCollectionMapping();
directcollectionmapping1.setAttributeName("contacts2");
directcollectionmapping1.setIsReadOnly(false);
directcollectionmapping1.setUsesIndirection(false);
directcollectionmapping1.setIsPrivateOwned(true);
this.configureContactContainer2(directcollectionmapping1);// bjv
directcollectionmapping1.setDirectFieldName("CONTACT2.NAME");
directcollectionmapping1.setReferenceTableName("CONTACT2");
directcollectionmapping1.addReferenceKeyFieldName("CONTACT2.ORDER_ID", "ORD.ID");
descriptor.addMapping(directcollectionmapping1);
// SECTION: DIRECTTOFIELDMAPPING
org.eclipse.persistence.mappings.DirectToFieldMapping directtofieldmapping = new org.eclipse.persistence.mappings.DirectToFieldMapping();
directtofieldmapping.setAttributeName("customerName");
directtofieldmapping.setIsReadOnly(false);
directtofieldmapping.setFieldName("ORD.CUSTNAME");
descriptor.addMapping(directtofieldmapping);
// SECTION: DIRECTTOFIELDMAPPING
org.eclipse.persistence.mappings.DirectToFieldMapping directtofieldmapping1 = new org.eclipse.persistence.mappings.DirectToFieldMapping();
directtofieldmapping1.setAttributeName("id");
directtofieldmapping1.setIsReadOnly(false);
directtofieldmapping1.setFieldName("ORD.ID");
descriptor.addMapping(directtofieldmapping1);
// SECTION: MANYTOMANYMAPPING
org.eclipse.persistence.mappings.ManyToManyMapping manytomanymapping = new org.eclipse.persistence.mappings.ManyToManyMapping();
manytomanymapping.setAttributeName("salesReps");
manytomanymapping.setIsReadOnly(false);
manytomanymapping.setUsesIndirection(false);
manytomanymapping.setReferenceClass(salesRepClass());
manytomanymapping.setIsPrivateOwned(false);
this.configureSalesRepContainer(manytomanymapping);// bjv
manytomanymapping.setRelationTableName("ORDREP");
manytomanymapping.addSourceRelationKeyFieldName("ORDREP.ORDER_ID", "ORD.ID");
manytomanymapping.addTargetRelationKeyFieldName("ORDREP.SALEREP_ID", "SALEREP.ID");
descriptor.addMapping(manytomanymapping);
// SECTION: MANYTOMANYMAPPING
org.eclipse.persistence.mappings.ManyToManyMapping manytomanymapping1 = new org.eclipse.persistence.mappings.ManyToManyMapping();
manytomanymapping1.setAttributeName("salesReps2");
manytomanymapping1.setIsReadOnly(false);
manytomanymapping1.setUsesIndirection(false);
manytomanymapping1.setReferenceClass(salesRepClass());
manytomanymapping1.setIsPrivateOwned(false);
this.configureSalesRepContainer2(manytomanymapping1);// bjv
manytomanymapping1.setRelationTableName("ORDREP2");
manytomanymapping1.addSourceRelationKeyFieldName("ORDREP2.ORDER_ID", "ORD.ID");
manytomanymapping1.addTargetRelationKeyFieldName("ORDREP2.SALEREP_ID", "SALEREP.ID");
descriptor.addMapping(manytomanymapping1);
// SECTION: ONETOMANYMAPPING
org.eclipse.persistence.mappings.OneToManyMapping onetomanymapping = new org.eclipse.persistence.mappings.OneToManyMapping();
onetomanymapping.setAttributeName("lines");
onetomanymapping.setIsReadOnly(false);
onetomanymapping.setUsesIndirection(false);
onetomanymapping.setReferenceClass(orderLineClass());
onetomanymapping.setIsPrivateOwned(true);
this.configureLineContainer(onetomanymapping);// bjv
onetomanymapping.addTargetForeignKeyFieldName("ORDLINE.ORDER_ID", "ORD.ID");
descriptor.addMapping(onetomanymapping);
// SECTION: TRANSFORMATIONMAPPING
org.eclipse.persistence.mappings.TransformationMapping transformationmapping = new org.eclipse.persistence.mappings.TransformationMapping();
transformationmapping.setAttributeName("total");
transformationmapping.setIsReadOnly(false);
transformationmapping.setUsesIndirection(true);
transformationmapping.setAttributeTransformation("getTotalFromRow");
transformationmapping.addFieldTransformation("ORD.TOTT", "getTotalTens");
transformationmapping.addFieldTransformation("ORD.TOTO", "getTotalOnes");
descriptor.addMapping(transformationmapping);
// SECTION: TRANSFORMATIONMAPPING
org.eclipse.persistence.mappings.TransformationMapping transformationmapping2 = new org.eclipse.persistence.mappings.TransformationMapping();
transformationmapping2.setAttributeName("total2");
transformationmapping2.setIsReadOnly(false);
transformationmapping2.setUsesIndirection(false);
transformationmapping2.setAttributeTransformation("getTotalFromRow2");
transformationmapping2.addFieldTransformation("ORD.TOTT2", "getTotalTens2");
transformationmapping2.addFieldTransformation("ORD.TOTO2", "getTotalOnes2");
descriptor.addMapping(transformationmapping2);
this.modifyOrderDescriptor(descriptor);// bjv
addDescriptor(descriptor);
}
/**
* modifications are marked with "bjv"
*/
protected void buildOrderLineDescriptor() {
RelationalDescriptor descriptor = new RelationalDescriptor();
// SECTION: DESCRIPTOR
descriptor.setJavaClass(orderLineClass());
Vector vector = new Vector();
vector.addElement("ORDLINE");
descriptor.setTableNames(vector);
descriptor.addPrimaryKeyFieldName("ORDLINE.ID");
// SECTION: PROPERTIES
descriptor.setIdentityMapClass(org.eclipse.persistence.internal.identitymaps.FullIdentityMap.class);
descriptor.setSequenceNumberName("orderline");
descriptor.setSequenceNumberFieldName("ID");
descriptor.setExistenceChecking("Check cache");
descriptor.setIdentityMapSize(100);
// SECTION: COPY POLICY
descriptor.createCopyPolicy("constructor");
// SECTION: INSTANTIATION POLICY
descriptor.createInstantiationPolicy("constructor");
// SECTION: DIRECTTOFIELDMAPPING
org.eclipse.persistence.mappings.DirectToFieldMapping directtofieldmapping = new org.eclipse.persistence.mappings.DirectToFieldMapping();
directtofieldmapping.setAttributeName("id");
directtofieldmapping.setIsReadOnly(false);
directtofieldmapping.setFieldName("ORDLINE.ID");
descriptor.addMapping(directtofieldmapping);
// SECTION: DIRECTTOFIELDMAPPING
org.eclipse.persistence.mappings.DirectToFieldMapping directtofieldmapping1 = new org.eclipse.persistence.mappings.DirectToFieldMapping();
directtofieldmapping1.setAttributeName("itemName");
directtofieldmapping1.setIsReadOnly(false);
directtofieldmapping1.setFieldName("ORDLINE.ITEM_NAME");
descriptor.addMapping(directtofieldmapping1);
// SECTION: DIRECTTOFIELDMAPPING
org.eclipse.persistence.mappings.DirectToFieldMapping directtofieldmapping2 = new org.eclipse.persistence.mappings.DirectToFieldMapping();
directtofieldmapping2.setAttributeName("quantity");
directtofieldmapping2.setIsReadOnly(false);
directtofieldmapping2.setFieldName("ORDLINE.QUANTITY");
descriptor.addMapping(directtofieldmapping2);
// SECTION: ONETOONEMAPPING
org.eclipse.persistence.mappings.OneToOneMapping onetoonemapping = new org.eclipse.persistence.mappings.OneToOneMapping();
onetoonemapping.setAttributeName("order");
onetoonemapping.setIsReadOnly(false);
onetoonemapping.setUsesIndirection(false);
onetoonemapping.setReferenceClass(this.orderClass());// bjv
onetoonemapping.setIsPrivateOwned(false);
onetoonemapping.addForeignKeyFieldName("ORDLINE.ORDER_ID", "ORD.ID");
descriptor.addMapping(onetoonemapping);
addDescriptor(descriptor);
}
/**
* modifications are marked with "bjv"
*/
protected void buildSalesRepDescriptor() {
RelationalDescriptor descriptor = new RelationalDescriptor();
// SECTION: DESCRIPTOR
descriptor.setJavaClass(salesRepClass());
Vector vector = new Vector();
vector.addElement("SALEREP");
descriptor.setTableNames(vector);
descriptor.addPrimaryKeyFieldName("SALEREP.ID");
// SECTION: PROPERTIES
descriptor.setIdentityMapClass(org.eclipse.persistence.internal.identitymaps.FullIdentityMap.class);
descriptor.setSequenceNumberName("salesrep");
descriptor.setSequenceNumberFieldName("ID");
descriptor.setExistenceChecking("Check cache");
descriptor.setIdentityMapSize(100);
// SECTION: COPY POLICY
descriptor.createCopyPolicy("constructor");
// SECTION: INSTANTIATION POLICY
descriptor.createInstantiationPolicy("constructor");
// SECTION: DIRECTTOFIELDMAPPING
org.eclipse.persistence.mappings.DirectToFieldMapping directtofieldmapping = new org.eclipse.persistence.mappings.DirectToFieldMapping();
directtofieldmapping.setAttributeName("id");
directtofieldmapping.setIsReadOnly(false);
directtofieldmapping.setFieldName("SALEREP.ID");
descriptor.addMapping(directtofieldmapping);
// SECTION: DIRECTTOFIELDMAPPING
org.eclipse.persistence.mappings.DirectToFieldMapping directtofieldmapping1 = new org.eclipse.persistence.mappings.DirectToFieldMapping();
directtofieldmapping1.setAttributeName("name");
directtofieldmapping1.setIsReadOnly(false);
directtofieldmapping1.setFieldName("SALEREP.NAME");
descriptor.addMapping(directtofieldmapping1);
// SECTION: MANYTOMANYMAPPING
org.eclipse.persistence.mappings.ManyToManyMapping manytomanymapping = new org.eclipse.persistence.mappings.ManyToManyMapping();
manytomanymapping.setAttributeName("orders");
manytomanymapping.setIsReadOnly(true);
manytomanymapping.setUsesIndirection(false);
manytomanymapping.setReferenceClass(this.orderClass());// bjv
manytomanymapping.setIsPrivateOwned(false);
manytomanymapping.useCollectionClass(java.util.Vector.class);
manytomanymapping.setRelationTableName("ORDREP");
manytomanymapping.addSourceRelationKeyFieldName("ORDREP.SALEREP_ID", "SALEREP.ID");
manytomanymapping.addTargetRelationKeyFieldName("ORDREP.ORDER_ID", "ORD.ID");
descriptor.addMapping(manytomanymapping);
// SECTION: MANYTOMANYMAPPING
org.eclipse.persistence.mappings.ManyToManyMapping manytomanymapping1 = new org.eclipse.persistence.mappings.ManyToManyMapping();
manytomanymapping1.setAttributeName("orders2");
manytomanymapping1.setIsReadOnly(true);
manytomanymapping1.setUsesIndirection(false);
manytomanymapping1.setReferenceClass(this.orderClass());// bjv
manytomanymapping1.setIsPrivateOwned(false);
manytomanymapping1.useCollectionClass(java.util.Vector.class);
manytomanymapping1.setRelationTableName("ORDREP2");
manytomanymapping1.addSourceRelationKeyFieldName("ORDREP2.SALEREP_ID", "SALEREP.ID");
manytomanymapping1.addTargetRelationKeyFieldName("ORDREP2.ORDER_ID", "ORD.ID");
descriptor.addMapping(manytomanymapping1);
addDescriptor(descriptor);
}
protected abstract void configureContactContainer(org.eclipse.persistence.mappings.DirectCollectionMapping directcollectionmapping);
protected void configureContactContainer2(org.eclipse.persistence.mappings.DirectCollectionMapping directcollectionmapping) {
directcollectionmapping.useCollectionClass(java.util.Stack.class);
}
protected abstract void configureLineContainer(org.eclipse.persistence.mappings.OneToManyMapping onetomanymapping);
protected abstract void configureSalesRepContainer(org.eclipse.persistence.mappings.ManyToManyMapping manytomanymapping);
protected void configureSalesRepContainer2(org.eclipse.persistence.mappings.ManyToManyMapping manytomanymapping) {
manytomanymapping.useMapClass(org.eclipse.persistence.testing.tests.transparentindirection.TestHashtable.class, "getKey");
}
protected abstract void modifyOrderDescriptor(RelationalDescriptor descriptor);
protected abstract Class orderClass();
protected abstract Class orderLineClass();
protected abstract Class salesRepClass();
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/JAXBIntListTestCases.java | 2105 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Denise Smith June 05, 2009 - Initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.listofobjects;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
public class JAXBIntListTestCases extends JAXBIntegerListTestCases {
private Type typeToUnmarshalTo;
public JAXBIntListTestCases(String name) throws Exception {
super(name);
}
protected Type getTypeToUnmarshalTo() throws Exception {
if(typeToUnmarshalTo == null){
Type listOfInts = new ParameterizedType() {
Type[] typeArgs = {int.class};
public Type[] getActualTypeArguments() { return typeArgs;}
public Type getOwnerType() { return null; }
public Type getRawType() { return List.class; }
};
typeToUnmarshalTo = listOfInts;
}
return typeToUnmarshalTo;
}
protected Object getControlObject() {
ArrayList<Integer> integers = new ArrayList<Integer>();
integers.add(10);
integers.add(20);
integers.add(30);
integers.add(40);
QName qname = new QName("examplenamespace", "root");
JAXBElement jaxbElement = new JAXBElement(qname, Object.class, null);
jaxbElement.setValue(integers);
return jaxbElement;
}
}
| epl-1.0 |
Distrotech/icedtea6-1.13 | generated/com/sun/tools/javac/resources/javac_zh_CN.java | 9383 | package com.sun.tools.javac.resources;
import java.util.ListResourceBundle;
public final class javac_zh_CN extends ListResourceBundle {
protected final Object[][] getContents() {
return new Object[][] {
{ "javac.err.empty.A.argument", "-A \u9700\u8981\u4E00\u4E2A\u53C2\u6570\uFF1B\u4F7F\u7528 ''-Akey'' \u6216 ''-Akey=value''" },
{ "javac.err.error.writing.file", "\u5199\u5165 {0} \u65F6\u51FA\u9519\uFF1B{1}" },
{ "javac.err.file.not.directory", "\u4E0D\u662F\u76EE\u5F55: {0}" },
{ "javac.err.file.not.file", "\u4E0D\u662F\u6587\u4EF6: {0}" },
{ "javac.err.file.not.found", "\u627E\u4E0D\u5230\u6587\u4EF6\uFF1A {0}" },
{ "javac.err.invalid.A.key", "\u6CE8\u91CA\u5904\u7406\u5668\u9009\u9879\"{0}\"\u4E2D\u7684\u5173\u952E\u5B57\u4E0D\u662F\u4EE5\u70B9\u5206\u9694\u7684\u6807\u8BC6\u7B26\u5E8F\u5217" },
{ "javac.err.invalid.arg", "\u65E0\u6548\u7684\u53C2\u6570\uFF1A {0}" },
{ "javac.err.invalid.flag", "\u65E0\u6548\u7684\u6807\u5FD7\uFF1A {0}" },
{ "javac.err.invalid.source", "\u65E0\u6548\u7684\u6E90\u7248\u672C\uFF1A {0}" },
{ "javac.err.invalid.target", "\u65E0\u6548\u7684\u76EE\u6807\u7248\u672C\uFF1A {0}" },
{ "javac.err.no.source.files", "\u65E0\u6E90\u6587\u4EF6" },
{ "javac.err.req.arg", "{0} \u9700\u8981\u53C2\u6570" },
{ "javac.fullVersion", "{0} \u5B8C\u6574\u7248\u672C \"{1}\"" },
{ "javac.msg.bug", "\u7F16\u8BD1\u5668 ({0}) \u4E2D\u51FA\u73B0\u5F02\u5E38\u3002 \u5982\u679C\u5728 Bug Parade \u4E2D\u6CA1\u6709\u627E\u5230\u8BE5\u9519\u8BEF\uFF0C\u8BF7\u5728 Java Developer Connection (http://java.sun.com/webapps/bugreport) \u5BF9\u8BE5\u9519\u8BEF\u8FDB\u884C\u5F52\u6863\u3002 \u8BF7\u5728\u62A5\u544A\u4E2D\u9644\u4E0A\u60A8\u7684\u7A0B\u5E8F\u548C\u4EE5\u4E0B\u8BCA\u65AD\u4FE1\u606F\u3002\u8C22\u8C22\u60A8\u7684\u5408\u4F5C\u3002" },
{ "javac.msg.io", "\n\n\u53D1\u751F\u8F93\u5165/\u8F93\u51FA\u9519\u8BEF\u3002\n\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u53C2\u9605\u4EE5\u4E0B\u5806\u6808\u8FFD\u8E2A\u3002\n" },
{ "javac.msg.proc.annotation.uncaught.exception", "\n\n\u6CE8\u91CA\u5904\u7406\u7A0B\u5E8F\u629B\u51FA\u672A\u6355\u83B7\u7684\u5F02\u5E38\u3002\n\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u53C2\u9605\u4EE5\u4E0B\u5806\u6808\u8FFD\u8E2A\u3002\n" },
{ "javac.msg.resource", "\n\n\u7CFB\u7EDF\u8D44\u6E90\u4E0D\u8DB3\u3002\n\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u53C2\u9605\u4EE5\u4E0B\u5806\u6808\u8FFD\u8E2A\u3002\n" },
{ "javac.msg.usage", "\u7528\u6CD5: {0} <options> <source files>\n-help \u7528\u4E8E\u5217\u51FA\u53EF\u80FD\u7684\u9009\u9879" },
{ "javac.msg.usage.header", "\u7528\u6CD5\uFF1A{0} <\u9009\u9879> <\u6E90\u6587\u4EF6>\n\u5176\u4E2D\uFF0C\u53EF\u80FD\u7684\u9009\u9879\u5305\u62EC\uFF1A" },
{ "javac.msg.usage.nonstandard.footer", "\u8FD9\u4E9B\u9009\u9879\u90FD\u662F\u975E\u6807\u51C6\u9009\u9879\uFF0C\u5982\u6709\u66F4\u6539\uFF0C\u6055\u4E0D\u53E6\u884C\u901A\u77E5\u3002" },
{ "javac.opt.A", "\u4F20\u9012\u7ED9\u6CE8\u91CA\u5904\u7406\u7A0B\u5E8F\u7684\u9009\u9879" },
{ "javac.opt.J", "\u76F4\u63A5\u5C06 <\u6807\u5FD7> \u4F20\u9012\u7ED9\u8FD0\u884C\u65F6\u7CFB\u7EDF" },
{ "javac.opt.X", "\u8F93\u51FA\u975E\u6807\u51C6\u9009\u9879\u7684\u63D0\u8981" },
{ "javac.opt.Xbootclasspath.a", "\u7F6E\u4E8E\u5F15\u5BFC\u7C7B\u8DEF\u5F84\u4E4B\u540E" },
{ "javac.opt.Xbootclasspath.p", "\u7F6E\u4E8E\u5F15\u5BFC\u7C7B\u8DEF\u5F84\u4E4B\u524D" },
{ "javac.opt.Xlint", "\u542F\u7528\u5EFA\u8BAE\u7684\u8B66\u544A" },
{ "javac.opt.Xlint.suboptlist", "\u542F\u7528\u6216\u7981\u7528\u7279\u5B9A\u7684\u8B66\u544A" },
{ "javac.opt.Xstdout", "\u91CD\u5B9A\u5411\u6807\u51C6\u8F93\u51FA" },
{ "javac.opt.arg.class", "<class>" },
{ "javac.opt.arg.class.list", "<class1>[,<class2>,<class3>...]" },
{ "javac.opt.arg.directory", "<\u76EE\u5F55>" },
{ "javac.opt.arg.dirs", "<\u76EE\u5F55>" },
{ "javac.opt.arg.encoding", "<\u7F16\u7801>" },
{ "javac.opt.arg.file", "<\u6587\u4EF6\u540D>" },
{ "javac.opt.arg.flag", "<\u6807\u5FD7>" },
{ "javac.opt.arg.key.equals.value", "key[=value]" },
{ "javac.opt.arg.number", "<\u7F16\u53F7>" },
{ "javac.opt.arg.path", "<\u8DEF\u5F84>" },
{ "javac.opt.arg.pathname", "<\u8DEF\u5F84\u540D>" },
{ "javac.opt.arg.release", "<\u7248\u672C>" },
{ "javac.opt.bootclasspath", "\u8986\u76D6\u5F15\u5BFC\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E" },
{ "javac.opt.classpath", "\u6307\u5B9A\u67E5\u627E\u7528\u6237\u7C7B\u6587\u4EF6\u548C\u6CE8\u91CA\u5904\u7406\u7A0B\u5E8F\u7684\u4F4D\u7F6E" },
{ "javac.opt.d", "\u6307\u5B9A\u5B58\u653E\u751F\u6210\u7684\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E" },
{ "javac.opt.deprecation", "\u8F93\u51FA\u4F7F\u7528\u5DF2\u8FC7\u65F6\u7684 API \u7684\u6E90\u4F4D\u7F6E" },
{ "javac.opt.encoding", "\u6307\u5B9A\u6E90\u6587\u4EF6\u4F7F\u7528\u7684\u5B57\u7B26\u7F16\u7801" },
{ "javac.opt.endorseddirs", "\u8986\u76D6\u7B7E\u540D\u7684\u6807\u51C6\u8DEF\u5F84\u7684\u4F4D\u7F6E" },
{ "javac.opt.extdirs", "\u8986\u76D6\u5B89\u88C5\u7684\u6269\u5C55\u76EE\u5F55\u7684\u4F4D\u7F6E" },
{ "javac.opt.g", "\u751F\u6210\u6240\u6709\u8C03\u8BD5\u4FE1\u606F" },
{ "javac.opt.g.lines.vars.source", "\u53EA\u751F\u6210\u67D0\u4E9B\u8C03\u8BD5\u4FE1\u606F" },
{ "javac.opt.g.none", "\u4E0D\u751F\u6210\u4EFB\u4F55\u8C03\u8BD5\u4FE1\u606F" },
{ "javac.opt.help", "\u8F93\u51FA\u6807\u51C6\u9009\u9879\u7684\u63D0\u8981" },
{ "javac.opt.implicit", "\u6307\u5B9A\u662F\u5426\u4E3A\u9690\u5F0F\u5F15\u7528\u6587\u4EF6\u751F\u6210\u7C7B\u6587\u4EF6 " },
{ "javac.opt.maxerrs", "\u8BBE\u7F6E\u8981\u8F93\u51FA\u7684\u9519\u8BEF\u7684\u6700\u5927\u6570\u76EE" },
{ "javac.opt.maxwarns", "\u8BBE\u7F6E\u8981\u8F93\u51FA\u7684\u8B66\u544A\u7684\u6700\u5927\u6570\u76EE" },
{ "javac.opt.moreinfo", "\u8F93\u51FA\u7C7B\u578B\u53D8\u91CF\u7684\u6269\u5C55\u4FE1\u606F" },
{ "javac.opt.nogj", "\u8BED\u8A00\u4E2D\u4E0D\u63A5\u53D7\u6CDB\u578B" },
{ "javac.opt.nowarn", "\u4E0D\u751F\u6210\u4EFB\u4F55\u8B66\u544A" },
{ "javac.opt.prefer", "\u6307\u5B9A\u8BFB\u53D6\u6587\u4EF6\uFF0C\u5F53\u540C\u65F6\u627E\u5230\u9690\u5F0F\u7F16\u8BD1\u7C7B\u7684\u6E90\u6587\u4EF6\u548C\u7C7B\u6587\u4EF6\u65F6" },
{ "javac.opt.print", "\u8F93\u51FA\u6307\u5B9A\u7C7B\u578B\u7684\u6587\u672C\u8868\u793A" },
{ "javac.opt.printProcessorInfo", "\u8F93\u51FA\u6709\u5173\u8BF7\u6C42\u5904\u7406\u7A0B\u5E8F\u5904\u7406\u54EA\u4E9B\u6CE8\u91CA\u7684\u4FE1\u606F" },
{ "javac.opt.printRounds", "\u8F93\u51FA\u6709\u5173\u6CE8\u91CA\u5904\u7406\u5FAA\u73AF\u7684\u4FE1\u606F" },
{ "javac.opt.printflat", "\u5728\u5185\u90E8\u7C7B\u8F6C\u6362\u4E4B\u540E\u8F93\u51FA\u62BD\u8C61\u8BED\u6CD5\u6811" },
{ "javac.opt.printsearch", "\u8F93\u51FA\u6709\u5173\u641C\u7D22\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E\u7684\u4FE1\u606F" },
{ "javac.opt.proc.none.only", "\u63A7\u5236\u662F\u5426\u6267\u884C\u6CE8\u91CA\u5904\u7406\u548C/\u6216\u7F16\u8BD1\u3002" },
{ "javac.opt.processor", "\u8981\u8FD0\u884C\u7684\u6CE8\u91CA\u5904\u7406\u7A0B\u5E8F\u7684\u540D\u79F0\uFF1B\u7ED5\u8FC7\u9ED8\u8BA4\u7684\u641C\u7D22\u8FDB\u7A0B" },
{ "javac.opt.processorpath", "\u6307\u5B9A\u67E5\u627E\u6CE8\u91CA\u5904\u7406\u7A0B\u5E8F\u7684\u4F4D\u7F6E" },
{ "javac.opt.prompt", "\u5728\u6BCF\u6B21\u51FA\u9519\u540E\u505C\u6B62" },
{ "javac.opt.retrofit", "\u66F4\u65B0\u4F7F\u7528\u6CDB\u578B\u7684\u73B0\u6709\u7C7B\u6587\u4EF6" },
{ "javac.opt.s", "\u53D1\u51FA java \u6E90\u800C\u4E0D\u662F\u7C7B\u6587\u4EF6" },
{ "javac.opt.scramble", "\u5728\u5B57\u8282\u7801\u4E2D\u6DF7\u6DC6\u4E13\u7528\u6807\u8BC6\u7B26" },
{ "javac.opt.scrambleall", "\u5728\u5B57\u8282\u7801\u4E2D\u6DF7\u6DC6\u8F6F\u4EF6\u5305\u53EF\u89C1\u6807\u8BC6\u7B26" },
{ "javac.opt.source", "\u63D0\u4F9B\u4E0E\u6307\u5B9A\u7248\u672C\u7684\u6E90\u517C\u5BB9\u6027" },
{ "javac.opt.sourceDest", "\u6307\u5B9A\u5B58\u653E\u751F\u6210\u7684\u6E90\u6587\u4EF6\u7684\u4F4D\u7F6E" },
{ "javac.opt.sourcepath", "\u6307\u5B9A\u67E5\u627E\u8F93\u5165\u6E90\u6587\u4EF6\u7684\u4F4D\u7F6E" },
{ "javac.opt.target", "\u751F\u6210\u7279\u5B9A VM \u7248\u672C\u7684\u7C7B\u6587\u4EF6" },
{ "javac.opt.verbose", "\u8F93\u51FA\u6709\u5173\u7F16\u8BD1\u5668\u6B63\u5728\u6267\u884C\u7684\u64CD\u4F5C\u7684\u6D88\u606F" },
{ "javac.opt.version", "\u7248\u672C\u4FE1\u606F" },
{ "javac.version", "{0} {1}" },
{ "javac.warn.source.target.conflict", "\u6E90\u7248\u672C {0} \u9700\u8981\u76EE\u6807\u7248\u672C {1}" },
{ "javac.warn.target.default.source.conflict", "\u76EE\u6807\u7248\u672C {0} \u4E0E\u9ED8\u8BA4\u7684\u6E90\u7248\u672C {1} \u51B2\u7A81" },
};
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | libcore/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java | 14920 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tests.api.java.util;
import dalvik.annotation.KnownFailure;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.Vector;
import tests.api.java.util.support.B;
import tests.support.resource.Support_Resources;
public class ResourceBundleTest extends junit.framework.TestCase {
/**
* java.util.ResourceBundle#getBundle(java.lang.String,
* java.util.Locale)
*/
public void test_getBundleLjava_lang_StringLjava_util_Locale() {
ResourceBundle bundle;
String name = "tests.support.Support_TestResource";
Locale defLocale = Locale.getDefault();
Locale.setDefault(new Locale("en", "US"));
bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
assertEquals("Wrong bundle fr_FR_VAR", "frFRVARValue4", bundle.getString("parent4"));
bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1"));
assertEquals("Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString("parent4"));
bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR"));
assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4"));
bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR"));
assertEquals("Wrong bundle de_FR_var", "enUSValue4", bundle.getString("parent4"));
Locale.setDefault(new Locale("fr", "FR", "VAR"));
bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1"));
assertEquals("Wrong bundle de_FR_var 2", "frFRVARValue4", bundle.getString("parent4"));
Locale.setDefault(new Locale("de", "US"));
bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var"));
assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4")
);
// Test with a security manager
Locale.setDefault(new Locale("en", "US"));
try {
ResourceBundle.getBundle(null, Locale.getDefault());
fail("NullPointerException expected");
} catch (NullPointerException ee) {
//expected
}
try {
ResourceBundle.getBundle("", new Locale("xx", "yy"));
fail("MissingResourceException expected");
} catch (MissingResourceException ee) {
//expected
}
Locale.setDefault(defLocale);
}
/**
* java.util.ResourceBundle#getBundle(java.lang.String,
* java.util.Locale, java.lang.ClassLoader)
*/
@KnownFailure("It's not allowed to pass null as parent class loader to"
+ " a new ClassLoader anymore. Maybe we need to change"
+ " URLClassLoader to allow this? It's not specified.")
public void test_getBundleLjava_lang_StringLjava_util_LocaleLjava_lang_ClassLoader() {
String classPath = System.getProperty("java.class.path");
StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator);
Vector<URL> urlVec = new Vector<URL>();
String resPackage = Support_Resources.RESOURCE_PACKAGE;
try {
while (tok.hasMoreTokens()) {
String path = tok.nextToken();
String url;
if (new File(path).isDirectory())
url = "file:" + path + resPackage + "subfolder/";
else
url = "jar:file:" + path + "!" + resPackage + "subfolder/";
urlVec.addElement(new URL(url));
}
} catch (MalformedURLException e) {
}
URL[] urls = new URL[urlVec.size()];
for (int i = 0; i < urlVec.size(); i++)
urls[i] = urlVec.elementAt(i);
URLClassLoader loader = new URLClassLoader(urls, null);
String name = Support_Resources.RESOURCE_PACKAGE_NAME
+ ".hyts_resource";
ResourceBundle bundle = ResourceBundle.getBundle(name, Locale
.getDefault());
assertEquals("Wrong value read", "parent", bundle.getString("property"));
bundle = ResourceBundle.getBundle(name, Locale.getDefault(), loader);
assertEquals("Wrong cached value",
"resource", bundle.getString("property"));
try {
ResourceBundle.getBundle(null, Locale.getDefault(), loader);
fail("NullPointerException expected");
} catch (NullPointerException ee) {
//expected
}
try {
ResourceBundle.getBundle(name, null, loader);
fail("NullPointerException expected");
} catch (NullPointerException ee) {
//expected
}
try {
ResourceBundle.getBundle(name, Locale.getDefault(), (ClassLoader) null);
fail("NullPointerException expected");
} catch (NullPointerException ee) {
//expected
}
try {
ResourceBundle.getBundle("", Locale.getDefault(), loader);
fail("MissingResourceException expected");
} catch (MissingResourceException ee) {
//expected
}
// Regression test for Harmony-3823
B bb = new B();
String s = bb.find("nonexistent");
s = bb.find("name");
assertEquals("Wrong property got", "Name", s);
}
/**
* java.util.ResourceBundle#getString(java.lang.String)
*/
public void test_getStringLjava_lang_String() {
ResourceBundle bundle;
String name = "tests.support.Support_TestResource";
Locale.setDefault(new Locale("en", "US"));
bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
assertEquals("Wrong value parent4",
"frFRVARValue4", bundle.getString("parent4"));
assertEquals("Wrong value parent3",
"frFRValue3", bundle.getString("parent3"));
assertEquals("Wrong value parent2",
"frValue2", bundle.getString("parent2"));
assertEquals("Wrong value parent1",
"parentValue1", bundle.getString("parent1"));
assertEquals("Wrong value child3",
"frFRVARChildValue3", bundle.getString("child3"));
assertEquals("Wrong value child2",
"frFRVARChildValue2", bundle.getString("child2"));
assertEquals("Wrong value child1",
"frFRVARChildValue1", bundle.getString("child1"));
try {
bundle.getString(null);
fail("NullPointerException expected");
} catch (NullPointerException ee) {
//expected
}
try {
bundle.getString("");
fail("MissingResourceException expected");
} catch (MissingResourceException ee) {
//expected
}
try {
bundle.getString("IntegerVal");
fail("ClassCastException expected");
} catch (ClassCastException ee) {
//expected
}
}
public void test_getBundle_getClassName() {
// Regression test for Harmony-1759
Locale locale = Locale.GERMAN;
String nonExistentBundle = "Non-ExistentBundle";
try {
ResourceBundle.getBundle(nonExistentBundle, locale, this.getClass()
.getClassLoader());
fail("MissingResourceException expected!");
} catch (MissingResourceException e) {
assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
}
try {
ResourceBundle.getBundle(nonExistentBundle, locale);
fail("MissingResourceException expected!");
} catch (MissingResourceException e) {
assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
}
locale = Locale.getDefault();
try {
ResourceBundle.getBundle(nonExistentBundle);
fail("MissingResourceException expected!");
} catch (MissingResourceException e) {
assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
}
}
class Mock_ResourceBundle extends ResourceBundle {
@Override
public Enumeration<String> getKeys() {
return null;
}
@Override
protected Object handleGetObject(String key) {
return null;
}
}
public void test_constructor() {
assertNotNull(new Mock_ResourceBundle());
}
public void test_getLocale() {
ResourceBundle bundle;
String name = "tests.support.Support_TestResource";
Locale loc = Locale.getDefault();
Locale.setDefault(new Locale("en", "US"));
bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
assertEquals("fr_FR_VAR", bundle.getLocale().toString());
bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1"));
assertEquals("fr_FR", bundle.getLocale().toString());
bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR"));
assertEquals("fr", bundle.getLocale().toString());
bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR"));
assertEquals("en_US", bundle.getLocale().toString());
bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1"));
assertEquals("en_US", bundle.getLocale().toString());
bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var"));
assertEquals("en_US", bundle.getLocale().toString());
Locale.setDefault(loc);
}
public void test_getObjectLjava_lang_String() {
ResourceBundle bundle;
String name = "tests.support.Support_TestResource";
Locale.setDefault(new Locale("en", "US"));
bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
assertEquals("Wrong value parent4",
"frFRVARValue4", (String)bundle.getObject("parent4"));
assertEquals("Wrong value parent3",
"frFRValue3", (String)bundle.getObject("parent3"));
assertEquals("Wrong value parent2",
"frValue2", (String) bundle.getObject("parent2"));
assertEquals("Wrong value parent1",
"parentValue1", (String)bundle.getObject("parent1"));
assertEquals("Wrong value child3",
"frFRVARChildValue3", (String)bundle.getObject("child3"));
assertEquals("Wrong value child2",
"frFRVARChildValue2", (String) bundle.getObject("child2"));
assertEquals("Wrong value child1",
"frFRVARChildValue1", (String)bundle.getObject("child1"));
assertEquals("Wrong value IntegerVal",
1, bundle.getObject("IntegerVal"));
try {
bundle.getObject(null);
fail("NullPointerException expected");
} catch (NullPointerException ee) {
//expected
}
try {
bundle.getObject("");
fail("MissingResourceException expected");
} catch (MissingResourceException ee) {
//expected
}
}
public void test_getStringArrayLjava_lang_String() {
ResourceBundle bundle;
String name = "tests.support.Support_TestResource";
Locale.setDefault(new Locale("en", "US"));
bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
String[] array = bundle.getStringArray("StringArray");
for(int i = 0; i < array.length; i++) {
assertEquals("Str" + (i + 1), array[i]);
}
try {
bundle.getStringArray(null);
fail("NullPointerException expected");
} catch (NullPointerException ee) {
//expected
}
try {
bundle.getStringArray("");
fail("MissingResourceException expected");
} catch (MissingResourceException ee) {
//expected
}
try {
bundle.getStringArray("IntegerVal");
fail("ClassCastException expected");
} catch (ClassCastException ee) {
//expected
}
}
public void test_getBundleLjava_lang_String() {
ResourceBundle bundle;
String name = "tests.support.Support_TestResource";
Locale defLocale = Locale.getDefault();
Locale.setDefault(new Locale("en", "US"));
bundle = ResourceBundle.getBundle(name);
assertEquals("enUSValue4", bundle.getString("parent4"));
Locale.setDefault(new Locale("fr", "FR", "v1"));
bundle = ResourceBundle.getBundle(name);
assertEquals("Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString("parent4"));
Locale.setDefault(new Locale("fr", "US", "VAR"));
bundle = ResourceBundle.getBundle(name);
assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4"));
Locale.setDefault(new Locale("de", "FR", "VAR"));
bundle = ResourceBundle.getBundle(name);
assertEquals("Wrong bundle de_FR_var", "parentValue4", bundle.getString("parent4"));
Locale.setDefault(new Locale("de", "FR", "v1"));
bundle = ResourceBundle.getBundle(name);
assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4"));
Locale.setDefault(new Locale("de", "FR", "var"));
bundle = ResourceBundle.getBundle(name);
assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4"));
try {
ResourceBundle.getBundle(null);
fail("NullPointerException expected");
} catch (NullPointerException ee) {
//expected
}
try {
ResourceBundle.getBundle("");
fail("MissingResourceException expected");
} catch (MissingResourceException ee) {
//expected
}
Locale.setDefault(defLocale);
}
}
| gpl-2.0 |
marcoaandrade/DC-UFSCar-ES2-201601--Grupo-da-Rapeize-v1.2 | src/main/java/net/sf/jabref/logic/msbib/MSBibEntry.java | 43771 | /* Copyright (C) 2003-2016 JabRef contributors.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package net.sf.jabref.logic.msbib;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import net.sf.jabref.importer.fileformat.ImportFormat;
import net.sf.jabref.logic.layout.LayoutFormatter;
import net.sf.jabref.logic.layout.format.RemoveBrackets;
import net.sf.jabref.logic.layout.format.XMLChars;
import net.sf.jabref.logic.mods.PageNumbers;
import net.sf.jabref.logic.mods.PersonName;
import net.sf.jabref.logic.util.strings.StringUtil;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.BibtexEntryTypes;
import net.sf.jabref.model.entry.EntryType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Date: May 15, 2007; May 03, 2007
* <p>
* History
* May 03, 2007 - Added export functionality
* May 15, 2007 - Added import functionality
* May 16, 2007 - Changed all interger entries to strings,
* except LCID which must be an integer.
* To avoid exception during integer parsing
* the exception is caught and LCID is set to zero.
* Jan 06, 2012 - Changed the XML element ConferenceName to present
* the Booktitle instead of the organization field content
*
* @author S M Mahbub Murshed (udvranto@yahoo.com)
* @version 2.0.0
* @see <a href="http://mahbub.wordpress.com/2007/03/24/details-of-microsoft-office-2007-bibliographic-format-compared-to-bibtex/">ms office 2007 bibliography format compared to bibtex</a>
* @see <a href="http://mahbub.wordpress.com/2007/03/22/deciphering-microsoft-office-2007-bibliography-format/">deciphering ms office 2007 bibliography format</a>
* See http://www.ecma-international.org/publications/standards/Ecma-376.htm
*/
class MSBibEntry {
private static final Log LOGGER = LogFactory.getLog(MSBibEntry.class);
private String sourceType = "Misc";
private String bibTexEntry;
private String tag;
private static final String GUID = null;
private int LCID = -1;
private List<PersonName> authors;
private List<PersonName> bookAuthors;
private List<PersonName> editors;
private List<PersonName> translators;
private List<PersonName> producerNames;
private List<PersonName> composers;
private List<PersonName> conductors;
private List<PersonName> performers;
private List<PersonName> writers;
private List<PersonName> directors;
private List<PersonName> compilers;
private List<PersonName> interviewers;
private List<PersonName> interviewees;
private List<PersonName> inventors;
private List<PersonName> counsels;
private String title;
private String year;
private String month;
private String day;
private String shortTitle;
private String comments;
private PageNumbers pages;
private String volume;
private String numberOfVolumes;
private String edition;
private String standardNumber;
private String publisher;
private String address;
private String bookTitle;
private String chapterNumber;
private String journalName;
private String issue;
private String periodicalTitle;
private String conferenceName;
private String department;
private String institution;
private String thesisType;
private String internetSiteTitle;
private String dateAccessed;
private String url;
private String productionCompany;
private String publicationTitle;
private String medium;
private String albumTitle;
private String recordingNumber;
private String theater;
private String distributor;
private String broadcastTitle;
private String broadcaster;
private String station;
private String type;
private String patentNumber;
private String court;
private String reporter;
private String caseNumber;
private String abbreviatedCaseNumber;
private String bibTexSeries;
private String bibTexAbstract;
private String bibTexKeyWords;
private String bibTexCrossRef;
private String bibTex_HowPublished;
private String bibTexAffiliation;
private String bibTexContents;
private String bibTexCopyright;
private String bibTexPrice;
private String bibTexSize;
/* SM 2010.10 intype, paper support */
private String bibTexInType;
private String bibTexPaper;
private static final String BIBTEX = "BIBTEX_";
private static final String MSBIB = "msbib-";
private static final String B_COLON = "b:";
// reduced subset, supports only "CITY , STATE, COUNTRY"
// \b(\w+)\s?[,]?\s?(\w+)\s?[,]?\s?(\w+)\b
// WORD SPACE , SPACE WORD SPACE , SPACE WORD
// tested using http://www.javaregex.com/test.html
private static final Pattern ADDRESS_PATTERN = Pattern.compile("\\b(\\w+)\\s*[,]?\\s*(\\w+)\\s*[,]?\\s*(\\w+)\\b");
// Allows 20.3-2007|||20/3- 2007 etc.
// (\d{1,2})\s?[.,-/]\s?(\d{1,2})\s?[.,-/]\s?(\d{2,4})
// 1-2 DIGITS SPACE SEPERATOR SPACE 1-2 DIGITS SPACE SEPERATOR SPACE 2-4 DIGITS
// tested using http://www.javaregex.com/test.html
private static final Pattern DATE_PATTERN = Pattern
.compile("(\\d{1,2})\\s*[.,-/]\\s*(\\d{1,2})\\s*[.,-/]\\s*(\\d{2,4})");
public MSBibEntry(BibEntry bibtex) {
populateFromBibtex(bibtex);
}
public MSBibEntry(Element entry, String bcol) {
populateFromXml(entry, bcol);
}
private String getFromXml(String name, Element entry) {
String value = null;
NodeList nodeLst = entry.getElementsByTagName(name);
if (nodeLst.getLength() > 0) {
value = nodeLst.item(0).getTextContent();
}
return value;
}
private void populateFromXml(Element entry, String bcol) {
String temp;
sourceType = getFromXml(bcol + "SourceType", entry);
tag = getFromXml(bcol + "Tag", entry);
temp = getFromXml(bcol + "LCID", entry);
if (temp != null) {
try {
LCID = Integer.parseInt(temp);
} catch (NumberFormatException e) {
LCID = -1;
}
}
title = getFromXml(bcol + "Title", entry);
year = getFromXml(bcol + "Year", entry);
month = getFromXml(bcol + "Month", entry);
day = getFromXml(bcol + "Day", entry);
shortTitle = getFromXml(bcol + "ShortTitle", entry);
comments = getFromXml(bcol + "Comments", entry);
temp = getFromXml(bcol + "Pages", entry);
if (temp != null) {
pages = new PageNumbers(temp);
}
volume = getFromXml(bcol + "Volume", entry);
numberOfVolumes = getFromXml(bcol + "NumberVolumes", entry);
edition = getFromXml(bcol + "Edition", entry);
standardNumber = getFromXml(bcol + "StandardNumber", entry);
publisher = getFromXml(bcol + "Publisher", entry);
String city = getFromXml(bcol + "City", entry);
String state = getFromXml(bcol + "StateProvince", entry);
String country = getFromXml(bcol + "CountryRegion", entry);
StringBuffer addressBuffer = new StringBuffer();
if (city != null) {
addressBuffer.append(city).append(", ");
}
if (state != null) {
addressBuffer.append(state).append(' ');
}
if (country != null) {
addressBuffer.append(country);
}
address = addressBuffer.toString().trim();
if (address.isEmpty() || ",".equals(address)) {
address = null;
}
bookTitle = getFromXml(bcol + "BookTitle", entry);
chapterNumber = getFromXml(bcol + "ChapterNumber", entry);
journalName = getFromXml(bcol + "JournalName", entry);
issue = getFromXml(bcol + "Issue", entry);
periodicalTitle = getFromXml(bcol + "PeriodicalTitle", entry);
conferenceName = getFromXml(bcol + "ConferenceName", entry);
department = getFromXml(bcol + "Department", entry);
institution = getFromXml(bcol + "Institution", entry);
thesisType = getFromXml(bcol + "ThesisType", entry);
internetSiteTitle = getFromXml(bcol + "InternetSiteTitle", entry);
String month = getFromXml(bcol + "MonthAccessed", entry);
String day = getFromXml(bcol + "DayAccessed", entry);
String year = getFromXml(bcol + "YearAccessed", entry);
dateAccessed = "";
if (month != null) {
dateAccessed += month + ' ';
}
if (day != null) {
dateAccessed += day + ", ";
}
if (year != null) {
dateAccessed += year;
}
dateAccessed = dateAccessed.trim();
if (dateAccessed.isEmpty() || ",".equals(dateAccessed)) {
dateAccessed = null;
}
url = getFromXml(bcol + "URL", entry);
productionCompany = getFromXml(bcol + "ProductionCompany", entry);
publicationTitle = getFromXml(bcol + "PublicationTitle", entry);
medium = getFromXml(bcol + "Medium", entry);
albumTitle = getFromXml(bcol + "AlbumTitle", entry);
recordingNumber = getFromXml(bcol + "RecordingNumber", entry);
theater = getFromXml(bcol + "Theater", entry);
distributor = getFromXml(bcol + "Distributor", entry);
broadcastTitle = getFromXml(bcol + "BroadcastTitle", entry);
broadcaster = getFromXml(bcol + "Broadcaster", entry);
station = getFromXml(bcol + "Station", entry);
type = getFromXml(bcol + "Type", entry);
patentNumber = getFromXml(bcol + "PatentNumber", entry);
court = getFromXml(bcol + "Court", entry);
reporter = getFromXml(bcol + "Reporter", entry);
caseNumber = getFromXml(bcol + "CaseNumber", entry);
abbreviatedCaseNumber = getFromXml(bcol + "AbbreviatedCaseNumber", entry);
bibTexSeries = getFromXml(bcol + BIBTEX + "Series", entry);
bibTexAbstract = getFromXml(bcol + BIBTEX + "Abstract", entry);
bibTexKeyWords = getFromXml(bcol + BIBTEX + "KeyWords", entry);
bibTexCrossRef = getFromXml(bcol + BIBTEX + "CrossRef", entry);
bibTex_HowPublished = getFromXml(bcol + BIBTEX + "HowPublished", entry);
bibTexAffiliation = getFromXml(bcol + BIBTEX + "Affiliation", entry);
bibTexContents = getFromXml(bcol + BIBTEX + "Contents", entry);
bibTexCopyright = getFromXml(bcol + BIBTEX + "Copyright", entry);
bibTexPrice = getFromXml(bcol + BIBTEX + "Price", entry);
bibTexSize = getFromXml(bcol + BIBTEX + "Size", entry);
NodeList nodeLst = entry.getElementsByTagName(bcol + "Author");
if (nodeLst.getLength() > 0) {
getAuthors((Element) nodeLst.item(0), bcol);
}
}
private void populateFromBibtex(BibEntry bibtex) {
sourceType = getMSBibSourceType(bibtex);
if (bibtex.hasField(BibEntry.KEY_FIELD)) {
tag = bibtex.getCiteKey();
}
if (bibtex.hasField("language")) {
LCID = getLCID(bibtex.getField("language"));
}
if (bibtex.hasField("title")) {
String temp = bibtex.getField("title");
// TODO: remove LaTex syntax
title = new RemoveBrackets().format(temp);
}
if (bibtex.hasField("year")) {
year = bibtex.getField("year");
}
if (bibtex.hasField("month")) {
month = bibtex.getField("month");
}
if (bibtex.hasField(MSBIB + "day")) {
day = bibtex.getField(MSBIB + "day");
}
if (bibtex.hasField(MSBIB + "shorttitle")) {
shortTitle = bibtex.getField(MSBIB + "shorttitle");
}
if (bibtex.hasField("note")) {
comments = bibtex.getField("note");
}
if (bibtex.hasField("pages")) {
pages = new PageNumbers(bibtex.getField("pages"));
}
if (bibtex.hasField("volume")) {
volume = bibtex.getField("volume");
}
if (bibtex.hasField(MSBIB + "numberofvolume")) {
numberOfVolumes = bibtex.getField(MSBIB + "numberofvolume");
}
if (bibtex.hasField("edition")) {
edition = bibtex.getField("edition");
}
standardNumber = "";
if (bibtex.hasField("isbn")) {
standardNumber += " ISBN: " + bibtex.getField("isbn"); /* SM: 2010.10: lower case */
}
if (bibtex.hasField("issn")) {
standardNumber += " ISSN: " + bibtex.getField("issn"); /* SM: 2010.10: lower case */
}
if (bibtex.hasField("lccn")) {
standardNumber += " LCCN: " + bibtex.getField("lccn"); /* SM: 2010.10: lower case */
}
if (bibtex.hasField("mrnumber")) {
standardNumber += " MRN: " + bibtex.getField("mrnumber");
}
/* SM: 2010.10 begin DOI support */
if (bibtex.hasField("doi")) {
standardNumber += " DOI: " + bibtex.getField("doi");
}
/* SM: 2010.10 end DOI support */
if (standardNumber.isEmpty()) {
standardNumber = null;
}
if (bibtex.hasField("publisher")) {
publisher = bibtex.getField("publisher");
}
if (bibtex.hasField("address")) {
address = bibtex.getField("address");
}
if (bibtex.hasField("booktitle")) {
bookTitle = bibtex.getField("booktitle");
}
if (bibtex.hasField("chapter")) {
chapterNumber = bibtex.getField("chapter");
}
if (bibtex.hasField("journal")) {
journalName = bibtex.getField("journal");
}
if (bibtex.hasField("number")) {
issue = bibtex.getField("number");
}
if (bibtex.hasField(MSBIB + "periodical")) {
periodicalTitle = bibtex.getField(MSBIB + "periodical");
}
if (bibtex.hasField("booktitle")) {
conferenceName = bibtex.getField("booktitle");
}
if (bibtex.hasField("school")) {
department = bibtex.getField("school");
}
if (bibtex.hasField("institution")) {
institution = bibtex.getField("institution");
}
/* SM: 2010.10 Modified for default source types */
if (bibtex.hasField("type")) {
thesisType = bibtex.getField("type");
} else {
if ("techreport".equalsIgnoreCase(bibtex.getType())) {
thesisType = "Tech. rep.";
} else if ("mastersthesis".equalsIgnoreCase(bibtex.getType())) {
thesisType = "Master's thesis";
} else if ("phdthesis".equalsIgnoreCase(bibtex.getType())) {
thesisType = "Ph.D. dissertation";
} else if ("unpublished".equalsIgnoreCase(bibtex.getType())) {
thesisType = "unpublished";
}
}
if (("InternetSite".equals(sourceType) || "DocumentFromInternetSite".equals(sourceType))
&& (bibtex.hasField("title"))) {
internetSiteTitle = bibtex.getField("title");
}
if (bibtex.hasField(MSBIB + "accessed")) {
dateAccessed = bibtex.getField(MSBIB + "accessed");
}
if (bibtex.hasField("url")) {
url = bibtex.getField("url"); /* SM: 2010.10: lower case */
}
if (bibtex.hasField(MSBIB + "productioncompany")) {
productionCompany = bibtex.getField(MSBIB + "productioncompany");
}
if (("ElectronicSource".equals(sourceType)
|| "Art".equals(sourceType)
|| "Misc".equals(sourceType))
&& (bibtex.hasField("title"))) {
publicationTitle = bibtex.getField("title");
}
if (bibtex.hasField(MSBIB + "medium")) {
medium = bibtex.getField(MSBIB + "medium");
}
if ("SoundRecording".equals(sourceType) && (bibtex.hasField("title"))) {
albumTitle = bibtex.getField("title");
}
if (bibtex.hasField(MSBIB + "recordingnumber")) {
recordingNumber = bibtex.getField(MSBIB + "recordingnumber");
}
if (bibtex.hasField(MSBIB + "theater")) {
theater = bibtex.getField(MSBIB + "theater");
}
if (bibtex.hasField(MSBIB + "distributor")) {
distributor = bibtex.getField(MSBIB + "distributor");
}
if ("Interview".equals(sourceType) && (bibtex.hasField("title"))) {
broadcastTitle = bibtex.getField("title");
}
if (bibtex.hasField(MSBIB + "broadcaster")) {
broadcaster = bibtex.getField(MSBIB + "broadcaster");
}
if (bibtex.hasField(MSBIB + "station")) {
station = bibtex.getField(MSBIB + "station");
}
if (bibtex.hasField(MSBIB + "type")) {
type = bibtex.getField(MSBIB + "type");
}
if (bibtex.hasField(MSBIB + "patentnumber")) {
patentNumber = bibtex.getField(MSBIB + "patentnumber");
}
if (bibtex.hasField(MSBIB + "court")) {
court = bibtex.getField(MSBIB + "court");
}
if (bibtex.hasField(MSBIB + "reporter")) {
reporter = bibtex.getField(MSBIB + "reporter");
}
if (bibtex.hasField(MSBIB + "casenumber")) {
caseNumber = bibtex.getField(MSBIB + "casenumber");
}
if (bibtex.hasField(MSBIB + "abbreviatedcasenumber")) {
abbreviatedCaseNumber = bibtex.getField(MSBIB + "abbreviatedcasenumber");
}
if (bibtex.hasField("series")) {
bibTexSeries = bibtex.getField("series");
}
if (bibtex.hasField("abstract")) {
bibTexAbstract = bibtex.getField("abstract");
}
if (bibtex.hasField("keywords")) {
bibTexKeyWords = bibtex.getField("keywords");
}
if (bibtex.hasField("crossref")) {
bibTexCrossRef = bibtex.getField("crossref");
}
if (bibtex.hasField("howpublished")) {
bibTex_HowPublished = bibtex.getField("howpublished");
}
if (bibtex.hasField("affiliation")) {
bibTexAffiliation = bibtex.getField("affiliation");
}
if (bibtex.hasField("contents")) {
bibTexContents = bibtex.getField("contents");
}
if (bibtex.hasField("copyright")) {
bibTexCopyright = bibtex.getField("copyright");
}
if (bibtex.hasField("price")) {
bibTexPrice = bibtex.getField("price");
}
if (bibtex.hasField("size")) {
bibTexSize = bibtex.getField("size");
}
/* SM: 2010.10 end intype, paper support */
if (bibtex.hasField("intype")) {
bibTexInType = bibtex.getField("intype");
}
if (bibtex.hasField("paper")) {
bibTexPaper = bibtex.getField("paper");
}
if (bibtex.hasField("author")) {
authors = getAuthors(bibtex.getField("author"));
}
if (bibtex.hasField("editor")) {
editors = getAuthors(bibtex.getField("editor"));
}
boolean FORMATXML = false;
if (FORMATXML) {
title = format(title);
bibTexAbstract = format(bibTexAbstract);
}
}
private String format(String value) {
if (value == null) {
return null;
}
String result;
LayoutFormatter chars = new XMLChars();
result = chars.format(value);
return result;
}
// http://www.microsoft.com/globaldev/reference/lcid-all.mspx
private int getLCID(String language) {
// TODO: add language to LCID mapping
return 0;
}
// http://www.microsoft.com/globaldev/reference/lcid-all.mspx
private String getLanguage(int LCID) {
// TODO: add language to LCID mapping
return "english";
}
private List<PersonName> getSpecificAuthors(String type, Element authors, String bcol) {
List<PersonName> result = null;
NodeList nodeLst = authors.getElementsByTagName(bcol + type);
if (nodeLst.getLength() <= 0) {
return result;
}
nodeLst = ((Element) nodeLst.item(0)).getElementsByTagName(bcol + "NameList");
if (nodeLst.getLength() <= 0) {
return result;
}
NodeList person = ((Element) nodeLst.item(0)).getElementsByTagName(bcol + "Person");
if (person.getLength() <= 0) {
return result;
}
result = new LinkedList<>();
for (int i = 0; i < person.getLength(); i++) {
NodeList firstName = ((Element) person.item(i)).getElementsByTagName(bcol + "First");
NodeList lastName = ((Element) person.item(i)).getElementsByTagName(bcol + "Last");
NodeList middleName = ((Element) person.item(i)).getElementsByTagName(bcol + "Middle");
PersonName name = new PersonName();
if (firstName.getLength() > 0) {
name.setFirstname(firstName.item(0).getTextContent());
}
if (middleName.getLength() > 0) {
name.setMiddlename(middleName.item(0).getTextContent());
}
if (lastName.getLength() > 0) {
name.setSurname(lastName.item(0).getTextContent());
}
result.add(name);
}
return result;
}
private void getAuthors(Element authorsElem, String bcol) {
authors = getSpecificAuthors("Author", authorsElem, bcol);
bookAuthors = getSpecificAuthors("BookAuthor", authorsElem, bcol);
editors = getSpecificAuthors("Editor", authorsElem, bcol);
translators = getSpecificAuthors("Translator", authorsElem, bcol);
producerNames = getSpecificAuthors("ProducerName", authorsElem, bcol);
composers = getSpecificAuthors("Composer", authorsElem, bcol);
conductors = getSpecificAuthors("Conductor", authorsElem, bcol);
performers = getSpecificAuthors("Performer", authorsElem, bcol);
writers = getSpecificAuthors("Writer", authorsElem, bcol);
directors = getSpecificAuthors("Director", authorsElem, bcol);
compilers = getSpecificAuthors("Compiler", authorsElem, bcol);
interviewers = getSpecificAuthors("Interviewer", authorsElem, bcol);
interviewees = getSpecificAuthors("Interviewee", authorsElem, bcol);
inventors = getSpecificAuthors("Inventor", authorsElem, bcol);
counsels = getSpecificAuthors("Counsel", authorsElem, bcol);
}
private List<PersonName> getAuthors(String authors) {
List<PersonName> result = new LinkedList<>();
if (authors.contains(" and ")) {
String[] names = authors.split(" and ");
for (String name : names) {
result.add(new PersonName(name));
}
} else {
result.add(new PersonName(authors));
}
return result;
}
private String getMSBibSourceType(BibEntry bibtex) {
String bibtexType = bibtex.getType();
String result = "Misc";
if ("book".equalsIgnoreCase(bibtexType)) {
result = "Book";
} else if ("inbook".equalsIgnoreCase(bibtexType)) {
result = "BookSection";
bibTexEntry = "inbook";
} /* SM 2010.10: generalized */ else if ("booklet".equalsIgnoreCase(bibtexType)) {
result = "BookSection";
bibTexEntry = "booklet";
} else if ("incollection".equalsIgnoreCase(bibtexType)) {
result = "BookSection";
bibTexEntry = "incollection";
} else if ("article".equalsIgnoreCase(bibtexType)) {
result = "JournalArticle";
} else if ("inproceedings".equalsIgnoreCase(bibtexType)) {
result = "ConferenceProceedings";
bibTexEntry = "inproceedings";
} /* SM 2010.10: generalized */ else if ("conference".equalsIgnoreCase(bibtexType)) {
result = "ConferenceProceedings";
bibTexEntry = "conference";
} else if ("proceedings".equalsIgnoreCase(bibtexType)) {
result = "ConferenceProceedings";
bibTexEntry = "proceedings";
} else if ("collection".equalsIgnoreCase(bibtexType)) {
result = "ConferenceProceedings";
bibTexEntry = "collection";
} else if ("techreport".equalsIgnoreCase(bibtexType)) {
result = "Report";
bibTexEntry = "techreport";
} /* SM 2010.10: generalized */ else if ("manual".equalsIgnoreCase(bibtexType)) {
result = "Report";
bibTexEntry = "manual";
} else if ("mastersthesis".equalsIgnoreCase(bibtexType)) {
result = "Report";
bibTexEntry = "mastersthesis";
} else if ("phdthesis".equalsIgnoreCase(bibtexType)) {
result = "Report";
bibTexEntry = "phdthesis";
} else if ("unpublished".equalsIgnoreCase(bibtexType)) {
result = "Report";
bibTexEntry = "unpublished";
} else if ("patent".equalsIgnoreCase(bibtexType)) {
result = "Patent";
} else if ("misc".equalsIgnoreCase(bibtexType)) {
result = "Misc";
} else if ("electronic".equalsIgnoreCase(bibtexType)) {
result = "Misc";
bibTexEntry = "electronic";
}
return result;
}
private Node getDOMrepresentation() {
Node result = null;
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
result = getDOMrepresentation(documentBuilder.newDocument());
} catch (ParserConfigurationException e) {
LOGGER.warn("Could not create DocumentBuilder", e);
}
return result;
}
private void addField(Document document, Element parent, String name, String value) {
if (value == null) {
return;
}
Element elem = document.createElement(B_COLON + name);
elem.appendChild(document.createTextNode(StringUtil.stripNonValidXMLCharacters(value)));
parent.appendChild(elem);
}
private void addAuthor(Document document, Element allAuthors, String entryName, List<PersonName> authorsLst) {
if (authorsLst == null) {
return;
}
Element authorTop = document.createElement(B_COLON + entryName);
Element nameList = document.createElement(B_COLON + "NameList");
for (PersonName name : authorsLst) {
Element person = document.createElement(B_COLON + "Person");
addField(document, person, "Last", name.getSurname());
addField(document, person, "Middle", name.getMiddlename());
addField(document, person, "First", name.getFirstname());
nameList.appendChild(person);
}
authorTop.appendChild(nameList);
allAuthors.appendChild(authorTop);
}
private void addAddress(Document document, Element parent, String address) {
if (address == null) {
return;
}
Matcher matcher = ADDRESS_PATTERN.matcher(address);
if (matcher.matches() && (matcher.groupCount() > 3)) {
addField(document, parent, "City", matcher.group(1));
addField(document, parent, "StateProvince", matcher.group(2));
addField(document, parent, "CountryRegion", matcher.group(3));
} else {
/* SM: 2010.10 generalized */
addField(document, parent, "City", address);
}
}
private void addDate(Document document, Element parent, String date, String extra) {
if (date == null) {
return;
}
Matcher matcher = DATE_PATTERN.matcher(date);
if (matcher.matches() && (matcher.groupCount() > 3)) {
addField(document, parent, "Month" + extra, matcher.group(1));
addField(document, parent, "Day" + extra, matcher.group(2));
addField(document, parent, "Year" + extra, matcher.group(3));
}
}
public Element getDOMrepresentation(Document document) {
Element msbibEntry = document.createElement(B_COLON + "Source");
addField(document, msbibEntry, "SourceType", sourceType);
addField(document, msbibEntry, BIBTEX + "Entry", bibTexEntry);
addField(document, msbibEntry, "Tag", tag);
addField(document, msbibEntry, "GUID", GUID);
if (LCID >= 0) {
addField(document, msbibEntry, "LCID", Integer.toString(LCID));
}
addField(document, msbibEntry, "Title", title);
addField(document, msbibEntry, "Year", year);
addField(document, msbibEntry, "ShortTitle", shortTitle);
addField(document, msbibEntry, "Comments", comments);
Element allAuthors = document.createElement(B_COLON + "Author");
addAuthor(document, allAuthors, "Author", authors);
String bookAuthor = "BookAuthor";
addAuthor(document, allAuthors, bookAuthor, bookAuthors);
addAuthor(document, allAuthors, "Editor", editors);
addAuthor(document, allAuthors, "Translator", translators);
addAuthor(document, allAuthors, "ProducerName", producerNames);
addAuthor(document, allAuthors, "Composer", composers);
addAuthor(document, allAuthors, "Conductor", conductors);
addAuthor(document, allAuthors, "Performer", performers);
addAuthor(document, allAuthors, "Writer", writers);
addAuthor(document, allAuthors, "Director", directors);
addAuthor(document, allAuthors, "Compiler", compilers);
addAuthor(document, allAuthors, "Interviewer", interviewers);
addAuthor(document, allAuthors, "Interviewee", interviewees);
addAuthor(document, allAuthors, "Inventor", inventors);
addAuthor(document, allAuthors, "Counsel", counsels);
msbibEntry.appendChild(allAuthors);
if (pages != null) {
addField(document, msbibEntry, "Pages", pages.toString("-"));
}
addField(document, msbibEntry, "Volume", volume);
addField(document, msbibEntry, "NumberVolumes", numberOfVolumes);
addField(document, msbibEntry, "Edition", edition);
addField(document, msbibEntry, "StandardNumber", standardNumber);
addField(document, msbibEntry, "Publisher", publisher);
addAddress(document, msbibEntry, address);
addField(document, msbibEntry, "BookTitle", bookTitle);
addField(document, msbibEntry, "ChapterNumber", chapterNumber);
addField(document, msbibEntry, "JournalName", journalName);
addField(document, msbibEntry, "Issue", issue);
addField(document, msbibEntry, "PeriodicalTitle", periodicalTitle);
addField(document, msbibEntry, "ConferenceName", conferenceName);
addField(document, msbibEntry, "Department", department);
addField(document, msbibEntry, "Institution", institution);
addField(document, msbibEntry, "ThesisType", thesisType);
addField(document, msbibEntry, "InternetSiteTitle", internetSiteTitle);
addDate(document, msbibEntry, dateAccessed, "Accessed");
/* SM 2010.10 added month export */
addField(document, msbibEntry, "Month", month);
addField(document, msbibEntry, "URL", url);
addField(document, msbibEntry, "ProductionCompany", productionCompany);
addField(document, msbibEntry, "PublicationTitle", publicationTitle);
addField(document, msbibEntry, "Medium", medium);
addField(document, msbibEntry, "AlbumTitle", albumTitle);
addField(document, msbibEntry, "RecordingNumber", recordingNumber);
addField(document, msbibEntry, "Theater", theater);
addField(document, msbibEntry, "Distributor", distributor);
addField(document, msbibEntry, "BroadcastTitle", broadcastTitle);
addField(document, msbibEntry, "Broadcaster", broadcaster);
addField(document, msbibEntry, "Station", station);
addField(document, msbibEntry, "Type", type);
addField(document, msbibEntry, "PatentNumber", patentNumber);
addField(document, msbibEntry, "Court", court);
addField(document, msbibEntry, "Reporter", reporter);
addField(document, msbibEntry, "CaseNumber", caseNumber);
addField(document, msbibEntry, "AbbreviatedCaseNumber", abbreviatedCaseNumber);
addField(document, msbibEntry, BIBTEX + "Series", bibTexSeries);
addField(document, msbibEntry, BIBTEX + "Abstract", bibTexAbstract);
addField(document, msbibEntry, BIBTEX + "KeyWords", bibTexKeyWords);
addField(document, msbibEntry, BIBTEX + "CrossRef", bibTexCrossRef);
addField(document, msbibEntry, BIBTEX + "HowPublished", bibTex_HowPublished);
addField(document, msbibEntry, BIBTEX + "Affiliation", bibTexAffiliation);
addField(document, msbibEntry, BIBTEX + "Contents", bibTexContents);
addField(document, msbibEntry, BIBTEX + "Copyright", bibTexCopyright);
addField(document, msbibEntry, BIBTEX + "Price", bibTexPrice);
addField(document, msbibEntry, BIBTEX + "Size", bibTexSize);
/* SM: 2010.10 end intype, paper support */
addField(document, msbibEntry, BIBTEX + "InType", bibTexInType);
addField(document, msbibEntry, BIBTEX + "Paper", bibTexPaper);
return msbibEntry;
}
private void parseSingleStandardNumber(String type, String bibtype, String standardNum, Map<String, String> map) {
// tested using http://www.javaregex.com/test.html
Pattern pattern = Pattern.compile(':' + type + ":(.[^:]+)");
Matcher matcher = pattern.matcher(standardNum);
if (matcher.matches()) {
map.put(bibtype, matcher.group(1));
}
}
private void parseStandardNumber(String standardNum, Map<String, String> map) {
if (standardNumber == null) {
return;
}
parseSingleStandardNumber("ISBN", "isbn", standardNum, map); /* SM: 2010.10: lower case */
parseSingleStandardNumber("ISSN", "issn", standardNum, map); /* SM: 2010.10: lower case */
parseSingleStandardNumber("LCCN", "lccn", standardNum, map); /* SM: 2010.10: lower case */
parseSingleStandardNumber("MRN", "mrnumber", standardNum, map);
/* SM: 2010.10 begin DOI support */
parseSingleStandardNumber("DOI", "doi", standardNum, map);
/* SM: 2010.10 end DOI support */
}
private void addAuthor(Map<String, String> map, String type, List<PersonName> authors) {
if (authors == null) {
return;
}
String allAuthors = authors.stream().map(name -> name.getFullname()).collect(Collectors.joining(" and "));
map.put(type, allAuthors);
}
private EntryType mapMSBibToBibtexType(String msbib) {
EntryType bibtex;
switch (msbib) {
case "Book":
bibtex = BibtexEntryTypes.BOOK;
break;
case "BookSection":
bibtex = BibtexEntryTypes.INBOOK;
break;
case "JournalArticle":
case "ArticleInAPeriodical":
bibtex = BibtexEntryTypes.ARTICLE;
break;
case "ConferenceProceedings":
bibtex = BibtexEntryTypes.CONFERENCE;
break;
case "Report":
bibtex = BibtexEntryTypes.TECHREPORT;
break;
case "InternetSite":
case "DocumentFromInternetSite":
case "ElectronicSource":
case "Art":
case "SoundRecording":
case "Performance":
case "Film":
case "Interview":
case "Patent":
case "Case":
default:
bibtex = BibtexEntryTypes.MISC;
break;
}
return bibtex;
}
public BibEntry getBibtexRepresentation() {
BibEntry entry;
if (tag == null) {
entry = new BibEntry(ImportFormat.DEFAULT_BIBTEXENTRY_ID, mapMSBibToBibtexType(sourceType).getName());
} else {
entry = new BibEntry(tag, mapMSBibToBibtexType(sourceType).getName()); // id assumes an existing database so don't
}
// Todo: add check for BibTexEntry types
Map<String, String> hm = new HashMap<>();
if (tag != null) {
hm.put(BibEntry.KEY_FIELD, tag);
}
if (LCID >= 0) {
hm.put("language", getLanguage(LCID));
}
if (title != null) {
hm.put("title", title);
}
if (year != null) {
hm.put("year", year);
}
if (shortTitle != null) {
hm.put(MSBIB + "shorttitle", shortTitle);
}
if (comments != null) {
hm.put("note", comments);
}
addAuthor(hm, "author", authors);
addAuthor(hm, MSBIB + "bookauthor", bookAuthors);
addAuthor(hm, "editor", editors);
addAuthor(hm, MSBIB + "translator", translators);
addAuthor(hm, MSBIB + "producername", producerNames);
addAuthor(hm, MSBIB + "composer", composers);
addAuthor(hm, MSBIB + "conductor", conductors);
addAuthor(hm, MSBIB + "performer", performers);
addAuthor(hm, MSBIB + "writer", writers);
addAuthor(hm, MSBIB + "director", directors);
addAuthor(hm, MSBIB + "compiler", compilers);
addAuthor(hm, MSBIB + "interviewer", interviewers);
addAuthor(hm, MSBIB + "interviewee", interviewees);
addAuthor(hm, MSBIB + "inventor", inventors);
addAuthor(hm, MSBIB + "counsel", counsels);
if (pages != null) {
hm.put("pages", pages.toString("--"));
}
if (volume != null) {
hm.put("volume", volume);
}
if (numberOfVolumes != null) {
hm.put(MSBIB + "numberofvolume", numberOfVolumes);
}
if (edition != null) {
hm.put("edition", edition);
}
if (edition != null) {
hm.put("edition", edition);
}
parseStandardNumber(standardNumber, hm);
if (publisher != null) {
hm.put("publisher", publisher);
}
if (publisher != null) {
hm.put("publisher", publisher);
}
if (address != null) {
hm.put("address", address);
}
if (bookTitle != null) {
hm.put("booktitle", bookTitle);
}
if (chapterNumber != null) {
hm.put("chapter", chapterNumber);
}
if (journalName != null) {
hm.put("journal", journalName);
}
if (issue != null) {
hm.put("number", issue);
}
if (month != null) {
hm.put("month", month);
}
if (periodicalTitle != null) {
hm.put("organization", periodicalTitle);
}
if (conferenceName != null) {
hm.put("organization", conferenceName);
}
if (department != null) {
hm.put("school", department);
}
if (institution != null) {
hm.put("institution", institution);
}
if (dateAccessed != null) {
hm.put(MSBIB + "accessed", dateAccessed);
}
if (url != null) {
hm.put("url", url);
}
if (productionCompany != null) {
hm.put(MSBIB + "productioncompany", productionCompany);
}
if (medium != null) {
hm.put(MSBIB + "medium", medium);
}
if (recordingNumber != null) {
hm.put(MSBIB + "recordingnumber", recordingNumber);
}
if (theater != null) {
hm.put(MSBIB + "theater", theater);
}
if (distributor != null) {
hm.put(MSBIB + "distributor", distributor);
}
if (broadcaster != null) {
hm.put(MSBIB + "broadcaster", broadcaster);
}
if (station != null) {
hm.put(MSBIB + "station", station);
}
if (type != null) {
hm.put(MSBIB + "type", type);
}
if (patentNumber != null) {
hm.put(MSBIB + "patentnumber", patentNumber);
}
if (court != null) {
hm.put(MSBIB + "court", court);
}
if (reporter != null) {
hm.put(MSBIB + "reporter", reporter);
}
if (caseNumber != null) {
hm.put(MSBIB + "casenumber", caseNumber);
}
if (abbreviatedCaseNumber != null) {
hm.put(MSBIB + "abbreviatedcasenumber", abbreviatedCaseNumber);
}
if (bibTexSeries != null) {
hm.put("series", bibTexSeries);
}
if (bibTexAbstract != null) {
hm.put("abstract", bibTexAbstract);
}
if (bibTexKeyWords != null) {
hm.put("keywords", bibTexKeyWords);
}
if (bibTexCrossRef != null) {
hm.put("crossref", bibTexCrossRef);
}
if (bibTex_HowPublished != null) {
hm.put("howpublished", bibTex_HowPublished);
}
if (bibTexAffiliation != null) {
hm.put("affiliation", bibTexAffiliation);
}
if (bibTexContents != null) {
hm.put("contents", bibTexContents);
}
if (bibTexCopyright != null) {
hm.put("copyright", bibTexCopyright);
}
if (bibTexPrice != null) {
hm.put("price", bibTexPrice);
}
if (bibTexSize != null) {
hm.put("size", bibTexSize);
}
entry.setField(hm);
return entry;
}
/*
* render as XML
*
* TODO This is untested.
*/
@Override
public String toString() {
StringWriter result = new StringWriter();
try {
DOMSource source = new DOMSource(getDOMrepresentation());
StreamResult streamResult = new StreamResult(result);
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.transform(source, streamResult);
} catch (TransformerException e) {
LOGGER.warn("Could not build XML representation", e);
}
return result.toString();
}
}
| gpl-2.0 |
WelcomeHUME/svn-caucho-com-resin | modules/kernel/src/com/caucho/config/gen/CacheGenerator.java | 11468 | /*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.config.gen;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import javax.cache.Cache;
import javax.cache.annotation.CacheDefaults;
import javax.cache.annotation.CacheKey;
import javax.cache.annotation.CacheKeyGenerator;
import javax.cache.annotation.CacheKeyParam;
import javax.cache.annotation.CachePut;
import javax.cache.annotation.CacheRemoveAll;
import javax.cache.annotation.CacheRemoveEntry;
import javax.cache.annotation.CacheResolverFactory;
import javax.cache.annotation.CacheResult;
import javax.cache.annotation.CacheValue;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import com.caucho.config.ConfigException;
import com.caucho.config.util.CacheKeyGeneratorImpl;
import com.caucho.config.util.CacheKeyImpl;
import com.caucho.config.util.CacheUtil;
import com.caucho.inject.Module;
import com.caucho.java.JavaWriter;
import com.caucho.util.L10N;
/**
* Represents the caching interception
*/
@Module
public class CacheGenerator<X> extends AbstractAspectGenerator<X> {
private static final L10N L = new L10N(CacheGenerator.class);
private CacheResult _cacheResult;
private CachePut _cachePut;
private CacheRemoveEntry _cacheRemove;
private CacheRemoveAll _cacheRemoveAll;
private Class<?> _keyGenerator = CacheKeyGenerator.class;
private Class<?> _cacheResolver = CacheResolverFactory.class;
private String _cacheName;
private String _cacheInstance;
private String _keyGenInstance;
public CacheGenerator(CacheFactory<X> factory,
AnnotatedMethod<? super X> method,
AspectGenerator<X> next,
CacheResult cacheResult,
CachePut cachePut,
CacheRemoveEntry cacheRemove,
CacheRemoveAll cacheRemoveAll)
{
super(factory, method, next);
_cacheResult = cacheResult;
_cachePut = cachePut;
_cacheRemove = cacheRemove;
_cacheRemoveAll = cacheRemoveAll;
if (_cacheResult != null) {
_cacheName = _cacheResult.cacheName();
_keyGenerator = _cacheResult.cacheKeyGenerator();
_cacheResolver = _cacheResult.cacheResolverFactory();
}
else if (_cachePut != null) {
_cacheName = _cachePut.cacheName();
_keyGenerator = _cachePut.cacheKeyGenerator();
_cacheResolver = _cachePut.cacheResolverFactory();
}
else if (_cacheRemove != null) {
_cacheName = _cacheRemove.cacheName();
_keyGenerator = _cacheRemove.cacheKeyGenerator();
_cacheResolver = _cacheRemove.cacheResolverFactory();
}
else if (_cacheRemoveAll != null) {
_cacheName = _cacheRemoveAll.cacheName();
_cacheResolver = _cacheRemoveAll.cacheResolverFactory();
}
else
throw new IllegalStateException();
CacheDefaults cacheDefaults
= method.getDeclaringType().getAnnotation(CacheDefaults.class);
if (cacheDefaults != null) {
if ("".equals(_cacheName))
_cacheName = cacheDefaults.cacheName();
if (CacheKeyGenerator.class.equals(_keyGenerator))
_keyGenerator = cacheDefaults.cacheKeyGenerator();
if (CacheResolverFactory.class.equals(_cacheResolver))
_cacheResolver = cacheDefaults.cacheResolverFactory();
}
if ("".equals(_cacheName)) {
Method javaMethod = method.getJavaMember();
_cacheName = (javaMethod.getDeclaringClass().getName()
+ "." + javaMethod.getName());
}
if (CacheKeyGenerator.class.equals(_keyGenerator))
_keyGenerator = null;
if (CacheResolverFactory.class.equals(_cacheResolver))
_cacheResolver = null;
}
//
// bean prologue generation
//
/**
* Generates the static class prologue
*/
@Override
public void generateMethodPrologue(JavaWriter out, HashMap<String, Object> map)
throws IOException
{
super.generateMethodPrologue(out, map);
_cacheInstance = "__caucho_cache_" + out.generateId();
out.println();
out.println("private static final javax.cache.Cache " + _cacheInstance);
out.print(" = com.caucho.config.util.CacheUtil.getCache(\"");
out.printJavaString(_cacheName);
out.print("\");");
if (_keyGenerator != null
|| _cacheResolver != null) {
_keyGenInstance = "__caucho_cache_key_" + out.generateId();
out.println();
out.println("private static final "
+ CacheKeyGeneratorImpl.class.getName()
+ " " + _keyGenInstance);
out.print(" = new " + CacheKeyGeneratorImpl.class.getName() + "(");
if (_keyGenerator != null) {
out.print("new " + _keyGenerator.getName() + "()");
}
else {
out.print("null");
}
if (_cacheResolver != null) {
out.print(", new " + _cacheResolver.getName() + "()");
}
else {
out.print(", null");
}
out.print(", \"");
out.printJavaString(_cacheName);
out.print("\"");
out.print(", " + getJavaClass().getName() + ".class");
Method method = getJavaMethod();
out.print(",\"");
out.printJavaString(method.getName());
out.print("\"");
for (Class<?> param : method.getParameterTypes()) {
out.print(",");
out.printClass(param);
out.print(".class");
}
out.println(");");
}
}
//
// method generation code
//
/**
* Generates the interceptor code after the try-block and before the call.
*
* <code><pre>
* retType myMethod(...)
* {
* try {
* [pre-call]
* retValue = super.myMethod(...);
* }
* </pre></code>
*/
@Override
public void generatePreCall(JavaWriter out) throws IOException
{
out.println(Cache.class.getName() + " caucho_cache = " + _cacheInstance + ";");;
buildCacheResolver(out);
buildCacheKey(out);
if (_cacheResult != null && ! _cacheResult.skipGet()) {
out.println("Object cacheValue = caucho_cache.get(candiCacheKey);");
out.println("if (cacheValue != null) {");
out.print(" return (");
out.printClass(getJavaMethod().getReturnType());
out.println(") cacheValue;");
out.println("}");
}
if (_cachePut != null && ! _cachePut.afterInvocation()) {
AnnotatedParameter<?> value = getCacheValueParam();
if (value == null)
throw new ConfigException(L.l("@CachePut requires a @CacheValue"));
out.println("caucho_cache.put(candiCacheKey, a" + value.getPosition() + ");");
}
if (_cacheRemove != null && ! _cacheRemove.afterInvocation()) {
out.println("caucho_cache.remove(candiCacheKey);");
}
super.generatePreCall(out);
}
/**
* Generates the interceptor code after invocation and before the call.
*
* <code><pre>
* retType myMethod(...)
* {
* try {
* retValue = super.myMethod(...);
* [post-call]
* return retValue;
* } finally {
* ...
* }
* }
* </pre></code>
*/
@Override
public void generatePostCall(JavaWriter out) throws IOException
{
super.generatePostCall(out);
if (_cacheResult != null) {
out.println("caucho_cache.put(candiCacheKey, result);");
}
if (_cachePut != null && _cachePut.afterInvocation()) {
AnnotatedParameter<?> value = getCacheValueParam();
if (value == null)
throw new ConfigException(L.l("@CachePut requires a @CacheValue"));
out.println("caucho_cache.put(candiCacheKey, a" + value.getPosition() + ");");
}
if (_cacheRemove != null && _cacheRemove.afterInvocation()) {
out.println("caucho_cache.remove(candiCacheKey);");
}
if (_cacheRemoveAll != null) {
out.println("caucho_cache.removeAll();");
}
}
private void buildCacheResolver(JavaWriter out)
throws IOException
{
if (_cacheResolver == null)
return;
out.print("caucho_cache = " + _keyGenInstance + ".resolveCache(");
out.print("caucho_cache, ");
out.print(getInstanceName());
List params = getParameters();
for (int i = 0; i < params.size(); i++) {
out.print(", ");
out.print("a" + i);
}
out.println(");");
}
private void buildCacheKey(JavaWriter out)
throws IOException
{
out.println();
out.println(CacheKey.class.getName() + " candiCacheKey");
if (_keyGenInstance != null) {
out.print(" = " + _keyGenInstance + ".generateKey(");
out.print(getInstanceName());
List params = getParameters();
for (int i = 0; i < params.size(); i++) {
out.print(", ");
out.print("a" + i);
}
out.println(");");
}
else {
out.print(" = new " + CacheKeyImpl.class.getName() + "(");
List params = getMethod().getParameters();
boolean isCacheKeyParam = isCacheKeyParam(params);
boolean isFirst = true;
for (int i = 0; i < params.size(); i++) {
AnnotatedParameter<?> param = (AnnotatedParameter<?>) params.get(i);
if (param.isAnnotationPresent(CacheValue.class))
continue;
if (isCacheKeyParam && ! param.isAnnotationPresent(CacheKeyParam.class))
continue;
if (! isFirst)
out.print(", ");
out.print("a" + i);
isFirst = false;
}
out.println(");");
}
}
private void buildInvocationContext(JavaWriter out)
throws IOException
{
out.print(CacheUtil.class.getName() + ".generateKeyContext(");
out.print(")");
}
private boolean isCacheKeyParam(List<AnnotatedParameter<?>> params)
{
for (AnnotatedParameter<?> param : params) {
if (param.isAnnotationPresent(CacheKeyParam.class)) {
return true;
}
}
return false;
}
private AnnotatedParameter<?> getCacheValueParam()
{
for (AnnotatedParameter<?> param : getParameters()) {
if (param.isAnnotationPresent(CacheValue.class)) {
return param;
}
}
return null;
}
private List<AnnotatedParameter<?>> getParameters()
{
return (List) getMethod().getParameters();
}
} | gpl-2.0 |
yyuu/libmysql-java | src/testsuite/simple/DateTest.java | 14321 | /*
Copyright 2002-2004 MySQL AB, 2008 Sun Microsystems
All rights reserved. Use is subject to license terms.
The MySQL Connector/J is licensed under the terms of the GPL,
like most MySQL Connectors. There are special exceptions to the
terms and conditions of the GPL as it is applied to this software,
see the FLOSS License Exception available on mysql.com.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
package testsuite.simple;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Properties;
import java.util.TimeZone;
import testsuite.BaseTestCase;
import com.mysql.jdbc.SQLError;
/**
*
* @author Mark Matthews
* @version $Id$
*/
public class DateTest extends BaseTestCase {
// ~ Constructors
// -----------------------------------------------------------
/**
* Creates a new DateTest object.
*
* @param name
* DOCUMENT ME!
*/
public DateTest(String name) {
super(name);
}
// ~ Methods
// ----------------------------------------------------------------
/**
* Runs all test cases in this test suite
*
* @param args
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(DateTest.class);
}
/**
* DOCUMENT ME!
*
* @throws Exception
* DOCUMENT ME!
*/
public void setUp() throws Exception {
super.setUp();
createTestTable();
}
/**
* DOCUMENT ME!
*
* @throws SQLException
* DOCUMENT ME!
*/
public void testTimestamp() throws SQLException {
this.pstmt = this.conn
.prepareStatement("INSERT INTO DATETEST(tstamp, dt, dtime, tm) VALUES (?, ?, ?, ?)");
// TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 6);
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.HOUR, 7);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.AM_PM, Calendar.AM);
cal.getTime();
System.out.println(cal);
// DateFormat df = SimpleDateFormat.getInstance();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// df.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp nowTstamp = new Timestamp(cal.getTime().getTime());
java.sql.Date nowDate = new java.sql.Date(cal.getTime().getTime());
Timestamp nowDatetime = new Timestamp(cal.getTime().getTime());
java.sql.Time nowTime = new java.sql.Time(cal.getTime().getTime());
System.out
.println("** Times with given calendar (before storing) **\n");
System.out.println("TIMESTAMP:\t" + nowTstamp.getTime() + " -> "
+ df.format(nowTstamp));
System.out.println("DATE:\t\t" + nowDate.getTime() + " -> "
+ df.format(nowDate));
System.out.println("DATETIME:\t" + nowDatetime.getTime() + " -> "
+ df.format(nowDatetime));
System.out.println("DATE:\t\t" + nowDate.getTime() + " -> "
+ df.format(nowDate));
System.out.println("TIME:\t\t" + nowTime.getTime() + " -> "
+ df.format(nowTime));
System.out.println("\n");
this.pstmt.setTimestamp(1, nowTstamp, calGMT);
// have to use the same TimeZone as used to create or there will be
// shift
this.pstmt.setDate(2, nowDate, cal);
this.pstmt.setTimestamp(3, nowDatetime, calGMT);
// have to use the same TimeZone as used to create or there will be
// shift
this.pstmt.setTime(4, nowTime, cal);
this.pstmt.execute();
this.pstmt.getUpdateCount();
this.pstmt.clearParameters();
this.rs = this.stmt.executeQuery("SELECT * from DATETEST");
java.sql.Date thenDate = null;
while (this.rs.next()) {
Timestamp thenTstamp = this.rs.getTimestamp(1, calGMT);
thenDate = this.rs.getDate(2, cal);
java.sql.Timestamp thenDatetime = this.rs.getTimestamp(3, calGMT);
java.sql.Time thenTime = this.rs.getTime(4, cal);
System.out
.println("** Times with given calendar (retrieved from database) **\n");
System.out.println("TIMESTAMP:\t" + thenTstamp.getTime() + " -> "
+ df.format(thenTstamp));
System.out.println("DATE:\t\t" + thenDate.getTime() + " -> "
+ df.format(thenDate));
System.out.println("DATETIME:\t" + thenDatetime.getTime() + " -> "
+ df.format(thenDatetime));
System.out.println("TIME:\t\t" + thenTime.getTime() + " -> "
+ df.format(thenTime));
System.out.println("\n");
}
this.rs.close();
this.rs = null;
}
public void testNanosParsing() throws SQLException {
try {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testNanosParsing");
this.stmt
.executeUpdate("CREATE TABLE testNanosParsing (dateIndex int, field1 VARCHAR(32))");
this.stmt
.executeUpdate("INSERT INTO testNanosParsing VALUES (1, '1969-12-31 18:00:00.0'), "
+ "(2, '1969-12-31 18:00:00.000000090'), "
+ "(3, '1969-12-31 18:00:00.000000900'), "
+ "(4, '1969-12-31 18:00:00.000009000'), "
+ "(5, '1969-12-31 18:00:00.000090000'), "
+ "(6, '1969-12-31 18:00:00.000900000'), "
+ "(7, '1969-12-31 18:00:00.')");
this.rs = this.stmt
.executeQuery("SELECT field1 FROM testNanosParsing ORDER BY dateIndex ASC");
assertTrue(this.rs.next());
assertTrue(this.rs.getTimestamp(1).getNanos() == 0);
assertTrue(this.rs.next());
assertTrue(this.rs.getTimestamp(1).getNanos() + " != 90", this.rs
.getTimestamp(1).getNanos() == 90);
assertTrue(this.rs.next());
assertTrue(this.rs.getTimestamp(1).getNanos() + " != 900", this.rs
.getTimestamp(1).getNanos() == 900);
assertTrue(this.rs.next());
assertTrue(this.rs.getTimestamp(1).getNanos() + " != 9000", this.rs
.getTimestamp(1).getNanos() == 9000);
assertTrue(this.rs.next());
assertTrue(this.rs.getTimestamp(1).getNanos() + " != 90000",
this.rs.getTimestamp(1).getNanos() == 90000);
assertTrue(this.rs.next());
assertTrue(this.rs.getTimestamp(1).getNanos() + " != 900000",
this.rs.getTimestamp(1).getNanos() == 900000);
assertTrue(this.rs.next());
try {
this.rs.getTimestamp(1);
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
.getSQLState()));
}
} finally {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testNanosParsing");
}
}
private void createTestTable() throws SQLException {
//
// Catch the error, the table might exist
//
try {
this.stmt.executeUpdate("DROP TABLE DATETEST");
} catch (SQLException SQLE) {
;
}
this.stmt
.executeUpdate("CREATE TABLE DATETEST (tstamp TIMESTAMP, dt DATE, dtime DATETIME, tm TIME)");
}
/**
* Tests the configurability of all-zero date/datetime/timestamp handling in
* the driver.
*
* @throws Exception
* if the test fails.
*/
public void testZeroDateBehavior() throws Exception {
try {
this.stmt
.executeUpdate("DROP TABLE IF EXISTS testZeroDateBehavior");
this.stmt
.executeUpdate("CREATE TABLE testZeroDateBehavior(fieldAsString VARCHAR(32), fieldAsDateTime DATETIME)");
this.stmt
.executeUpdate("INSERT INTO testZeroDateBehavior VALUES ('0000-00-00 00:00:00', '0000-00-00 00:00:00')");
Properties props = new Properties();
props.setProperty("zeroDateTimeBehavior", "round");
Connection roundConn = getConnectionWithProps(props);
Statement roundStmt = roundConn.createStatement();
this.rs = roundStmt
.executeQuery("SELECT fieldAsString, fieldAsDateTime FROM testZeroDateBehavior");
this.rs.next();
assertEquals("0001-01-01", this.rs.getDate(1).toString());
assertEquals("0001-01-01 00:00:00.0",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0", Locale.US).format(this.rs.getTimestamp(1)));
assertEquals("0001-01-01", this.rs.getDate(2).toString());
assertEquals("0001-01-01 00:00:00.0",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0", Locale.US).format(this.rs.getTimestamp(2)));
PreparedStatement roundPrepStmt = roundConn
.prepareStatement("SELECT fieldAsString, fieldAsDateTime FROM testZeroDateBehavior");
this.rs = roundPrepStmt.executeQuery();
this.rs.next();
assertEquals("0001-01-01", this.rs.getDate(1).toString());
assertEquals("0001-01-01 00:00:00.0",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0", Locale.US).format(this.rs.getTimestamp(1)));
assertEquals("0001-01-01", this.rs.getDate(2).toString());
assertEquals("0001-01-01 00:00:00.0",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0", Locale.US).format(this.rs.getTimestamp(2)));
props = new Properties();
props.setProperty("zeroDateTimeBehavior", "convertToNull");
Connection nullConn = getConnectionWithProps(props);
Statement nullStmt = nullConn.createStatement();
this.rs = nullStmt
.executeQuery("SELECT fieldAsString, fieldAsDateTime FROM testZeroDateBehavior");
this.rs.next();
assertTrue(null == this.rs.getDate(1));
assertTrue(null == this.rs.getTimestamp(1));
assertTrue(null == this.rs.getDate(2));
assertTrue(null == this.rs.getTimestamp(2));
PreparedStatement nullPrepStmt = nullConn
.prepareStatement("SELECT fieldAsString, fieldAsDateTime FROM testZeroDateBehavior");
this.rs = nullPrepStmt.executeQuery();
this.rs.next();
assertTrue(null == this.rs.getDate(1));
assertTrue(null == this.rs.getTimestamp(1));
assertTrue(null == this.rs.getDate(2));
assertTrue(null == this.rs.getTimestamp(2));
assertTrue(null == this.rs.getString(2));
props = new Properties();
props.setProperty("zeroDateTimeBehavior", "exception");
Connection exceptionConn = getConnectionWithProps(props);
Statement exceptionStmt = exceptionConn.createStatement();
this.rs = exceptionStmt
.executeQuery("SELECT fieldAsString, fieldAsDateTime FROM testZeroDateBehavior");
this.rs.next();
try {
this.rs.getDate(1);
fail("Exception should have been thrown when trying to retrieve invalid date");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
.getSQLState()));
}
try {
this.rs.getTimestamp(1);
fail("Exception should have been thrown when trying to retrieve invalid date");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
.getSQLState()));
}
try {
this.rs.getDate(2);
fail("Exception should have been thrown when trying to retrieve invalid date");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
.getSQLState()));
}
try {
this.rs.getTimestamp(2);
fail("Exception should have been thrown when trying to retrieve invalid date");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
.getSQLState()));
}
PreparedStatement exceptionPrepStmt = exceptionConn
.prepareStatement("SELECT fieldAsString, fieldAsDateTime FROM testZeroDateBehavior");
try {
this.rs = exceptionPrepStmt.executeQuery();
this.rs.next();
this.rs.getDate(2);
fail("Exception should have been thrown when trying to retrieve invalid date");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
.getSQLState()));
}
} finally {
this.stmt
.executeUpdate("DROP TABLE IF EXISTS testZeroDateBehavior");
}
}
public void testReggieBug() throws Exception {
try {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testReggieBug");
this.stmt.executeUpdate("CREATE TABLE testReggieBug (field1 DATE)");
PreparedStatement pStmt = this.conn
.prepareStatement("INSERT INTO testReggieBug VALUES (?)");
pStmt.setDate(1, new Date(2004 - 1900, 07, 28));
pStmt.executeUpdate();
this.rs = this.stmt.executeQuery("SELECT * FROM testReggieBug");
this.rs.next();
System.out.println(this.rs.getDate(1));
this.rs = this.conn.prepareStatement("SELECT * FROM testReggieBug")
.executeQuery();
this.rs.next();
System.out.println(this.rs.getDate(1));
} finally {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testReggieBug");
}
}
public void testNativeConversions() throws Exception {
Timestamp ts = new Timestamp(System.currentTimeMillis());
Date dt = new Date(ts.getTime());
Time tm = new Time(ts.getTime());
createTable("testNativeConversions", "(time_field TIME, date_field DATE, datetime_field DATETIME, timestamp_field TIMESTAMP)");
this.pstmt = this.conn.prepareStatement("INSERT INTO testNativeConversions VALUES (?,?,?,?)");
this.pstmt.setTime(1, tm);
this.pstmt.setDate(2, dt);
this.pstmt.setTimestamp(3, ts);
this.pstmt.setTimestamp(4, ts);
this.pstmt.execute();
this.pstmt.close();
this.pstmt = this.conn.prepareStatement("SELECT time_field, date_field, datetime_field, timestamp_field FROM testNativeConversions");
this.rs = this.pstmt.executeQuery();
assertTrue(this.rs.next());
System.out.println(this.rs.getTime(1));
System.out.println(this.rs.getTime(2));
System.out.println(this.rs.getTime(3));
System.out.println(this.rs.getTime(4));
System.out.println();
System.out.println(this.rs.getDate(1));
System.out.println(this.rs.getDate(2));
System.out.println(this.rs.getDate(3));
System.out.println(this.rs.getDate(4));
System.out.println();
System.out.println(this.rs.getTimestamp(1));
System.out.println(this.rs.getTimestamp(2));
System.out.println(this.rs.getTimestamp(3));
System.out.println(this.rs.getTimestamp(4));
}
}
| gpl-2.0 |
emmeryn/intellij-ocaml | OCamlSources/src/manuylov/maxim/ocaml/lang/parser/psi/element/OCamlOperatorName.java | 1009 | /*
* OCaml Support For IntelliJ Platform.
* Copyright (C) 2010 Maxim Manuylov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
*/
package manuylov.maxim.ocaml.lang.parser.psi.element;
import manuylov.maxim.ocaml.lang.parser.psi.OCamlElement;
/**
* @author Maxim.Manuylov
* Date: 21.03.2009
*/
public interface OCamlOperatorName extends OCamlElement {
}
| gpl-2.0 |
saeder/CodenameOne | Ports/CLDC11/src/java/lang/OutOfMemoryError.java | 1842 | /*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores
* CA 94065 USA or visit www.oracle.com if you need additional information or
* have any questions.
*/
package java.lang;
/**
* Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
* Since: JDK1.0, CLDC 1.0
*/
public class OutOfMemoryError extends java.lang.VirtualMachineError{
/**
* Constructs an OutOfMemoryError with no detail message.
*/
public OutOfMemoryError(){
//TODO codavaj!!
}
/**
* Constructs an OutOfMemoryError with the specified detail message.
* s - the detail message.
*/
public OutOfMemoryError(java.lang.String s){
//TODO codavaj!!
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | cts/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_static_range/d/T_invoke_static_range_13.java | 743 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dot.junit.opcodes.invoke_static_range.d;
public class T_invoke_static_range_13 {
public void run() {
}
}
| gpl-2.0 |
md-5/jdk10 | test/jdk/java/net/Socket/SoTimeout.java | 2920 | /*
* Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4156625
@summary Socket.setSoTimeout(T) can cause incorrect delay of T
under green threads
@author Tom Rodriguez
*/
/*
* This program depends a bit on the particular behaviour of the green
* threads scheduler to produce the problem, but given that the underlying
* bug a green threads bug, I think that's OK.
*/
import java.net.*;
public class SoTimeout implements Runnable {
static ServerSocket serverSocket;
static long timeWritten;
static InetAddress addr;
static int port;
public static void main(String[] args) throws Exception {
addr = InetAddress.getLocalHost();
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(addr, 0));
port = serverSocket.getLocalPort();
byte[] b = new byte[12];
Thread t = new Thread(new SoTimeout());
t.start();
Socket s = serverSocket.accept();
serverSocket.close();
// set a 5 second timeout on the socket
s.setSoTimeout(5000);
s.getInputStream().read(b, 0, b.length);
s.close();
long waited = System.currentTimeMillis() - timeWritten;
// this sequence should complete fairly quickly and if it
// takes something resembling the the SoTimeout value then
// we are probably incorrectly blocking and not waking up
if (waited > 2000) {
throw new Exception("shouldn't take " + waited + " to complete");
}
}
public void run() {
try {
byte[] b = new byte[12];
Socket s = new Socket(addr, port);
Thread.yield();
timeWritten = System.currentTimeMillis();
s.getOutputStream().write(b, 0, 12);
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| gpl-2.0 |
sbbic/core | odk/examples/DevelopersGuide/GUI/RoadmapItemStateChangeListener.java | 3235 | /*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* the BSD license.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*************************************************************************/
import com.sun.star.awt.XItemListener;
import com.sun.star.lang.EventObject;
import com.sun.star.beans.XPropertySet;
import com.sun.star.uno.UnoRuntime;
public class RoadmapItemStateChangeListener implements XItemListener {
private final com.sun.star.lang.XMultiServiceFactory m_xMSFDialogModel;
public RoadmapItemStateChangeListener(com.sun.star.lang.XMultiServiceFactory xMSFDialogModel) {
m_xMSFDialogModel = xMSFDialogModel;
}
public void itemStateChanged(com.sun.star.awt.ItemEvent itemEvent) {
try {
// get the new ID of the roadmap that is supposed to refer to the new step of the dialogmodel
int nNewID = itemEvent.ItemId;
XPropertySet xDialogModelPropertySet = UnoRuntime.queryInterface(XPropertySet.class, m_xMSFDialogModel);
int nOldStep = ((Integer) xDialogModelPropertySet.getPropertyValue("Step")).intValue();
// in the following line "ID" and "Step" are mixed together.
// In fact in this case they denot the same
if (nNewID != nOldStep){
xDialogModelPropertySet.setPropertyValue("Step", Integer.valueOf(nNewID));
}
} catch (com.sun.star.uno.Exception exception) {
exception.printStackTrace(System.err);
}
}
public void disposing(EventObject eventObject) {
}
}
| gpl-3.0 |
danielbejaranogonzalez/Mobile-Network-Designer | db/hsqldb/src/org/hsqldb/util/SqlToolSprayer.java | 7203 | /* Copyright (c) 2001-2008, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb.util;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
/* $Id: SqlToolSprayer.java,v 1.21 2007/06/12 02:37:57 unsaved Exp $ */
/**
* Sql Tool Sprayer.
* Invokes SqlTool.objectMain() multiple times with the same SQL.
* Invokes for multiple urlids and/or retries.
*
* See JavaDocs for the main method for syntax of how to run.
*
* System properties used if set:
* <UL>
* <LI>sqltoolsprayer.period (in ms.)</LI>
* <LI>sqltoolsprayer.maxtime (in ms.)</LI>
* <LI>sqltoolsprayer.rcfile (filepath)</LI>
* </UL>
*
* @see @main()
* @version $Revision: 1.21 $
* @author Blaine Simpson unsaved@users
*/
public class SqlToolSprayer {
public static String LS = System.getProperty("line.separator");
private static String SYNTAX_MSG =
"SYNTAX: java [-D...] SqlToolSprayer 'SQL;' [urlid1 urlid2...]\n"
+ "System properties you may use [default values]:\n"
+ " sqltoolsprayer.period (in ms.) [500]\n"
+ " sqltoolsprayer.maxtime (in ms.) [0]\n"
+ " sqltoolsprayer.monfile (filepath) [none]\n"
+ " sqltoolsprayer.rcfile (filepath) [none. SqlTool default used.]"
+ "\n sqltoolsprayer.propfile (filepath) [none]";
static {
if (!LS.equals("\n")) {
SYNTAX_MSG = SYNTAX_MSG.replaceAll("\n", LS);
}
}
public static void main(String[] sa) {
if (sa.length < 1) {
System.err.println(SYNTAX_MSG);
System.exit(4);
}
long period = ((System.getProperty("sqltoolsprayer.period") == null)
? 500
: Integer.parseInt(
System.getProperty("sqltoolsprayer.period")));
long maxtime = ((System.getProperty("sqltoolsprayer.maxtime") == null)
? 0
: Integer.parseInt(
System.getProperty("sqltoolsprayer.maxtime")));
String rcFile = System.getProperty("sqltoolsprayer.rcfile");
String propfile = System.getProperty("sqltoolsprayer.propfile");
File monitorFile =
(System.getProperty("sqltoolsprayer.monfile") == null) ? null
: new File(
System.getProperty(
"sqltoolsprayer.monfile"));
ArrayList urlids = new ArrayList();
if (propfile != null) {
try {
getUrlsFromPropFile(propfile, urlids);
} catch (Exception e) {
System.err.println("Failed to load property file '" + propfile
+ "': " + e);
System.exit(3);
}
}
for (int i = 1; i < sa.length; i++) {
urlids.add(sa[i]);
}
boolean[] status = new boolean[urlids.size()];
for (int i = 0; i < status.length; i++) {
status[i] = false;
}
String[] withRcArgs = {
"--sql", sa[0], "--rcfile", rcFile, null
};
String[] withoutRcArgs = {
"--sql", sa[0], null
};
String[] sqlToolArgs = (rcFile == null) ? withoutRcArgs
: withRcArgs;
boolean onefailed = false;
long startTime = (new Date()).getTime();
while (true) {
if (monitorFile != null && !monitorFile.exists()) {
System.err.println("Required file is gone: " + monitorFile);
System.exit(2);
}
onefailed = false;
for (int i = 0; i < status.length; i++) {
if (status[i]) {
continue;
}
sqlToolArgs[sqlToolArgs.length - 1] = (String) urlids.get(i);
try {
new SqlTool().objectMain(sqlToolArgs);
status[i] = true;
System.err.println("Success for instance '"
+ urlids.get(i) + "'");
} catch (SqlTool.SqlToolException se) {
onefailed = true;
}
}
if (!onefailed) {
break;
}
if (maxtime == 0 || (new Date()).getTime() > startTime + maxtime) {
break;
}
try {
Thread.sleep(period);
} catch (InterruptedException ie) {}
}
ArrayList failedUrlids = new ArrayList();
// If all statuses true, then System.exit(0);
for (int i = 0; i < status.length; i++) {
if (status[i] != true) {
failedUrlids.add(urlids.get(i));
}
}
if (failedUrlids.size() > 0) {
System.err.println("Failed instances: " + failedUrlids);
System.exit(1);
}
System.exit(0);
}
private static void getUrlsFromPropFile(String fileName,
ArrayList al) throws Exception {
Properties p = new Properties();
p.load(new FileInputStream(fileName));
int i = -1;
String val;
while (true) {
i++;
val = p.getProperty("server.urlid." + i);
if (val == null) {
return;
}
al.add(val);
}
}
}
| gpl-3.0 |
syslover33/ctank | java/android-sdk-linux_r24.4.1_src/sources/android-23/android/hardware/camera2/legacy/LegacyFocusStateMapper.java | 12333 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.hardware.camera2.legacy;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.camera2.impl.CameraMetadataNative;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.utils.ParamsUtils;
import android.util.Log;
import java.util.Objects;
import static android.hardware.camera2.CaptureRequest.*;
import static com.android.internal.util.Preconditions.*;
/**
* Map capture request data into legacy focus state transitions.
*
* <p>This object will asynchronously process auto-focus changes, so no interaction
* with it is necessary beyond reading the current state and updating with the latest trigger.</p>
*/
@SuppressWarnings("deprecation")
public class LegacyFocusStateMapper {
private static String TAG = "LegacyFocusStateMapper";
private static final boolean DEBUG = false;
private final Camera mCamera;
private int mAfStatePrevious = CONTROL_AF_STATE_INACTIVE;
private String mAfModePrevious = null;
/** Guard mAfRun and mAfState */
private final Object mLock = new Object();
/** Guard access with mLock */
private int mAfRun = 0;
/** Guard access with mLock */
private int mAfState = CONTROL_AF_STATE_INACTIVE;
/**
* Instantiate a new focus state mapper.
*
* @param camera a non-{@code null} camera1 device
*
* @throws NullPointerException if any of the args were {@code null}
*/
public LegacyFocusStateMapper(Camera camera) {
mCamera = checkNotNull(camera, "camera must not be null");
}
/**
* Process the AF triggers from the request as a camera1 autofocus routine.
*
* <p>This method should be called after the parameters are {@link LegacyRequestMapper mapped}
* with the request.</p>
*
* <p>Callbacks are processed in the background, and the next call to {@link #mapResultTriggers}
* will have the latest AF state as reflected by the camera1 callbacks.</p>
*
* <p>None of the arguments will be mutated.</p>
*
* @param captureRequest a non-{@code null} request
* @param parameters a non-{@code null} parameters corresponding to this request (read-only)
*/
public void processRequestTriggers(CaptureRequest captureRequest,
Camera.Parameters parameters) {
checkNotNull(captureRequest, "captureRequest must not be null");
/*
* control.afTrigger
*/
int afTrigger = ParamsUtils.getOrDefault(captureRequest, CONTROL_AF_TRIGGER,
CONTROL_AF_TRIGGER_IDLE);
final String afMode = parameters.getFocusMode();
if (!Objects.equals(mAfModePrevious, afMode)) {
if (DEBUG) {
Log.v(TAG, "processRequestTriggers - AF mode switched from " + mAfModePrevious +
" to " + afMode);
}
// Switching modes always goes back to INACTIVE; ignore callbacks from previous modes
synchronized (mLock) {
++mAfRun;
mAfState = CONTROL_AF_STATE_INACTIVE;
}
mCamera.cancelAutoFocus();
}
mAfModePrevious = afMode;
// Passive AF Scanning
{
final int currentAfRun;
synchronized (mLock) {
currentAfRun = mAfRun;
}
Camera.AutoFocusMoveCallback afMoveCallback = new Camera.AutoFocusMoveCallback() {
@Override
public void onAutoFocusMoving(boolean start, Camera camera) {
synchronized (mLock) {
int latestAfRun = mAfRun;
if (DEBUG) {
Log.v(TAG,
"onAutoFocusMoving - start " + start + " latest AF run " +
latestAfRun + ", last AF run " + currentAfRun
);
}
if (currentAfRun != latestAfRun) {
Log.d(TAG,
"onAutoFocusMoving - ignoring move callbacks from old af run"
+ currentAfRun
);
return;
}
int newAfState = start ?
CONTROL_AF_STATE_PASSIVE_SCAN :
CONTROL_AF_STATE_PASSIVE_FOCUSED;
// We never send CONTROL_AF_STATE_PASSIVE_UNFOCUSED
switch (afMode) {
case Parameters.FOCUS_MODE_CONTINUOUS_PICTURE:
case Parameters.FOCUS_MODE_CONTINUOUS_VIDEO:
break;
// This callback should never be sent in any other AF mode
default:
Log.w(TAG, "onAutoFocus - got unexpected onAutoFocus in mode "
+ afMode);
}
mAfState = newAfState;
}
}
};
// Only set move callback if we can call autofocus.
switch (afMode) {
case Parameters.FOCUS_MODE_AUTO:
case Parameters.FOCUS_MODE_MACRO:
case Parameters.FOCUS_MODE_CONTINUOUS_PICTURE:
case Parameters.FOCUS_MODE_CONTINUOUS_VIDEO:
mCamera.setAutoFocusMoveCallback(afMoveCallback);
}
}
// AF Locking
switch (afTrigger) {
case CONTROL_AF_TRIGGER_START:
int afStateAfterStart;
switch (afMode) {
case Parameters.FOCUS_MODE_AUTO:
case Parameters.FOCUS_MODE_MACRO:
afStateAfterStart = CONTROL_AF_STATE_ACTIVE_SCAN;
break;
case Parameters.FOCUS_MODE_CONTINUOUS_PICTURE:
case Parameters.FOCUS_MODE_CONTINUOUS_VIDEO:
afStateAfterStart = CONTROL_AF_STATE_PASSIVE_SCAN;
break;
default:
// EDOF, INFINITY
afStateAfterStart = CONTROL_AF_STATE_INACTIVE;
}
final int currentAfRun;
synchronized (mLock) {
currentAfRun = ++mAfRun;
mAfState = afStateAfterStart;
}
if (DEBUG) {
Log.v(TAG, "processRequestTriggers - got AF_TRIGGER_START, " +
"new AF run is " + currentAfRun);
}
// Avoid calling autofocus unless we are in a state that supports calling this.
if (afStateAfterStart == CONTROL_AF_STATE_INACTIVE) {
break;
}
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
synchronized (mLock) {
int latestAfRun = mAfRun;
if (DEBUG) {
Log.v(TAG, "onAutoFocus - success " + success + " latest AF run " +
latestAfRun + ", last AF run " + currentAfRun);
}
// Ignore old auto-focus results, since another trigger was requested
if (latestAfRun != currentAfRun) {
Log.d(TAG, String.format("onAutoFocus - ignoring AF callback " +
"(old run %d, new run %d)", currentAfRun, latestAfRun));
return;
}
int newAfState = success ?
CONTROL_AF_STATE_FOCUSED_LOCKED :
CONTROL_AF_STATE_NOT_FOCUSED_LOCKED;
switch (afMode) {
case Parameters.FOCUS_MODE_AUTO:
case Parameters.FOCUS_MODE_CONTINUOUS_PICTURE:
case Parameters.FOCUS_MODE_CONTINUOUS_VIDEO:
case Parameters.FOCUS_MODE_MACRO:
break;
// This callback should never be sent in any other AF mode
default:
Log.w(TAG, "onAutoFocus - got unexpected onAutoFocus in mode "
+ afMode);
}
mAfState = newAfState;
}
}
});
break;
case CONTROL_AF_TRIGGER_CANCEL:
synchronized (mLock) {
int updatedAfRun;
synchronized (mLock) {
updatedAfRun = ++mAfRun;
mAfState = CONTROL_AF_STATE_INACTIVE;
}
mCamera.cancelAutoFocus();
if (DEBUG) {
Log.v(TAG, "processRequestTriggers - got AF_TRIGGER_CANCEL, " +
"new AF run is " + updatedAfRun);
}
}
break;
case CONTROL_AF_TRIGGER_IDLE:
// No action necessary. The callbacks will handle transitions.
break;
default:
Log.w(TAG, "processRequestTriggers - ignoring unknown control.afTrigger = "
+ afTrigger);
}
}
/**
* Update the {@code result} camera metadata map with the new value for the
* {@code control.afState}.
*
* <p>AF callbacks are processed in the background, and each call to {@link #mapResultTriggers}
* will have the latest AF state as reflected by the camera1 callbacks.</p>
*
* @param result a non-{@code null} result
*/
public void mapResultTriggers(CameraMetadataNative result) {
checkNotNull(result, "result must not be null");
int newAfState;
synchronized (mLock) {
newAfState = mAfState;
}
if (DEBUG && newAfState != mAfStatePrevious) {
Log.v(TAG, String.format("mapResultTriggers - afState changed from %s to %s",
afStateToString(mAfStatePrevious), afStateToString(newAfState)));
}
result.set(CaptureResult.CONTROL_AF_STATE, newAfState);
mAfStatePrevious = newAfState;
}
private static String afStateToString(int afState) {
switch (afState) {
case CONTROL_AF_STATE_ACTIVE_SCAN:
return "ACTIVE_SCAN";
case CONTROL_AF_STATE_FOCUSED_LOCKED:
return "FOCUSED_LOCKED";
case CONTROL_AF_STATE_INACTIVE:
return "INACTIVE";
case CONTROL_AF_STATE_NOT_FOCUSED_LOCKED:
return "NOT_FOCUSED_LOCKED";
case CONTROL_AF_STATE_PASSIVE_FOCUSED:
return "PASSIVE_FOCUSED";
case CONTROL_AF_STATE_PASSIVE_SCAN:
return "PASSIVE_SCAN";
case CONTROL_AF_STATE_PASSIVE_UNFOCUSED:
return "PASSIVE_UNFOCUSED";
default :
return "UNKNOWN(" + afState + ")";
}
}
}
| gpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Admin/src/ims/admin/domain/MosSelect.java | 2047 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.admin.domain;
// Generated from form domain impl
public interface MosSelect extends ims.domain.DomainInterface
{
// Generated from form domain interface definition
/**
* Returns a MosList based on the search criteria in the passed in filter
*/
public ims.core.vo.MemberOfStaffShortVoCollection listMembersOfStaff(ims.core.vo.MemberOfStaffShortVo filter);
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/coe/vo/FallAssessmentDetails.java | 6741 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.coe.vo;
/**
* Linked to coe.assessment tools.Fall Assessment Details business object (ID: 1013100005).
*/
public class FallAssessmentDetails extends ims.coe.assessmenttools.vo.FallAssessmentDetailsRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public FallAssessmentDetails()
{
}
public FallAssessmentDetails(Integer id, int version)
{
super(id, version);
}
public FallAssessmentDetails(ims.coe.vo.beans.FallAssessmentDetailsBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.assessment = bean.getAssessment();
this.select = bean.getSelect();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.coe.vo.beans.FallAssessmentDetailsBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.assessment = bean.getAssessment();
this.select = bean.getSelect();
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.coe.vo.beans.FallAssessmentDetailsBean bean = null;
if(map != null)
bean = (ims.coe.vo.beans.FallAssessmentDetailsBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.coe.vo.beans.FallAssessmentDetailsBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("ASSESSMENT"))
return getAssessment();
if(fieldName.equals("SELECT"))
return getSelect();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getAssessmentIsNotNull()
{
return this.assessment != null;
}
public Integer getAssessment()
{
return this.assessment;
}
public void setAssessment(Integer value)
{
this.isValidated = false;
this.assessment = value;
}
public boolean getSelectIsNotNull()
{
return this.select != null;
}
public Boolean getSelect()
{
return this.select;
}
public void setSelect(Boolean value)
{
this.isValidated = false;
this.select = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
FallAssessmentDetails clone = new FallAssessmentDetails(this.id, this.version);
clone.assessment = this.assessment;
clone.select = this.select;
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(FallAssessmentDetails.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A FallAssessmentDetails object cannot be compared an Object of type " + obj.getClass().getName());
}
FallAssessmentDetails compareObj = (FallAssessmentDetails)obj;
int retVal = 0;
if (retVal == 0)
{
if(this.getID_FallAssessmentDetails() == null && compareObj.getID_FallAssessmentDetails() != null)
return -1;
if(this.getID_FallAssessmentDetails() != null && compareObj.getID_FallAssessmentDetails() == null)
return 1;
if(this.getID_FallAssessmentDetails() != null && compareObj.getID_FallAssessmentDetails() != null)
retVal = this.getID_FallAssessmentDetails().compareTo(compareObj.getID_FallAssessmentDetails());
}
return retVal;
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.assessment != null)
count++;
if(this.select != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 2;
}
protected Integer assessment;
protected Boolean select;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/core/admin/vo/NotificationsRefVoCollection.java | 5237 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.admin.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to core.admin.Notifications business object (ID: 1004100043).
*/
public class NotificationsRefVoCollection extends ims.vo.ValueObjectCollection implements ims.domain.IDomainCollectionGetter, ims.vo.ImsCloneable, Iterable<NotificationsRefVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<NotificationsRefVo> col = new ArrayList<NotificationsRefVo>();
public final String getBoClassName()
{
return "ims.core.admin.domain.objects.Notifications";
}
public ims.domain.IDomainGetter[] getIDomainGetterItems()
{
ims.domain.IDomainGetter[] result = new ims.domain.IDomainGetter[col.size()];
col.toArray(result);
return result;
}
public boolean add(NotificationsRefVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, NotificationsRefVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(NotificationsRefVo instance)
{
return col.indexOf(instance);
}
public NotificationsRefVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, NotificationsRefVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(NotificationsRefVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(NotificationsRefVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
NotificationsRefVoCollection clone = new NotificationsRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((NotificationsRefVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
return true;
}
public String[] validate()
{
return null;
}
public NotificationsRefVo[] toArray()
{
NotificationsRefVo[] arr = new NotificationsRefVo[col.size()];
col.toArray(arr);
return arr;
}
public NotificationsRefVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public NotificationsRefVoCollection sort(SortOrder order)
{
return sort(new NotificationsRefVoComparator(order));
}
@SuppressWarnings("unchecked")
public NotificationsRefVoCollection sort(Comparator comparator)
{
Collections.sort(this.col, comparator);
return this;
}
public Iterator<NotificationsRefVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class NotificationsRefVoComparator implements Comparator
{
private int direction = 1;
public NotificationsRefVoComparator()
{
this(SortOrder.ASCENDING);
}
public NotificationsRefVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
this.direction = -1;
}
}
public int compare(Object obj1, Object obj2)
{
NotificationsRefVo voObj1 = (NotificationsRefVo)obj1;
NotificationsRefVo voObj2 = (NotificationsRefVo)obj2;
return direction*(voObj1.compareTo(voObj2));
}
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/coe/vo/AssessmentLeisure.java | 15040 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.coe.vo;
/**
* Linked to nursing.assessment.Assessment Component business object (ID: 1015100001).
*/
public class AssessmentLeisure extends ims.nursing.vo.AssessmentComponent implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public AssessmentLeisure()
{
}
public AssessmentLeisure(Integer id, int version)
{
super(id, version);
}
public AssessmentLeisure(ims.coe.vo.beans.AssessmentLeisureBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.iscomplete = bean.getIsComplete();
this.assessmentinfo = ims.nursing.vo.AssessmentInfoCollection.buildFromBeanCollection(bean.getAssessmentInfo());
this.copy = bean.getCopy();
this.componenttype = bean.getComponentType() == null ? null : ims.nursing.vo.lookups.AssessmentComponentType.buildLookup(bean.getComponentType());
this.lastassessmentinfo = bean.getLastAssessmentInfo() == null ? null : bean.getLastAssessmentInfo().buildVo();
this.careplantemplate = ims.nursing.vo.CarePlanTemplateCollection.buildFromBeanCollection(bean.getCarePlanTemplate());
this.careplans = ims.nursing.vo.CarePlanCollection.buildFromBeanCollection(bean.getCarePlans());
this.leisureclubs = ims.coe.vo.LeisureClubCollection.buildFromBeanCollection(bean.getLeisureClubs());
this.hobbies = bean.getHobbies();
this.enjoydoingmost = bean.getEnjoyDoingMost();
this.preferencesoftime = bean.getPreferencesOfTime();
this.alcoholsocially = bean.getAlcoholSocially() == null ? null : ims.core.vo.lookups.YesNoUnknown.buildLookup(bean.getAlcoholSocially());
this.alcoholdetails = bean.getAlcoholDetails();
this.alcoholunits = bean.getAlcoholUnits();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.coe.vo.beans.AssessmentLeisureBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.iscomplete = bean.getIsComplete();
this.assessmentinfo = ims.nursing.vo.AssessmentInfoCollection.buildFromBeanCollection(bean.getAssessmentInfo());
this.copy = bean.getCopy();
this.componenttype = bean.getComponentType() == null ? null : ims.nursing.vo.lookups.AssessmentComponentType.buildLookup(bean.getComponentType());
this.lastassessmentinfo = bean.getLastAssessmentInfo() == null ? null : bean.getLastAssessmentInfo().buildVo(map);
this.careplantemplate = ims.nursing.vo.CarePlanTemplateCollection.buildFromBeanCollection(bean.getCarePlanTemplate());
this.careplans = ims.nursing.vo.CarePlanCollection.buildFromBeanCollection(bean.getCarePlans());
this.leisureclubs = ims.coe.vo.LeisureClubCollection.buildFromBeanCollection(bean.getLeisureClubs());
this.hobbies = bean.getHobbies();
this.enjoydoingmost = bean.getEnjoyDoingMost();
this.preferencesoftime = bean.getPreferencesOfTime();
this.alcoholsocially = bean.getAlcoholSocially() == null ? null : ims.core.vo.lookups.YesNoUnknown.buildLookup(bean.getAlcoholSocially());
this.alcoholdetails = bean.getAlcoholDetails();
this.alcoholunits = bean.getAlcoholUnits();
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.coe.vo.beans.AssessmentLeisureBean bean = null;
if(map != null)
bean = (ims.coe.vo.beans.AssessmentLeisureBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.coe.vo.beans.AssessmentLeisureBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("LEISURECLUBS"))
return getLeisureClubs();
if(fieldName.equals("HOBBIES"))
return getHobbies();
if(fieldName.equals("ENJOYDOINGMOST"))
return getEnjoyDoingMost();
if(fieldName.equals("PREFERENCESOFTIME"))
return getPreferencesOfTime();
if(fieldName.equals("ALCOHOLSOCIALLY"))
return getAlcoholSocially();
if(fieldName.equals("ALCOHOLDETAILS"))
return getAlcoholDetails();
if(fieldName.equals("ALCOHOLUNITS"))
return getAlcoholUnits();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getLeisureClubsIsNotNull()
{
return this.leisureclubs != null;
}
public ims.coe.vo.LeisureClubCollection getLeisureClubs()
{
return this.leisureclubs;
}
public void setLeisureClubs(ims.coe.vo.LeisureClubCollection value)
{
this.isValidated = false;
this.leisureclubs = value;
}
public boolean getHobbiesIsNotNull()
{
return this.hobbies != null;
}
public String getHobbies()
{
return this.hobbies;
}
public static int getHobbiesMaxLength()
{
return 255;
}
public void setHobbies(String value)
{
this.isValidated = false;
this.hobbies = value;
}
public boolean getEnjoyDoingMostIsNotNull()
{
return this.enjoydoingmost != null;
}
public String getEnjoyDoingMost()
{
return this.enjoydoingmost;
}
public static int getEnjoyDoingMostMaxLength()
{
return 255;
}
public void setEnjoyDoingMost(String value)
{
this.isValidated = false;
this.enjoydoingmost = value;
}
public boolean getPreferencesOfTimeIsNotNull()
{
return this.preferencesoftime != null;
}
public String getPreferencesOfTime()
{
return this.preferencesoftime;
}
public static int getPreferencesOfTimeMaxLength()
{
return 500;
}
public void setPreferencesOfTime(String value)
{
this.isValidated = false;
this.preferencesoftime = value;
}
public boolean getAlcoholSociallyIsNotNull()
{
return this.alcoholsocially != null;
}
public ims.core.vo.lookups.YesNoUnknown getAlcoholSocially()
{
return this.alcoholsocially;
}
public void setAlcoholSocially(ims.core.vo.lookups.YesNoUnknown value)
{
this.isValidated = false;
this.alcoholsocially = value;
}
public boolean getAlcoholDetailsIsNotNull()
{
return this.alcoholdetails != null;
}
public String getAlcoholDetails()
{
return this.alcoholdetails;
}
public static int getAlcoholDetailsMaxLength()
{
return 255;
}
public void setAlcoholDetails(String value)
{
this.isValidated = false;
this.alcoholdetails = value;
}
public boolean getAlcoholUnitsIsNotNull()
{
return this.alcoholunits != null;
}
public Integer getAlcoholUnits()
{
return this.alcoholunits;
}
public void setAlcoholUnits(Integer value)
{
this.isValidated = false;
this.alcoholunits = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
if(this.assessmentinfo != null)
{
if(!this.assessmentinfo.isValidated())
{
this.isBusy = false;
return false;
}
}
if(this.lastassessmentinfo != null)
{
if(!this.lastassessmentinfo.isValidated())
{
this.isBusy = false;
return false;
}
}
if(this.careplantemplate != null)
{
if(!this.careplantemplate.isValidated())
{
this.isBusy = false;
return false;
}
}
if(this.careplans != null)
{
if(!this.careplans.isValidated())
{
this.isBusy = false;
return false;
}
}
if(this.leisureclubs != null)
{
if(!this.leisureclubs.isValidated())
{
this.isBusy = false;
return false;
}
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
if(this.assessmentinfo != null)
{
String[] listOfOtherErrors = this.assessmentinfo.validate();
if(listOfOtherErrors != null)
{
for(int x = 0; x < listOfOtherErrors.length; x++)
{
listOfErrors.add(listOfOtherErrors[x]);
}
}
}
if(this.lastassessmentinfo != null)
{
String[] listOfOtherErrors = this.lastassessmentinfo.validate();
if(listOfOtherErrors != null)
{
for(int x = 0; x < listOfOtherErrors.length; x++)
{
listOfErrors.add(listOfOtherErrors[x]);
}
}
}
if(this.careplantemplate != null)
{
String[] listOfOtherErrors = this.careplantemplate.validate();
if(listOfOtherErrors != null)
{
for(int x = 0; x < listOfOtherErrors.length; x++)
{
listOfErrors.add(listOfOtherErrors[x]);
}
}
}
if(this.careplans != null)
{
String[] listOfOtherErrors = this.careplans.validate();
if(listOfOtherErrors != null)
{
for(int x = 0; x < listOfOtherErrors.length; x++)
{
listOfErrors.add(listOfOtherErrors[x]);
}
}
}
if(this.leisureclubs != null)
{
String[] listOfOtherErrors = this.leisureclubs.validate();
if(listOfOtherErrors != null)
{
for(int x = 0; x < listOfOtherErrors.length; x++)
{
listOfErrors.add(listOfOtherErrors[x]);
}
}
}
if(this.preferencesoftime != null)
if(this.preferencesoftime.length() > 500)
listOfErrors.add("The length of the field [preferencesoftime] in the value object [ims.coe.vo.AssessmentLeisure] is too big. It should be less or equal to 500");
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
AssessmentLeisure clone = new AssessmentLeisure(this.id, this.version);
clone.iscomplete = this.iscomplete;
if(this.assessmentinfo == null)
clone.assessmentinfo = null;
else
clone.assessmentinfo = (ims.nursing.vo.AssessmentInfoCollection)this.assessmentinfo.clone();
clone.copy = this.copy;
if(this.componenttype == null)
clone.componenttype = null;
else
clone.componenttype = (ims.nursing.vo.lookups.AssessmentComponentType)this.componenttype.clone();
if(this.lastassessmentinfo == null)
clone.lastassessmentinfo = null;
else
clone.lastassessmentinfo = (ims.nursing.vo.AssessmentInfo)this.lastassessmentinfo.clone();
if(this.careplantemplate == null)
clone.careplantemplate = null;
else
clone.careplantemplate = (ims.nursing.vo.CarePlanTemplateCollection)this.careplantemplate.clone();
if(this.careplans == null)
clone.careplans = null;
else
clone.careplans = (ims.nursing.vo.CarePlanCollection)this.careplans.clone();
if(this.leisureclubs == null)
clone.leisureclubs = null;
else
clone.leisureclubs = (ims.coe.vo.LeisureClubCollection)this.leisureclubs.clone();
clone.hobbies = this.hobbies;
clone.enjoydoingmost = this.enjoydoingmost;
clone.preferencesoftime = this.preferencesoftime;
if(this.alcoholsocially == null)
clone.alcoholsocially = null;
else
clone.alcoholsocially = (ims.core.vo.lookups.YesNoUnknown)this.alcoholsocially.clone();
clone.alcoholdetails = this.alcoholdetails;
clone.alcoholunits = this.alcoholunits;
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(AssessmentLeisure.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A AssessmentLeisure object cannot be compared an Object of type " + obj.getClass().getName());
}
AssessmentLeisure compareObj = (AssessmentLeisure)obj;
int retVal = 0;
if (retVal == 0)
{
if(this.getID_AssessmentComponent() == null && compareObj.getID_AssessmentComponent() != null)
return -1;
if(this.getID_AssessmentComponent() != null && compareObj.getID_AssessmentComponent() == null)
return 1;
if(this.getID_AssessmentComponent() != null && compareObj.getID_AssessmentComponent() != null)
retVal = this.getID_AssessmentComponent().compareTo(compareObj.getID_AssessmentComponent());
}
return retVal;
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = super.countFieldsWithValue();
if(this.leisureclubs != null)
count++;
if(this.hobbies != null)
count++;
if(this.enjoydoingmost != null)
count++;
if(this.preferencesoftime != null)
count++;
if(this.alcoholsocially != null)
count++;
if(this.alcoholdetails != null)
count++;
if(this.alcoholunits != null)
count++;
return count;
}
public int countValueObjectFields()
{
return super.countValueObjectFields() + 7;
}
protected ims.coe.vo.LeisureClubCollection leisureclubs;
protected String hobbies;
protected String enjoydoingmost;
protected String preferencesoftime;
protected ims.core.vo.lookups.YesNoUnknown alcoholsocially;
protected String alcoholdetails;
protected Integer alcoholunits;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Billing/src/ims/billing/forms/adddiscountdialog/GlobalContext.java | 1973 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.billing.forms.adddiscountdialog;
import java.io.Serializable;
public final class GlobalContext extends ims.framework.FormContext implements Serializable
{
private static final long serialVersionUID = 1L;
public GlobalContext(ims.framework.Context context)
{
super(context);
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/clinical/vo/beans/SkinPreperationVoBean.java | 4121 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.vo.beans;
public class SkinPreperationVoBean extends ims.vo.ValueObjectBean
{
public SkinPreperationVoBean()
{
}
public SkinPreperationVoBean(ims.clinical.vo.SkinPreperationVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.skinpreparationused = vo.getSkinPreparationUsed() == null ? null : (ims.vo.LookupInstanceBean)vo.getSkinPreparationUsed().getBean();
this.batchno = vo.getBatchNo();
this.expirydate = vo.getExpiryDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getExpiryDate().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.clinical.vo.SkinPreperationVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.skinpreparationused = vo.getSkinPreparationUsed() == null ? null : (ims.vo.LookupInstanceBean)vo.getSkinPreparationUsed().getBean();
this.batchno = vo.getBatchNo();
this.expirydate = vo.getExpiryDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getExpiryDate().getBean();
}
public ims.clinical.vo.SkinPreperationVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.clinical.vo.SkinPreperationVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.clinical.vo.SkinPreperationVo vo = null;
if(map != null)
vo = (ims.clinical.vo.SkinPreperationVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.clinical.vo.SkinPreperationVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.vo.LookupInstanceBean getSkinPreparationUsed()
{
return this.skinpreparationused;
}
public void setSkinPreparationUsed(ims.vo.LookupInstanceBean value)
{
this.skinpreparationused = value;
}
public String getBatchNo()
{
return this.batchno;
}
public void setBatchNo(String value)
{
this.batchno = value;
}
public ims.framework.utils.beans.DateBean getExpiryDate()
{
return this.expirydate;
}
public void setExpiryDate(ims.framework.utils.beans.DateBean value)
{
this.expirydate = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean skinpreparationused;
private String batchno;
private ims.framework.utils.beans.DateBean expirydate;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/admin/vo/beans/AppointmentOutcomeConfigVoBean.java | 7154 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.admin.vo.beans;
public class AppointmentOutcomeConfigVoBean extends ims.vo.ValueObjectBean
{
public AppointmentOutcomeConfigVoBean()
{
}
public AppointmentOutcomeConfigVoBean(ims.admin.vo.AppointmentOutcomeConfigVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.appointmentoutcomereasons = vo.getAppointmentOutcomeReasons() == null ? null : vo.getAppointmentOutcomeReasons().getBeanCollection();
this.showfirstdefinitivetreatment = vo.getShowFirstDefinitiveTreatment();
this.canaddtowaitinglist = vo.getCanAddtoWaitingList();
this.canaddtobookedlist = vo.getCanAddtoBookedList();
this.canaddtoplannedlist = vo.getCanAddtoPlannedList();
this.canmakeappointment = vo.getCanMakeAppointment();
this.canmakeonwardreferral = vo.getCanMakeOnwardReferral();
this.cantransfer = vo.getCanTransfer();
this.appointmentoutcome = vo.getAppointmentOutcome() == null ? null : (ims.vo.LookupInstanceBean)vo.getAppointmentOutcome().getBean();
this.firstdefinitivetreatmentevent = vo.getFirstDefinitiveTreatmentEvent() == null ? null : (ims.pathways.vo.beans.EventLiteVoBean)vo.getFirstDefinitiveTreatmentEvent().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.admin.vo.AppointmentOutcomeConfigVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.appointmentoutcomereasons = vo.getAppointmentOutcomeReasons() == null ? null : vo.getAppointmentOutcomeReasons().getBeanCollection();
this.showfirstdefinitivetreatment = vo.getShowFirstDefinitiveTreatment();
this.canaddtowaitinglist = vo.getCanAddtoWaitingList();
this.canaddtobookedlist = vo.getCanAddtoBookedList();
this.canaddtoplannedlist = vo.getCanAddtoPlannedList();
this.canmakeappointment = vo.getCanMakeAppointment();
this.canmakeonwardreferral = vo.getCanMakeOnwardReferral();
this.cantransfer = vo.getCanTransfer();
this.appointmentoutcome = vo.getAppointmentOutcome() == null ? null : (ims.vo.LookupInstanceBean)vo.getAppointmentOutcome().getBean();
this.firstdefinitivetreatmentevent = vo.getFirstDefinitiveTreatmentEvent() == null ? null : (ims.pathways.vo.beans.EventLiteVoBean)vo.getFirstDefinitiveTreatmentEvent().getBean(map);
}
public ims.admin.vo.AppointmentOutcomeConfigVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.admin.vo.AppointmentOutcomeConfigVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.admin.vo.AppointmentOutcomeConfigVo vo = null;
if(map != null)
vo = (ims.admin.vo.AppointmentOutcomeConfigVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.admin.vo.AppointmentOutcomeConfigVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.admin.vo.beans.AppointmentOutcomeReasonVoBean[] getAppointmentOutcomeReasons()
{
return this.appointmentoutcomereasons;
}
public void setAppointmentOutcomeReasons(ims.admin.vo.beans.AppointmentOutcomeReasonVoBean[] value)
{
this.appointmentoutcomereasons = value;
}
public Boolean getShowFirstDefinitiveTreatment()
{
return this.showfirstdefinitivetreatment;
}
public void setShowFirstDefinitiveTreatment(Boolean value)
{
this.showfirstdefinitivetreatment = value;
}
public Boolean getCanAddtoWaitingList()
{
return this.canaddtowaitinglist;
}
public void setCanAddtoWaitingList(Boolean value)
{
this.canaddtowaitinglist = value;
}
public Boolean getCanAddtoBookedList()
{
return this.canaddtobookedlist;
}
public void setCanAddtoBookedList(Boolean value)
{
this.canaddtobookedlist = value;
}
public Boolean getCanAddtoPlannedList()
{
return this.canaddtoplannedlist;
}
public void setCanAddtoPlannedList(Boolean value)
{
this.canaddtoplannedlist = value;
}
public Boolean getCanMakeAppointment()
{
return this.canmakeappointment;
}
public void setCanMakeAppointment(Boolean value)
{
this.canmakeappointment = value;
}
public Boolean getCanMakeOnwardReferral()
{
return this.canmakeonwardreferral;
}
public void setCanMakeOnwardReferral(Boolean value)
{
this.canmakeonwardreferral = value;
}
public Boolean getCanTransfer()
{
return this.cantransfer;
}
public void setCanTransfer(Boolean value)
{
this.cantransfer = value;
}
public ims.vo.LookupInstanceBean getAppointmentOutcome()
{
return this.appointmentoutcome;
}
public void setAppointmentOutcome(ims.vo.LookupInstanceBean value)
{
this.appointmentoutcome = value;
}
public ims.pathways.vo.beans.EventLiteVoBean getFirstDefinitiveTreatmentEvent()
{
return this.firstdefinitivetreatmentevent;
}
public void setFirstDefinitiveTreatmentEvent(ims.pathways.vo.beans.EventLiteVoBean value)
{
this.firstdefinitivetreatmentevent = value;
}
private Integer id;
private int version;
private ims.admin.vo.beans.AppointmentOutcomeReasonVoBean[] appointmentoutcomereasons;
private Boolean showfirstdefinitivetreatment;
private Boolean canaddtowaitinglist;
private Boolean canaddtobookedlist;
private Boolean canaddtoplannedlist;
private Boolean canmakeappointment;
private Boolean canmakeonwardreferral;
private Boolean cantransfer;
private ims.vo.LookupInstanceBean appointmentoutcome;
private ims.pathways.vo.beans.EventLiteVoBean firstdefinitivetreatmentevent;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/ClinicalNoteStatusVoAssembler.java | 20094 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:31
*
*/
package ims.core.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Neil McAnaspie
*/
public class ClinicalNoteStatusVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.core.vo.ClinicalNoteStatusVo copy(ims.core.vo.ClinicalNoteStatusVo valueObjectDest, ims.core.vo.ClinicalNoteStatusVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_ClinicalNoteNoteStatus(valueObjectSrc.getID_ClinicalNoteNoteStatus());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// Status
valueObjectDest.setStatus(valueObjectSrc.getStatus());
// MOS
valueObjectDest.setMOS(valueObjectSrc.getMOS());
// DateTime
valueObjectDest.setDateTime(valueObjectSrc.getDateTime());
// ClinicalNote
valueObjectDest.setClinicalNote(valueObjectSrc.getClinicalNote());
// CorrectionReason
valueObjectDest.setCorrectionReason(valueObjectSrc.getCorrectionReason());
// CorrectionConfirmed
valueObjectDest.setCorrectionConfirmed(valueObjectSrc.getCorrectionConfirmed());
// CorrectedBy
valueObjectDest.setCorrectedBy(valueObjectSrc.getCorrectedBy());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createClinicalNoteStatusVoCollectionFromClinicalNoteNoteStatus(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.clinical.domain.objects.ClinicalNoteNoteStatus objects.
*/
public static ims.core.vo.ClinicalNoteStatusVoCollection createClinicalNoteStatusVoCollectionFromClinicalNoteNoteStatus(java.util.Set domainObjectSet)
{
return createClinicalNoteStatusVoCollectionFromClinicalNoteNoteStatus(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.core.clinical.domain.objects.ClinicalNoteNoteStatus objects.
*/
public static ims.core.vo.ClinicalNoteStatusVoCollection createClinicalNoteStatusVoCollectionFromClinicalNoteNoteStatus(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.core.vo.ClinicalNoteStatusVoCollection voList = new ims.core.vo.ClinicalNoteStatusVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject = (ims.core.clinical.domain.objects.ClinicalNoteNoteStatus) iterator.next();
ims.core.vo.ClinicalNoteStatusVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.core.clinical.domain.objects.ClinicalNoteNoteStatus objects.
*/
public static ims.core.vo.ClinicalNoteStatusVoCollection createClinicalNoteStatusVoCollectionFromClinicalNoteNoteStatus(java.util.List domainObjectList)
{
return createClinicalNoteStatusVoCollectionFromClinicalNoteNoteStatus(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.core.clinical.domain.objects.ClinicalNoteNoteStatus objects.
*/
public static ims.core.vo.ClinicalNoteStatusVoCollection createClinicalNoteStatusVoCollectionFromClinicalNoteNoteStatus(DomainObjectMap map, java.util.List domainObjectList)
{
ims.core.vo.ClinicalNoteStatusVoCollection voList = new ims.core.vo.ClinicalNoteStatusVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject = (ims.core.clinical.domain.objects.ClinicalNoteNoteStatus) domainObjectList.get(i);
ims.core.vo.ClinicalNoteStatusVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.core.clinical.domain.objects.ClinicalNoteNoteStatus set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractClinicalNoteNoteStatusSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.ClinicalNoteStatusVoCollection voCollection)
{
return extractClinicalNoteNoteStatusSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractClinicalNoteNoteStatusSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.ClinicalNoteStatusVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.core.vo.ClinicalNoteStatusVo vo = voCollection.get(i);
ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject = ClinicalNoteStatusVoAssembler.extractClinicalNoteNoteStatus(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.core.clinical.domain.objects.ClinicalNoteNoteStatus list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractClinicalNoteNoteStatusList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.ClinicalNoteStatusVoCollection voCollection)
{
return extractClinicalNoteNoteStatusList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractClinicalNoteNoteStatusList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.ClinicalNoteStatusVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.core.vo.ClinicalNoteStatusVo vo = voCollection.get(i);
ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject = ClinicalNoteStatusVoAssembler.extractClinicalNoteNoteStatus(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.core.clinical.domain.objects.ClinicalNoteNoteStatus object.
* @param domainObject ims.core.clinical.domain.objects.ClinicalNoteNoteStatus
*/
public static ims.core.vo.ClinicalNoteStatusVo create(ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.clinical.domain.objects.ClinicalNoteNoteStatus object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.core.vo.ClinicalNoteStatusVo create(DomainObjectMap map, ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.core.vo.ClinicalNoteStatusVo valueObject = (ims.core.vo.ClinicalNoteStatusVo) map.getValueObject(domainObject, ims.core.vo.ClinicalNoteStatusVo.class);
if ( null == valueObject )
{
valueObject = new ims.core.vo.ClinicalNoteStatusVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.core.clinical.domain.objects.ClinicalNoteNoteStatus
*/
public static ims.core.vo.ClinicalNoteStatusVo insert(ims.core.vo.ClinicalNoteStatusVo valueObject, ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.core.clinical.domain.objects.ClinicalNoteNoteStatus
*/
public static ims.core.vo.ClinicalNoteStatusVo insert(DomainObjectMap map, ims.core.vo.ClinicalNoteStatusVo valueObject, ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_ClinicalNoteNoteStatus(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// Status
ims.domain.lookups.LookupInstance instance1 = domainObject.getStatus();
if ( null != instance1 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance1.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance1.getImage().getImageId(), instance1.getImage().getImagePath());
}
color = instance1.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.ClinicalNotesStatus voLookup1 = new ims.core.vo.lookups.ClinicalNotesStatus(instance1.getId(),instance1.getText(), instance1.isActive(), null, img, color);
ims.core.vo.lookups.ClinicalNotesStatus parentVoLookup1 = voLookup1;
ims.domain.lookups.LookupInstance parent1 = instance1.getParent();
while (parent1 != null)
{
if (parent1.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent1.getImage().getImageId(), parent1.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent1.getColor();
if (color != null)
color.getValue();
parentVoLookup1.setParent(new ims.core.vo.lookups.ClinicalNotesStatus(parent1.getId(),parent1.getText(), parent1.isActive(), null, img, color));
parentVoLookup1 = parentVoLookup1.getParent();
parent1 = parent1.getParent();
}
valueObject.setStatus(voLookup1);
}
// MOS
valueObject.setMOS(ims.core.vo.domain.MemberOfStaffLiteVoAssembler.create(map, domainObject.getMOS()) );
// DateTime
java.util.Date DateTime = domainObject.getDateTime();
if ( null != DateTime )
{
valueObject.setDateTime(new ims.framework.utils.DateTime(DateTime) );
}
// ClinicalNote
valueObject.setClinicalNote(domainObject.getClinicalNote());
// CorrectionReason
valueObject.setCorrectionReason(domainObject.getCorrectionReason());
// CorrectionConfirmed
valueObject.setCorrectionConfirmed( domainObject.isCorrectionConfirmed() );
// CorrectedBy
valueObject.setCorrectedBy(ims.core.vo.domain.MemberOfStaffLiteVoAssembler.create(map, domainObject.getCorrectedBy()) );
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.core.clinical.domain.objects.ClinicalNoteNoteStatus extractClinicalNoteNoteStatus(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.ClinicalNoteStatusVo valueObject)
{
return extractClinicalNoteNoteStatus(domainFactory, valueObject, new HashMap());
}
public static ims.core.clinical.domain.objects.ClinicalNoteNoteStatus extractClinicalNoteNoteStatus(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.ClinicalNoteStatusVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_ClinicalNoteNoteStatus();
ims.core.clinical.domain.objects.ClinicalNoteNoteStatus domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.clinical.domain.objects.ClinicalNoteNoteStatus)domMap.get(valueObject);
}
// ims.core.vo.ClinicalNoteStatusVo ID_ClinicalNoteNoteStatus field is unknown
domainObject = new ims.core.clinical.domain.objects.ClinicalNoteNoteStatus();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_ClinicalNoteNoteStatus());
if (domMap.get(key) != null)
{
return (ims.core.clinical.domain.objects.ClinicalNoteNoteStatus)domMap.get(key);
}
domainObject = (ims.core.clinical.domain.objects.ClinicalNoteNoteStatus) domainFactory.getDomainObject(ims.core.clinical.domain.objects.ClinicalNoteNoteStatus.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_ClinicalNoteNoteStatus());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value1 = null;
if ( null != valueObject.getStatus() )
{
value1 =
domainFactory.getLookupInstance(valueObject.getStatus().getID());
}
domainObject.setStatus(value1);
domainObject.setMOS(ims.core.vo.domain.MemberOfStaffLiteVoAssembler.extractMemberOfStaff(domainFactory, valueObject.getMOS(), domMap));
ims.framework.utils.DateTime dateTime3 = valueObject.getDateTime();
java.util.Date value3 = null;
if ( dateTime3 != null )
{
value3 = dateTime3.getJavaDate();
}
domainObject.setDateTime(value3);
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getClinicalNote() != null && valueObject.getClinicalNote().equals(""))
{
valueObject.setClinicalNote(null);
}
domainObject.setClinicalNote(valueObject.getClinicalNote());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getCorrectionReason() != null && valueObject.getCorrectionReason().equals(""))
{
valueObject.setCorrectionReason(null);
}
domainObject.setCorrectionReason(valueObject.getCorrectionReason());
domainObject.setCorrectionConfirmed(valueObject.getCorrectionConfirmed());
domainObject.setCorrectedBy(ims.core.vo.domain.MemberOfStaffLiteVoAssembler.extractMemberOfStaff(domainFactory, valueObject.getCorrectedBy(), domMap));
return domainObject;
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ClinicalAdmin/src/ims/clinicaladmin/forms/tumourserummarkers/Logic.java | 1766 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 4972.23166)
// Copyright (C) 1995-2013 IMS MAXIMS. All rights reserved.
package ims.clinicaladmin.forms.tumourserummarkers;
public class Logic extends BaseLogic
{
private static final long serialVersionUID = 1L;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Clinical/src/ims/clinical/forms/edischargediagnosiscomponent/IFormUILogicCode.java | 1789 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.forms.edischargediagnosiscomponent;
public interface IFormUILogicCode
{
// No methods yet.
}
| agpl-3.0 |
eXist-db/exist | exist-core/src/main/java/org/exist/xquery/functions/session/GetAttribute.java | 3036 | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* info@exist-db.org
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.xquery.functions.session;
import org.exist.dom.QName;
import org.exist.http.servlets.SessionWrapper;
import org.exist.xquery.*;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;
import java.util.Optional;
/**
* Returns an attribute stored in the current session or an empty sequence
* if the attribute does not exist.
*
* @author Wolfgang Meier
* @author Loren Cahlander
* @author <a href="mailto:adam@evolvedbinary.com">Adam Retter</a>
*/
public class GetAttribute extends SessionFunction {
public final static FunctionSignature signature =
new FunctionSignature(
new QName("get-attribute", SessionModule.NAMESPACE_URI, SessionModule.PREFIX),
"Returns an attribute stored in the current session object or an empty sequence " +
"if the attribute cannot be found.",
new SequenceType[]{
new FunctionParameterSequenceType("name", Type.STRING, Cardinality.EXACTLY_ONE, "The session attribute name")
},
new FunctionReturnSequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE, "the attribute value"));
public GetAttribute(final XQueryContext context) {
super(context, signature);
}
@Override
public Sequence eval(final Sequence[] args, final Optional<SessionWrapper> session) throws XPathException {
if (!session.isPresent()) {
return Sequence.EMPTY_SEQUENCE;
}
final String attributeName = args[0].getStringValue();
final Optional<Object> maybeAttributeValue = withValidSession(session.get(), s -> Optional.ofNullable(s.getAttribute(attributeName))).orElse(Optional.empty());
if (!maybeAttributeValue.isPresent()) {
return Sequence.EMPTY_SEQUENCE;
}
final Object o = maybeAttributeValue.get();
return XPathUtil.javaObjectToXPath(o, context);
}
}
| lgpl-2.1 |
elsiklab/intermine | intermine/web/main/src/org/intermine/webservice/server/SessionService.java | 1510 | package org.intermine.webservice.server;
/*
* Copyright (C) 2002-2017 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileManager;
import org.intermine.webservice.server.core.JSONService;
/**
* Open a new 24-hour session.
*
* For authenticated users this just issues a new 24hr token,
* but for unauthenticated users it assigns a new in-memory profile,
* allowing users to save lists
* and all that good authenticated stuff, without actually creating a user.
*
* @author Alex Kalderimis
*
*/
public class SessionService extends JSONService
{
/** @param im The InterMine state object **/
public SessionService(InterMineAPI im) {
super(im);
}
@Override
protected String getResultsKey() {
return "token";
}
@Override
protected void execute() throws Exception {
ProfileManager pm = im.getProfileManager();
Profile p;
if (isAuthenticated()) {
p = getPermission().getProfile();
} else {
p = pm.createAnonymousProfile();
p.disableSaving();
}
String token = pm.generate24hrKey(p);
addResultValue(token, false);
}
}
| lgpl-2.1 |
stoksey69/googleads-java-lib | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201506/o/InStreamAdSpec.java | 3284 |
package com.google.api.ads.adwords.jaxws.v201506.o;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Placement request/response object which provides details about instream
* ad types, options, and other available configuration variables.
*
*
* <p>Java class for InStreamAdSpec complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="InStreamAdSpec">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="inStreamTypes" type="{https://adwords.google.com/api/adwords/o/v201506}InStreamAdSpec.InStreamType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="durations" type="{http://www.w3.org/2001/XMLSchema}long" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InStreamAdSpec", propOrder = {
"inStreamTypes",
"durations"
})
public class InStreamAdSpec {
@XmlSchemaType(name = "string")
protected List<InStreamAdSpecInStreamType> inStreamTypes;
@XmlElement(type = Long.class)
protected List<Long> durations;
/**
* Gets the value of the inStreamTypes property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the inStreamTypes property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getInStreamTypes().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link InStreamAdSpecInStreamType }
*
*
*/
public List<InStreamAdSpecInStreamType> getInStreamTypes() {
if (inStreamTypes == null) {
inStreamTypes = new ArrayList<InStreamAdSpecInStreamType>();
}
return this.inStreamTypes;
}
/**
* Gets the value of the durations property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the durations property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDurations().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Long }
*
*
*/
public List<Long> getDurations() {
if (durations == null) {
durations = new ArrayList<Long>();
}
return this.durations;
}
}
| apache-2.0 |
treejames/GeoprocessingAppstore | src/com/esri/gpt/control/webharvest/client/atom/OpenSearchAtomInfoProcessor.java | 1524 | /* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.esri.gpt.control.webharvest.client.atom;
/**
* This class is used to create open search based atom info
* processor.
*
*/
public class OpenSearchAtomInfoProcessor extends BaseAtomInfoProcessor {
@Override
public void preInitialize() {
// setAtomInfoClassName(atomInfoClassName);
}
/**
* Sets post create options.
* @param atomInfo base atom info
*/
@Override
public void postCreate(BaseAtomInfo atomInfo) {
atomInfo.setHitCountCollectorClassName("com.esri.gpt.control.webharvest.client.atom.OpenSearchHitCountCollector");
initializeHitCountCollector();
try {
atomInfo.setTotalResults(atomInfo.getHitCountCollector().collectHitCount(atomInfo.getUrl()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// add more logic if needed
}
}
| apache-2.0 |
mbiarnes/uberfire-extensions | uberfire-widgets/uberfire-widgets-core/uberfire-widgets-core-client/src/main/java/org/uberfire/ext/widgets/core/client/wizards/WizardPopupFooter.java | 4051 | /*
* Copyright 2014 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES 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.uberfire.ext.widgets.core.client.wizards;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ModalFooter;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Widget;
import org.uberfire.commons.validation.PortablePreconditions;
/**
* A Modal Footer used by the Wizard
*/
public class WizardPopupFooter extends ModalFooter {
private static WizardPopupFooterBinder uiBinder = GWT.create( WizardPopupFooterBinder.class );
private final Command cmdPreviousButton;
private final Command cmdNextButton;
private final Command cmdCancelButton;
private final Command cmdFinishButton;
interface WizardPopupFooterBinder
extends
UiBinder<Widget, WizardPopupFooter> {
}
@UiField
Button btnPrevious;
@UiField
Button btnNext;
@UiField
Button btnCancel;
@UiField
Button btnFinish;
public WizardPopupFooter( final Command cmdPreviousButton,
final Command cmdNextButton,
final Command cmdCancelButton,
final Command cmdFinishButton ) {
this.cmdPreviousButton = PortablePreconditions.checkNotNull( "cmdPreviousButton",
cmdPreviousButton );
this.cmdNextButton = PortablePreconditions.checkNotNull( "cmdNextButton",
cmdNextButton );
this.cmdCancelButton = PortablePreconditions.checkNotNull( "cmdCancelButton",
cmdCancelButton );
this.cmdFinishButton = PortablePreconditions.checkNotNull( "cmdFinishButton",
cmdFinishButton );
add( uiBinder.createAndBindUi( this ) );
}
public void enablePreviousButton( final boolean enabled ) {
btnPrevious.setEnabled( enabled );
}
public void enableNextButton( final boolean enabled ) {
btnNext.setEnabled( enabled );
}
public void enableFinishButton( final boolean enabled ) {
btnFinish.setEnabled( enabled );
if ( enabled ) {
btnFinish.setType( ButtonType.PRIMARY );
} else {
btnFinish.setType( ButtonType.DEFAULT );
}
}
public void setPreviousButtonFocus( final boolean focused ) {
btnPrevious.setFocus( focused );
}
public void setNextButtonFocus( final boolean focused ) {
btnNext.setFocus( focused );
}
@UiHandler("btnPrevious")
public void onPreviousButtonClick( final ClickEvent e ) {
cmdPreviousButton.execute();
}
@UiHandler("btnNext")
public void onNextButtonClick( final ClickEvent e ) {
cmdNextButton.execute();
}
@UiHandler("btnCancel")
public void onCancelButtonClick( final ClickEvent e ) {
cmdCancelButton.execute();
}
@UiHandler("btnFinish")
public void onFinishButtonClick( final ClickEvent e ) {
cmdFinishButton.execute();
}
}
| apache-2.0 |
springning/xmemcached | src/main/java/net/rubyeye/xmemcached/command/CommandType.java | 400 | package net.rubyeye.xmemcached.command;
/**
* Command Type for memcached protocol.
*
* @author dennis
*
*/
public enum CommandType {
NOOP, STATS, FLUSH_ALL, GET_ONE, GET_MANY, SET, REPLACE, ADD, EXCEPTION, DELETE, VERSION, QUIT, INCR, DECR, GETS_ONE, GETS_MANY, CAS, APPEND, PREPEND, GET_HIT, GET_MISS, VERBOSITY, AUTH_LIST, AUTH_START, AUTH_STEP, TOUCH, GAT, GATQ, SET_MANY;
} | apache-2.0 |
lanceleverich/drools | drools-compiler/src/main/java/org/drools/compiler/lang/descr/CompositePackageDescr.java | 6201 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.drools.compiler.lang.descr;
import org.drools.compiler.builder.impl.KnowledgeBuilderImpl;
import org.kie.api.io.Resource;
import org.kie.internal.builder.ResourceChange;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class CompositePackageDescr extends PackageDescr {
private CompositeAssetFilter filter;
public CompositePackageDescr() { }
public CompositePackageDescr(Resource resource, PackageDescr packageDescr) {
super(packageDescr.getNamespace(), packageDescr.getDocumentation());
internalAdd(resource, packageDescr);
}
public void addPackageDescr(Resource resource, PackageDescr packageDescr) {
if (!getNamespace().equals(packageDescr.getNamespace())) {
throw new RuntimeException("Composing PackageDescr (" + packageDescr.getName()
+ ") in different namespaces (namespace=" + getNamespace()
+ " packageDescr=" + packageDescr.getNamespace() + ")" );
}
internalAdd(resource, packageDescr);
}
private void internalAdd(Resource resource, PackageDescr packageDescr) {
List<ImportDescr> currentImports = getImports();
for (ImportDescr descr : packageDescr.getImports()) {
if (!currentImports.contains(descr)) {
addImport(descr);
descr.setResource(resource);
}
}
List<FunctionImportDescr> currentFunctionImports = getFunctionImports();
for (FunctionImportDescr descr : packageDescr.getFunctionImports()) {
if (!currentFunctionImports.contains(descr)) {
addFunctionImport(descr);
descr.setResource(resource);
}
}
List<AccumulateImportDescr> accumulateImports = getAccumulateImports();
for (AccumulateImportDescr descr : packageDescr.getAccumulateImports()) {
if (!accumulateImports.contains(descr)) {
addAccumulateImport(descr);
descr.setResource(resource);
}
}
List<AttributeDescr> currentAttributeDescrs = getAttributes();
for (AttributeDescr descr : packageDescr.getAttributes()) {
if (!currentAttributeDescrs.contains(descr)) {
addAttribute(descr);
descr.setResource(resource);
}
}
List<GlobalDescr> currentGlobalDescrs = getGlobals();
for (GlobalDescr descr : packageDescr.getGlobals()) {
if (!currentGlobalDescrs.contains(descr)) {
addGlobal(descr);
descr.setResource(resource);
}
}
List<FunctionDescr> currentFunctionDescrs = getFunctions();
for (FunctionDescr descr : packageDescr.getFunctions()) {
if (!currentFunctionDescrs.contains(descr)) {
addFunction(descr);
descr.setResource(resource);
}
}
List<RuleDescr> ruleDescrs = getRules();
for (RuleDescr descr : packageDescr.getRules()) {
if (!ruleDescrs.contains(descr)) {
addRule(descr);
descr.setResource(resource);
}
}
List<TypeDeclarationDescr> typeDeclarationDescrs = getTypeDeclarations();
for (TypeDeclarationDescr descr : packageDescr.getTypeDeclarations()) {
if (!typeDeclarationDescrs.contains(descr)) {
addTypeDeclaration(descr);
descr.setResource(resource);
}
}
List<EnumDeclarationDescr> enumDeclarationDescrs = getEnumDeclarations();
for (EnumDeclarationDescr enumDescr : packageDescr.getEnumDeclarations()) {
if (!enumDeclarationDescrs.contains(enumDescr)) {
addEnumDeclaration(enumDescr);
enumDescr.setResource(resource);
}
}
Set<EntryPointDeclarationDescr> entryPointDeclarationDescrs = getEntryPointDeclarations();
for (EntryPointDeclarationDescr descr : packageDescr.getEntryPointDeclarations()) {
if (!entryPointDeclarationDescrs.contains(descr)) {
addEntryPointDeclaration(descr);
descr.setResource(resource);
}
}
Set<WindowDeclarationDescr> windowDeclarationDescrs = getWindowDeclarations();
for (WindowDeclarationDescr descr : packageDescr.getWindowDeclarations()) {
if (!windowDeclarationDescrs.contains(descr)) {
addWindowDeclaration(descr);
descr.setResource(resource);
}
}
}
public CompositeAssetFilter getFilter() {
return filter;
}
public void addFilter( KnowledgeBuilderImpl.AssetFilter f ) {
if( f != null ) {
if( filter == null ) {
this.filter = new CompositeAssetFilter();
}
this.filter.filters.add( f );
}
}
public static class CompositeAssetFilter implements KnowledgeBuilderImpl.AssetFilter {
public List<KnowledgeBuilderImpl.AssetFilter> filters = new ArrayList<KnowledgeBuilderImpl.AssetFilter>();
@Override
public Action accept(ResourceChange.Type type, String pkgName, String assetName) {
for( KnowledgeBuilderImpl.AssetFilter filter : filters ) {
Action result = filter.accept(type, pkgName, assetName);
if( !Action.DO_NOTHING.equals( result ) ) {
return result;
}
}
return Action.DO_NOTHING;
}
}
}
| apache-2.0 |
oscarceballos/flink-1.3.2 | flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/pregel/ComputeFunction.java | 8825 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.flink.graph.pregel;
import org.apache.flink.api.common.aggregators.Aggregator;
import org.apache.flink.api.common.functions.IterationRuntimeContext;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Vertex;
import org.apache.flink.types.Either;
import org.apache.flink.types.Value;
import org.apache.flink.util.Collector;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
/**
* The base class for the message-passing functions between vertices as a part of a {@link VertexCentricIteration}.
*
* @param <K> The type of the vertex key (the vertex identifier).
* @param <VV> The type of the vertex value (the state of the vertex).
* @param <EV> The type of the values that are associated with the edges.
* @param <Message> The type of the message sent between vertices along the edges.
*/
public abstract class ComputeFunction<K, VV, EV, Message> implements Serializable {
private static final long serialVersionUID = 1L;
// --------------------------------------------------------------------------------------------
// Public API Methods
// --------------------------------------------------------------------------------------------
/**
* This method is invoked once per superstep, for each active vertex.
* A vertex is active during a superstep, if at least one message was produced for it,
* in the previous superstep. During the first superstep, all vertices are active.
* <p>
* This method can iterate over all received messages, set the new vertex value, and
* send messages to other vertices (which will be delivered in the next superstep).
*
* @param vertex The vertex executing this function
* @param messages The messages that were sent to this vertex in the previous superstep
* @throws Exception
*/
public abstract void compute(Vertex<K, VV> vertex, MessageIterator<Message> messages) throws Exception;
/**
* This method is executed once per superstep before the vertex update function is invoked for each vertex.
*
* @throws Exception Exceptions in the pre-superstep phase cause the superstep to fail.
*/
public void preSuperstep() throws Exception {}
/**
* This method is executed once per superstep after the vertex update function has been invoked for each vertex.
*
* @throws Exception Exceptions in the post-superstep phase cause the superstep to fail.
*/
public void postSuperstep() throws Exception {}
/**
* Gets an {@link java.lang.Iterable} with all out-going edges. This method is mutually exclusive with
* {@link #sendMessageToAllNeighbors(Object)} and may be called only once.
*
* @return An iterator with all edges.
*/
public final Iterable<Edge<K, EV>> getEdges() {
verifyEdgeUsage();
this.edgeIterator.set(edges);
return this.edgeIterator;
}
/**
* Sends the given message to all vertices that adjacent to the changed vertex.
* This method is mutually exclusive to the method {@link #getEdges()} and may be called only once.
*
* @param m The message to send.
*/
public final void sendMessageToAllNeighbors(Message m) {
verifyEdgeUsage();
outMsg.f1 = m;
while (edges.hasNext()) {
Tuple next = edges.next();
outMsg.f0 = next.getField(1);
out.collect(Either.Right(outMsg));
}
}
/**
* Sends the given message to the vertex identified by the given key. If the target vertex does not exist,
* the next superstep will cause an exception due to a non-deliverable message.
*
* @param target The key (id) of the target vertex to message.
* @param m The message.
*/
public final void sendMessageTo(K target, Message m) {
outMsg.f0 = target;
outMsg.f1 = m;
out.collect(Either.Right(outMsg));
}
/**
* Sets the new value of this vertex.
*
* This should be called at most once per ComputeFunction.
*
* @param newValue The new vertex value.
*/
public final void setNewVertexValue(VV newValue) {
if(setNewVertexValueCalled) {
throw new IllegalStateException("setNewVertexValue should only be called at most once per updateVertex");
}
setNewVertexValueCalled = true;
outVertex.f1 = newValue;
out.collect(Either.Left(outVertex));
}
// --------------------------------------------------------------------------------------------
/**
* Gets the number of the superstep, starting at <tt>1</tt>.
*
* @return The number of the current superstep.
*/
public final int getSuperstepNumber() {
return this.runtimeContext.getSuperstepNumber();
}
/**
* Gets the iteration aggregator registered under the given name. The iteration aggregator combines
* all aggregates globally once per superstep and makes them available in the next superstep.
*
* @param name The name of the aggregator.
* @return The aggregator registered under this name, or {@code null}, if no aggregator was registered.
*/
public final <T extends Aggregator<?>> T getIterationAggregator(String name) {
return this.runtimeContext.getIterationAggregator(name);
}
/**
* Get the aggregated value that an aggregator computed in the previous iteration.
*
* @param name The name of the aggregator.
* @return The aggregated value of the previous iteration.
*/
public final <T extends Value> T getPreviousIterationAggregate(String name) {
return this.runtimeContext.getPreviousIterationAggregate(name);
}
/**
* Gets the broadcast data set registered under the given name. Broadcast data sets
* are available on all parallel instances of a function. They can be registered via
* {@link org.apache.flink.graph.pregel.VertexCentricConfiguration#addBroadcastSet(String, DataSet)}.
*
* @param name The name under which the broadcast set is registered.
* @return The broadcast data set.
*/
public final <T> Collection<T> getBroadcastSet(String name) {
return this.runtimeContext.getBroadcastVariable(name);
}
// --------------------------------------------------------------------------------------------
// internal methods and state
// --------------------------------------------------------------------------------------------
private Vertex<K, VV> outVertex;
private Tuple2<K, Message> outMsg;
private IterationRuntimeContext runtimeContext;
private Iterator<Edge<K, EV>> edges;
private Collector<Either<?, ?>> out;
private EdgesIterator<K, EV> edgeIterator;
private boolean edgesUsed;
private boolean setNewVertexValueCalled;
void init(IterationRuntimeContext context) {
this.runtimeContext = context;
this.outVertex = new Vertex<>();
this.outMsg = new Tuple2<>();
this.edgeIterator = new EdgesIterator<>();
}
@SuppressWarnings("unchecked")
void set(K vertexId, Iterator<Edge<K, EV>> edges,
Collector<Either<Vertex<K, VV>, Tuple2<K, Message>>> out) {
this.outVertex.f0 = vertexId;
this.edges = edges;
this.out = (Collector<Either<?, ?>>) (Collector<?>) out;
this.edgesUsed = false;
setNewVertexValueCalled = false;
}
private void verifyEdgeUsage() throws IllegalStateException {
if (edgesUsed) {
throw new IllegalStateException(
"Can use either 'getEdges()' or 'sendMessageToAllNeighbors()' exactly once.");
}
edgesUsed = true;
}
private static final class EdgesIterator<K, EV>
implements Iterator<Edge<K, EV>>, Iterable<Edge<K, EV>>
{
private Iterator<Edge<K, EV>> input;
private Edge<K, EV> edge = new Edge<>();
void set(Iterator<Edge<K, EV>> input) {
this.input = input;
}
@Override
public boolean hasNext() {
return input.hasNext();
}
@Override
public Edge<K, EV> next() {
Edge<K, EV> next = input.next();
edge.setSource(next.f0);
edge.setTarget(next.f1);
edge.setValue(next.f2);
return edge;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<Edge<K, EV>> iterator() {
return this;
}
}
}
| apache-2.0 |
twitter-forks/bazel | third_party/java/proguard/proguard6.2.2/src/proguard/optimize/evaluation/LivenessAnalyzer.java | 18516 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2019 Guardsquare NV
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.optimize.evaluation;
import proguard.classfile.*;
import proguard.classfile.attribute.*;
import proguard.classfile.attribute.visitor.*;
import proguard.classfile.instruction.*;
import proguard.classfile.instruction.visitor.InstructionVisitor;
import proguard.classfile.util.SimplifiedVisitor;
import proguard.evaluation.BasicInvocationUnit;
import proguard.evaluation.value.*;
import proguard.util.ArrayUtil;
/**
* This AttributeVisitor analyzes the liveness of the variables in the code
* attributes that it visits, based on partial evaluation.
*
* @author Eric Lafortune
*/
public class LivenessAnalyzer
extends SimplifiedVisitor
implements AttributeVisitor,
InstructionVisitor,
ExceptionInfoVisitor
{
//*
private static final boolean DEBUG = false;
/*/
private static boolean DEBUG = System.getProperty("la") != null;
//*/
private static final int MAX_VARIABLES_SIZE = 64;
private final PartialEvaluator partialEvaluator;
private final boolean runPartialEvaluator;
private final InitializationFinder initializationFinder;
private final boolean runInitializationFinder;
private long[] isAliveBefore = new long[ClassConstants.TYPICAL_CODE_LENGTH];
private long[] isAliveAfter = new long[ClassConstants.TYPICAL_CODE_LENGTH];
private long[] isCategory2 = new long[ClassConstants.TYPICAL_CODE_LENGTH];
// Fields acting as global temporary variables.
private boolean checkAgain;
private long alive;
/**
* Creates a new LivenessAnalyzer.
*/
public LivenessAnalyzer()
{
this(new ReferenceTracingValueFactory(new BasicValueFactory()));
}
/**
* Creates a new LivenessAnalyzer. This private constructor gets around
* the constraint that it's not allowed to add statements before calling
* 'this'.
*/
private LivenessAnalyzer(ReferenceTracingValueFactory referenceTracingValueFactory)
{
this(new PartialEvaluator(referenceTracingValueFactory,
new ReferenceTracingInvocationUnit(new BasicInvocationUnit(referenceTracingValueFactory)),
true,
referenceTracingValueFactory),
true);
}
/**
* Creates a new LivenessAnalyzer. This private constructor gets around
* the constraint that it's not allowed to add statements before calling
* 'this'.
*/
private LivenessAnalyzer(PartialEvaluator partialEvaluator,
boolean runPartialEvaluator)
{
this(partialEvaluator,
runPartialEvaluator,
new InitializationFinder(partialEvaluator, false),
true);
}
/**
* Creates a new LivenessAnalyzer that will use the given partial evaluator
* and initialization finder.
* @param partialEvaluator the evaluator to be used for the analysis.
* @param runPartialEvaluator specifies whether to run this evaluator on
* every code attribute that is visited.
* @param initializationFinder the initialization finder to be used for
* the analysis.
* @param runInitializationFinder specifies whether to run this
* initialization finder on every code
* attribute that is visited.
*/
public LivenessAnalyzer(PartialEvaluator partialEvaluator,
boolean runPartialEvaluator,
InitializationFinder initializationFinder,
boolean runInitializationFinder)
{
this.partialEvaluator = partialEvaluator;
this.runPartialEvaluator = runPartialEvaluator;
this.initializationFinder = initializationFinder;
this.runInitializationFinder = runInitializationFinder;
}
/**
* Returns whether the instruction at the given offset has ever been
* executed during the partial evaluation.
*/
public boolean isTraced(int instructionOffset)
{
return partialEvaluator.isTraced(instructionOffset);
}
/**
* Returns whether the specified variable is alive before the instruction
* at the given offset.
*/
public boolean isAliveBefore(int instructionOffset, int variableIndex)
{
return variableIndex >= MAX_VARIABLES_SIZE ?
partialEvaluator.getVariablesBefore(instructionOffset).getValue(variableIndex) != null :
(isAliveBefore[instructionOffset] & (1L << variableIndex)) != 0;
}
/**
* Sets whether the specified variable is alive before the instruction
* at the given offset.
*/
public void setAliveBefore(int instructionOffset, int variableIndex, boolean alive)
{
if (variableIndex < MAX_VARIABLES_SIZE)
{
if (alive)
{
isAliveBefore[instructionOffset] |= 1L << variableIndex;
}
else
{
isAliveBefore[instructionOffset] &= ~(1L << variableIndex);
}
}
}
/**
* Returns whether the specified variable is alive after the instruction
* at the given offset.
*/
public boolean isAliveAfter(int instructionOffset, int variableIndex)
{
return variableIndex >= MAX_VARIABLES_SIZE ?
partialEvaluator.getVariablesAfter(instructionOffset).getValue(variableIndex) != null :
(isAliveAfter[instructionOffset] & (1L << variableIndex)) != 0;
}
/**
* Sets whether the specified variable is alive after the instruction
* at the given offset.
*/
public void setAliveAfter(int instructionOffset, int variableIndex, boolean alive)
{
if (variableIndex < MAX_VARIABLES_SIZE)
{
if (alive)
{
isAliveAfter[instructionOffset] |= 1L << variableIndex;
}
else
{
isAliveAfter[instructionOffset] &= ~(1L << variableIndex);
}
}
}
/**
* Returns whether the specified variable takes up two entries after the
* instruction at the given offset.
*/
public boolean isCategory2(int instructionOffset, int variableIndex)
{
return variableIndex >= MAX_VARIABLES_SIZE ?
partialEvaluator.getVariablesBefore(instructionOffset).getValue(variableIndex) != null &&
partialEvaluator.getVariablesBefore(instructionOffset).getValue(variableIndex).isCategory2() :
(isCategory2[instructionOffset] & (1L << variableIndex)) != 0;
}
/**
* Sets whether the specified variable takes up two entries after the
* instruction at the given offset.
*/
public void setCategory2(int instructionOffset, int variableIndex, boolean category2)
{
if (variableIndex < MAX_VARIABLES_SIZE)
{
if (category2)
{
isCategory2[instructionOffset] |= 1L << variableIndex;
}
else
{
isCategory2[instructionOffset] &= ~(1L << variableIndex);
}
}
}
// Implementations for AttributeVisitor.
public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
{
// DEBUG =
// clazz.getName().equals("abc/Def") &&
// method.getName(clazz).equals("abc");
if (DEBUG)
{
System.out.println();
System.out.println("Liveness analysis: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
}
int codeLength = codeAttribute.u4codeLength;
int variablesSize = codeAttribute.u2maxLocals;
// Initialize the global arrays.
isAliveBefore = ArrayUtil.ensureArraySize(isAliveBefore, codeLength, 0L);
isAliveAfter = ArrayUtil.ensureArraySize(isAliveAfter, codeLength, 0L);
isCategory2 = ArrayUtil.ensureArraySize(isCategory2, codeLength, 0L);
// Evaluate the method.
if (runPartialEvaluator)
{
partialEvaluator.visitCodeAttribute(clazz, method, codeAttribute);
}
if (runInitializationFinder)
{
initializationFinder.visitCodeAttribute(clazz, method, codeAttribute);
}
// We'll only really analyze the first 64 variables.
if (variablesSize > MAX_VARIABLES_SIZE)
{
variablesSize = MAX_VARIABLES_SIZE;
}
// Mark liveness blocks, as many times as necessary.
do
{
checkAgain = false;
alive = 0L;
// Loop over all traced instructions, backward.
for (int offset = codeLength - 1; offset >= 0; offset--)
{
if (partialEvaluator.isTraced(offset))
{
// Update the liveness based on the branch targets.
InstructionOffsetValue branchTargets = partialEvaluator.branchTargets(offset);
if (branchTargets != null)
{
// Update the liveness right after the branch instruction.
alive = combinedLiveness(branchTargets);
}
// Merge the current liveness.
alive |= isAliveAfter[offset];
// Update the liveness after the instruction.
isAliveAfter[offset] = alive;
// Update the current liveness based on the instruction.
codeAttribute.instructionAccept(clazz, method, offset, this);
// Merge the current liveness.
alive |= isAliveBefore[offset];
// Update the liveness before the instruction.
if ((~isAliveBefore[offset] & alive) != 0L)
{
isAliveBefore[offset] = alive;
// Do we have to check again after this loop?
InstructionOffsetValue branchOrigins = partialEvaluator.branchOrigins(offset);
if (branchOrigins != null &&
offset < branchOrigins.maximumValue())
{
checkAgain = true;
}
}
}
}
// Account for the liveness at the start of the exception handlers.
codeAttribute.exceptionsAccept(clazz, method, this);
}
while (checkAgain);
// Loop over all instructions, to mark variables that take up two entries.
for (int offset = 0; offset < codeLength; offset++)
{
if (partialEvaluator.isTraced(offset))
{
// Loop over all variables.
for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
{
// Is the variable alive and a category 2 type?
if (isAliveBefore(offset, variableIndex))
{
Value value = partialEvaluator.getVariablesBefore(offset).getValue(variableIndex);
if (value != null && value.isCategory2())
{
// Mark it as such.
setCategory2(offset, variableIndex, true);
// Mark the next variable as well.
setAliveBefore(offset, variableIndex + 1, true);
setCategory2( offset, variableIndex + 1, true);
}
}
// Is the variable alive and a category 2 type?
if (isAliveAfter(offset, variableIndex))
{
Value value = partialEvaluator.getVariablesAfter(offset).getValue(variableIndex);
if (value != null && value.isCategory2())
{
// Mark it as such.
setCategory2(offset, variableIndex, true);
// Mark the next variable as well.
setAliveAfter(offset, variableIndex + 1, true);
setCategory2( offset, variableIndex + 1, true);
}
}
}
}
}
if (DEBUG)
{
// Loop over all instructions.
for (int offset = 0; offset < codeLength; offset++)
{
if (partialEvaluator.isTraced(offset))
{
long aliveBefore = isAliveBefore[offset];
long aliveAfter = isAliveAfter[offset];
long category2 = isCategory2[offset];
// Print out the liveness of all variables before the instruction.
for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
{
long variableMask = (1L << variableIndex);
System.out.print((aliveBefore & variableMask) == 0L ? '.' :
(category2 & variableMask) == 0L ? 'x' :
'*');
}
// Print out the instruction itself.
System.out.println(" "+ InstructionFactory.create(codeAttribute.code, offset).toString(offset));
// Print out the liveness of all variables after the instruction.
for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
{
long variableMask = (1L << variableIndex);
System.out.print((aliveAfter & variableMask) == 0L ? '.' :
(category2 & variableMask) == 0L ? 'x' :
'=');
}
System.out.println();
}
}
}
}
// Implementations for InstructionVisitor.
public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
{
int variableIndex = variableInstruction.variableIndex;
if (variableIndex < MAX_VARIABLES_SIZE)
{
long livenessMask = 1L << variableIndex;
// Is it a load instruction or a store instruction?
if (variableInstruction.isLoad())
{
// Start marking the variable before the load instruction.
alive |= livenessMask;
}
else
{
// Stop marking the variable before the store instruction.
alive &= ~livenessMask;
// But do mark the variable right after the store instruction.
isAliveAfter[offset] |= livenessMask;
}
}
}
public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
{
// Special case: variable 0 ('this') in an initializer has to be alive
// as long as it hasn't been initialized.
if (offset == initializationFinder.superInitializationOffset())
{
alive |= 1L;
}
}
// Implementations for ExceptionInfoVisitor.
public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
{
// Are any variables alive at the start of the handler?
long alive = isAliveBefore[exceptionInfo.u2handlerPC];
if (alive != 0L)
{
// Set the same liveness flags for the entire try block.
int startOffset = exceptionInfo.u2startPC;
int endOffset = exceptionInfo.u2endPC;
for (int offset = startOffset; offset < endOffset; offset++)
{
if (partialEvaluator.isTraced(offset))
{
if ((~(isAliveBefore[offset] & isAliveAfter[offset]) & alive) != 0L)
{
isAliveBefore[offset] |= alive;
isAliveAfter[offset] |= alive;
// Check again after having marked this try block.
checkAgain = true;
}
}
}
}
}
// Small utility methods.
/**
* Returns the combined liveness mask of the variables right before the
* specified instruction offsets.
*/
private long combinedLiveness(InstructionOffsetValue instructionOffsetValue)
{
long alive = 0L;
int count = instructionOffsetValue.instructionOffsetCount();
for (int index = 0; index < count; index++)
{
alive |= isAliveBefore[instructionOffsetValue.instructionOffset(index)];
}
return alive;
}
}
| apache-2.0 |
gkatsikas/onos | core/net/src/main/java/org/onosproject/net/intent/impl/phase/Installing.java | 1876 | /*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.onosproject.net.intent.impl.phase;
import org.onosproject.net.intent.IntentData;
import org.onosproject.net.intent.impl.IntentProcessor;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onosproject.net.intent.IntentState.INSTALLING;
/**
* Represents a phase where an intent is being installed.
*/
class Installing extends FinalIntentProcessPhase {
private final IntentProcessor processor;
private final IntentData data;
private final Optional<IntentData> stored;
/**
* Create an installing phase.
*
* @param processor intent processor that does work for installing
* @param data intent data containing an intent to be installed
* @param stored intent data already stored
*/
Installing(IntentProcessor processor, IntentData data, Optional<IntentData> stored) {
this.processor = checkNotNull(processor);
this.data = checkNotNull(data);
this.stored = checkNotNull(stored);
this.data.setState(INSTALLING);
}
@Override
public void preExecute() {
processor.apply(stored, Optional.of(data));
}
@Override
public IntentData data() {
return data;
}
}
| apache-2.0 |
romartin/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-core-common/src/test/java/org/kie/workbench/common/stunner/core/command/impl/CompositeCommandTest.java | 12686 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.kie.workbench.common.stunner.core.command.impl;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandResultBuilder;
import org.kie.workbench.common.stunner.core.graph.command.impl.AbstractGraphCommand;
import org.kie.workbench.common.stunner.core.rule.RuleViolation;
import org.kie.workbench.common.stunner.core.rule.violations.RuleViolationImpl;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.Silent.class)
public class CompositeCommandTest {
private static CommandResult<RuleViolation> SOME_ERROR_VIOLATION =
new CommandResultImpl<>(CommandResult.Type.ERROR,
Collections.singletonList(new RuleViolationImpl("failed")));
@Mock
GraphCommandExecutionContext commandExecutionContext;
private CompositeCommandStub tested;
@Before
public void setup() throws Exception {
this.tested = spy(new CompositeCommandStub());
}
@Test
@SuppressWarnings("unchecked")
public void testInitialize() {
assertFalse(tested.isInitialized());
tested.ensureInitialized(commandExecutionContext);
assertTrue(tested.isInitialized());
}
@Test
@SuppressWarnings("unchecked")
public void testAllow() {
CommandResult<RuleViolation> result = tested.allow(commandExecutionContext);
assertNotNull(result);
assertEquals(CommandResult.Type.INFO,
result.getType());
verify(tested,
times(1)).addCommand(any(CommandStub.class));
}
@Test
@SuppressWarnings("unchecked")
public void testExecute() {
CommandResult<RuleViolation> result = tested.execute(commandExecutionContext);
assertNotNull(result);
assertEquals(CommandResult.Type.INFO,
result.getType());
verify(tested,
times(1)).addCommand(any(CommandStub.class));
}
@Test
@SuppressWarnings("unchecked")
public void testExecute1Failed() {
Command c1 = mockSuccessCommandOperations();
when(c1.execute(eq(commandExecutionContext))).thenReturn(SOME_ERROR_VIOLATION);
Command c2 = mockSuccessCommandOperations();
Command c3 = mockSuccessCommandOperations();
CompositeCommand command = new CompositeCommand.Builder<>()
.addCommand(c1)
.addCommand(c2)
.addCommand(c3)
.build();
CommandResult result = command.execute(commandExecutionContext);
assertEquals(CommandResult.Type.ERROR,
result.getType());
verify(c1, times(1)).execute(eq(commandExecutionContext));
verify(c1, never()).undo(eq(commandExecutionContext));
verify(c2, never()).execute(eq(commandExecutionContext));
verify(c2, never()).undo(eq(commandExecutionContext));
verify(c3, never()).execute(eq(commandExecutionContext));
verify(c3, never()).undo(eq(commandExecutionContext));
}
@Test
@SuppressWarnings("unchecked")
public void testExecute2FailedThenUndo() {
Command c1 = mockSuccessCommandOperations();
Command c2 = mockSuccessCommandOperations();
when(c2.execute(eq(commandExecutionContext))).thenReturn(SOME_ERROR_VIOLATION);
Command c3 = mockSuccessCommandOperations();
CompositeCommand command = new CompositeCommand.Builder<>()
.addCommand(c1)
.addCommand(c2)
.addCommand(c3)
.build();
CommandResult result = command.execute(commandExecutionContext);
assertEquals(CommandResult.Type.ERROR,
result.getType());
verify(c1, times(1)).execute(eq(commandExecutionContext));
verify(c1, times(1)).undo(eq(commandExecutionContext));
verify(c2, times(1)).execute(eq(commandExecutionContext));
verify(c2, never()).undo(eq(commandExecutionContext));
verify(c3, never()).execute(eq(commandExecutionContext));
verify(c3, never()).undo(eq(commandExecutionContext));
}
@Test
@SuppressWarnings("unchecked")
public void testExecute3FailedThenUndo() {
Command c1 = mockSuccessCommandOperations();
Command c2 = mockSuccessCommandOperations();
Command c3 = mockSuccessCommandOperations();
when(c3.execute(eq(commandExecutionContext))).thenReturn(SOME_ERROR_VIOLATION);
CompositeCommand command = new CompositeCommand.Builder<>()
.addCommand(c1)
.addCommand(c2)
.addCommand(c3)
.build();
CommandResult result = command.execute(commandExecutionContext);
assertEquals(CommandResult.Type.ERROR,
result.getType());
verify(c1, times(1)).execute(eq(commandExecutionContext));
verify(c1, times(1)).undo(eq(commandExecutionContext));
verify(c2, times(1)).execute(eq(commandExecutionContext));
verify(c2, times(1)).undo(eq(commandExecutionContext));
verify(c3, times(1)).execute(eq(commandExecutionContext));
verify(c3, never()).undo(eq(commandExecutionContext));
}
@Test
@SuppressWarnings("unchecked")
public void testUndo3Failed() {
Command c1 = mockSuccessCommandOperations();
Command c2 = mockSuccessCommandOperations();
Command c3 = mockSuccessCommandOperations();
when(c3.undo(eq(commandExecutionContext))).thenReturn(SOME_ERROR_VIOLATION);
CompositeCommand command = new CompositeCommand.Builder<>()
.addCommand(c1)
.addCommand(c2)
.addCommand(c3)
.build();
CommandResult result = command.undo(commandExecutionContext);
assertEquals(CommandResult.Type.ERROR,
result.getType());
verify(c3, times(1)).undo(eq(commandExecutionContext));
verify(c3, never()).execute(eq(commandExecutionContext));
verify(c2, never()).undo(eq(commandExecutionContext));
verify(c2, never()).execute(eq(commandExecutionContext));
verify(c1, never()).undo(eq(commandExecutionContext));
verify(c1, never()).execute(eq(commandExecutionContext));
}
@Test
@SuppressWarnings("unchecked")
public void testUndo2FailedSoRedo() {
Command c1 = mockSuccessCommandOperations();
Command c2 = mockSuccessCommandOperations();
when(c2.undo(eq(commandExecutionContext))).thenReturn(SOME_ERROR_VIOLATION);
Command c3 = mockSuccessCommandOperations();
CompositeCommand command = new CompositeCommand.Builder<>()
.addCommand(c1)
.addCommand(c2)
.addCommand(c3)
.build();
CommandResult result = command.undo(commandExecutionContext);
assertEquals(CommandResult.Type.ERROR,
result.getType());
verify(c3, times(1)).undo(eq(commandExecutionContext));
verify(c3, times(1)).execute(eq(commandExecutionContext));
verify(c2, times(1)).undo(eq(commandExecutionContext));
verify(c2, never()).execute(eq(commandExecutionContext));
verify(c1, never()).undo(eq(commandExecutionContext));
verify(c1, never()).execute(eq(commandExecutionContext));
}
@Test
@SuppressWarnings("unchecked")
public void testUndo1FailedSoRedo() {
Command c1 = mockSuccessCommandOperations();
when(c1.undo(eq(commandExecutionContext))).thenReturn(SOME_ERROR_VIOLATION);
Command c2 = mockSuccessCommandOperations();
Command c3 = mockSuccessCommandOperations();
CompositeCommand command = new CompositeCommand.Builder<>()
.addCommand(c1)
.addCommand(c2)
.addCommand(c3)
.build();
CommandResult result = command.undo(commandExecutionContext);
assertEquals(CommandResult.Type.ERROR,
result.getType());
verify(c3, times(1)).undo(eq(commandExecutionContext));
verify(c3, times(1)).execute(eq(commandExecutionContext));
verify(c2, times(1)).undo(eq(commandExecutionContext));
verify(c2, times(1)).execute(eq(commandExecutionContext));
verify(c1, times(1)).undo(eq(commandExecutionContext));
verify(c1, never()).execute(eq(commandExecutionContext));
}
@SuppressWarnings("unchecked")
private Command mockSuccessCommandOperations() {
Command command = mock(Command.class);
when(command.allow(eq(commandExecutionContext))).thenReturn(GraphCommandResultBuilder.SUCCESS);
when(command.execute(eq(commandExecutionContext))).thenReturn(GraphCommandResultBuilder.SUCCESS);
when(command.undo(eq(commandExecutionContext))).thenReturn(GraphCommandResultBuilder.SUCCESS);
return command;
}
private static class CompositeCommandStub extends AbstractCompositeCommand<GraphCommandExecutionContext, RuleViolation> {
@Override
protected CompositeCommandStub initialize(GraphCommandExecutionContext context) {
super.initialize(context);
addCommand(new CommandStub());
return this;
}
@Override
protected CommandResult<RuleViolation> doAllow(GraphCommandExecutionContext context,
Command<GraphCommandExecutionContext, RuleViolation> command) {
return GraphCommandResultBuilder.SUCCESS;
}
@Override
protected CommandResult<RuleViolation> doExecute(GraphCommandExecutionContext context,
Command<GraphCommandExecutionContext, RuleViolation> command) {
return GraphCommandResultBuilder.SUCCESS;
}
@Override
protected CommandResult<RuleViolation> doUndo(GraphCommandExecutionContext context,
Command<GraphCommandExecutionContext, RuleViolation> command) {
return GraphCommandResultBuilder.SUCCESS;
}
}
private static class CommandStub extends AbstractGraphCommand {
private final CommandResult<RuleViolation> executeResult;
private CommandStub() {
this.executeResult = GraphCommandResultBuilder.SUCCESS;
}
public CommandStub(CommandResult<RuleViolation> executeResult) {
this.executeResult = executeResult;
}
@Override
protected CommandResult<RuleViolation> check(GraphCommandExecutionContext context) {
return GraphCommandResultBuilder.SUCCESS;
}
@Override
public CommandResult<RuleViolation> allow(GraphCommandExecutionContext context) {
return GraphCommandResultBuilder.SUCCESS;
}
@Override
public CommandResult<RuleViolation> execute(GraphCommandExecutionContext context) {
return executeResult;
}
@Override
public CommandResult<RuleViolation> undo(GraphCommandExecutionContext context) {
return GraphCommandResultBuilder.SUCCESS;
}
}
}
| apache-2.0 |
jimma/xerces | src/org/apache/xml/serialize/HTMLdtd.java | 19010 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Aug 21, 2000:
// Fixed bug in isElement and made HTMLdtd public.
// Contributed by Eric SCHAEFFER" <eschaeffer@posterconseil.com>
package org.apache.xml.serialize;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Locale;
import org.apache.xerces.dom.DOMMessageFormatter;
/**
* Utility class for accessing information specific to HTML documents.
* The HTML DTD is expressed as three utility function groups. Two methods
* allow for checking whether an element requires an open tag on printing
* ({@link #isEmptyTag}) or on parsing ({@link #isOptionalClosing}).
* <P>
* Two other methods translate character references from name to value and
* from value to name. A small entities resource is loaded into memory the
* first time any of these methods is called for fast and efficient access.
*
* @deprecated This class was deprecated in Xerces 2.9.0. It is recommended
* that new applications use JAXP's Transformation API for XML (TrAX) for
* serializing HTML. See the Xerces documentation for more information.
* @version $Revision$ $Date$
* @author <a href="mailto:arkin@intalio.com">Assaf Arkin</a>
*/
public final class HTMLdtd
{
/**
* Public identifier for HTML 4.01 (Strict) document type.
*/
public static final String HTMLPublicId = "-//W3C//DTD HTML 4.01//EN";
/**
* System identifier for HTML 4.01 (Strict) document type.
*/
public static final String HTMLSystemId =
"http://www.w3.org/TR/html4/strict.dtd";
/**
* Public identifier for XHTML 1.0 (Strict) document type.
*/
public static final String XHTMLPublicId =
"-//W3C//DTD XHTML 1.0 Strict//EN";
/**
* System identifier for XHTML 1.0 (Strict) document type.
*/
public static final String XHTMLSystemId =
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";
/**
* Table of reverse character reference mapping. Character codes are held
* as single-character strings, mapped to their reference name.
*/
private static Hashtable _byChar;
/**
* Table of entity name to value mapping. Entities are held as strings,
* character references as <TT>Character</TT> objects.
*/
private static Hashtable _byName;
private static Hashtable _boolAttrs;
/**
* Holds element definitions.
*/
private static Hashtable _elemDefs;
/**
* Locates the HTML entities file that is loaded upon initialization.
* This file is a resource loaded with the default class loader.
*/
private static final String ENTITIES_RESOURCE = "HTMLEntities.res";
/**
* Only opening tag should be printed.
*/
private static final int ONLY_OPENING = 0x0001;
/**
* Element contains element content only.
*/
private static final int ELEM_CONTENT = 0x0002;
/**
* Element preserve spaces.
*/
private static final int PRESERVE = 0x0004;
/**
* Optional closing tag.
*/
private static final int OPT_CLOSING = 0x0008;
/**
* Element is empty (also means only opening tag)
*/
private static final int EMPTY = 0x0010 | ONLY_OPENING;
/**
* Allowed to appear in head.
*/
private static final int ALLOWED_HEAD = 0x0020;
/**
* When opened, closes P.
*/
private static final int CLOSE_P = 0x0040;
/**
* When opened, closes DD or DT.
*/
private static final int CLOSE_DD_DT = 0x0080;
/**
* When opened, closes itself.
*/
private static final int CLOSE_SELF = 0x0100;
/**
* When opened, closes another table section.
*/
private static final int CLOSE_TABLE = 0x0200;
/**
* When opened, closes TH or TD.
*/
private static final int CLOSE_TH_TD = 0x04000;
/**
* Returns true if element is declared to be empty. HTML elements are
* defines as empty in the DTD, not by the document syntax.
*
* @param tagName The element tag name (upper case)
* @return True if element is empty
*/
public static boolean isEmptyTag( String tagName )
{
return isElement( tagName, EMPTY );
}
/**
* Returns true if element is declared to have element content.
* Whitespaces appearing inside element content will be ignored,
* other text will simply report an error.
*
* @param tagName The element tag name (upper case)
* @return True if element content
*/
public static boolean isElementContent( String tagName )
{
return isElement( tagName, ELEM_CONTENT );
}
/**
* Returns true if element's textual contents preserves spaces.
* This only applies to PRE and TEXTAREA, all other HTML elements
* do not preserve space.
*
* @param tagName The element tag name (upper case)
* @return True if element's text content preserves spaces
*/
public static boolean isPreserveSpace( String tagName )
{
return isElement( tagName, PRESERVE );
}
/**
* Returns true if element's closing tag is optional and need not
* exist. An error will not be reported for such elements if they
* are not closed. For example, <tt>LI</tt> is most often not closed.
*
* @param tagName The element tag name (upper case)
* @return True if closing tag implied
*/
public static boolean isOptionalClosing( String tagName )
{
return isElement( tagName, OPT_CLOSING );
}
/**
* Returns true if element's closing tag is generally not printed.
* For example, <tt>LI</tt> should not print the closing tag.
*
* @param tagName The element tag name (upper case)
* @return True if only opening tag should be printed
*/
public static boolean isOnlyOpening( String tagName )
{
return isElement( tagName, ONLY_OPENING );
}
/**
* Returns true if the opening of one element (<tt>tagName</tt>) implies
* the closing of another open element (<tt>openTag</tt>). For example,
* every opening <tt>LI</tt> will close the previously open <tt>LI</tt>,
* and every opening <tt>BODY</tt> will close the previously open <tt>HEAD</tt>.
*
* @param tagName The newly opened element
* @param openTag The already opened element
* @return True if closing tag closes opening tag
*/
public static boolean isClosing( String tagName, String openTag )
{
// Several elements are defined as closing the HEAD
if ( openTag.equalsIgnoreCase( "HEAD" ) )
return ! isElement( tagName, ALLOWED_HEAD );
// P closes iteself
if ( openTag.equalsIgnoreCase( "P" ) )
return isElement( tagName, CLOSE_P );
// DT closes DD, DD closes DT
if ( openTag.equalsIgnoreCase( "DT" ) || openTag.equalsIgnoreCase( "DD" ) )
return isElement( tagName, CLOSE_DD_DT );
// LI and OPTION close themselves
if ( openTag.equalsIgnoreCase( "LI" ) || openTag.equalsIgnoreCase( "OPTION" ) )
return isElement( tagName, CLOSE_SELF );
// Each of these table sections closes all the others
if ( openTag.equalsIgnoreCase( "THEAD" ) || openTag.equalsIgnoreCase( "TFOOT" ) ||
openTag.equalsIgnoreCase( "TBODY" ) || openTag.equalsIgnoreCase( "TR" ) ||
openTag.equalsIgnoreCase( "COLGROUP" ) )
return isElement( tagName, CLOSE_TABLE );
// TD closes TH and TH closes TD
if ( openTag.equalsIgnoreCase( "TH" ) || openTag.equalsIgnoreCase( "TD" ) )
return isElement( tagName, CLOSE_TH_TD );
return false;
}
/**
* Returns true if the specified attribute it a URI and should be
* escaped appropriately. In HTML URIs are escaped differently
* than normal attributes.
*
* @param tagName The element's tag name
* @param attrName The attribute's name
*/
public static boolean isURI( String tagName, String attrName )
{
// Stupid checks.
return ( attrName.equalsIgnoreCase( "href" ) || attrName.equalsIgnoreCase( "src" ) );
}
/**
* Returns true if the specified attribute is a boolean and should be
* printed without the value. This applies to attributes that are true
* if they exist, such as selected (OPTION/INPUT).
*
* @param tagName The element's tag name
* @param attrName The attribute's name
*/
public static boolean isBoolean( String tagName, String attrName )
{
String[] attrNames;
attrNames = (String[]) _boolAttrs.get( tagName.toUpperCase(Locale.ENGLISH) );
if ( attrNames == null )
return false;
for ( int i = 0 ; i < attrNames.length ; ++i )
if ( attrNames[ i ].equalsIgnoreCase( attrName ) )
return true;
return false;
}
/**
* Returns the value of an HTML character reference by its name. If the
* reference is not found or was not defined as a character reference,
* returns EOF (-1).
*
* @param name Name of character reference
* @return Character code or EOF (-1)
*/
public static int charFromName( String name )
{
Object value;
initialize();
value = _byName.get( name );
if ( value != null && value instanceof Integer ) {
return ( (Integer) value ).intValue();
}
return -1;
}
/**
* Returns the name of an HTML character reference based on its character
* value. Only valid for entities defined from character references. If no
* such character value was defined, return null.
*
* @param value Character value of entity
* @return Entity's name or null
*/
public static String fromChar(int value )
{
if (value > 0xffff)
return null;
String name;
initialize();
name = (String) _byChar.get( new Integer( value ) );
return name;
}
/**
* Initialize upon first access. Will load all the HTML character references
* into a list that is accessible by name or character value and is optimized
* for character substitution. This method may be called any number of times
* but will execute only once.
*/
private static void initialize()
{
InputStream is = null;
BufferedReader reader = null;
int index;
String name;
String value;
int code;
String line;
// Make sure not to initialize twice.
if ( _byName != null )
return;
try {
_byName = new Hashtable();
_byChar = new Hashtable();
is = HTMLdtd.class.getResourceAsStream( ENTITIES_RESOURCE );
if ( is == null ) {
throw new RuntimeException(
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.SERIALIZER_DOMAIN,
"ResourceNotFound", new Object[] {ENTITIES_RESOURCE}));
}
reader = new BufferedReader( new InputStreamReader( is, "ASCII" ) );
line = reader.readLine();
while ( line != null ) {
if ( line.length() == 0 || line.charAt( 0 ) == '#' ) {
line = reader.readLine();
continue;
}
index = line.indexOf( ' ' );
if ( index > 1 ) {
name = line.substring( 0, index );
++index;
if ( index < line.length() ) {
value = line.substring( index );
index = value.indexOf( ' ' );
if ( index > 0 )
value = value.substring( 0, index );
code = Integer.parseInt( value );
defineEntity( name, (char) code );
}
}
line = reader.readLine();
}
is.close();
} catch ( Exception except ) {
throw new RuntimeException(
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.SERIALIZER_DOMAIN,
"ResourceNotLoaded", new Object[] {ENTITIES_RESOURCE, except.toString()}));
} finally {
if ( is != null ) {
try {
is.close();
} catch ( Exception except ) { }
}
}
}
/**
* Defines a new character reference. The reference's name and value are
* supplied. Nothing happens if the character reference is already defined.
* <P>
* Unlike internal entities, character references are a string to single
* character mapping. They are used to map non-ASCII characters both on
* parsing and printing, primarily for HTML documents. '<amp;' is an
* example of a character reference.
*
* @param name The entity's name
* @param value The entity's value
*/
private static void defineEntity( String name, char value )
{
if ( _byName.get( name ) == null ) {
_byName.put( name, new Integer( value ) );
_byChar.put( new Integer( value ), name );
}
}
private static void defineElement( String name, int flags )
{
_elemDefs.put( name, new Integer( flags ) );
}
private static void defineBoolean( String tagName, String attrName )
{
defineBoolean( tagName, new String[] { attrName } );
}
private static void defineBoolean( String tagName, String[] attrNames )
{
_boolAttrs.put( tagName, attrNames );
}
private static boolean isElement( String name, int flag )
{
Integer flags;
flags = (Integer) _elemDefs.get( name.toUpperCase(Locale.ENGLISH) );
if ( flags == null ) {
return false;
}
return ( ( flags.intValue() & flag ) == flag );
}
static
{
_elemDefs = new Hashtable();
defineElement( "ADDRESS", CLOSE_P );
defineElement( "AREA", EMPTY );
defineElement( "BASE", EMPTY | ALLOWED_HEAD );
defineElement( "BASEFONT", EMPTY );
defineElement( "BLOCKQUOTE", CLOSE_P );
defineElement( "BODY", OPT_CLOSING );
defineElement( "BR", EMPTY );
defineElement( "COL", EMPTY );
defineElement( "COLGROUP", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE );
defineElement( "DD", OPT_CLOSING | ONLY_OPENING | CLOSE_DD_DT );
defineElement( "DIV", CLOSE_P );
defineElement( "DL", ELEM_CONTENT | CLOSE_P );
defineElement( "DT", OPT_CLOSING | ONLY_OPENING | CLOSE_DD_DT );
defineElement( "FIELDSET", CLOSE_P );
defineElement( "FORM", CLOSE_P );
defineElement( "FRAME", EMPTY | OPT_CLOSING );
defineElement( "H1", CLOSE_P );
defineElement( "H2", CLOSE_P );
defineElement( "H3", CLOSE_P );
defineElement( "H4", CLOSE_P );
defineElement( "H5", CLOSE_P );
defineElement( "H6", CLOSE_P );
defineElement( "HEAD", ELEM_CONTENT | OPT_CLOSING );
defineElement( "HR", EMPTY | CLOSE_P );
defineElement( "HTML", ELEM_CONTENT | OPT_CLOSING );
defineElement( "IMG", EMPTY );
defineElement( "INPUT", EMPTY );
defineElement( "ISINDEX", EMPTY | ALLOWED_HEAD );
defineElement( "LI", OPT_CLOSING | ONLY_OPENING | CLOSE_SELF );
defineElement( "LINK", EMPTY | ALLOWED_HEAD );
defineElement( "MAP", ALLOWED_HEAD );
defineElement( "META", EMPTY | ALLOWED_HEAD );
defineElement( "OL", ELEM_CONTENT | CLOSE_P );
defineElement( "OPTGROUP", ELEM_CONTENT );
defineElement( "OPTION", OPT_CLOSING | ONLY_OPENING | CLOSE_SELF );
defineElement( "P", OPT_CLOSING | CLOSE_P | CLOSE_SELF );
defineElement( "PARAM", EMPTY );
defineElement( "PRE", PRESERVE | CLOSE_P );
defineElement( "SCRIPT", ALLOWED_HEAD | PRESERVE );
defineElement( "NOSCRIPT", ALLOWED_HEAD | PRESERVE );
defineElement( "SELECT", ELEM_CONTENT );
defineElement( "STYLE", ALLOWED_HEAD | PRESERVE );
defineElement( "TABLE", ELEM_CONTENT | CLOSE_P );
defineElement( "TBODY", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE );
defineElement( "TD", OPT_CLOSING | CLOSE_TH_TD );
defineElement( "TEXTAREA", PRESERVE );
defineElement( "TFOOT", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE );
defineElement( "TH", OPT_CLOSING | CLOSE_TH_TD );
defineElement( "THEAD", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE );
defineElement( "TITLE", ALLOWED_HEAD );
defineElement( "TR", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE );
defineElement( "UL", ELEM_CONTENT | CLOSE_P );
_boolAttrs = new Hashtable();
defineBoolean( "AREA", "href" );
defineBoolean( "BUTTON", "disabled" );
defineBoolean( "DIR", "compact" );
defineBoolean( "DL", "compact" );
defineBoolean( "FRAME", "noresize" );
defineBoolean( "HR", "noshade" );
defineBoolean( "IMAGE", "ismap" );
defineBoolean( "INPUT", new String[] { "defaultchecked", "checked", "readonly", "disabled" } );
defineBoolean( "LINK", "link" );
defineBoolean( "MENU", "compact" );
defineBoolean( "OBJECT", "declare" );
defineBoolean( "OL", "compact" );
defineBoolean( "OPTGROUP", "disabled" );
defineBoolean( "OPTION", new String[] { "default-selected", "selected", "disabled" } );
defineBoolean( "SCRIPT", "defer" );
defineBoolean( "SELECT", new String[] { "multiple", "disabled" } );
defineBoolean( "STYLE", "disabled" );
defineBoolean( "TD", "nowrap" );
defineBoolean( "TH", "nowrap" );
defineBoolean( "TEXTAREA", new String[] { "disabled", "readonly" } );
defineBoolean( "UL", "compact" );
initialize();
}
}
| apache-2.0 |
zazi/Wikidata-Toolkit | wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/json/jackson/JacksonReference.java | 3566 | package org.wikidata.wdtk.datamodel.json.jackson;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.wikidata.wdtk.datamodel.helpers.Equality;
import org.wikidata.wdtk.datamodel.helpers.Hash;
import org.wikidata.wdtk.datamodel.helpers.ToString;
import org.wikidata.wdtk.datamodel.interfaces.Reference;
import org.wikidata.wdtk.datamodel.interfaces.Snak;
import org.wikidata.wdtk.datamodel.interfaces.SnakGroup;
import org.wikidata.wdtk.util.NestedIterator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Jackson implementation of {@link Reference}.
*
* @author Fredo Erxleben
* @author Markus Kroetzsch
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class JacksonReference implements Reference {
private List<SnakGroup> snakGroups = null;
/**
* Map of property id strings to snaks, as used to encode snaks in JSON.
*/
Map<String, List<JacksonSnak>> snaks;
/**
* List of property string ids that encodes the desired order of snaks,
* which is not specified by the map.
*/
List<String> propertyOrder;
@JsonIgnore
@Override
public List<SnakGroup> getSnakGroups() {
if (this.snakGroups == null) {
this.snakGroups = SnakGroupFromJson.makeSnakGroups(this.snaks,
this.propertyOrder);
}
return this.snakGroups;
}
/**
* Sets the map of snaks to the given value. Only for use by Jackson during
* deserialization.
*
* @param snaks
* new value
*/
public void setSnaks(Map<String, List<JacksonSnak>> snaks) {
this.snaks = snaks;
this.snakGroups = null; // clear cache
}
/**
* Returns the map of snaks as found in JSON. Only for use by Jackson during
* serialization.
*
* @return the map of snaks
*/
public Map<String, List<JacksonSnak>> getSnaks() {
return this.snaks;
}
/**
* Sets the list of property ids to the given value. Only for use by Jackson
* during deserialization.
*
* @param propertyOrder
* new value
*/
@JsonProperty("snaks-order")
public void setPropertyOrder(List<String> propertyOrder) {
this.propertyOrder = propertyOrder;
this.snakGroups = null; // clear cache
}
/**
* Returns the list of property ids used to order snaks as found in JSON.
* Only for use by Jackson during serialization.
*
* @return the list of property ids
*/
@JsonProperty("snaks-order")
public List<String> getPropertyOrder() {
return this.propertyOrder;
}
@Override
public Iterator<Snak> getAllSnaks() {
return new NestedIterator<>(getSnakGroups());
}
@Override
public int hashCode() {
return Hash.hashCode(this);
}
@Override
public boolean equals(Object obj) {
return Equality.equalsReference(this, obj);
}
@Override
public String toString() {
return ToString.toString(this);
}
}
| apache-2.0 |
skarsaune/hawtio | hawtio-log/src/main/java/io/hawt/log/log4j/Log4jLogQueryMBean.java | 501 | package io.hawt.log.log4j;
import io.hawt.log.support.LogQuerySupportMBean;
import org.apache.log4j.spi.LoggingEvent;
/**
* The MBean operations for {@link Log4jLogQuery}
*/
public interface Log4jLogQueryMBean extends LogQuerySupportMBean {
/**
* Provides a hook you can call if the underlying log4j
* configuration is reloaded so that you can force the appender
* to get re-registered.
*/
void reconnectAppender();
public void logMessage(LoggingEvent record);
}
| apache-2.0 |
MaTriXy/immutables | value-fixture/src/org/immutables/fixture/style/EnclosingBuilderNew.java | 1142 | /*
Copyright 2014 Immutables Authors and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES 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.immutables.fixture.style;
import org.immutables.value.Value;
import org.immutables.value.Value.Style.ImplementationVisibility;
/**
* Feature combination
* <ul>
* <li>Nested Builder using constructor "new" invokation
* </ul>
*/
@Value.Enclosing
@Value.Style(
builder = "new",
visibility = ImplementationVisibility.PRIVATE)
public abstract class EnclosingBuilderNew {
@Value.Immutable
public static class Hidden {}
void use() {
new ImmutableEnclosingBuilderNew.HiddenBuilder().build();
}
}
| apache-2.0 |
apache/accumulo | test/src/main/java/org/apache/accumulo/test/compaction/TestCompactionStrategy.java | 2548 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.accumulo.test.compaction;
import java.util.Map;
import org.apache.accumulo.core.metadata.StoredTabletFile;
import org.apache.accumulo.core.metadata.TabletFile;
import org.apache.accumulo.tserver.compaction.CompactionPlan;
import org.apache.accumulo.tserver.compaction.CompactionStrategy;
import org.apache.accumulo.tserver.compaction.MajorCompactionRequest;
@SuppressWarnings("removal")
public class TestCompactionStrategy extends CompactionStrategy {
private String inputPrefix = "Z";
private String dropPrefix = "Z";
private boolean shouldCompact = false;
@Override
public void init(Map<String,String> options) {
if (options.containsKey("inputPrefix"))
inputPrefix = options.get("inputPrefix");
if (options.containsKey("dropPrefix"))
dropPrefix = options.get("dropPrefix");
if (options.containsKey("shouldCompact"))
shouldCompact = Boolean.parseBoolean(options.get("shouldCompact"));
}
@Override
public boolean shouldCompact(MajorCompactionRequest request) {
if (shouldCompact)
return true;
for (TabletFile file : request.getFiles().keySet()) {
if (file.getFileName().startsWith(inputPrefix))
return true;
if (file.getFileName().startsWith(dropPrefix))
return true;
}
return false;
}
@Override
public CompactionPlan getCompactionPlan(MajorCompactionRequest request) {
CompactionPlan plan = new CompactionPlan();
for (StoredTabletFile file : request.getFiles().keySet()) {
if (file.getFileName().startsWith(dropPrefix)) {
plan.deleteFiles.add(file);
} else if (file.getFileName().startsWith(inputPrefix)) {
plan.inputFiles.add(file);
}
}
return plan;
}
}
| apache-2.0 |
alipayhuber/hack-hbase | hbase-client/src/main/java/org/apache/hadoop/hbase/client/Append.java | 4075 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.hadoop.hbase.client;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.util.Bytes;
/**
* Performs Append operations on a single row.
* <p>
* Note that this operation does not appear atomic to readers. Appends are done
* under a single row lock, so write operations to a row are synchronized, but
* readers do not take row locks so get and scan operations can see this
* operation partially completed.
* <p>
* To append to a set of columns of a row, instantiate an Append object with the
* row to append to. At least one column to append must be specified using the
* {@link #add(byte[], byte[], byte[])} method.
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class Append extends Mutation {
private static final String RETURN_RESULTS = "_rr_";
/**
* @param returnResults
* True (default) if the append operation should return the results.
* A client that is not interested in the result can save network
* bandwidth setting this to false.
*/
public void setReturnResults(boolean returnResults) {
setAttribute(RETURN_RESULTS, Bytes.toBytes(returnResults));
}
/**
* @return current setting for returnResults
*/
public boolean isReturnResults() {
byte[] v = getAttribute(RETURN_RESULTS);
return v == null ? true : Bytes.toBoolean(v);
}
/**
* Create a Append operation for the specified row.
* <p>
* At least one column must be appended to.
* @param row row key; makes a local copy of passed in array.
*/
public Append(byte[] row) {
this(row, 0, row.length);
}
/** Create a Append operation for the specified row.
* <p>
* At least one column must be appended to.
* @param rowArray Makes a copy out of this buffer.
* @param rowOffset
* @param rowLength
*/
public Append(final byte [] rowArray, final int rowOffset, final int rowLength) {
checkRow(rowArray, rowOffset, rowLength);
this.row = Bytes.copy(rowArray, rowOffset, rowLength);
}
/**
* Add the specified column and value to this Append operation.
* @param family family name
* @param qualifier column qualifier
* @param value value to append to specified column
* @return this
*/
public Append add(byte [] family, byte [] qualifier, byte [] value) {
KeyValue kv = new KeyValue(this.row, family, qualifier, this.ts, KeyValue.Type.Put, value);
return add(kv);
}
/**
* Add column and value to this Append operation.
* @param cell
* @return This instance
*/
@SuppressWarnings("unchecked")
public Append add(final Cell cell) {
// Presume it is KeyValue for now.
KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
byte [] family = kv.getFamily();
List<Cell> list = this.familyMap.get(family);
if (list == null) {
list = new ArrayList<Cell>();
}
// find where the new entry should be placed in the List
list.add(kv);
this.familyMap.put(family, list);
return this;
}
}
| apache-2.0 |
kahboom/apiman | gateway/engine/beans/src/main/java/io/apiman/gateway/engine/beans/util/QueryMap.java | 2228 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.gateway.engine.beans.util;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.stream.Collectors;
/**
* A map of query parameters to associated values. It is possible to
* have multiple values for a given key.
*
* @author Marc Savy {@literal <msavy@redhat.com>}
*/
public class QueryMap extends CaseInsensitiveStringMultiMap implements Serializable {
private static final long serialVersionUID = -3539301043663183648L;
/**
* Construct map with default capacity.
*/
public QueryMap() {
super();
}
/**
* Construct a QueryMap.
*
* @param sizeHint the size hint
*/
public QueryMap(int sizeHint) {
super(sizeHint);
}
@Override
public String toString() {
return toQueryString();
}
@SuppressWarnings("nls")
public String toQueryString() { // TODO optimise
List<Entry<String, String>> elems = getEntries();
Collections.reverse(elems);
return elems.stream()
.map(pair -> URLEnc(pair.getKey()) + "=" + URLEnc(pair.getValue()))
.collect(Collectors.joining("&"));
}
private String URLEnc(String str) {
try {
return URLEncoder.encode(str, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
System.err.println("Unable to URLEncode" + str); //$NON-NLS-1$
return str;
}
}
}
| apache-2.0 |
masaki-yamakawa/geode | geode-junit/src/main/java/org/apache/geode/test/micrometer/MicrometerAssertions.java | 2135 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information
* regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2
* .0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 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.geode.test.micrometer;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Timer;
/**
* Entry point for assertions for Micrometer meters.
*/
public class MicrometerAssertions {
/**
* Creates an assertion to evaluate the given meter.
*
* @param meter the meter to evaluate
* @return the created assertion object
*/
public static MeterAssert assertThat(Meter meter) {
return new MeterAssert(meter);
}
/**
* Creates an assertion to evaluate the given counter.
*
* @param counter the counter to evaluate
* @return the created assertion object
*/
public static CounterAssert assertThat(Counter counter) {
return new CounterAssert(counter);
}
/**
* Creates an assertion to evaluate the given gauge.
*
* @param gauge the gauge to evaluate
* @return the created assertion object
*/
public static GaugeAssert assertThat(Gauge gauge) {
return new GaugeAssert(gauge);
}
/**
* Creates an assertion to evaluate the given timer.
*
* @param timer the timer to evaluate
* @return the created assertion object
*/
public static TimerAssert assertThat(Timer timer) {
return new TimerAssert(timer);
}
}
| apache-2.0 |
kimchy/compass | src/main/test/org/compass/annotations/test/dynamic/jexl/JexlDynamicTests.java | 1216 | package org.compass.annotations.test.dynamic.jexl;
import java.util.Calendar;
import org.compass.annotations.test.AbstractAnnotationsTestCase;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;
import org.compass.core.Resource;
import org.compass.core.config.CompassConfiguration;
/**
* @author kimchy
*/
public class JexlDynamicTests extends AbstractAnnotationsTestCase {
protected void addExtraConf(CompassConfiguration conf) {
conf.addClass(A.class);
}
public void testSimpleExpression() throws Exception {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
A a = new A();
a.setId(1);
a.setValue("value");
a.setValue2("value2");
Calendar cal = Calendar.getInstance();
cal.set(1977, 4, 1);
a.setDate(cal.getTime());
session.save(a);
Resource resource = session.loadResource(A.class, 1);
assertEquals("valuevalue2", resource.getValue("test"));
assertEquals("value", resource.getValue("test2"));
assertEquals("1977", resource.getValue("date"));
tr.commit();
session.close();
}
}
| apache-2.0 |
siosio/intellij-community | platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java | 40857 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.colors.impl;
import com.intellij.BundleBase;
import com.intellij.DynamicBundle;
import com.intellij.application.options.EditorFontsConstants;
import com.intellij.configurationStore.SerializableScheme;
import com.intellij.ide.ui.ColorBlindness;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.*;
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.options.Scheme;
import com.intellij.openapi.options.SchemeState;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.Ref;
import com.intellij.ui.ColorUtil;
import com.intellij.util.JdomKt;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.JBIterable;
import org.jdom.Element;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
@SuppressWarnings("UseJBColor")
public abstract class AbstractColorsScheme extends EditorFontCacheImpl implements EditorColorsScheme, SerializableScheme {
public static final TextAttributes INHERITED_ATTRS_MARKER = new TextAttributes();
public static final Color INHERITED_COLOR_MARKER = ColorUtil.marker("INHERITED_COLOR_MARKER");
public static final Color NULL_COLOR_MARKER = ColorUtil.marker("NULL_COLOR_MARKER");
public static final int CURR_VERSION = 142;
public static final String NAME_BUNDLE_PROPERTY = "lcNameBundle";
public static final String NAME_KEY_PROPERTY = "lcNameKey";
protected EditorColorsScheme myParentScheme;
@NotNull private FontPreferences myFontPreferences
= new DelegatingFontPreferences(() -> AppEditorFontOptions.getInstance().getFontPreferences());
@NotNull private FontPreferences myConsoleFontPreferences = new DelegatingFontPreferences(() -> myFontPreferences);
private final ValueElementReader myValueReader = new TextAttributesReader();
private String mySchemeName;
private boolean myIsSaveNeeded;
private boolean myCanBeDeleted = true;
// version influences XML format and triggers migration
private int myVersion = CURR_VERSION;
Map<ColorKey, Color> myColorsMap = new HashMap<>();
Map<@NonNls String, TextAttributes> myAttributesMap = new HashMap<>();
@NonNls private static final String EDITOR_FONT = "font";
@NonNls private static final String CONSOLE_FONT = "console-font";
@NonNls private static final String EDITOR_FONT_NAME = "EDITOR_FONT_NAME";
@NonNls private static final String CONSOLE_FONT_NAME = "CONSOLE_FONT_NAME";
private Color myDeprecatedBackgroundColor = null;
@NonNls private static final String SCHEME_ELEMENT = "scheme";
@NonNls public static final String NAME_ATTR = "name";
@NonNls private static final String VERSION_ATTR = "version";
@NonNls private static final String BASE_ATTRIBUTES_ATTR = "baseAttributes";
@NonNls private static final String DEFAULT_SCHEME_ATTR = "default_scheme";
@NonNls private static final String PARENT_SCHEME_ATTR = "parent_scheme";
@NonNls private static final String OPTION_ELEMENT = "option";
@NonNls private static final String COLORS_ELEMENT = "colors";
@NonNls private static final String ATTRIBUTES_ELEMENT = "attributes";
@NonNls private static final String VALUE_ELEMENT = "value";
@NonNls private static final String BACKGROUND_COLOR_NAME = "BACKGROUND";
@NonNls private static final String LINE_SPACING = "LINE_SPACING";
@NonNls private static final String CONSOLE_LINE_SPACING = "CONSOLE_LINE_SPACING";
@NonNls private static final String FONT_SCALE = "FONT_SCALE";
@NonNls private static final String EDITOR_FONT_SIZE = "EDITOR_FONT_SIZE";
@NonNls private static final String CONSOLE_FONT_SIZE = "CONSOLE_FONT_SIZE";
@NonNls private static final String EDITOR_LIGATURES = "EDITOR_LIGATURES";
@NonNls private static final String CONSOLE_LIGATURES = "CONSOLE_LIGATURES";
//region Meta info-related fields
private final Properties myMetaInfo = new Properties();
private final static SimpleDateFormat META_INFO_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
@NonNls private static final String META_INFO_ELEMENT = "metaInfo";
@NonNls private static final String PROPERTY_ELEMENT = "property";
@NonNls private static final String PROPERTY_NAME_ATTR = "name";
@NonNls private static final String META_INFO_CREATION_TIME = "created";
@NonNls private static final String META_INFO_MODIFIED_TIME = "modified";
@NonNls private static final String META_INFO_IDE = "ide";
@NonNls private static final String META_INFO_IDE_VERSION = "ideVersion";
@NonNls private static final String META_INFO_ORIGINAL = "originalScheme";
//endregion
protected AbstractColorsScheme(EditorColorsScheme parentScheme) {
myParentScheme = parentScheme;
}
public AbstractColorsScheme() {
}
public void setDefaultMetaInfo(@Nullable AbstractColorsScheme parentScheme) {
myMetaInfo.setProperty(META_INFO_CREATION_TIME, META_INFO_DATE_FORMAT.format(new Date()));
myMetaInfo.setProperty(META_INFO_IDE, PlatformUtils.getPlatformPrefix());
myMetaInfo.setProperty(META_INFO_IDE_VERSION, ApplicationInfoEx.getInstanceEx().getStrictVersion());
if (parentScheme != null && parentScheme != EmptyColorScheme.INSTANCE) {
myMetaInfo.setProperty(META_INFO_ORIGINAL, parentScheme.getName());
}
}
@NotNull
@Override
public Color getDefaultBackground() {
final Color c = getAttributes(HighlighterColors.TEXT).getBackgroundColor();
return c != null ? c : Color.white;
}
@NotNull
@Override
public Color getDefaultForeground() {
final Color c = getAttributes(HighlighterColors.TEXT).getForegroundColor();
return c != null ? c : Color.black;
}
@NotNull
@Override
public String getName() {
return mySchemeName;
}
@NotNull
@Override
public String getDisplayName() {
if (!(this instanceof ReadOnlyColorsScheme)) {
EditorColorsScheme original = getOriginal();
if (original instanceof ReadOnlyColorsScheme) {
return original.getDisplayName();
}
}
String baseName = Scheme.getBaseName(getName()); //NON-NLS
return ObjectUtils.chooseNotNull(getLocalizedName(), baseName);
}
@Nullable
@Nls
protected String getLocalizedName() {
String bundlePath = getMetaProperties().getProperty(NAME_BUNDLE_PROPERTY);
String bundleKey = getMetaProperties().getProperty(NAME_KEY_PROPERTY);
if (bundlePath != null && bundleKey != null) {
ResourceBundle bundle = DynamicBundle.INSTANCE.getResourceBundle(bundlePath, getClass().getClassLoader());
return BundleBase.messageOrDefault(bundle, bundleKey, null);
}
return null;
}
@Override
public void setFont(EditorFontType key, Font font) {
}
@Override
public abstract Object clone();
public void copyTo(AbstractColorsScheme newScheme) {
if (myConsoleFontPreferences instanceof DelegatingFontPreferences) {
newScheme.setUseEditorFontPreferencesInConsole();
}
else {
newScheme.setConsoleFontPreferences(myConsoleFontPreferences);
}
if (myFontPreferences instanceof DelegatingFontPreferences) {
newScheme.setUseAppFontPreferencesInEditor();
}
else {
newScheme.setFontPreferences(myFontPreferences);
}
newScheme.myAttributesMap = new HashMap<>(myAttributesMap);
newScheme.myColorsMap = new HashMap<>(myColorsMap);
newScheme.myVersion = myVersion;
}
@NotNull
public Set<ColorKey> getColorKeys() {
return myColorsMap.keySet();
}
/**
* Returns the attributes defined in this scheme (not inherited from a parent).
*/
@SuppressWarnings("unused") // for Rider
@NotNull
public Map<@NonNls String, TextAttributes> getDirectlyDefinedAttributes() {
return new HashMap<>(myAttributesMap);
}
@Override
public void setEditorFontName(String fontName) {
ModifiableFontPreferences currPreferences = ensureEditableFontPreferences();
boolean useLigatures = currPreferences.useLigatures();
int editorFontSize = getEditorFontSize();
currPreferences.clear();
currPreferences.register(fontName, editorFontSize);
currPreferences.setUseLigatures(useLigatures);
initFonts();
}
@Override
public void setEditorFontSize(int fontSize) {
fontSize = EditorFontsConstants.checkAndFixEditorFontSize(fontSize);
ensureEditableFontPreferences().register(myFontPreferences.getFontFamily(), fontSize);
initFonts();
}
@Override
public void setUseAppFontPreferencesInEditor() {
myFontPreferences = new DelegatingFontPreferences(()-> AppEditorFontOptions.getInstance().getFontPreferences());
initFonts();
}
@Override
public boolean isUseAppFontPreferencesInEditor() {
return myFontPreferences instanceof DelegatingFontPreferences;
}
@Override
public void setLineSpacing(float lineSpacing) {
ensureEditableFontPreferences().setLineSpacing(lineSpacing);
}
@NotNull
@Override
public Font getFont(EditorFontType key) {
return myFontPreferences instanceof DelegatingFontPreferences ? EditorFontCache.getInstance().getFont(key) : super.getFont(key);
}
@Override
public void setName(@NotNull String name) {
mySchemeName = name;
}
@NotNull
@Override
public FontPreferences getFontPreferences() {
return myFontPreferences;
}
@Override
public void setFontPreferences(@NotNull FontPreferences preferences) {
preferences.copyTo(ensureEditableFontPreferences());
initFonts();
}
@Override
@NlsSafe
public String getEditorFontName() {
return AppEditorFontOptions.NEW_FONT_SELECTOR ? myFontPreferences.getFontFamily() : getFont(EditorFontType.PLAIN).getFamily();
}
@Override
public int getEditorFontSize() {
return myFontPreferences.getSize(myFontPreferences.getFontFamily());
}
@Override
public float getLineSpacing() {
return myFontPreferences.getLineSpacing();
}
protected void initFonts() {
reset();
}
@Override
protected EditorColorsScheme getFontCacheScheme() {
return this;
}
@NonNls
public String toString() {
return getName();
}
@Override
public void readExternal(@NotNull Element parentNode) {
UISettings settings = UISettings.getInstanceOrNull();
ColorBlindness blindness = settings == null ? null : settings.getColorBlindness();
myValueReader.setAttribute(blindness == null ? null : blindness.name());
if (SCHEME_ELEMENT.equals(parentNode.getName())) {
readScheme(parentNode);
}
else {
List<Element> children = parentNode.getChildren(SCHEME_ELEMENT);
if (children.isEmpty()) {
throw new InvalidDataException("Scheme is not valid");
}
for (Element element : children) {
readScheme(element);
}
}
initFonts();
myVersion = CURR_VERSION;
}
private void readScheme(Element node) {
myDeprecatedBackgroundColor = null;
if (!SCHEME_ELEMENT.equals(node.getName())) {
return;
}
setName(node.getAttributeValue(NAME_ATTR));
int readVersion = Integer.parseInt(node.getAttributeValue(VERSION_ATTR, "0"));
if (readVersion > CURR_VERSION) {
throw new IllegalStateException("Unsupported color scheme version: " + readVersion);
}
myVersion = readVersion;
String isDefaultScheme = node.getAttributeValue(DEFAULT_SCHEME_ATTR);
boolean isDefault = isDefaultScheme != null && Boolean.parseBoolean(isDefaultScheme);
if (!isDefault) {
myParentScheme = getDefaultScheme(node.getAttributeValue(PARENT_SCHEME_ATTR, EmptyColorScheme.NAME));
}
myMetaInfo.clear();
Ref<Float> fontScale = Ref.create();
boolean clearEditorFonts = true;
boolean clearConsoleFonts = true;
for (Element childNode : node.getChildren()) {
String childName = childNode.getName();
switch (childName) {
case OPTION_ELEMENT:
readSettings(childNode, isDefault, fontScale);
break;
case EDITOR_FONT:
readFontSettings(ensureEditableFontPreferences(), childNode, isDefault, fontScale.get(), clearEditorFonts);
clearEditorFonts = false;
break;
case CONSOLE_FONT:
readFontSettings(ensureEditableConsoleFontPreferences(), childNode, isDefault, fontScale.get(), clearConsoleFonts);
clearConsoleFonts = false;
break;
case COLORS_ELEMENT:
readColors(childNode);
break;
case ATTRIBUTES_ELEMENT:
readAttributes(childNode);
break;
case META_INFO_ELEMENT:
readMetaInfo(childNode);
break;
}
}
if (myDeprecatedBackgroundColor != null) {
TextAttributes textAttributes = myAttributesMap.get(HighlighterColors.TEXT.getExternalName());
if (textAttributes == null) {
textAttributes = new TextAttributes(Color.black, myDeprecatedBackgroundColor, null, EffectType.BOXED, Font.PLAIN);
myAttributesMap.put(HighlighterColors.TEXT.getExternalName(), textAttributes);
}
else {
textAttributes.setBackgroundColor(myDeprecatedBackgroundColor);
}
}
if (myConsoleFontPreferences.getEffectiveFontFamilies().isEmpty()) {
myFontPreferences.copyTo(myConsoleFontPreferences);
}
initFonts();
}
@NotNull
private static EditorColorsScheme getDefaultScheme(@NotNull String name) {
DefaultColorSchemesManager manager = DefaultColorSchemesManager.getInstance();
EditorColorsScheme defaultScheme = manager.getScheme(name);
if (defaultScheme == null) {
defaultScheme = new TemporaryParent(name);
}
return defaultScheme;
}
private void readMetaInfo(@NotNull Element metaInfoElement) {
myMetaInfo.clear();
for (Element e: metaInfoElement.getChildren()) {
if (PROPERTY_ELEMENT.equals(e.getName())) {
String propertyName = e.getAttributeValue(PROPERTY_NAME_ATTR);
if (propertyName != null) {
myMetaInfo.setProperty(propertyName, e.getText());
}
}
}
}
public void readAttributes(@NotNull Element childNode) {
for (Element e : childNode.getChildren(OPTION_ELEMENT)) {
String keyName = e.getAttributeValue(NAME_ATTR);
Element valueElement = e.getChild(VALUE_ELEMENT);
TextAttributes attr = valueElement != null ? myValueReader.read(TextAttributes.class, valueElement) :
e.getAttributeValue(BASE_ATTRIBUTES_ATTR) != null ? INHERITED_ATTRS_MARKER :
null;
if (attr != null) {
myAttributesMap.put(keyName, attr);
}
}
}
public void readColors(@NotNull Element childNode) {
for (Element colorElement : childNode.getChildren(OPTION_ELEMENT)) {
String keyName = colorElement.getAttributeValue(NAME_ATTR);
Color valueColor = myValueReader.read(Color.class, colorElement);
if (valueColor == null && colorElement.getAttributeValue(BASE_ATTRIBUTES_ATTR) != null) {
valueColor = INHERITED_COLOR_MARKER;
}
if (BACKGROUND_COLOR_NAME.equals(keyName)) {
// This setting has been deprecated to usages of HighlighterColors.TEXT attributes.
myDeprecatedBackgroundColor = valueColor;
}
ColorKey name = ColorKey.find(keyName);
myColorsMap.put(name, ObjectUtils.notNull(valueColor, NULL_COLOR_MARKER));
}
}
private void readSettings(@NotNull Element childNode, boolean isDefault, @NotNull Ref<Float> fontScale) {
switch (childNode.getAttributeValue(NAME_ATTR)) {
case FONT_SCALE: {
fontScale.set(myValueReader.read(Float.class, childNode));
break;
}
case LINE_SPACING: {
Float value = myValueReader.read(Float.class, childNode);
if (value != null) setLineSpacing(value);
break;
}
case EDITOR_FONT_SIZE: {
int value = readFontSize(childNode, isDefault, fontScale.get());
if (value > 0) setEditorFontSize(value);
break;
}
case EDITOR_FONT_NAME: {
String value = myValueReader.read(String.class, childNode);
if (value != null) setEditorFontName(value);
break;
}
case CONSOLE_LINE_SPACING: {
Float value = myValueReader.read(Float.class, childNode);
if (value != null) setConsoleLineSpacing(value);
break;
}
case CONSOLE_FONT_SIZE: {
int value = readFontSize(childNode, isDefault, fontScale.get());
if (value > 0) setConsoleFontSize(value);
break;
}
case CONSOLE_FONT_NAME: {
String value = myValueReader.read(String.class, childNode);
if (value != null) setConsoleFontName(value);
break;
}
case EDITOR_LIGATURES: {
Boolean value = myValueReader.read(Boolean.class, childNode);
if (value != null) ensureEditableFontPreferences().setUseLigatures(value);
break;
}
case CONSOLE_LIGATURES: {
Boolean value = myValueReader.read(Boolean.class, childNode);
if (value != null) {
ensureEditableConsoleFontPreferences().setUseLigatures(value);
}
break;
}
}
}
private int readFontSize(Element element, boolean isDefault, Float fontScale) {
if (isDefault) {
return UISettings.getDefFontSize();
}
Integer intSize = myValueReader.read(Integer.class, element);
if (intSize == null) {
return -1;
}
return UISettings.restoreFontSize(intSize, fontScale);
}
private void readFontSettings(@NotNull ModifiableFontPreferences preferences,
@NotNull Element element,
boolean isDefaultScheme,
@Nullable Float fontScale,
boolean clearFonts) {
if (clearFonts) preferences.clearFonts();
List children = element.getChildren(OPTION_ELEMENT);
String fontFamily = null;
int size = -1;
for (Object child : children) {
Element e = (Element)child;
if (EDITOR_FONT_NAME.equals(e.getAttributeValue(NAME_ATTR))) {
fontFamily = myValueReader.read(String.class, e);
}
else if (EDITOR_FONT_SIZE.equals(e.getAttributeValue(NAME_ATTR))) {
size = readFontSize(e, isDefaultScheme, fontScale);
}
}
if (fontFamily != null && size > 1) {
preferences.register(fontFamily, size);
}
else if (fontFamily != null) {
preferences.addFontFamily(fontFamily);
}
}
public void writeExternal(Element parentNode) {
parentNode.setAttribute(NAME_ATTR, getName());
parentNode.setAttribute(VERSION_ATTR, Integer.toString(myVersion));
/*
* FONT_SCALE is used to correctly identify the font size in both the JRE-managed HiDPI mode and
* the IDE-managed HiDPI mode: {@link UIUtil#isJreHiDPIEnabled()}. Also, it helps to distinguish
* the "hidpi-aware" scheme version from the previous one. Namely, the absence of the FONT_SCALE
* attribute in the scheme indicates the previous "hidpi-unaware" scheme and the restored font size
* is reset to default. It's assumed this (transition case) happens only once, after which the IDE
* will be able to restore the font size according to its scale and the IDE HiDPI mode. The default
* FONT_SCALE value should also be written by that reason.
*/
if (!(myFontPreferences instanceof DelegatingFontPreferences) || !(myConsoleFontPreferences instanceof DelegatingFontPreferences)) {
JdomKt.addOptionTag(parentNode, FONT_SCALE, String.valueOf(UISettings.getDefFontScale())); // must precede font options
}
if (myParentScheme != null && myParentScheme != EmptyColorScheme.INSTANCE) {
parentNode.setAttribute(PARENT_SCHEME_ATTR, myParentScheme.getName());
}
if (!myMetaInfo.isEmpty()) {
parentNode.addContent(metaInfoToElement());
}
// IJ has used a 'single customizable font' mode for ages. That's why we want to support that format now, when it's possible
// to specify fonts sequence (see getFontPreferences()), there are big chances that many clients still will use a single font.
// That's why we want to use old format when zero or one font is selected and 'extended' format otherwise.
boolean useOldFontFormat = myFontPreferences.getEffectiveFontFamilies().size() <= 1;
if (!(myFontPreferences instanceof DelegatingFontPreferences)) {
JdomKt.addOptionTag(parentNode, LINE_SPACING, String.valueOf(getLineSpacing()));
if (useOldFontFormat) {
JdomKt.addOptionTag(parentNode, EDITOR_FONT_SIZE, String.valueOf(getEditorFontSize()));
JdomKt.addOptionTag(parentNode, EDITOR_FONT_NAME, myFontPreferences.getFontFamily());
}
else {
writeFontPreferences(EDITOR_FONT, parentNode, myFontPreferences);
}
writeLigaturesPreferences(parentNode, myFontPreferences, EDITOR_LIGATURES);
}
if (!(myConsoleFontPreferences instanceof DelegatingFontPreferences)) {
if (myConsoleFontPreferences.getEffectiveFontFamilies().size() <= 1) {
JdomKt.addOptionTag(parentNode, CONSOLE_FONT_NAME, getConsoleFontName());
if (getConsoleFontSize() != getEditorFontSize()) {
JdomKt.addOptionTag(parentNode, CONSOLE_FONT_SIZE, Integer.toString(getConsoleFontSize()));
}
}
else {
writeFontPreferences(CONSOLE_FONT, parentNode, myConsoleFontPreferences);
}
writeLigaturesPreferences(parentNode, myConsoleFontPreferences, CONSOLE_LIGATURES);
if ((myFontPreferences instanceof DelegatingFontPreferences) || getConsoleLineSpacing() != getLineSpacing()) {
JdomKt.addOptionTag(parentNode, CONSOLE_LINE_SPACING, Float.toString(getConsoleLineSpacing()));
}
}
Element colorElements = new Element(COLORS_ELEMENT);
Element attrElements = new Element(ATTRIBUTES_ELEMENT);
writeColors(colorElements);
writeAttributes(attrElements);
if (!colorElements.getChildren().isEmpty()) {
parentNode.addContent(colorElements);
}
if (!attrElements.getChildren().isEmpty()) {
parentNode.addContent(attrElements);
}
myIsSaveNeeded = false;
}
private static void writeLigaturesPreferences(Element parentNode, FontPreferences preferences, String optionName) {
if (preferences.useLigatures()) {
JdomKt.addOptionTag(parentNode, optionName, String.valueOf(true));
}
}
private static void writeFontPreferences(@NotNull String key, @NotNull Element parent, @NotNull FontPreferences preferences) {
for (String fontFamily : preferences.getRealFontFamilies()) {
Element element = new Element(key);
JdomKt.addOptionTag(element, EDITOR_FONT_NAME, fontFamily);
JdomKt.addOptionTag(element, EDITOR_FONT_SIZE, String.valueOf(preferences.getSize(fontFamily)));
parent.addContent(element);
}
}
private void writeAttributes(@NotNull Element attrElements) {
List<Map.Entry<String, TextAttributes>> list = new ArrayList<>(myAttributesMap.entrySet());
list.sort(Map.Entry.comparingByKey());
for (Map.Entry<String, TextAttributes> entry : list) {
String keyName = entry.getKey();
TextAttributes attributes = entry.getValue();
writeAttribute(attrElements, TextAttributesKey.find(keyName), attributes);
}
}
private void writeAttribute(@NotNull Element attrElements,
@NotNull TextAttributesKey key,
@NotNull TextAttributes attributes) {
if (attributes == INHERITED_ATTRS_MARKER) {
TextAttributesKey baseKey = key.getFallbackAttributeKey();
// IDEA-162774 do not store if inheritance = on in the parent scheme
TextAttributes parentAttributes = myParentScheme instanceof AbstractColorsScheme ?
((AbstractColorsScheme)myParentScheme).getDirectlyDefinedAttributes(key) : null;
boolean parentOverwritingInheritance = parentAttributes != null && parentAttributes != INHERITED_ATTRS_MARKER;
if (parentOverwritingInheritance) {
attrElements.addContent(new Element(OPTION_ELEMENT)
.setAttribute(NAME_ATTR, key.getExternalName())
.setAttribute(BASE_ATTRIBUTES_ATTR, baseKey != null ? baseKey.getExternalName() : ""));
}
return;
}
if (myParentScheme != null) {
// fallback attributes must be not used, otherwise derived scheme as copy will not have such key
TextAttributes parentAttributes = myParentScheme instanceof AbstractColorsScheme
? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedAttributes(key)
: myParentScheme.getAttributes(key);
if (attributes.equals(parentAttributes)) {
return;
}
}
Element valueElement = new Element(VALUE_ELEMENT);
attributes.writeExternal(valueElement);
attrElements.addContent(new Element(OPTION_ELEMENT).setAttribute(NAME_ATTR, key.getExternalName()).addContent(valueElement));
}
public void optimizeAttributeMap() {
EditorColorsScheme parentScheme = myParentScheme;
if (parentScheme == null) {
return;
}
myAttributesMap.entrySet().removeIf(entry -> {
String keyName = entry.getKey();
TextAttributes attrs = entry.getValue();
TextAttributesKey key = TextAttributesKey.find(keyName);
if (attrs == INHERITED_ATTRS_MARKER) {
return !hasExplicitlyDefinedAttributes(parentScheme, key);
}
TextAttributes parent = parentScheme instanceof DefaultColorsScheme ?
((DefaultColorsScheme)parentScheme).getAttributes(key, false) : parentScheme.getAttributes(key);
return Comparing.equal(parent, attrs);
});
myColorsMap.keySet().removeAll(JBIterable.from(myColorsMap.keySet()).filter(
key -> {
Color color = myColorsMap.get(key);
if (color == INHERITED_COLOR_MARKER) {
return !hasExplicitlyDefinedColors(parentScheme, key);
}
Color parent = parentScheme instanceof DefaultColorsScheme ?
((DefaultColorsScheme)parentScheme).getColor(key, false) : parentScheme.getColor(key);
return Comparing.equal(parent, color == NULL_COLOR_MARKER ? null : color);
}
).toList());
}
private static boolean hasExplicitlyDefinedAttributes(@NotNull EditorColorsScheme scheme, @NotNull TextAttributesKey key) {
TextAttributes directAttrs =
scheme instanceof DefaultColorsScheme ? ((DefaultColorsScheme)scheme).getDirectlyDefinedAttributes(key) : null;
return directAttrs != null && directAttrs != INHERITED_ATTRS_MARKER;
}
private static boolean hasExplicitlyDefinedColors(@NotNull EditorColorsScheme scheme, @NotNull ColorKey key) {
Color directColor =
scheme instanceof DefaultColorsScheme ? ((DefaultColorsScheme)scheme).getDirectlyDefinedColor(key) : null;
return directColor != null && directColor != INHERITED_COLOR_MARKER;
}
@NotNull
private Element metaInfoToElement() {
Element metaInfoElement = new Element(META_INFO_ELEMENT);
myMetaInfo.setProperty(META_INFO_MODIFIED_TIME, META_INFO_DATE_FORMAT.format(new Date()));
List<String> sortedPropertyNames = new ArrayList<>(myMetaInfo.stringPropertyNames());
sortedPropertyNames.sort(null);
for (String propertyName : sortedPropertyNames) {
String value = myMetaInfo.getProperty(propertyName);
Element propertyInfo = new Element(PROPERTY_ELEMENT);
propertyInfo.setAttribute(PROPERTY_NAME_ATTR, propertyName);
propertyInfo.setText(value);
metaInfoElement.addContent(propertyInfo);
}
return metaInfoElement;
}
private void writeColors(Element colorElements) {
List<ColorKey> list = new ArrayList<>(myColorsMap.keySet());
list.sort(null);
for (ColorKey key : list) {
writeColor(colorElements, key);
}
}
private void writeColor(@NotNull Element colorElements, @NotNull ColorKey key) {
Color color = myColorsMap.get(key);
if (color == INHERITED_COLOR_MARKER) {
ColorKey fallbackKey = key.getFallbackColorKey();
Color parentFallback = myParentScheme instanceof AbstractColorsScheme ?
((AbstractColorsScheme)myParentScheme).getDirectlyDefinedColor(key) : null;
boolean parentOverwritingInheritance = parentFallback != null && parentFallback != INHERITED_COLOR_MARKER;
if (fallbackKey != null && parentOverwritingInheritance) {
colorElements.addContent(new Element(OPTION_ELEMENT)
.setAttribute(NAME_ATTR, key.getExternalName())
.setAttribute(BASE_ATTRIBUTES_ATTR, fallbackKey.getExternalName()));
}
return;
}
if (myParentScheme != null) {
Color parent = myParentScheme instanceof AbstractColorsScheme
? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedColor(key)
: myParentScheme.getColor(key);
if (parent != null && colorsEqual(color, parent)) {
return;
}
}
String rgb = "";
if (color != NULL_COLOR_MARKER) {
rgb = Integer.toString(0xFFFFFF & color.getRGB(), 16);
int alpha = 0xFF & color.getAlpha();
if (alpha != 0xFF) rgb += Integer.toString(alpha, 16);
}
JdomKt.addOptionTag(colorElements, key.getExternalName(), rgb);
}
protected static boolean colorsEqual(@Nullable Color c1, @Nullable Color c2) {
if (c1 == NULL_COLOR_MARKER) return c1 == c2;
return Comparing.equal(c1, c2 == NULL_COLOR_MARKER ? null : c2);
}
private ModifiableFontPreferences ensureEditableFontPreferences() {
if (!(myFontPreferences instanceof ModifiableFontPreferences)) {
ModifiableFontPreferences editablePrefs = new FontPreferencesImpl();
myFontPreferences.copyTo(editablePrefs);
myFontPreferences = editablePrefs;
((FontPreferencesImpl)myFontPreferences).setChangeListener(() -> initFonts());
}
return (ModifiableFontPreferences)myFontPreferences;
}
@NotNull
@Override
public FontPreferences getConsoleFontPreferences() {
return myConsoleFontPreferences;
}
@Override
public void setUseEditorFontPreferencesInConsole() {
myConsoleFontPreferences = new DelegatingFontPreferences(() -> myFontPreferences);
initFonts();
}
@Override
public boolean isUseEditorFontPreferencesInConsole() {
return myConsoleFontPreferences instanceof DelegatingFontPreferences;
}
@Override
public void setConsoleFontPreferences(@NotNull FontPreferences preferences) {
preferences.copyTo(ensureEditableConsoleFontPreferences());
initFonts();
}
@Override
@NotNull
@NlsSafe
public String getConsoleFontName() {
return myConsoleFontPreferences.getFontFamily();
}
private ModifiableFontPreferences ensureEditableConsoleFontPreferences() {
if (!(myConsoleFontPreferences instanceof ModifiableFontPreferences)) {
ModifiableFontPreferences editablePrefs = new FontPreferencesImpl();
myConsoleFontPreferences.copyTo(editablePrefs);
myConsoleFontPreferences = editablePrefs;
}
return (ModifiableFontPreferences)myConsoleFontPreferences;
}
@Override
public void setConsoleFontName(String fontName) {
ModifiableFontPreferences consolePreferences = ensureEditableConsoleFontPreferences();
int consoleFontSize = getConsoleFontSize();
consolePreferences.clear();
consolePreferences.register(fontName, consoleFontSize);
}
@Override
public int getConsoleFontSize() {
String font = getConsoleFontName();
UISettings uiSettings = UISettings.getInstanceOrNull();
if ((uiSettings == null || !uiSettings.getPresentationMode()) && myConsoleFontPreferences.hasSize(font)) {
return myConsoleFontPreferences.getSize(font);
}
return getEditorFontSize();
}
@Override
public void setConsoleFontSize(int fontSize) {
ModifiableFontPreferences consoleFontPreferences = ensureEditableConsoleFontPreferences();
fontSize = EditorFontsConstants.checkAndFixEditorFontSize(fontSize);
consoleFontPreferences.register(getConsoleFontName(), fontSize);
initFonts();
}
@Override
public float getConsoleLineSpacing() {
return myConsoleFontPreferences.getLineSpacing();
}
@Override
public void setConsoleLineSpacing(float lineSpacing) {
ensureEditableConsoleFontPreferences().setLineSpacing(lineSpacing);
}
@Nullable
protected TextAttributes getFallbackAttributes(@NotNull TextAttributesKey fallbackKey) {
TextAttributesKey cur = fallbackKey;
while (true) {
TextAttributes attrs = getDirectlyDefinedAttributes(cur);
TextAttributesKey next = cur.getFallbackAttributeKey();
if (attrs != null && (attrs != INHERITED_ATTRS_MARKER || next == null)) {
return attrs;
}
if (next == null) return null;
cur = next;
}
}
@Nullable
protected Color getFallbackColor(@NotNull ColorKey fallbackKey) {
ColorKey cur = fallbackKey;
while (true) {
Color color = getDirectlyDefinedColor(cur);
if (color == NULL_COLOR_MARKER) return null;
ColorKey next = cur.getFallbackColorKey();
if (color != null && (color != INHERITED_COLOR_MARKER || next == null)) {
return color;
}
if (next == null) return null;
cur = next;
}
}
/**
* Looks for explicitly specified attributes either in the scheme or its parent scheme. No fallback keys are used.
*
* @param key The key to use for search.
* @return Explicitly defined attribute or {@code null} if not found.
*/
@Nullable
public TextAttributes getDirectlyDefinedAttributes(@NotNull TextAttributesKey key) {
TextAttributes attributes = myAttributesMap.get(key.getExternalName());
return attributes != null ? attributes :
myParentScheme instanceof AbstractColorsScheme ? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedAttributes(key) :
null;
}
/**
* Looks for explicitly specified color either in the scheme or its parent scheme. No fallback keys are used.
*
* @param key The key to use for search.
* @return Explicitly defined color or {@code null} if not found.
*/
@Nullable
public Color getDirectlyDefinedColor(@NotNull ColorKey key) {
Color color = myColorsMap.get(key);
return color != null ? color :
myParentScheme instanceof AbstractColorsScheme ? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedColor(key) :
null;
}
@NotNull
@Override
public SchemeState getSchemeState() {
return myIsSaveNeeded ? SchemeState.POSSIBLY_CHANGED : SchemeState.UNCHANGED;
}
public void setSaveNeeded(boolean value) {
myIsSaveNeeded = value;
}
public boolean isReadOnly() { return false; }
@NotNull
@Override
public Properties getMetaProperties() {
return myMetaInfo;
}
public boolean canBeDeleted() {
return myCanBeDeleted;
}
public void setCanBeDeleted(boolean canBeDeleted) {
myCanBeDeleted = canBeDeleted;
}
public boolean isVisible() {
return true;
}
public static boolean isVisible(@NotNull EditorColorsScheme scheme) {
return !(scheme instanceof AbstractColorsScheme) || ((AbstractColorsScheme)scheme).isVisible();
}
@Nullable
public AbstractColorsScheme getOriginal() {
String originalSchemeName = getMetaProperties().getProperty(META_INFO_ORIGINAL);
if (originalSchemeName != null) {
EditorColorsScheme originalScheme = EditorColorsManager.getInstance().getScheme(originalSchemeName);
if (originalScheme instanceof AbstractColorsScheme && originalScheme != this) return (AbstractColorsScheme)originalScheme;
}
return null;
}
public EditorColorsScheme getParentScheme() {
return myParentScheme;
}
@NotNull
@Override
public Element writeScheme() {
Element root = new Element("scheme");
writeExternal(root);
return root;
}
public boolean settingsEqual(Object other) {
return settingsEqual(other, null);
}
public boolean settingsEqual(Object other, @Nullable Predicate<? super ColorKey> colorKeyFilter) {
if (!(other instanceof AbstractColorsScheme)) return false;
AbstractColorsScheme otherScheme = (AbstractColorsScheme)other;
// parent is used only for default schemes (e.g. Darcula bundled in all ide (opposite to IDE-specific, like Cobalt))
if (getBaseDefaultScheme(this) != getBaseDefaultScheme(otherScheme)) {
return false;
}
for (String propertyName : myMetaInfo.stringPropertyNames()) {
if (propertyName.equals(META_INFO_CREATION_TIME) ||
propertyName.equals(META_INFO_MODIFIED_TIME) ||
propertyName.equals(META_INFO_IDE) ||
propertyName.equals(META_INFO_IDE_VERSION) ||
propertyName.equals(META_INFO_ORIGINAL)
) {
continue;
}
if (!Objects.equals(myMetaInfo.getProperty(propertyName), otherScheme.myMetaInfo.getProperty(propertyName))) {
return false;
}
}
return areDelegatingOrEqual(myFontPreferences, otherScheme.getFontPreferences()) &&
areDelegatingOrEqual(myConsoleFontPreferences, otherScheme.getConsoleFontPreferences()) &&
attributesEqual(otherScheme) &&
colorsEqual(otherScheme, colorKeyFilter);
}
protected static boolean areDelegatingOrEqual(@NotNull FontPreferences preferences1, @NotNull FontPreferences preferences2) {
boolean isDelegating1 = preferences1 instanceof DelegatingFontPreferences;
boolean isDelegating2 = preferences2 instanceof DelegatingFontPreferences;
return isDelegating1 || isDelegating2 ? isDelegating1 && isDelegating2 : preferences1.equals(preferences2);
}
protected boolean attributesEqual(AbstractColorsScheme otherScheme) {
return myAttributesMap.equals(otherScheme.myAttributesMap);
}
protected boolean colorsEqual(AbstractColorsScheme otherScheme, @Nullable Predicate<? super ColorKey> colorKeyFilter) {
if (myColorsMap.size() != otherScheme.myColorsMap.size()) return false;
for (Map.Entry<ColorKey, Color> entry : myColorsMap.entrySet()) {
Color c1 = entry.getValue();
ColorKey key = entry.getKey();
Color c2 = otherScheme.myColorsMap.get(key);
if (!colorsEqual(c1, c2)) return false;
}
return true;
}
@Nullable
private static EditorColorsScheme getBaseDefaultScheme(@NotNull EditorColorsScheme scheme) {
if (!(scheme instanceof AbstractColorsScheme)) {
return null;
}
if (scheme instanceof DefaultColorsScheme) {
return scheme;
}
EditorColorsScheme parent = ((AbstractColorsScheme)scheme).myParentScheme;
return parent != null ? getBaseDefaultScheme(parent) : null;
}
private static class TemporaryParent extends EditorColorsSchemeImpl {
private final String myParentName;
TemporaryParent(@NotNull String parentName) {
super(EmptyColorScheme.INSTANCE);
myParentName = parentName;
}
@NonNls
public String getParentName() {
return myParentName;
}
}
public void setParent(@NotNull EditorColorsScheme newParent) {
assert newParent instanceof ReadOnlyColorsScheme : "New parent scheme must be read-only";
myParentScheme = newParent;
}
void resolveParent(@NotNull Function<? super String, ? extends EditorColorsScheme> nameResolver) {
if (myParentScheme instanceof TemporaryParent) {
String parentName = ((TemporaryParent)myParentScheme).getParentName();
EditorColorsScheme newParent = nameResolver.apply(parentName);
if (!(newParent instanceof ReadOnlyColorsScheme)) {
throw new InvalidDataException(parentName);
}
myParentScheme = newParent;
}
}
}
| apache-2.0 |
codeaudit/OG-Platform | projects/OG-Component/src/main/java/com/opengamma/component/factory/provider/RemoteProvidersComponentFactory.java | 11201 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.component.factory.provider;
import java.lang.reflect.Constructor;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.component.ComponentInfo;
import com.opengamma.component.ComponentRepository;
import com.opengamma.component.ComponentServer;
import com.opengamma.component.factory.AbstractComponentFactory;
import com.opengamma.component.factory.ComponentInfoAttributes;
import com.opengamma.component.rest.RemoteComponentServer;
import com.opengamma.provider.permission.PermissionCheckProvider;
import com.opengamma.provider.permission.impl.ProviderBasedPermissionResolver;
import com.opengamma.util.ReflectionUtils;
import com.opengamma.util.auth.AuthUtils;
/**
* Component factory for accessing remote providers from the local machine.
*/
@BeanDefinition
public class RemoteProvidersComponentFactory extends AbstractComponentFactory {
/**
* The remote URI.
*/
@PropertyDefinition(validate = "notNull")
private URI _baseUri;
/**
* The flag determining whether the component should be published by REST (default true).
*/
@PropertyDefinition
private boolean _publishRest = true;
//-------------------------------------------------------------------------
@Override
public void init(ComponentRepository repo, LinkedHashMap<String, String> configuration) {
RemoteComponentServer remote = new RemoteComponentServer(_baseUri);
ComponentServer server = remote.getComponentServer();
for (ComponentInfo info : server.getComponentInfos()) {
initComponent(repo, info);
}
}
/**
* Initialize the remote component.
*
* @param repo the local repository, not null
* @param info the remote information, not null
*/
protected void initComponent(ComponentRepository repo, ComponentInfo info) {
URI componentUri = info.getUri();
if (info.getAttributes().containsKey(ComponentInfoAttributes.REMOTE_CLIENT_JAVA) &&
info.getAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA).endsWith("Provider")) {
String remoteTypeStr = info.getAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA);
Class<?> remoteType = ReflectionUtils.loadClass(remoteTypeStr);
Constructor<?> con = ReflectionUtils.findConstructor(remoteType, URI.class);
Object target = ReflectionUtils.newInstance(con, componentUri);
repo.registerComponent(info, target);
if (isPublishRest()) {
repo.getRestComponents().republish(info);
}
if (info.getType() == PermissionCheckProvider.class) {
connectPermissionCheckProvider(repo, info, (PermissionCheckProvider) target);
}
}
}
/**
* Connect the permission check provider to the local authorization system.
*
* @param repo the local repository, not null
* @param info the remote information, not null
* @param provider the remote provider, not null
*/
protected void connectPermissionCheckProvider(ComponentRepository repo, ComponentInfo info, PermissionCheckProvider provider) {
if (AuthUtils.isPermissive() == false && info.getAttributes().containsKey(ComponentInfoAttributes.ACCEPTED_TYPES)) {
String[] permissionPrefixes = StringUtils.split(info.getAttribute(ComponentInfoAttributes.ACCEPTED_TYPES), ',');
for (String permissionPrefix : permissionPrefixes) {
AuthUtils.getPermissionResolver().register(
new ProviderBasedPermissionResolver(permissionPrefix, provider));
}
}
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code RemoteProvidersComponentFactory}.
* @return the meta-bean, not null
*/
public static RemoteProvidersComponentFactory.Meta meta() {
return RemoteProvidersComponentFactory.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(RemoteProvidersComponentFactory.Meta.INSTANCE);
}
@Override
public RemoteProvidersComponentFactory.Meta metaBean() {
return RemoteProvidersComponentFactory.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the remote URI.
* @return the value of the property, not null
*/
public URI getBaseUri() {
return _baseUri;
}
/**
* Sets the remote URI.
* @param baseUri the new value of the property, not null
*/
public void setBaseUri(URI baseUri) {
JodaBeanUtils.notNull(baseUri, "baseUri");
this._baseUri = baseUri;
}
/**
* Gets the the {@code baseUri} property.
* @return the property, not null
*/
public final Property<URI> baseUri() {
return metaBean().baseUri().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the flag determining whether the component should be published by REST (default true).
* @return the value of the property
*/
public boolean isPublishRest() {
return _publishRest;
}
/**
* Sets the flag determining whether the component should be published by REST (default true).
* @param publishRest the new value of the property
*/
public void setPublishRest(boolean publishRest) {
this._publishRest = publishRest;
}
/**
* Gets the the {@code publishRest} property.
* @return the property, not null
*/
public final Property<Boolean> publishRest() {
return metaBean().publishRest().createProperty(this);
}
//-----------------------------------------------------------------------
@Override
public RemoteProvidersComponentFactory clone() {
return JodaBeanUtils.cloneAlways(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
RemoteProvidersComponentFactory other = (RemoteProvidersComponentFactory) obj;
return JodaBeanUtils.equal(getBaseUri(), other.getBaseUri()) &&
(isPublishRest() == other.isPublishRest()) &&
super.equals(obj);
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = hash * 31 + JodaBeanUtils.hashCode(getBaseUri());
hash = hash * 31 + JodaBeanUtils.hashCode(isPublishRest());
return hash ^ super.hashCode();
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(96);
buf.append("RemoteProvidersComponentFactory{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
@Override
protected void toString(StringBuilder buf) {
super.toString(buf);
buf.append("baseUri").append('=').append(JodaBeanUtils.toString(getBaseUri())).append(',').append(' ');
buf.append("publishRest").append('=').append(JodaBeanUtils.toString(isPublishRest())).append(',').append(' ');
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code RemoteProvidersComponentFactory}.
*/
public static class Meta extends AbstractComponentFactory.Meta {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code baseUri} property.
*/
private final MetaProperty<URI> _baseUri = DirectMetaProperty.ofReadWrite(
this, "baseUri", RemoteProvidersComponentFactory.class, URI.class);
/**
* The meta-property for the {@code publishRest} property.
*/
private final MetaProperty<Boolean> _publishRest = DirectMetaProperty.ofReadWrite(
this, "publishRest", RemoteProvidersComponentFactory.class, Boolean.TYPE);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, (DirectMetaPropertyMap) super.metaPropertyMap(),
"baseUri",
"publishRest");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -332625701: // baseUri
return _baseUri;
case -614707837: // publishRest
return _publishRest;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends RemoteProvidersComponentFactory> builder() {
return new DirectBeanBuilder<RemoteProvidersComponentFactory>(new RemoteProvidersComponentFactory());
}
@Override
public Class<? extends RemoteProvidersComponentFactory> beanType() {
return RemoteProvidersComponentFactory.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code baseUri} property.
* @return the meta-property, not null
*/
public final MetaProperty<URI> baseUri() {
return _baseUri;
}
/**
* The meta-property for the {@code publishRest} property.
* @return the meta-property, not null
*/
public final MetaProperty<Boolean> publishRest() {
return _publishRest;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -332625701: // baseUri
return ((RemoteProvidersComponentFactory) bean).getBaseUri();
case -614707837: // publishRest
return ((RemoteProvidersComponentFactory) bean).isPublishRest();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case -332625701: // baseUri
((RemoteProvidersComponentFactory) bean).setBaseUri((URI) newValue);
return;
case -614707837: // publishRest
((RemoteProvidersComponentFactory) bean).setPublishRest((Boolean) newValue);
return;
}
super.propertySet(bean, propertyName, newValue, quiet);
}
@Override
protected void validate(Bean bean) {
JodaBeanUtils.notNull(((RemoteProvidersComponentFactory) bean)._baseUri, "baseUri");
super.validate(bean);
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| apache-2.0 |
wangcy6/storm_app | frame/apache-flume-1.7.0-src/flume-ng-core/src/main/java/org/apache/flume/serialization/Seekable.java | 988 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.serialization;
import java.io.IOException;
public interface Seekable {
void seek(long position) throws IOException;
long tell() throws IOException;
}
| apache-2.0 |
jerrinot/hazelcast | hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/connector/keyvalue/KvMetadataJsonResolver.java | 3642 | /*
* Copyright 2021 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.sql.impl.connector.keyvalue;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.jet.sql.impl.extract.JsonQueryTargetDescriptor;
import com.hazelcast.jet.sql.impl.inject.JsonUpsertTargetDescriptor;
import com.hazelcast.sql.impl.schema.MappingField;
import com.hazelcast.sql.impl.QueryException;
import com.hazelcast.sql.impl.extract.QueryPath;
import com.hazelcast.sql.impl.schema.TableField;
import com.hazelcast.sql.impl.schema.map.MapTableField;
import com.hazelcast.sql.impl.type.QueryDataType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;
import static com.hazelcast.jet.sql.impl.connector.SqlConnector.JSON_FLAT_FORMAT;
import static com.hazelcast.jet.sql.impl.connector.keyvalue.KvMetadataResolver.extractFields;
import static com.hazelcast.jet.sql.impl.connector.keyvalue.KvMetadataResolver.maybeAddDefaultField;
public final class KvMetadataJsonResolver implements KvMetadataResolver {
public static final KvMetadataJsonResolver INSTANCE = new KvMetadataJsonResolver();
private KvMetadataJsonResolver() {
}
@Override
public Stream<String> supportedFormats() {
return Stream.of(JSON_FLAT_FORMAT);
}
@Override
public Stream<MappingField> resolveAndValidateFields(
boolean isKey,
List<MappingField> userFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
if (userFields.isEmpty()) {
throw QueryException.error("Column list is required for JSON format");
}
return extractFields(userFields, isKey).entrySet().stream()
.map(entry -> {
QueryPath path = entry.getKey();
if (path.getPath() == null) {
throw QueryException.error("Cannot use the '" + path + "' field with JSON serialization");
}
return entry.getValue();
});
}
@Override
public KvMetadata resolveMetadata(
boolean isKey,
List<MappingField> resolvedFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(resolvedFields, isKey);
List<TableField> fields = new ArrayList<>();
for (Entry<QueryPath, MappingField> entry : fieldsByPath.entrySet()) {
QueryPath path = entry.getKey();
QueryDataType type = entry.getValue().type();
String name = entry.getValue().name();
fields.add(new MapTableField(name, type, false, path));
}
maybeAddDefaultField(isKey, resolvedFields, fields, QueryDataType.OBJECT);
return new KvMetadata(
fields,
JsonQueryTargetDescriptor.INSTANCE,
JsonUpsertTargetDescriptor.INSTANCE
);
}
}
| apache-2.0 |
BeatCoding/droolsjbpm-integration | jbpm-simulation/src/main/java/org/jbpm/simulation/impl/SimulationNodeInstance.java | 3412 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.jbpm.simulation.impl;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.jbpm.simulation.ActivitySimulator;
import org.jbpm.simulation.SimulationContext;
import org.jbpm.simulation.SimulationEvent;
import org.jbpm.workflow.instance.impl.NodeInstanceImpl;
import org.kie.api.definition.process.Connection;
import org.kie.api.definition.process.Node;
import org.kie.api.runtime.process.NodeInstance;
public class SimulationNodeInstance extends NodeInstanceImpl {
private static final long serialVersionUID = -1965605499505300424L;
@Override
public void internalTrigger(NodeInstance from, String type) {
SimulationContext context = SimulationContext.getContext();
ActivitySimulator simulator = context.getRegistry().getSimulator(getNode());
SimulationEvent event = simulator.simulate(this, context);
context.getRepository().storeEvent(event);
long thisNodeCurrentTime = context.getClock().getCurrentTime();
List<Connection> outgoing = getNode().getOutgoingConnections().get(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE);
for (Connection conn : outgoing) {
if (context.getCurrentPath().getSequenceFlowsIds().contains(conn.getMetaData().get("UniqueId"))) {
// handle loops
if (context.isLoopLimitExceeded((String) conn.getMetaData().get("UniqueId"))) {
continue;
}
context.addExecutedNode((String) conn.getMetaData().get("UniqueId"));
triggerConnection(conn);
// reset clock to the value of this node
context.getClock().advanceTime((thisNodeCurrentTime - context.getClock().getCurrentTime()), TimeUnit.MILLISECONDS);
}
}
long currentNodeId = getNodeId();
// handle boundary events
for (String boundaryEvent : context.getCurrentPath().getBoundaryEventIds()) {
Node boundaryEventNode = null;
for (Node node : getNode().getNodeContainer().getNodes()) {
if (node.getMetaData().get("UniqueId").equals(boundaryEvent) &&
node.getMetaData().get("AttachedTo").equals(getNode().getMetaData().get("UniqueId"))) {
boundaryEventNode = node;
break;
}
}
if (boundaryEventNode != null) {
NodeInstance next = ((org.jbpm.workflow.instance.NodeInstanceContainer) getNodeInstanceContainer()).getNodeInstance(boundaryEventNode);
setNodeId(boundaryEventNode.getId());
this.trigger(next, org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE);
}
}
setNodeId(currentNodeId);
}
}
| apache-2.0 |
apixandru/intellij-community | platform/testFramework/src/com/intellij/testFramework/fixtures/BareTestFixtureTestCase.java | 2868 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework.fixtures;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Disposer;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.SkipInHeadlessEnvironment;
import com.intellij.testFramework.SkipSlowTestLocally;
import com.intellij.testFramework.UsefulTestCase;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import static com.intellij.testFramework.PlatformTestUtil.SKIP_HEADLESS;
import static com.intellij.testFramework.PlatformTestUtil.SKIP_SLOW;
import static org.junit.Assume.assumeFalse;
public abstract class BareTestFixtureTestCase {
public static final Logger LOG = Logger.getInstance(BareTestFixtureTestCase.class);
@Rule public final TestName myNameRule = new TestName();
private BareTestFixture myFixture;
@Before
public final void setupFixture() throws Exception {
ApplicationInfoImpl.setInStressTest(UsefulTestCase.isPerformanceTest(null, getClass().getName()));
boolean headless = SKIP_HEADLESS && getClass().getAnnotation(SkipInHeadlessEnvironment.class) != null;
assumeFalse("Class '" + getClass().getName() + "' is skipped because it requires working UI environment", headless);
boolean slow = SKIP_SLOW && getClass().getAnnotation(SkipSlowTestLocally.class) != null;
assumeFalse("Class '" + getClass().getName() + "' is skipped because it is dog slow", slow);
myFixture = IdeaTestFixtureFactory.getFixtureFactory().createBareFixture();
myFixture.setUp();
Disposer.register(getTestRootDisposable(), ()-> ApplicationInfoImpl.setInStressTest(false));
}
@After
public final void tearDownFixture() throws Exception {
if (myFixture != null) {
myFixture.tearDown();
myFixture = null;
}
}
@NotNull
protected final String getTestName(boolean lowercaseFirstLetter) {
return PlatformTestUtil.getTestName(myNameRule.getMethodName(), lowercaseFirstLetter);
}
@NotNull
public final Disposable getTestRootDisposable() {
return myFixture.getTestRootDisposable();
}
} | apache-2.0 |
pkdevbox/stratos | components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/message/processor/topology/ClusterInstanceTerminatedProcessor.java | 5892 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.stratos.messaging.message.processor.topology;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.messaging.domain.instance.ClusterInstance;
import org.apache.stratos.messaging.domain.topology.Cluster;
import org.apache.stratos.messaging.domain.topology.ClusterStatus;
import org.apache.stratos.messaging.domain.topology.Service;
import org.apache.stratos.messaging.domain.topology.Topology;
import org.apache.stratos.messaging.event.topology.ClusterInstanceTerminatedEvent;
import org.apache.stratos.messaging.message.filter.topology.TopologyApplicationFilter;
import org.apache.stratos.messaging.message.filter.topology.TopologyClusterFilter;
import org.apache.stratos.messaging.message.filter.topology.TopologyServiceFilter;
import org.apache.stratos.messaging.message.processor.MessageProcessor;
import org.apache.stratos.messaging.message.processor.topology.updater.TopologyUpdater;
import org.apache.stratos.messaging.util.MessagingUtil;
/**
* This processor will act upon the cluster activated event
*/
public class ClusterInstanceTerminatedProcessor extends MessageProcessor {
private static final Log log = LogFactory.getLog(ClusterInstanceTerminatedProcessor.class);
private MessageProcessor nextProcessor;
@Override
public void setNext(MessageProcessor nextProcessor) {
this.nextProcessor = nextProcessor;
}
@Override
public boolean process(String type, String message, Object object) {
Topology topology = (Topology) object;
if (ClusterInstanceTerminatedEvent.class.getName().equals(type)) {
// Return if topology has not been initialized
if (!topology.isInitialized()) {
return false;
}
// Parse complete message and build event
ClusterInstanceTerminatedEvent event = (ClusterInstanceTerminatedEvent) MessagingUtil.
jsonToObject(message, ClusterInstanceTerminatedEvent.class);
TopologyUpdater.acquireWriteLockForCluster(event.getServiceName(), event.getClusterId());
try {
return doProcess(event, topology);
} finally {
TopologyUpdater.releaseWriteLockForCluster(event.getServiceName(), event.getClusterId());
}
} else {
if (nextProcessor != null) {
// ask the next processor to take care of the message.
return nextProcessor.process(type, message, topology);
} else {
throw new RuntimeException(String.format("Failed to process message using available message processors: [type] %s [body] %s", type, message));
}
}
}
private boolean doProcess(ClusterInstanceTerminatedEvent event, Topology topology) {
String applicationId = event.getAppId();
String serviceName = event.getServiceName();
String clusterId = event.getClusterId();
// Apply application filter
if(TopologyApplicationFilter.apply(applicationId)) {
return false;
}
// Apply service filter
if (TopologyServiceFilter.apply(serviceName)) {
return false;
}
// Apply cluster filter
if (TopologyClusterFilter.apply(clusterId)) {
return false;
}
// Validate event against the existing topology
Service service = topology.getService(event.getServiceName());
if (service == null) {
if (log.isWarnEnabled()) {
log.warn(String.format("Service does not exist: [service] %s",
event.getServiceName()));
}
return false;
}
Cluster cluster = service.getCluster(event.getClusterId());
if (cluster == null) {
if (log.isDebugEnabled()) {
log.debug(String.format("Cluster not exists in service: [service] %s [cluster] %s", event.getServiceName(),
event.getClusterId()));
return false;
}
} else {
// Apply changes to the topology
ClusterInstance context = cluster.getInstanceContexts(event.getInstanceId());
if (context == null) {
if (log.isDebugEnabled()) {
log.warn("Cluster Instance Context is already removed for [cluster] " +
event.getClusterId() + " [instance-id] " +
event.getInstanceId());
}
} else {
ClusterStatus status = ClusterStatus.Terminated;
if (!context.isStateTransitionValid(status)) {
log.error("Invalid State Transition from " + context.getStatus() + " to " + status);
}
context.setStatus(status);
cluster.removeInstanceContext(event.getInstanceId());
}
}
// Notify event listeners
notifyEventListeners(event);
return true;
}
}
| apache-2.0 |
mikesir87/arquillian-graphene | impl/src/main/java/org/jboss/arquillian/graphene/location/ContextRootStore.java | 1319 | /**
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.arquillian.graphene.location;
import java.net.URL;
public class ContextRootStore {
private URL url;
public ContextRootStore(URL url) {
this.url = url;
}
public URL getURL() {
return url;
}
public void setURL(URL url) {
this.url = url;
}
}
| apache-2.0 |
spodkowinski/cassandra | src/java/org/apache/cassandra/db/streaming/CassandraStreamReceiver.java | 9745 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.cassandra.db.streaming;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.db.compaction.OperationType;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.partitions.PartitionUpdate;
import org.apache.cassandra.db.rows.ThrottledUnfilteredIterator;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.db.view.View;
import org.apache.cassandra.dht.Bounds;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.sstable.ISSTableScanner;
import org.apache.cassandra.io.sstable.SSTableMultiWriter;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.streaming.IncomingStream;
import org.apache.cassandra.streaming.StreamReceiver;
import org.apache.cassandra.streaming.StreamSession;
import org.apache.cassandra.utils.CloseableIterator;
import org.apache.cassandra.utils.Throwables;
import org.apache.cassandra.utils.concurrent.Refs;
public class CassandraStreamReceiver implements StreamReceiver
{
private static final Logger logger = LoggerFactory.getLogger(CassandraStreamReceiver.class);
private static final int MAX_ROWS_PER_BATCH = Integer.getInteger("cassandra.repair.mutation_repair_rows_per_batch", 100);
private final ColumnFamilyStore cfs;
private final StreamSession session;
// Transaction tracking new files received
private final LifecycleTransaction txn;
// holds references to SSTables received
protected Collection<SSTableReader> sstables;
private final boolean requiresWritePath;
public CassandraStreamReceiver(ColumnFamilyStore cfs, StreamSession session, int totalFiles)
{
this.cfs = cfs;
this.session = session;
// this is an "offline" transaction, as we currently manually expose the sstables once done;
// this should be revisited at a later date, so that LifecycleTransaction manages all sstable state changes
this.txn = LifecycleTransaction.offline(OperationType.STREAM);
this.sstables = new ArrayList<>(totalFiles);
this.requiresWritePath = requiresWritePath(cfs);
}
public LifecycleTransaction getTransaction()
{
return txn;
}
public static CassandraStreamReceiver fromReceiver(StreamReceiver receiver)
{
Preconditions.checkArgument(receiver instanceof CassandraStreamReceiver);
return (CassandraStreamReceiver) receiver;
}
private static CassandraIncomingFile getFile(IncomingStream stream)
{
Preconditions.checkArgument(stream instanceof CassandraIncomingFile, "Wrong stream type: {}", stream);
return (CassandraIncomingFile) stream;
}
@Override
@SuppressWarnings("resource")
public void received(IncomingStream stream)
{
CassandraIncomingFile file = getFile(stream);
Collection<SSTableReader> finished = null;
SSTableMultiWriter sstable = file.getSSTable();
try
{
finished = sstable.finish(true);
}
catch (Throwable t)
{
Throwables.maybeFail(sstable.abort(t));
}
txn.update(finished, false);
sstables.addAll(finished);
}
@Override
public void discardStream(IncomingStream stream)
{
CassandraIncomingFile file = getFile(stream);
Throwables.maybeFail(file.getSSTable().abort(null));
}
@Override
public void abort()
{
sstables.clear();
txn.abort();
}
private boolean hasViews(ColumnFamilyStore cfs)
{
return !Iterables.isEmpty(View.findAll(cfs.metadata.keyspace, cfs.getTableName()));
}
private boolean hasCDC(ColumnFamilyStore cfs)
{
return cfs.metadata().params.cdc;
}
/*
* We have a special path for views and for CDC.
*
* For views, since the view requires cleaning up any pre-existing state, we must put all partitions
* through the same write path as normal mutations. This also ensures any 2is are also updated.
*
* For CDC-enabled tables, we want to ensure that the mutations are run through the CommitLog so they
* can be archived by the CDC process on discard.
*/
private boolean requiresWritePath(ColumnFamilyStore cfs) {
return hasCDC(cfs) || (session.streamOperation().requiresViewBuild() && hasViews(cfs));
}
private void sendThroughWritePath(ColumnFamilyStore cfs, Collection<SSTableReader> readers) {
boolean hasCdc = hasCDC(cfs);
ColumnFilter filter = ColumnFilter.all(cfs.metadata());
for (SSTableReader reader : readers)
{
Keyspace ks = Keyspace.open(reader.getKeyspaceName());
// When doing mutation-based repair we split each partition into smaller batches
// ({@link Stream MAX_ROWS_PER_BATCH}) to avoid OOMing and generating heap pressure
try (ISSTableScanner scanner = reader.getScanner();
CloseableIterator<UnfilteredRowIterator> throttledPartitions = ThrottledUnfilteredIterator.throttle(scanner, MAX_ROWS_PER_BATCH))
{
while (throttledPartitions.hasNext())
{
// MV *can* be applied unsafe if there's no CDC on the CFS as we flush
// before transaction is done.
//
// If the CFS has CDC, however, these updates need to be written to the CommitLog
// so they get archived into the cdc_raw folder
ks.apply(new Mutation(PartitionUpdate.fromIterator(throttledPartitions.next(), filter)),
hasCdc,
true,
false);
}
}
}
}
private synchronized void finishTransaction()
{
txn.finish();
}
@Override
public void finished()
{
boolean requiresWritePath = requiresWritePath(cfs);
Collection<SSTableReader> readers = sstables;
try (Refs<SSTableReader> refs = Refs.ref(readers))
{
if (requiresWritePath)
{
sendThroughWritePath(cfs, readers);
}
else
{
finishTransaction();
// add sstables (this will build secondary indexes too, see CASSANDRA-10130)
logger.debug("[Stream #{}] Received {} sstables from {} ({})", session.planId(), readers.size(), session.peer, readers);
cfs.addSSTables(readers);
//invalidate row and counter cache
if (cfs.isRowCacheEnabled() || cfs.metadata().isCounter())
{
List<Bounds<Token>> boundsToInvalidate = new ArrayList<>(readers.size());
readers.forEach(sstable -> boundsToInvalidate.add(new Bounds<Token>(sstable.first.getToken(), sstable.last.getToken())));
Set<Bounds<Token>> nonOverlappingBounds = Bounds.getNonOverlappingBounds(boundsToInvalidate);
if (cfs.isRowCacheEnabled())
{
int invalidatedKeys = cfs.invalidateRowCache(nonOverlappingBounds);
if (invalidatedKeys > 0)
logger.debug("[Stream #{}] Invalidated {} row cache entries on table {}.{} after stream " +
"receive task completed.", session.planId(), invalidatedKeys,
cfs.keyspace.getName(), cfs.getTableName());
}
if (cfs.metadata().isCounter())
{
int invalidatedKeys = cfs.invalidateCounterCache(nonOverlappingBounds);
if (invalidatedKeys > 0)
logger.debug("[Stream #{}] Invalidated {} counter cache entries on table {}.{} after stream " +
"receive task completed.", session.planId(), invalidatedKeys,
cfs.keyspace.getName(), cfs.getTableName());
}
}
}
}
}
@Override
public void cleanup()
{
// We don't keep the streamed sstables since we've applied them manually so we abort the txn and delete
// the streamed sstables.
if (requiresWritePath)
{
cfs.forceBlockingFlush();
abort();
}
}
}
| apache-2.0 |
mbaluch/keycloak | testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java | 6812 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.keycloak.testsuite.broker;
import org.jboss.arquillian.graphene.page.Page;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.representations.idm.ComponentRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.testsuite.AbstractKeycloakTest;
import org.keycloak.testsuite.federation.PassThroughFederatedUserStorageProvider;
import org.keycloak.testsuite.federation.PassThroughFederatedUserStorageProviderFactory;
import org.keycloak.testsuite.pages.AccountFederatedIdentityPage;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.UpdateAccountInformationPage;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient;
import static org.keycloak.testsuite.admin.ApiUtil.createUserWithAdminClient;
import static org.keycloak.testsuite.broker.BrokerTestConstants.REALM_PROV_NAME;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AccountLinkTest extends AbstractKeycloakTest {
public static final String CHILD_IDP = "child";
public static final String PARENT_IDP = "parent-idp";
public static final String PARENT_USERNAME = "parent";
@Page
protected AccountFederatedIdentityPage accountFederatedIdentityPage;
@Page
protected UpdateAccountInformationPage profilePage;
@Page
protected LoginPage loginPage;
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation realm = new RealmRepresentation();
realm.setRealm(CHILD_IDP);
realm.setEnabled(true);
testRealms.add(realm);
realm = new RealmRepresentation();
realm.setRealm(PARENT_IDP);
realm.setEnabled(true);
testRealms.add(realm);
}
@Before
public void beforeBrokerTest() {
if (testContext.isInitialized()) {
return;
}
// addIdpUser
RealmResource realmParent = adminClient.realms().realm(PARENT_IDP);
UserRepresentation user = new UserRepresentation();
user.setUsername(PARENT_USERNAME);
user.setEnabled(true);
String userId = createUserAndResetPasswordWithAdminClient(realmParent, user, "password");
// addChildUser
RealmResource realmChild = adminClient.realms().realm(CHILD_IDP);
user = new UserRepresentation();
user.setUsername("child");
user.setEnabled(true);
userId = createUserAndResetPasswordWithAdminClient(realmChild, user, "password");
// setupUserStorageProvider
ComponentRepresentation provider = new ComponentRepresentation();
provider.setName("passthrough");
provider.setProviderId(PassThroughFederatedUserStorageProviderFactory.PROVIDER_ID);
provider.setProviderType(UserStorageProvider.class.getName());
provider.setConfig(new MultivaluedHashMap<>());
provider.getConfig().putSingle("priority", Integer.toString(1));
realmChild.components().add(provider);
// createBroker
createParentChild();
testContext.setInitialized(true);
}
public void createParentChild() {
BrokerTestTools.createKcOidcBroker(adminClient, CHILD_IDP, PARENT_IDP, suiteContext);
}
@Test
public void testAccountLink() {
String childUsername = "child";
String childPassword = "password";
String childIdp = CHILD_IDP;
testAccountLink(childUsername, childPassword, childIdp);
}
@Test
public void testAccountLinkWithUserStorageProvider() {
String childUsername = PassThroughFederatedUserStorageProvider.PASSTHROUGH_USERNAME;
String childPassword = PassThroughFederatedUserStorageProvider.INITIAL_PASSWORD;
String childIdp = CHILD_IDP;
testAccountLink(childUsername, childPassword, childIdp);
}
protected void testAccountLink(String childUsername, String childPassword, String childIdp) {
accountFederatedIdentityPage.realm(childIdp);
accountFederatedIdentityPage.open();
loginPage.isCurrent();
loginPage.login(childUsername, childPassword);
assertTrue(accountFederatedIdentityPage.isCurrent());
accountFederatedIdentityPage.clickAddProvider(PARENT_IDP);
this.loginPage.isCurrent();
loginPage.login(PARENT_USERNAME, "password");
// Assert identity linked in account management
assertTrue(accountFederatedIdentityPage.isCurrent());
assertTrue(driver.getPageSource().contains("id=\"remove-" + PARENT_IDP + "\""));
// Logout from account management
accountFederatedIdentityPage.logout();
// Assert I am logged immediately to account management due to previously linked "test-user" identity
loginPage.isCurrent();
loginPage.clickSocial(PARENT_IDP);
loginPage.login(PARENT_USERNAME, "password");
System.out.println(driver.getCurrentUrl());
System.out.println("--------------------------------");
System.out.println(driver.getPageSource());
assertTrue(accountFederatedIdentityPage.isCurrent());
assertTrue(driver.getPageSource().contains("id=\"remove-" + PARENT_IDP + "\""));
// Unlink my "test-user"
accountFederatedIdentityPage.clickRemoveProvider(PARENT_IDP);
assertTrue(driver.getPageSource().contains("id=\"add-" + PARENT_IDP + "\""));
// Logout from account management
accountFederatedIdentityPage.logout();
this.loginPage.clickSocial(PARENT_IDP);
this.loginPage.login(PARENT_USERNAME, "password");
this.profilePage.assertCurrent();
}
}
| apache-2.0 |
pkuwm/incubator-eagle | eagle-core/eagle-data-process/eagle-stream-process-base/src/main/java/org/apache/eagle/partition/Weight.java | 1058 | /*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.eagle.partition;
public class Weight {
public String key;
public Double value;
public Weight(String key, Double value) {
this.key = key;
this.value = value;
}
}
| apache-2.0 |
meggermo/jackrabbit-oak | oak-segment/src/test/java/org/apache/jackrabbit/oak/plugins/segment/CancelableDiffTest.java | 4199 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.jackrabbit.oak.plugins.segment;
import com.google.common.base.Suppliers;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStateDiff;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
public class CancelableDiffTest {
@Test
public void testPropertyAddedInterruptible() throws Throwable {
PropertyState after = mock(PropertyState.class);
NodeStateDiff wrapped = mock(NodeStateDiff.class);
doReturn(true).when(wrapped).propertyAdded(after);
assertTrue(newCancelableDiff(wrapped, false).propertyAdded(after));
assertFalse(newCancelableDiff(wrapped, true).propertyAdded(after));
}
@Test
public void testPropertyChangedInterruptible() throws Throwable {
PropertyState before = mock(PropertyState.class);
PropertyState after = mock(PropertyState.class);
NodeStateDiff wrapped = mock(NodeStateDiff.class);
doReturn(true).when(wrapped).propertyChanged(before, after);
assertTrue(newCancelableDiff(wrapped, false).propertyChanged(before, after));
assertFalse(newCancelableDiff(wrapped, true).propertyChanged(before, after));
}
@Test
public void testPropertyDeletedInterruptible() throws Throwable {
PropertyState before = mock(PropertyState.class);
NodeStateDiff wrapped = mock(NodeStateDiff.class);
doReturn(true).when(wrapped).propertyDeleted(before);
assertTrue(newCancelableDiff(wrapped, false).propertyDeleted(before));
assertFalse(newCancelableDiff(wrapped, true).propertyDeleted(before));
}
@Test
public void testChildNodeAddedInterruptible() throws Throwable {
NodeState after = mock(NodeState.class);
NodeStateDiff wrapped = mock(NodeStateDiff.class);
doReturn(true).when(wrapped).childNodeAdded("name", after);
assertTrue(newCancelableDiff(wrapped, false).childNodeAdded("name", after));
assertFalse(newCancelableDiff(wrapped, true).childNodeAdded("name", after));
}
@Test
public void testChildNodeChangedInterruptible() throws Throwable {
NodeState before = mock(NodeState.class);
NodeState after = mock(NodeState.class);
NodeStateDiff wrapped = mock(NodeStateDiff.class);
doReturn(true).when(wrapped).childNodeChanged("name", before, after);
assertTrue(newCancelableDiff(wrapped, false).childNodeChanged("name", before, after));
assertFalse(newCancelableDiff(wrapped, true).childNodeChanged("name", before, after));
}
@Test
public void testChildNodeDeletedInterruptible() throws Throwable {
NodeState before = mock(NodeState.class);
NodeStateDiff wrapped = mock(NodeStateDiff.class);
doReturn(true).when(wrapped).childNodeDeleted("name", before);
assertTrue(newCancelableDiff(wrapped, false).childNodeDeleted("name", before));
assertFalse(newCancelableDiff(wrapped, true).childNodeDeleted("name", before));
}
private NodeStateDiff newCancelableDiff(NodeStateDiff wrapped, boolean cancel) {
return new CancelableDiff(wrapped, Suppliers.ofInstance(cancel));
}
}
| apache-2.0 |
tgummerer/buck | src/com/facebook/buck/android/AndroidInstrumentationTestDescription.java | 3967 | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.HasSourceUnderTest;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRules;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.InstallableApk;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
public class AndroidInstrumentationTestDescription
implements Description<AndroidInstrumentationTestDescription.Arg> {
public static final BuildRuleType TYPE = BuildRuleType.of("android_instrumentation_test");
private final Optional<Long> defaultTestRuleTimeoutMs;
public AndroidInstrumentationTestDescription(Optional<Long> defaultTestRuleTimeoutMs) {
this.defaultTestRuleTimeoutMs = defaultTestRuleTimeoutMs;
}
@Override
public BuildRuleType getBuildRuleType() {
return TYPE;
}
@Override
public Arg createUnpopulatedConstructorArg() {
return new Arg();
}
@Override
public <A extends Arg> AndroidInstrumentationTest createBuildRule(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
A args) {
BuildRule apk = resolver.getRule(args.apk);
if (!(apk instanceof InstallableApk)) {
throw new HumanReadableException(
"In %s, instrumentation_apk='%s' must be an android_binary(), apk_genrule() or " +
"android_instrumentation_apk(), but was %s().",
params.getBuildTarget(),
apk.getFullyQualifiedName(),
apk.getType());
}
return new AndroidInstrumentationTest(
params.appendExtraDeps(
BuildRules.getExportedRules(
params.getDeclaredDeps().get())),
new SourcePathResolver(resolver),
(InstallableApk) apk,
args.labels.get(),
args.contacts.get(),
resolver.getAllRules(args.sourceUnderTest.get()),
args.testRuleTimeoutMs.or(defaultTestRuleTimeoutMs));
}
public static ImmutableSet<BuildRule> validateAndGetSourcesUnderTest(
ImmutableSet<BuildTarget> sourceUnderTestTargets,
BuildRuleResolver resolver) {
ImmutableSet.Builder<BuildRule> sourceUnderTest = ImmutableSet.builder();
for (BuildTarget target : sourceUnderTestTargets) {
BuildRule rule = resolver.getRule(target);
sourceUnderTest.add(rule);
}
return sourceUnderTest.build();
}
@SuppressFieldNotInitialized
public static class Arg implements HasSourceUnderTest {
public BuildTarget apk;
public Optional<ImmutableSortedSet<Label>> labels;
public Optional<ImmutableSortedSet<String>> contacts;
public Optional<ImmutableSortedSet<BuildTarget>> sourceUnderTest;
public Optional<Long> testRuleTimeoutMs;
@Override
public ImmutableSortedSet<BuildTarget> getSourceUnderTest() {
return sourceUnderTest.get();
}
}
}
| apache-2.0 |
kay-kim/mongo-java-driver | driver/src/main/org/bson/BSONObject.java | 2616 | /*
* Copyright (c) 2008-2014 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.bson;
import java.util.Map;
import java.util.Set;
/**
* A key-value map that can be saved to the database.
*/
@SuppressWarnings("rawtypes")
public interface BSONObject {
/**
* Sets a name/value pair in this object.
*
* @param key Name to set
* @param v Corresponding value
* @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A <tt>null</tt>
* return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.)
*/
Object put(String key, Object v);
/**
* Sets all key/value pairs from an object into this object
*
* @param o the object
*/
void putAll(BSONObject o);
/**
* Sets all key/value pairs from a map into this object
*
* @param m the map
*/
void putAll(Map m);
/**
* Gets a field from this object by a given name.
*
* @param key The name of the field fetch
* @return The field, if found
*/
Object get(String key);
/**
* Returns a map representing this BSONObject.
*
* @return the map
*/
Map toMap();
/**
* Removes a field with a given name from this object.
*
* @param key The name of the field to remove
* @return The value removed from this object
*/
Object removeField(String key);
/**
* Deprecated
*
* @param key the key to check
* @return True if the key is present
* @deprecated Please use {@link #containsField(String)} instead
*/
@Deprecated
boolean containsKey(String key);
/**
* Checks if this object contains a field with the given name.
*
* @param s Field name for which to check
* @return True if the field is present
*/
boolean containsField(String s);
/**
* Returns this object's fields' names
*
* @return The names of the fields in this object
*/
Set<String> keySet();
}
| apache-2.0 |