repo_name
stringlengths 7
104
| file_path
stringlengths 11
238
| context
list | import_statement
stringlengths 103
6.85k
| code
stringlengths 60
38.4k
| next_line
stringlengths 10
824
| gold_snippet_index
int32 0
8
|
---|---|---|---|---|---|---|
mmonkey/Destinations | src/main/java/com/github/mmonkey/destinations/commands/ListWarpsCommand.java | [
"@Entity\n@DynamicUpdate\n@Table(name = \"access\", uniqueConstraints = {\n @UniqueConstraint(columnNames = \"access_id\")\n})\npublic class AccessEntity implements Serializable {\n\n private static final long serialVersionUID = -6492016883124144444L;\n\n @Id\n @Column(name = \"access_id\", unique = true, nullable = false)\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private long id;\n\n @Column(name = \"can_administrate\")\n private boolean canAdministrate;\n\n @ManyToOne(cascade = CascadeType.ALL)\n @JoinColumn(name = \"player_id\", nullable = false)\n private PlayerEntity player;\n\n /**\n * AccessEntity default constructor\n */\n public AccessEntity() {\n }\n\n /**\n * AccessEntity constructor\n *\n * @param canAdministrate boolean\n * @param player PlayerEntity\n */\n public AccessEntity(boolean canAdministrate, PlayerEntity player) {\n Preconditions.checkNotNull(canAdministrate);\n Preconditions.checkNotNull(player);\n\n this.canAdministrate = canAdministrate;\n this.player = player;\n }\n\n /**\n * @return long\n */\n public long getId() {\n return id;\n }\n\n /**\n * @param id long\n */\n public void setId(long id) {\n Preconditions.checkNotNull(id);\n\n this.id = id;\n }\n\n /**\n * @return boolean\n */\n public boolean isCanAdministrate() {\n return canAdministrate;\n }\n\n /**\n * @param canAdministrate boolean\n */\n public void setCanAdministrate(boolean canAdministrate) {\n this.canAdministrate = canAdministrate;\n }\n\n /**\n * @return PlayerEntity\n */\n public PlayerEntity getPlayer() {\n return player;\n }\n\n /**\n * @param player PlayerEntity\n */\n public void setPlayer(PlayerEntity player) {\n this.player = player;\n }\n\n}",
"@Entity\n@DynamicUpdate\n@Table(name = \"players\", uniqueConstraints = {\n @UniqueConstraint(columnNames = \"player_id\")\n})\n@NamedQueries({\n @NamedQuery(name = \"getPlayer\", query = \"from PlayerEntity p where p.identifier = :identifier\")\n})\npublic class PlayerEntity implements Serializable {\n\n private static final long serialVersionUID = -6211408372176281682L;\n\n @Id\n @Column(name = \"player_id\", unique = true, nullable = false)\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private long id;\n\n @Column(name = \"identifier\", unique = true, nullable = false)\n private String identifier;\n\n @Column(name = \"name\", unique = true, nullable = false)\n private String name;\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)\n private Set<BackEntity> backs = new HashSet<>();\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)\n private Set<BedEntity> beds = new HashSet<>();\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)\n private Set<HomeEntity> homes = new HashSet<>();\n\n /**\n * PlayerEntity default constructor\n */\n public PlayerEntity() {\n }\n\n /**\n * PlayerEntity constructor\n *\n * @param player Player\n */\n public PlayerEntity(Player player) {\n Preconditions.checkNotNull(player);\n\n this.identifier = player.getIdentifier();\n this.name = player.getName();\n }\n\n /**\n * @return long\n */\n public long getId() {\n return id;\n }\n\n /**\n * @param id long\n */\n public void setId(long id) {\n Preconditions.checkNotNull(id);\n\n this.id = id;\n }\n\n /**\n * @return String\n */\n public String getIdentifier() {\n return identifier;\n }\n\n /**\n * @param identifier String\n */\n public void setIdentifier(String identifier) {\n Preconditions.checkNotNull(identifier);\n\n this.identifier = identifier;\n }\n\n /**\n * @return String\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name String\n */\n public void setName(String name) {\n Preconditions.checkNotNull(name);\n\n this.name = name;\n }\n\n /**\n * @return Set<BackEntity>\n */\n public Set<BackEntity> getBacks() {\n return backs;\n }\n\n /**\n * @param backs Set<BackEntity>\n */\n public void setBacks(Set<BackEntity> backs) {\n Preconditions.checkNotNull(backs);\n\n this.backs = backs;\n }\n\n /**\n * @return Set<BedEntity>\n */\n public Set<BedEntity> getBeds() {\n return beds;\n }\n\n /**\n * @param beds Set<BedEntity>\n */\n public void setBeds(Set<BedEntity> beds) {\n Preconditions.checkNotNull(beds);\n\n this.beds = beds;\n }\n\n /**\n * @return Set<HomeEntity>\n */\n public Set<HomeEntity> getHomes() {\n return homes;\n }\n\n /**\n * @param homes Set<HomeEntity>\n */\n public void setHomes(Set<HomeEntity> homes) {\n Preconditions.checkNotNull(homes);\n\n this.homes = homes;\n }\n}",
"@Entity\n@DynamicUpdate\n@Table(name = \"warps\", uniqueConstraints = {\n @UniqueConstraint(columnNames = \"warp_id\"), @UniqueConstraint(columnNames = \"name\")\n})\n@NamedQueries({\n @NamedQuery(name = \"getWarps\", query = \"from WarpEntity\")\n})\npublic class WarpEntity implements Serializable {\n\n private static final long serialVersionUID = 8469390755174027818L;\n\n @Id\n @Column(name = \"warp_id\", unique = true, nullable = false)\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private long id;\n\n @Column(name = \"name\", unique = true, nullable = false)\n private String name;\n\n @Column(name = \"is_private\")\n private boolean isPrivate;\n\n @OneToOne(cascade = CascadeType.ALL)\n @JoinColumn(name = \"location_id\", nullable = false)\n private LocationEntity location;\n\n @ManyToOne\n @JoinColumn(name = \"owner_id\", nullable = false)\n private PlayerEntity owner;\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)\n private Set<AccessEntity> access;\n\n /**\n * WarpEntity default constructor\n */\n public WarpEntity() {\n }\n\n /**\n * WarpEntity constructor\n *\n * @param name String\n * @param isPrivate boolean\n * @param location LocationEntity\n * @param owner PlayerEntity\n */\n public WarpEntity(String name, boolean isPrivate, LocationEntity location, PlayerEntity owner) {\n Preconditions.checkNotNull(name);\n Preconditions.checkNotNull(location);\n Preconditions.checkNotNull(owner);\n\n this.name = name;\n this.isPrivate = isPrivate;\n this.location = location;\n this.owner = owner;\n }\n\n /**\n * @return long\n */\n public long getId() {\n return id;\n }\n\n /**\n * @param id long\n */\n public void setId(long id) {\n Preconditions.checkNotNull(id);\n\n this.id = id;\n }\n\n /**\n * @return String\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name String\n */\n public void setName(String name) {\n Preconditions.checkNotNull(name);\n\n this.name = name;\n }\n\n /**\n * @return boolean\n */\n public boolean isPrivate() {\n return isPrivate;\n }\n\n /**\n * @param isPrivate boolean\n */\n public void setPrivate(boolean isPrivate) {\n isPrivate = isPrivate;\n }\n\n /**\n * @return LocationEntity\n */\n public LocationEntity getLocation() {\n return location;\n }\n\n /**\n * @param location LocationEntity\n */\n public void setLocation(LocationEntity location) {\n Preconditions.checkNotNull(location);\n\n this.location = location;\n }\n\n /**\n * @return PlayerEntity\n */\n public PlayerEntity getOwner() {\n return owner;\n }\n\n /**\n * @param owner PlayerEntity\n */\n public void setOwner(PlayerEntity owner) {\n Preconditions.checkNotNull(owner);\n\n this.owner = owner;\n }\n\n /**\n * @return Set<AccessEntity>\n */\n public Set<AccessEntity> getAccess() {\n return access;\n }\n\n /**\n * @param access Set<AccessEntity>\n */\n public void setAccess(Set<AccessEntity> access) {\n Preconditions.checkNotNull(access);\n\n this.access = access;\n }\n\n}",
"public class PlayerCache {\n\n public static final PlayerCache instance = new PlayerCache();\n\n private final Map<Player, PlayerEntity> cache = new ConcurrentHashMap<>();\n private final Map<Player, ResourceBundle> resourceCache = new ConcurrentHashMap<>();\n\n /**\n * Get the PlayerEntity for this Player from the cache\n *\n * @param player Player\n * @return PlayerEntity\n */\n public PlayerEntity get(Player player) {\n if (!cache.containsKey(player)) {\n PlayerEntity playerEntity = PlayerUtil.getPlayerEntity(player);\n cache.put(player, playerEntity);\n }\n return cache.get(player);\n }\n\n /**\n * Set the PlayerEntity for this Player in the cache\n *\n * @param player Player\n * @param playerEntity PlayerEntity\n */\n public void set(Player player, PlayerEntity playerEntity) {\n cache.put(player, playerEntity);\n }\n\n /**\n * Get the ResourceBundle for this player from the cache\n *\n * @param player Player\n * @return ResourceBundle\n */\n public ResourceBundle getResourceCache(Player player) {\n if (!resourceCache.containsKey(player)) {\n ResourceBundle resourceBundle = ResourceBundle.getBundle(\"lang/messages\", player.getLocale());\n resourceCache.put(player, resourceBundle);\n }\n return resourceCache.get(player);\n }\n\n}",
"public class FormatUtil {\n\t\n\tpublic static final int COMMAND_WINDOW_LENGTH = 53;\n\t\n\t// Message Levels\n\tpublic static final TextColor SUCCESS = TextColors.GREEN;\n\tpublic static final TextColor WARN = TextColors.GOLD;\n\tpublic static final TextColor ERROR = TextColors.RED;\n\tpublic static final TextColor INFO = TextColors.WHITE;\n\tpublic static final TextColor DIALOG = TextColors.GRAY;\n\t\n\t// Object Levels\n\tpublic static final TextColor OBJECT = TextColors.GOLD;\n\tpublic static final TextColor DELETED_OBJECT = TextColors.RED;\n\t\n\t// Links\n\tpublic static final TextColor CANCEL = TextColors.RED;\n\tpublic static final TextColor DELETE = TextColors.RED;\n\tpublic static final TextColor CONFIRM = TextColors.GREEN;\n\tpublic static final TextColor GENERIC_LINK = TextColors.DARK_AQUA;\n\t\n\t//Other\n\tpublic static final TextColor HEADLINE = TextColors.DARK_GREEN;\n\t\n\tpublic static Text empty() {\n\t\t\n\t\tText.Builder text = Text.builder();\n\t\tfor (int i = 0; i < 20; i++) {\n\t\t\ttext.append(Text.NEW_LINE);\n\t\t}\n\t\t\n\t\treturn text.build();\n\t\t\n\t}\n\t\n\tpublic static String getFill(int length, char fill) {\n\t\treturn new String(new char[length]).replace('\\0', fill);\n\t}\n\t\n\tpublic static String getFill(int length) {\n\t\treturn new String(new char[length]).replace('\\0', ' ');\n\t}\n\t\n\tpublic FormatUtil(){\n\t}\n\n}",
"public class MessagesUtil {\n\n /**\n * Get the message associated with this key, for this player's locale\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text get(Player player, String key, Object... args) {\n ResourceBundle messages = PlayerCache.instance.getResourceCache(player);\n return messages.containsKey(key) ? Text.of(String.format(messages.getString(key), args)) : Text.EMPTY;\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as a success (green).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text success(Player player, String key, Object... args) {\n return Text.of(TextColors.GREEN, get(player, key, args));\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as a warning (gold).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text warning(Player player, String key, Object... args) {\n return Text.of(TextColors.GOLD, get(player, key, args));\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as an error (red).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text error(Player player, String key, Object... args) {\n return Text.of(TextColors.RED, get(player, key, args));\n }\n\n}",
"public class PlayerUtil {\n\n /**\n * Get the PlayerEntity in storage for this player\n *\n * @param player Player\n * @return PlayerEntity\n */\n public static PlayerEntity getPlayerEntity(Player player) {\n Optional<PlayerEntity> optional = PlayerRepository.instance.get(player);\n return optional.orElseGet(() -> PlayerRepository.instance.save(new PlayerEntity(player)));\n }\n\n /**\n * Get the last used bed for this player in the current world\n * If the last used bed has been deleted, or is currently occupied, get the next last bed (and so on)\n *\n * @param playerEntity PlayerEntity\n * @param player Player\n * @return BedEntity|null\n */\n public static BedEntity getBed(PlayerEntity playerEntity, Player player) {\n List<BedEntity> beds = new CopyOnWriteArrayList<>(playerEntity.getBeds());\n beds.sort(new BedComparator());\n\n Destinations.getInstance().getLogger().info(\"Beds: \" + beds.size());\n\n for (BedEntity bed : beds) {\n if (bed.getLocation().getWorld().getIdentifier().equals(player.getWorld().getUniqueId().toString())) {\n Location<World> block = player.getWorld().getLocation(bed.getLocation().getLocation().getBlockPosition());\n if (BlockUtil.isBed(block)) {\n if (!BlockUtil.isBedOccupied(block)) {\n return bed;\n }\n } else {\n playerEntity.getBeds().remove(bed);\n playerEntity = PlayerRepository.instance.save(playerEntity);\n PlayerCache.instance.set(player, playerEntity);\n }\n }\n }\n return null;\n }\n\n /**\n * Get a list of Player's homes from the world that player is currently in\n *\n * @param playerEntity PlayerEntity\n * @param location Location\n * @return Set<HomeEntity>\n */\n public static Set<HomeEntity> getFilteredHomes(PlayerEntity playerEntity, Location location) {\n Set<HomeEntity> filtered = new HashSet<>();\n playerEntity.getHomes().forEach(home -> {\n if (home.getLocation().getWorld().getIdentifier().equals(location.getExtent().getUniqueId().toString())) {\n filtered.add(home);\n }\n });\n return filtered;\n }\n\n /**\n * Get a player's home by name\n *\n * @param playerEntity PlayerEntity\n * @param name String\n * @return HomeEntity\n */\n public static HomeEntity getPlayerHomeByName(PlayerEntity playerEntity, String name) {\n for (HomeEntity home : playerEntity.getHomes()) {\n if (home.getName().equalsIgnoreCase(name)) {\n return home;\n }\n }\n return null;\n }\n\n /**\n * Get the next available name for a player's home\n *\n * @param playerEntity PlayerEntity\n * @return String\n */\n public static String getPlayerHomeAvailableName(PlayerEntity playerEntity) {\n int max = 0, temp = 0;\n for (HomeEntity home : playerEntity.getHomes()) {\n if (home.getName().startsWith(\"home\") && home.getName().matches(\".*\\\\d.*\")) {\n temp = Integer.parseInt(home.getName().replaceAll(\"[\\\\D]\", \"\"));\n }\n if (temp > max) {\n max = temp;\n }\n }\n if (playerEntity.getHomes().size() > max) {\n max = playerEntity.getHomes().size();\n }\n return (playerEntity.getHomes().size() == 0) ? \"home\" : \"home\" + Integer.toString(max + 1);\n }\n\n /**\n * Get a list of warps that this player can use\n *\n * @param playerEntity PlayerEntity\n * @return Set<WarpEntity>\n */\n public static Set<WarpEntity> getPlayerWarps(PlayerEntity playerEntity) {\n Set<WarpEntity> results = new HashSet<>();\n WarpCache.instance.get().forEach(warp -> {\n if (!warp.isPrivate()) {\n results.add(warp);\n } else if (warp.getOwner().getIdentifier().equals(playerEntity.getIdentifier())) {\n results.add(warp);\n } else {\n warp.getAccess().forEach(access -> {\n if (access.getPlayer().getIdentifier().equals(playerEntity.getIdentifier())) {\n results.add(warp);\n }\n });\n }\n });\n return results;\n }\n\n}"
] | import com.github.mmonkey.destinations.entities.AccessEntity;
import com.github.mmonkey.destinations.entities.PlayerEntity;
import com.github.mmonkey.destinations.entities.WarpEntity;
import com.github.mmonkey.destinations.persistence.cache.PlayerCache;
import com.github.mmonkey.destinations.utilities.FormatUtil;
import com.github.mmonkey.destinations.utilities.MessagesUtil;
import com.github.mmonkey.destinations.utilities.PlayerUtil;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.service.pagination.PaginationService;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextStyles;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList; | package com.github.mmonkey.destinations.commands;
public class ListWarpsCommand implements CommandExecutor {
public static final String[] ALIASES = {"warps", "listwarps"};
/**
* Get the Command Specifications for this command
*
* @return CommandSpec
*/
public static CommandSpec getCommandSpec() {
return CommandSpec.builder()
.permission("destionations.warp.use")
.description(Text.of("/warps or /listwarps"))
.extendedDescription(Text.of("Displays a list of your warps."))
.executor(new ListWarpsCommand())
.build();
}
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
if (!(src instanceof Player)) {
return CommandResult.empty();
}
Player player = (Player) src; | PlayerEntity playerEntity = PlayerCache.instance.get(player); | 3 |
edmocosta/queryfy | queryfy-core/src/test/java/org/evcode/queryfy/core/QueryStructureTest.java | [
"public enum OrderOperatorType implements Operator {\n ASC,\n DESC\n}",
"public class QueryParser extends BaseParser<Object> {\n\n final ParserConfig config;\n\n public QueryParser() {\n this.config = ParserConfig.DEFAULT;\n }\n\n public QueryParser(ParserConfig config) {\n this.config = config;\n }\n\n //Common rules\n Rule WS() {\n return OneOrMore(Ch(' '));\n }\n\n Rule OptionalWS() {\n return ZeroOrMore(Ch(' '));\n }\n\n Rule Minus() {\n return Ch('-');\n }\n\n Rule Plus() {\n return Ch('+');\n }\n\n Rule Comma() {\n return Ch(',');\n }\n\n Rule ArgumentsSeparator() {\n return String(config.getGrammar().getArgsSeparator());\n }\n\n Rule Integer() {\n return OneOrMore(Digit());\n }\n\n Rule Dot() {\n return Ch('.');\n }\n\n Rule Colon() {\n return Ch(':');\n }\n\n Rule FourDigits() {\n return NTimes(4, Digit());\n }\n\n Rule ThreeDigits() {\n return NTimes(3, Digit());\n }\n\n Rule TwoDigits() {\n return NTimes(2, Digit());\n }\n\n Rule Digit() {\n return CharRange('0', '9');\n }\n\n Rule Date() {\n LocalDateVar date = new LocalDateVar();\n return Sequence(\n FourDigits(), date.appendYear(match()),\n Minus(), TwoDigits(), date.appendMonth(match()),\n Minus(), TwoDigits(), date.appendDay(match()),\n push(date.get())\n );\n }\n\n Rule ZoneOffset() {\n return FirstOf(IgnoreCase('Z'),\n Sequence(FirstOf(Minus(), Plus()),\n FirstOf(Sequence(TwoDigits(), Optional(Colon()), TwoDigits(), Optional(Colon(), TwoDigits())),\n Sequence(TwoDigits(), Optional(Colon()), TwoDigits()),\n TwoDigits(),\n Digit()\n )\n )\n );\n }\n\n Rule ZoneId() {\n return Sequence(Ch('['),\n ZeroOrMore(Sequence(TestNot(AnyOf(\"\\r\\n\\\"\\\\[]\")), ANY)),\n Ch(']'));\n }\n\n Rule DateTime() {\n DateTimeVar dateTime = new DateTimeVar();\n return Sequence(\n FourDigits(), dateTime.appendYear(match()),\n Minus(), TwoDigits(), dateTime.appendMonth(match()),\n Minus(), TwoDigits(), dateTime.appendDay(match()),\n Ch('T'), TwoDigits(), dateTime.appendHour(match()),\n Colon(), TwoDigits(), dateTime.appendMinute(match()),\n Optional(Colon(), TwoDigits(), dateTime.appendSecond(match())),\n Optional(Sequence(FirstOf(Comma(), Dot()), Sequence(ThreeDigits(), dateTime.appendNanosecond(match())))),\n Optional(ZoneOffset(), dateTime.appendZoneOffset(match())),\n Optional(OptionalWS(), ZoneId(), dateTime.appendZoneId(match())),\n push(dateTime.get())\n );\n }\n\n Rule Time() {\n TimeVar time = new TimeVar();\n return Sequence(\n TwoDigits(), time.appendHour(match()), Colon(),\n TwoDigits(), time.appendMinute(match()),\n Optional(Colon(), TwoDigits(), time.appendSecond(match())),\n Optional(Sequence(FirstOf(Comma(), Dot()), Sequence(ThreeDigits(), time.appendNanosecond(match())))),\n Optional(ZoneOffset(), time.appendZoneOffset(match())),\n push(time.get()));\n }\n\n Rule Locale() {\n return Sequence(NTimes(2, CharRange('a', 'z')),\n Minus(),\n NTimes(2, CharRange('A', 'Z')));\n }\n\n Rule InsideBrackets(Rule rule) {\n return Sequence(Ch('['), rule, Ch(']'));\n }\n\n Rule NumericTypeQualifier() {\n return FirstOf(\n IgnoreCase(NumberVar.FLOAT),\n IgnoreCase(NumberVar.LONG),\n IgnoreCase(NumberVar.INTEGER),\n IgnoreCase(NumberVar.DOUBLE)\n );\n }\n\n Rule DoubleQuoteString() {\n StringBuilderVar str = new StringBuilderVar();\n return Sequence('\"', ZeroOrMore(FirstOf(Escape(str),\n Sequence(TestNot(AnyOf(\"\\r\\n\\\"\\\\\")), ANY, str.append(match())))).suppressSubnodes(), '\"',\n push(str.getString()));\n }\n\n Rule SingleQuoteString() {\n StringBuilderVar str = new StringBuilderVar();\n return Sequence('\\'', ZeroOrMore(FirstOf(Escape(str),\n Sequence(TestNot(AnyOf(\"\\r\\n'\\\\\")), ANY, str.append(match())))).suppressSubnodes(), '\\'',\n push(str.getString()));\n }\n\n Rule Escape(StringBuilderVar str) {\n return Sequence('\\\\', FirstOf(AnyOf(\"btnfr\\\"\\'\\\\\"), OctalEscape(), UnicodeEscape()), str.append(match()));\n }\n\n Rule OctalEscape() {\n return FirstOf(\n Sequence(CharRange('0', '3'), CharRange('0', '7'), CharRange('0', '7')),\n Sequence(CharRange('0', '7'), CharRange('0', '7')),\n CharRange('0', '7')\n );\n }\n\n Rule UnicodeEscape() {\n return Sequence(OneOrMore('u'), HexDigit(), HexDigit(), HexDigit(), HexDigit());\n }\n\n Rule HexDigit() {\n return FirstOf(CharRange('a', 'f'), CharRange('A', 'F'), CharRange('0', '9'));\n }\n\n Rule Arguments(ListVar listValues) {\n return Sequence(\n Value(),\n listValues.add(pop()),\n ZeroOrMore(Sequence(OptionalWS(),\n ArgumentsSeparator(),\n OptionalWS(),\n Value(),\n listValues.add(pop()))\n )\n );\n }\n\n //Grammar operators\n Rule ComparisionOperator() {\n return FirstOf(\n toOperator(ComparisionOperatorType.LOWER_EQUAL),\n toOperator(ComparisionOperatorType.LOWER),\n toOperator(ComparisionOperatorType.GREATER_EQUAL),\n toOperator(ComparisionOperatorType.GREATER)\n );\n }\n\n Rule EqualOperator() {\n return FirstOf(\n toOperator(ComparisionOperatorType.EQUAL),\n toOperator(ComparisionOperatorType.NOT_EQUAL)\n );\n }\n\n Rule IsNullOperator() {\n return Sequence(toOperator(SelectorOperatorType.IS_NULL),\n push(SelectorOperatorType.IS_NULL));\n }\n\n Rule IsNotNullOperator() {\n return Sequence(toOperator(SelectorOperatorType.IS_NOT_NULL),\n push(SelectorOperatorType.IS_NOT_NULL));\n }\n\n Rule IsTrueOperator() {\n return Sequence(toOperator(SelectorOperatorType.IS_TRUE),\n push(SelectorOperatorType.IS_TRUE));\n }\n\n Rule IsFalseOperator() {\n return Sequence(toOperator(SelectorOperatorType.IS_FALSE),\n push(SelectorOperatorType.IS_FALSE));\n }\n\n Rule IsEmptyOperator() {\n return Sequence(toOperator(SelectorOperatorType.IS_EMPTY),\n push(SelectorOperatorType.IS_EMPTY));\n }\n\n Rule IsNotEmptyOperator() {\n return Sequence(toOperator(SelectorOperatorType.IS_NOT_EMPTY),\n push(SelectorOperatorType.IS_NOT_EMPTY));\n }\n\n Rule InOperator() {\n return Sequence(toOperator(ListOperatorType.IN), push(ListOperatorType.IN));\n }\n\n Rule NotInOperator() {\n return Sequence(toOperator(ListOperatorType.NOT_IN), push(ListOperatorType.NOT_IN));\n }\n\n Rule LikeOperator() {\n return Sequence(toOperator(StringOperatorType.LIKE), push(StringOperatorType.LIKE));\n }\n\n Rule NotLikeOperator() {\n return Sequence(toOperator(StringOperatorType.NOT_LIKE), push(StringOperatorType.NOT_LIKE));\n }\n\n //Value rules\n Rule Numeric() {\n NumberVar number = new NumberVar();\n return Sequence(\n Sequence(Sequence(Optional(Sequence(Minus(), OptionalWS())), Integer(), Optional(Dot(), Integer())),\n number.setNumber(match())),\n Optional(Sequence(NumericTypeQualifier(), number.setTypeQualifier(match()))),\n push(number.get()));\n }\n\n Rule True() {\n return Sequence(String(config.getGrammar().getTrueValue()), push(Boolean.TRUE));\n }\n\n Rule False() {\n return Sequence(String(config.getGrammar().getFalseValue()), push(Boolean.FALSE));\n }\n\n Rule String() {\n return FirstOf(SingleQuoteString(), DoubleQuoteString());\n }\n\n Rule Temporal() {\n return FirstOf(DateTime(), Date(), Time());\n }\n\n Rule Value() {\n return FirstOf(Temporal(), Numeric(), String(), CustomFunction());\n }\n\n Rule CustomFunction() {\n Var<LinkedList<Object>> list = new Var<>();\n StringVar function = new StringVar();\n String functionPrefix = config.getGrammar().getCustomFunctionPrefix();\n\n return Sequence(functionPrefix, Sequence(QualifiedSelector(), push(match()), function.set((String) pop())),\n OptionalWS(), Ch('('), OptionalWS(), Optional(Sequence(list.set(new LinkedList<>()), CustomFunctionArguments(list))), OptionalWS(), Ch(')'),\n push(new FunctionNode(function.get(), list.isSet() ? list.get().toArray() : new Object[]{})));\n }\n\n Rule CustomFunctionArguments(Var<LinkedList<Object>> list) {\n return Sequence(Value(), list.get().add(pop()),\n ZeroOrMore(Sequence(OptionalWS(),\n ArgumentsSeparator(),\n OptionalWS(),\n Value(),\n list.get().add(pop()))\n )\n );\n }\n\n //Operations\n Rule SelectorOperation() {\n return Sequence(Selector(), WS(),\n FirstOf(IsNotNullOperator(), IsNullOperator(), IsTrueOperator(), IsFalseOperator(),\n IsNotEmptyOperator(), IsEmptyOperator()),\n pushSelectorOperation());\n }\n\n Rule InOperation() {\n ListVar<Object> list = new ListVar<>();\n return Sequence(Selector(), WS(), FirstOf(NotInOperator(), InOperator()),\n OptionalWS(),\n Ch('('),\n OptionalWS(), Arguments(list), OptionalWS(),\n Ch(')'), pushListOperation(list.get()));\n }\n\n Rule LikeOperation() {\n return Sequence(Selector(), WS(), FirstOf(NotLikeOperator(), LikeOperator()),\n WS(), FirstOf(String(), CustomFunction()), pushFilterOperation());\n }\n\n Rule EqualOperation() {\n return Sequence(Selector(), OptionalWS(), EqualOperator(), pushOperator(),\n OptionalWS(), FirstOf(True(), False(), Value()), pushFilterOperation());\n }\n\n Rule ComparisionOperation() {\n return Sequence(Selector(), OptionalWS(), ComparisionOperator(), pushOperator(),\n OptionalWS(), Value(), pushFilterOperation());\n }\n\n Rule Operations() {\n return FirstOf(EqualOperation(), ComparisionOperation(), SelectorOperation(), LikeOperation(), InOperation());\n }\n\n Rule LogicalOperation() {\n return FirstOf(Sequence(Ch('('), OptionalWS(), OrOperation(), OptionalWS(), Ch(')')), Operations());\n }\n\n Rule AndOperation() {\n return Sequence(LogicalOperation(), ZeroOrMore(Sequence(WS(), toOperator(LogicalOperatorType.AND), WS(),\n LogicalOperation(), pushLogicalOperation(LogicalOperatorType.AND))));\n }\n\n Rule OrOperation() {\n return Sequence(AndOperation(), ZeroOrMore(Sequence(WS(), toOperator(LogicalOperatorType.OR), WS(),\n AndOperation(), pushLogicalOperation(LogicalOperatorType.OR))));\n }\n\n //Query structure\n Rule Select() {\n return Sequence(toOperator(QueryOperatorType.SELECT), WS());\n }\n\n Rule QualifiedSelector() {\n return Sequence(SelectorPattern(), ZeroOrMore(Dot(), SelectorPattern()));\n }\n\n Rule Selector() {\n return Sequence(QualifiedSelector(), push(match()));\n }\n\n @MemoMismatches\n Rule SelectorPattern() {\n return OneOrMore(new SelectorMatcher());\n }\n\n Rule ProjectionSelectors() {\n ListVar<String> fields = new ListVar<>();\n return Sequence(\n Sequence(QualifiedSelector(), push(match())),\n fields.add((String) pop()),\n ZeroOrMore(Sequence(OptionalWS(),\n String(config.getGrammar().getArgsSeparator()),\n OptionalWS(),\n Sequence(QualifiedSelector(), push(match())),\n fields.add((String) pop()))\n ),\n pushProjectionSelectors(fields.get())\n );\n }\n\n Rule Where() {\n return Sequence(OptionalWS(), toOperator(QueryOperatorType.WHERE), WS());\n }\n\n Rule Limit() {\n return Sequence(toOperator(QueryOperatorType.LIMIT), WS(),\n Integer(), push(match()), OptionalWS(), ArgumentsSeparator(), OptionalWS(), Integer(),\n push(match()), pushLimitOperation());\n }\n\n Rule OrderSpecifier(OrderVar orderVar) {\n return Sequence(QualifiedSelector(), orderVar.setSelector(match()),\n Optional(WS(), FirstOf(toOperator(OrderOperatorType.ASC), toOperator(OrderOperatorType.DESC)),\n orderVar.setOperator((OrderOperatorType) config.getGrammar().getOperator(match()))));\n }\n\n Rule Order() {\n ListVar<OrderNode.OrderSpecifier> list = new ListVar<>();\n OrderVar orderVar = new OrderVar();\n\n return Sequence(\n toOperator(QueryOperatorType.ORDER),\n WS(),\n OrderSpecifier(orderVar),\n list.add(orderVar.get()),\n orderVar.clear(),\n ZeroOrMore(Sequence(OptionalWS(),\n String(config.getGrammar().getArgsSeparator()),\n OptionalWS(),\n OrderSpecifier(orderVar),\n list.add(orderVar.get()),\n orderVar.clear()\n )), pushOrderByOperation(list.get()));\n }\n\n //Parser entry point\n public Rule Query() {\n return Sequence(Optional(Select(), ProjectionSelectors(), Optional(FirstOf(Where(), Order(), Limit()))),\n Optional(OrOperation()),\n Optional(OptionalWS(), Order(), Optional(Limit())),\n Optional(OptionalWS(), Limit()), EOI);\n }\n\n //AST builder operations\n boolean pushOrderByOperation(LinkedList<OrderNode.OrderSpecifier> orderList) {\n push(new OrderNode(orderList));\n return true;\n }\n\n boolean pushLimitOperation() {\n Long limit = Long.parseLong(pop().toString());\n Long offset = Long.parseLong(pop().toString());\n return push(new LimitNode(offset, limit));\n }\n\n boolean pushProjectionSelectors(List<String> selectors) {\n ProjectionNode projection = new ProjectionNode(selectors\n .stream()\n .collect(Collectors.toSet()));\n return push(projection);\n }\n\n boolean pushOperator() {\n String value = match();\n Operator operator = config.getGrammar().getOperator(value);\n return push(operator);\n }\n\n boolean pushListOperation(List<Object> list) {\n ListOperatorType operator = (ListOperatorType) pop();\n String selector = (String) pop();\n\n List<Object> parsedValues = list.stream().map(this::parseValue)\n .collect(Collectors.toList());\n\n FilterNode node = new FilterNode(operator, selector, parsedValues);\n return push(node);\n }\n\n boolean pushFilterOperation() {\n Object value = parseValue(pop());\n Operator operator = (Operator) pop();\n String selector = (String) pop();\n FilterNode node = new FilterNode(operator, selector, Collections.singletonList(value));\n return push(node);\n }\n\n boolean pushSelectorOperation() {\n SelectorOperatorType operator = (SelectorOperatorType) pop();\n String selector = (String) pop();\n FilterNode node = new FilterNode(operator, selector, Collections.emptyList());\n return push(node);\n }\n\n boolean pushLogicalOperation(LogicalOperatorType operator) {\n Node rightNode = (Node) pop();\n Node leftNode = (Node) pop();\n\n Node logicalNode = operator == LogicalOperatorType.AND ?\n new AndNode(rightNode, leftNode) :\n new OrNode(rightNode, leftNode);\n\n return push(logicalNode);\n }\n\n Object parseValue(Object value) {\n if (value instanceof FunctionNode) {\n Objects.requireNonNull(config.getFunctionInvoker());\n FunctionNode functionValue = (FunctionNode) value;\n\n if (functionValue.getArguments() != null && functionValue.getArguments().length > 0) {\n for (int i = 0; i < functionValue.getArguments().length; i++) {\n if (functionValue.getArguments()[i] instanceof FunctionNode) {\n functionValue.getArguments()[i] = parseValue(functionValue.getArguments()[i]);\n }\n }\n }\n\n Object parsedValue = config.getFunctionInvoker()\n .invoke(functionValue.getFunction(), functionValue.getArguments());\n\n return parsedValue;\n }\n\n return value;\n }\n\n Rule toOperator(Operator operatorType) {\n Object[] parts = operatorParts(operatorType);\n\n if (parts.length == 1) {\n if (parts[0] instanceof Rule)\n return (Rule) parts[0];\n\n throw new RuntimeException(\"General error\");\n }\n\n return Sequence(parts);\n }\n\n Object[] operatorParts(Operator operatorType, Object... moreRules) {\n\n Set<String> symbols = operatorType.getOperatorSymbols(config.getGrammar());\n\n LinkedList<Rule> symbolsRule = new LinkedList<>();\n for (String symbol : symbols) {\n symbolsRule.add(operatorSymbolRule(symbol));\n }\n\n Rule rule = FirstOf(symbolsRule.toArray(new Object[0]));\n\n LinkedList<Object> allRules = new LinkedList<>();\n allRules.add(rule);\n allRules.addAll(Arrays.asList(moreRules));\n\n return allRules.toArray(new Object[0]);\n }\n\n Rule operatorSymbolRule(String operatorSymbol) {\n if (!operatorSymbol.contains(\" \")) {\n return operatorSymbol.length() == 1 ?\n Ch(operatorSymbol.charAt(0)) :\n String(operatorSymbol);\n }\n\n LinkedList<Rule> symbolParts = new LinkedList<>();\n String[] parts = operatorSymbol.split(\" \");\n for (int i = 0; i < parts.length; i++) {\n Rule operatorValue = parts[i].length() == 1 ?\n Ch(parts[i].charAt(0)) :\n String(parts[i]);\n\n symbolParts.add(operatorValue);\n\n if ((i + 1) < parts.length) {\n symbolParts.add(Ch(' '));\n }\n }\n\n return Sequence(symbolParts.toArray(new Object[0]));\n }\n}",
"public final class FilterNode implements Node {\n\n private final Operator operator;\n private final String selector;\n private final List<Object> args;\n\n public FilterNode(final Operator operator, final String selector, final List<Object> args) {\n this.operator = operator;\n this.selector = selector;\n this.args = args;\n }\n\n public Operator getOperator() {\n return operator;\n }\n\n public String getSelector() {\n return selector;\n }\n\n public List<Object> getArgs() {\n return args;\n }\n\n @Override\n public <R, A> R accept(final Visitor<R, A> visitor, A param) {\n return visitor.visit(this, param);\n }\n}",
"public final class LimitNode implements Node {\n\n private final Long offset;\n private final Long limit;\n\n public LimitNode(final Long offset, final Long limit) {\n this.offset = offset;\n this.limit = limit;\n }\n\n public Long getOffset() {\n return offset;\n }\n\n public Long getLimit() {\n return limit;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n LimitNode limitNode = (LimitNode) o;\n\n if (offset != null ? !offset.equals(limitNode.offset) : limitNode.offset != null) return false;\n return limit != null ? limit.equals(limitNode.limit) : limitNode.limit == null;\n }\n\n @Override\n public int hashCode() {\n int result = offset != null ? offset.hashCode() : 0;\n result = 31 * result + (limit != null ? limit.hashCode() : 0);\n return result;\n }\n\n @Override\n public <R, A> R accept(final Visitor<R, A> visitor, final A param) {\n return visitor.visit(this, param);\n }\n}",
"public final class OrderNode implements Node {\n\n private LinkedList<OrderSpecifier> orderSpecifiers = new LinkedList<>();\n\n public OrderNode(final LinkedList<OrderSpecifier> orderSpecifiers) {\n this.orderSpecifiers = orderSpecifiers;\n }\n\n public LinkedList<OrderSpecifier> getOrderSpecifiers() {\n return orderSpecifiers;\n }\n\n @Override\n public <R, A> R accept(final Visitor<R, A> visitor, final A param) {\n return visitor.visit(this, param);\n }\n\n public static class OrderSpecifier {\n\n private final String selector;\n private final OrderOperatorType operator;\n\n public OrderSpecifier(final String selector, final OrderOperatorType operator) {\n this.selector = selector;\n this.operator = operator;\n }\n\n public String getSelector() {\n return selector;\n }\n\n public OrderOperatorType getOperator() {\n return operator;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n OrderSpecifier that = (OrderSpecifier) o;\n\n if (selector != null ? !selector.equals(that.selector) : that.selector != null) return false;\n return operator == that.operator;\n }\n\n @Override\n public int hashCode() {\n int result = selector != null ? selector.hashCode() : 0;\n result = 31 * result + (operator != null ? operator.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"OrderSpecifier{\" +\n \"selector='\" + selector + '\\'' +\n \", operator=\" + operator +\n '}';\n }\n }\n}",
"public final class ProjectionNode implements Node {\n\n private final Set<String> selectors;\n\n public ProjectionNode(Set<String> selectors) {\n this.selectors = selectors;\n }\n\n public Set<String> getSelectors() {\n return Collections.unmodifiableSet(selectors);\n }\n\n @Override\n public <R, A> R accept(Visitor<R, A> visitor, A param) {\n return visitor.visit(this, param);\n }\n}",
"public class ExpressionParserUtils {\n public static ValueStack<Object> parse(String expression, Rule ruleTree) {\n ReportingParseRunner<Object> runner = new ReportingParseRunner<>(ruleTree);\n ParsingResult<Object> result = runner.run(expression);\n\n if (!result.matched || result.hasErrors()) {\n throw new IllegalArgumentException(\"Invalid query: \" + printParseErrors(result));\n }\n\n return result.valueStack;\n }\n}"
] | import java.util.Collections;
import java.util.List;
import org.evcode.queryfy.core.operator.OrderOperatorType;
import org.evcode.queryfy.core.parser.QueryParser;
import org.evcode.queryfy.core.parser.ast.FilterNode;
import org.evcode.queryfy.core.parser.ast.LimitNode;
import org.evcode.queryfy.core.parser.ast.OrderNode;
import org.evcode.queryfy.core.parser.ast.ProjectionNode;
import org.evcode.queryfy.core.utils.ExpressionParserUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.parboiled.Parboiled;
import org.parboiled.support.ValueStack;
import java.util.Arrays; | /*
* Copyright 2017 EVCode
*
* 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.evcode.queryfy.core;
@RunWith(JUnit4.class)
public class QueryStructureTest {
@Test
public void testQuery() {
List<String> oneTwoThreeSelectors = Arrays.asList("one", "two", "three");
testQuery("select one, two, three where one = 1 order by one limit 1,1",
oneTwoThreeSelectors,
1L, | Arrays.asList(new OrderNode.OrderSpecifier("one", OrderOperatorType.ASC)), | 4 |
isel-leic-mpd/mpd-2017-i41d | aula34-weather-webapp/src/main/java/weather/app/WeatherWebApp.java | [
"public class HttpRequest implements IRequest {\n @Override\n public Iterable<String> getContent(String path) {\n List<String> res = new ArrayList<>();\n try (InputStream in = new URL(path).openStream()) {\n /*\n * Consumir o Inputstream e adicionar dados ao res\n */\n try(BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {\n String line;\n while ((line = reader.readLine()) != null) {\n res.add(line);\n }\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n return res;\n }\n}",
"public class HttpServer {\n\n public interface HttpGetHandler extends Function<HttpServletRequest, String> {\n String apply(HttpServletRequest req);\n }\n\n private final Server server;\n private final ServletContextHandler container;\n\n public HttpServer(int port) {\n server = new Server(port); // Http Server no port\n container = new ServletContextHandler(); // Contentor de Servlets\n server.setHandler(container);\n }\n\n public HttpServer addServletHolder(String path, ServletHolder holder) {\n container.addServlet(holder, path);\n return this;\n }\n\n public HttpServer addHandler(String path, HttpGetHandler handler) {\n /*\n * Associação entre Path <-> Servlet\n */\n container.addServlet(new ServletHolder(new HtmlRenderServlet(handler)), path);\n return this;\n }\n\n public void run() throws Exception {\n server.start();\n server.join();\n }\n\n static class HtmlRenderServlet extends HttpServlet {\n private final HttpGetHandler handler;\n\n public HtmlRenderServlet(HttpGetHandler handler) {\n this.handler = handler;\n }\n\n @Override\n public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, IOException {\n Charset utf8 = Charset.forName(\"utf-8\");\n resp.setContentType(String.format(\"text/html; charset=%s\", utf8.name()));\n\n String respBody = handler.apply(req);\n\n byte[] respBodyBytes = respBody.getBytes(utf8);\n resp.setStatus(200);\n resp.setContentLength(respBodyBytes.length);\n OutputStream os = resp.getOutputStream();\n os.write(respBodyBytes);\n os.close();\n }\n }\n}",
"public class WeatherService implements AutoCloseable{\n\n private final WeatherWebApi api;\n\n public WeatherService(WeatherWebApi api) {\n this.api = api;\n }\n\n public WeatherService() {\n api = new WeatherWebApi(new HttpRequest());\n }\n\n public CompletableFuture<Stream<Location>> search(String query) {\n return api.search(query)\n .thenApply(str -> str\n .map(this::dtoToLocation));\n }\n\n protected Location dtoToLocation(LocationDto loc) {\n return new Location(\n loc.getCountry(),\n loc.getRegion(),\n loc.getLatitude(),\n loc.getLongitude(),\n last30daysWeather(loc.getLatitude(), loc.getLongitude())::join,\n (from, to) -> pastWeather(loc.getLatitude(), loc.getLongitude(), from, to).join());\n }\n\n public CompletableFuture<Stream<WeatherInfo>> last30daysWeather(double lat, double log) {\n return this.pastWeather(lat, log, now().minusDays(30), now().minusDays(1));\n }\n\n private static WeatherInfo dtoToWeatherInfo(WeatherInfoDto dto) {\n return new WeatherInfo(\n dto.getDate(),\n dto.getTempC(),\n dto.getDescription(),\n dto.getPrecipMM(),\n dto.getFeelsLikeC());\n }\n\n public CompletableFuture<Stream<WeatherInfo>> pastWeather(double lat, double log, LocalDate from, LocalDate to) {\n return api\n .pastWeather(lat, log, from, to)\n .thenApply(str -> str\n .map(dto -> dtoToWeatherInfo(dto)));\n }\n\n @Override\n public void close() throws Exception {\n api.close();\n }\n}",
"public class WeatherServiceCache extends WeatherService{\n\n public WeatherServiceCache(WeatherWebApi api) {\n super(api);\n }\n\n private final Map<Coords, Map<LocalDate, WeatherInfo>> cache = new HashMap<>();\n\n @Override\n protected Location dtoToLocation(LocationDto loc) {\n return new Location(\n loc.getCountry(),\n loc.getRegion(),\n loc.getLatitude(),\n loc.getLongitude(),\n last30daysWeatherSupplier(loc),\n (from, to) -> pastWeather(loc.getLatitude(), loc.getLongitude(), from, to).join());\n }\n\n private Supplier<Stream<WeatherInfo>> last30daysWeatherSupplier(LocationDto loc) {\n /**\n * Immediately dispatch request for last 30 days weather asynchronously.\n */\n CompletableFuture<Stream<WeatherInfo>> promise =\n last30daysWeather(loc.getLatitude(), loc.getLongitude());\n boolean[] firstReq = { true };\n /**\n * The supplier returns the result of the promise on first get.\n * Further invocations will call last30daysWeather() again which in turn\n * calls the pastWeather() of this WeatherServiceCache, which gets past\n * weather from cache.\n */\n return () -> {\n Stream<WeatherInfo> res = firstReq[0]\n ? promise.join()\n : last30daysWeather(loc.getLatitude(), loc.getLongitude()).join(); // ALREADY on cache.\n firstReq[0] = false;\n return res;\n };\n }\n\n @Override\n public CompletableFuture<Stream<WeatherInfo>> pastWeather(double lat, double log, LocalDate from, LocalDate to) {\n Coords location = new Coords(lat, log);\n Map<LocalDate, WeatherInfo> past = getOrCreate(location, cache);\n List<LocalDate> keys = Stream\n .iterate(from, prev -> prev.plusDays(1))\n .limit(ChronoUnit.DAYS.between(from, to.plusDays(1)))\n .collect(toList());\n if (past.keySet().containsAll(keys)) {\n CompletableFuture<Stream<WeatherInfo>> res = new CompletableFuture<>();\n res.complete(keys.stream().map(past::get));\n return res;\n }\n CompletableFuture<Stream<WeatherInfo>> values = super.pastWeather(lat, log, from, to);\n Iterator<LocalDate> keysIter = keys.iterator();\n return values.thenApply(vs -> vs\n .peek(item -> past.put(keysIter.next(), item)));\n }\n\n private static Map<LocalDate, WeatherInfo> getOrCreate(\n Coords coords,\n Map<Coords, Map<LocalDate, WeatherInfo>> cache)\n {\n Map<LocalDate, WeatherInfo> weathers = cache.get(coords);\n if(weathers == null) {\n weathers = new HashMap<>();\n cache.put(coords, weathers);\n }\n return weathers;\n }\n}",
"public class WeatherController {\n\n private final String root;\n\n private final WeatherService api;\n private final String getSearchView = load(\"views/search.html\");\n private final String searchCityView = load(\"views/searchCity.html\");\n private final String searchCityRow = load(\"views/searchCityRow.html\");\n private final String weather = load(\"views/weather.html\");\n private final String weatherRow = load(\"views/weatherRow.html\");\n\n private final ConcurrentHashMap<LatLog, CompletableFuture<String>>\n last30daysViewsCache = new ConcurrentHashMap<>();\n\n public WeatherController(WeatherService api) {\n this.api = api;\n try {\n this.root = getSystemResource(\".\").toURI().getPath();\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n }\n\n public String getSearch(HttpServletRequest req) {\n return getSearchView;\n }\n\n public String searchCity(HttpServletRequest req) {\n String city = req.getParameter(\"name\");\n String rows = api\n .search(city)\n .join()\n // Dispatch non-blocking request of Last 30 days weather\n .peek(l -> last30daysWeather(l.getLatitude(), l.getLongitude()))\n .map(l -> String.format(searchCityRow,\n l.getCountry(),\n l.getRegion(),\n linkForLocation(l)))\n .collect(Collectors.joining());\n return String.format(searchCityView, rows);\n }\n\n public String last30daysWeather(HttpServletRequest request) {\n String[] parts = request.getPathInfo().split(\"/\");\n double lat = Double.parseDouble(parts[1]);\n double log = Double.parseDouble(parts[2]);\n return last30daysWeather(lat, log).join();\n }\n\n public CompletableFuture<String> requestLast30daysWeather(double lat, double log) {\n return api\n .last30daysWeather(lat, log)\n .thenApply(past -> past\n .map(wi -> String.format(weatherRow,\n wi.getDate(),\n wi.getTempC(),\n wi.getFeelsLikeC(),\n wi.getDescription(),\n wi.getPrecipMM()))\n .collect(Collectors.joining()))\n .thenApply(rows -> String.format(weather, rows));\n }\n\n /**\n * First tries load from last30daysViewsCache.\n * If it does not exist look in file system: loadLast30daysWeather(lat, log);\n * Otherwise request to service: requestLast30daysWeather(lat, log);\n */\n private CompletableFuture<String> last30daysWeather(double lat, double log) {\n LatLog coords = new LatLog(lat, log);\n CompletableFuture<String> last30days = last30daysViewsCache.get(coords);\n if (last30days == null) {\n String view = loadLast30daysWeather(lat, log); // Search on file system\n if(view == null) { // Not in file system\n last30days = requestLast30daysWeather(lat, log) // Request to service\n .thenApply(v -> writeLast30daysWeather(lat, log, v)); // Save on disk\n }\n else { // Already in File System\n last30days = new CompletableFuture<>();\n last30days.complete(view);\n }\n last30daysViewsCache.putIfAbsent(coords, last30days); // Save on cache\n }\n return last30days;\n }\n\n private String loadLast30daysWeather(double lat, double log) {\n String path = root + lat + \"-\" + log + \".html\";\n File file = new File(path);\n URI uri = !file.exists() ? null : file.toURI();\n return uri == null ? null : load(uri);\n }\n\n private String writeLast30daysWeather(double lat, double log, String view) {\n try {\n String path = root + lat + \"-\" + log + \".html\";\n try (FileWriter fw = new FileWriter(path)) {\n fw.write(view);\n fw.flush();\n }\n }catch (IOException e) {\n throw new RuntimeException(e);\n }\n return view;\n }\n\n private static String linkForLocation(Location l) {\n return String.format(\"<a href=\\\"/weather/%s/%s/last30days/\\\">%s</a>\",\n l.getLatitude(), l.getLongitude(), l.getRegion());\n }\n\n private static String load(String path) {\n return load(ClassLoader.getSystemResource(path));\n }\n private static String load(URL url) {\n try {\n return load(url.toURI());\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n }\n private static String load(URI uri) {\n try {\n Path path = Paths.get(uri);\n return lines(path).collect(Collectors.joining());\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n private static final class LatLog {\n final double lat, log;\n public LatLog(double lat, double log) {\n this.lat = lat; this.log = log;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n LatLog latLog = (LatLog) o;\n\n if (Double.compare(latLog.lat, lat) != 0) return false;\n return Double.compare(latLog.log, log) == 0;\n\n }\n\n @Override\n public int hashCode() {\n int result;\n long temp;\n temp = Double.doubleToLongBits(lat);\n result = (int) (temp ^ (temp >>> 32));\n temp = Double.doubleToLongBits(log);\n result = 31 * result + (int) (temp ^ (temp >>> 32));\n return result;\n }\n }\n}",
"public class WeatherWebApi {\n\n private static final String WEATHER_TOKEN;\n private static final String WEATHER_HOST = \"http://api.worldweatheronline.com\";\n private static final String WEATHER_PAST = \"/premium/v1/past-weather.ashx\";\n private static final String WEATHER_PAST_ARGS =\n \"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s\";\n private static final String WEATHER_SEARCH=\"/premium/v1/search.ashx?query=%s\";\n private static final String WEATHER_SEARCH_ARGS=\"&format=tab&key=%s\";\n\n static {\n try {\n URL keyFile = ClassLoader.getSystemResource(\"worldweatheronline-app-key.txt\");\n if(keyFile == null) {\n throw new IllegalStateException(\n \"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt\");\n } else {\n InputStream keyStream = keyFile.openStream();\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {\n WEATHER_TOKEN = reader.readLine();\n }\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n private final IRequest req;\n\n public WeatherWebApi(IRequest req) {\n this.req = req;\n }\n\n /**\n * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****\n */\n\n public Iterable<LocationDto> search(String query) {\n String path = WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;\n String url = String.format(path, query, WEATHER_TOKEN);\n Iterable<String> content = () -> req.getContent(url).iterator();\n Iterable<String> iterable =\tfilter(content, (String s) -> !s.startsWith(\"#\"));\n return map(iterable, LocationDto::valueOf);\n }\n\n /**\n * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****\n */\n public Iterable<WeatherInfoDto> pastWeather(\n double lat,\n double log,\n LocalDate from,\n LocalDate to\n ) {\n String query = lat + \",\" + log;\n String path = WEATHER_HOST + WEATHER_PAST +\n String.format(WEATHER_PAST_ARGS, query, from, to, WEATHER_TOKEN);\n Iterable<String> content = () -> req.getContent(path).iterator();\n Iterable<String> stringIterable = filter(content, s->!s.startsWith(\"#\"));\n Iterable<String>filtered = skip(stringIterable,1);\t// Skip line: Not Available\n int[] counter = {0};\n Predicate<String> isEvenLine = item -> ++counter[0] % 2==0;\n filtered = filter(filtered,isEvenLine);//even lines filter\n return map(filtered, WeatherInfoDto::valueOf); //to weatherinfo objects\n }\n}"
] | import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletHolder;
import util.HttpRequest;
import util.HttpServer;
import weather.WeatherService;
import weather.WeatherServiceCache;
import weather.controllers.WeatherController;
import weather.data.WeatherWebApi;
import static java.lang.ClassLoader.getSystemResource; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* 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 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 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/>.
*/
package weather.app;
public class WeatherWebApp {
public static void main(String[] args) throws Exception {
try(HttpRequest http = new HttpRequest()) { | WeatherService service = new WeatherServiceCache(new WeatherWebApi(http)); | 2 |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/server/FetchIndexFromDb.java | [
"public class MalformedNanopubException extends Exception {\n\n\tprivate static final long serialVersionUID = -1022546557206977739L;\n\n\tpublic MalformedNanopubException(String message) {\n\t\tsuper(message);\n\t}\n\n}",
"public interface Nanopub {\n\n\t// URIs in the nanopub namespace:\n\tpublic static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI(\"http://www.nanopub.org/nschema#Nanopublication\");\n\tpublic static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI(\"http://www.nanopub.org/nschema#hasAssertion\");\n\tpublic static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI(\"http://www.nanopub.org/nschema#hasProvenance\");\n\tpublic static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI(\"http://www.nanopub.org/nschema#hasPublicationInfo\");\n\n\t// URIs that link nanopublications:\n\tpublic static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI(\"http://purl.org/nanopub/x/supersedes\");\n\n\tpublic IRI getUri();\n\n\tpublic IRI getHeadUri();\n\n\tpublic Set<Statement> getHead();\n\n\tpublic IRI getAssertionUri();\n\n\tpublic Set<Statement> getAssertion();\n\n\tpublic IRI getProvenanceUri();\n\n\tpublic Set<Statement> getProvenance();\n\n\tpublic IRI getPubinfoUri();\n\n\tpublic Set<Statement> getPubinfo();\n\n\tpublic Set<IRI> getGraphUris();\n\n\t// TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,\n\t// we might not need the following three methods anymore...\n\n\tpublic Calendar getCreationTime();\n\n\tpublic Set<IRI> getAuthors();\n\n\tpublic Set<IRI> getCreators();\n\n\tpublic int getTripleCount();\n\n\tpublic long getByteCount();\n\n}",
"public class NanopubUtils {\n\n\tprivate NanopubUtils() {} // no instances allowed\n\n\tprivate static final List<Pair<String,String>> defaultNamespaces = new ArrayList<>();\n\n\tstatic {\n\t\tdefaultNamespaces.add(Pair.of(\"rdf\", \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"));\n\t\tdefaultNamespaces.add(Pair.of(\"rdfs\", \"http://www.w3.org/2000/01/rdf-schema#\"));\n\t\tdefaultNamespaces.add(Pair.of(\"rdfg\", \"http://www.w3.org/2004/03/trix/rdfg-1/\"));\n\t\tdefaultNamespaces.add(Pair.of(\"xsd\", \"http://www.w3.org/2001/XMLSchema#\"));\n\t\tdefaultNamespaces.add(Pair.of(\"owl\", \"http://www.w3.org/2002/07/owl#\"));\n\t\tdefaultNamespaces.add(Pair.of(\"dct\", \"http://purl.org/dc/terms/\"));\n\t\tdefaultNamespaces.add(Pair.of(\"dce\", \"http://purl.org/dc/elements/1.1/\"));\n\t\tdefaultNamespaces.add(Pair.of(\"pav\", \"http://purl.org/pav/\"));\n\t\tdefaultNamespaces.add(Pair.of(\"prov\", \"http://www.w3.org/ns/prov#\"));\n\t\tdefaultNamespaces.add(Pair.of(\"np\", \"http://www.nanopub.org/nschema#\"));\n\t}\n\n\tpublic static List<Pair<String,String>> getDefaultNamespaces() {\n\t\treturn defaultNamespaces;\n\t}\n\n\tpublic static List<Statement> getStatements(Nanopub nanopub) {\n\t\tList<Statement> s = new ArrayList<>();\n\t\ts.addAll(getSortedList(nanopub.getHead()));\n\t\ts.addAll(getSortedList(nanopub.getAssertion()));\n\t\ts.addAll(getSortedList(nanopub.getProvenance()));\n\t\ts.addAll(getSortedList(nanopub.getPubinfo()));\n\t\treturn s;\n\t}\n\n\tprivate static List<Statement> getSortedList(Set<Statement> s) {\n\t\tList<Statement> l = new ArrayList<Statement>(s);\n\t\tCollections.sort(l, new Comparator<Statement>() {\n\n\t\t\t@Override\n\t\t\tpublic int compare(Statement st1, Statement st2) {\n\t\t\t\t// TODO better sorting\n\t\t\t\treturn st1.toString().compareTo(st2.toString());\n\t\t\t}\n\n\t\t});\n\t\treturn l;\n\t}\n\n\tpublic static void writeToStream(Nanopub nanopub, OutputStream out, RDFFormat format)\n\t\t\tthrows RDFHandlerException {\n\t\twriteNanopub(nanopub, format, new OutputStreamWriter(out, Charset.forName(\"UTF-8\")));\n\t}\n\n\tpublic static String writeToString(Nanopub nanopub, RDFFormat format) throws RDFHandlerException {\n\t\tStringWriter sw = new StringWriter();\n\t\twriteNanopub(nanopub, format, sw);\n\t\treturn sw.toString();\n\t}\n\n\tprivate static void writeNanopub(Nanopub nanopub, RDFFormat format, Writer writer)\n\t\t\tthrows RDFHandlerException {\n\t\tif (format.equals(TrustyNanopubUtils.STNP_FORMAT)) {\n\t\t\ttry {\n\t\t\t\twriter.write(TrustyNanopubUtils.getTrustyDigestString(nanopub));\n\t\t\t\twriter.flush();\n\t\t\t\twriter.close();\n\t\t\t} catch (IOException ex) {\n\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t}\n\t\t} else {\n\t\t\tRDFWriter rdfWriter = Rio.createWriter(format, writer);\n\t\t\tpropagateToHandler(nanopub, rdfWriter);\n\t\t}\n\t}\n\n\tpublic static void propagateToHandler(Nanopub nanopub, RDFHandler handler)\n\t\t\tthrows RDFHandlerException {\n\t\thandler.startRDF();\n\t\tif (nanopub instanceof NanopubWithNs && !((NanopubWithNs) nanopub).getNsPrefixes().isEmpty()) {\n\t\t\tNanopubWithNs np = (NanopubWithNs) nanopub;\n\t\t\tfor (String p : np.getNsPrefixes()) {\n\t\t\t\thandler.handleNamespace(p, np.getNamespace(p));\n\t\t\t}\n\t\t} else {\n\t\t\thandler.handleNamespace(\"this\", nanopub.getUri().toString());\n\t\t\tfor (Pair<String,String> p : defaultNamespaces) {\n\t\t\t\thandler.handleNamespace(p.getLeft(), p.getRight());\n\t\t\t}\n\t\t}\n\t\tfor (Statement st : getStatements(nanopub)) {\n\t\t\thandler.handleStatement(st);\n\t\t}\n\t\thandler.endRDF();\n\t}\n\n\tpublic static RDFParser getParser(RDFFormat format) {\n\t\tRDFParser p = Rio.createParser(format);\n\t\tp.getParserConfig().set(BasicParserSettings.NAMESPACES, new HashSet<Namespace>());\n\t\treturn p;\n\t}\n\n\tpublic static Set<String> getUsedPrefixes(NanopubWithNs np) {\n\t\tSet<String> usedPrefixes = new HashSet<String>();\n\t\tCustomTrigWriter writer = new CustomTrigWriter(usedPrefixes);\n\t\ttry {\n\t\t\tNanopubUtils.propagateToHandler(np, writer);\n\t\t} catch (RDFHandlerException ex) {\n\t\t\tex.printStackTrace();\n\t\t\treturn usedPrefixes;\n\t\t}\n\t\treturn usedPrefixes;\n\t}\n\n}",
"public class IndexUtils {\n\n\tprivate IndexUtils() {} // no instances allowed\n\n\tpublic static boolean isIndex(Nanopub np) {\n\t\tfor (Statement st : np.getPubinfo()) {\n\t\t\tif (!st.getSubject().equals(np.getUri())) continue;\n\t\t\tif (!st.getPredicate().equals(RDF.TYPE)) continue;\n\t\t\tif (!st.getObject().equals(NanopubIndex.NANOPUB_INDEX_URI)) continue;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic static NanopubIndex castToIndex(Nanopub np) throws MalformedNanopubException {\n\t\tif (np instanceof NanopubIndex) {\n\t\t\treturn (NanopubIndex) np;\n\t\t} else {\n\t\t\treturn new NanopubIndexImpl(np);\n\t\t}\n\t}\n\n}",
"public interface NanopubIndex extends Nanopub {\n\n\tpublic static final IRI NANOPUB_INDEX_URI = SimpleValueFactory.getInstance().createIRI(\"http://purl.org/nanopub/x/NanopubIndex\");\n\tpublic static final IRI INCOMPLETE_INDEX_URI = SimpleValueFactory.getInstance().createIRI(\"http://purl.org/nanopub/x/IncompleteIndex\");\n\tpublic static final IRI INDEX_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI(\"http://purl.org/nanopub/x/IndexAssertion\");\n\tpublic static final IRI INCLUDES_ELEMENT_URI = SimpleValueFactory.getInstance().createIRI(\"http://purl.org/nanopub/x/includesElement\");\n\tpublic static final IRI INCLUDES_SUBINDEX_URI = SimpleValueFactory.getInstance().createIRI(\"http://purl.org/nanopub/x/includesSubindex\");\n\tpublic static final IRI APPENDS_INDEX_URI = SimpleValueFactory.getInstance().createIRI(\"http://purl.org/nanopub/x/appendsIndex\");\n\n\tpublic static final int MAX_SIZE = 1000;\n\n\tpublic Set<IRI> getElements();\n\n\tpublic Set<IRI> getSubIndexes();\n\n\tpublic IRI getAppendedIndex();\n\n\tpublic boolean isIncomplete();\n\n\tpublic String getName();\n\n\tpublic String getDescription();\n\n\tpublic Set<IRI> getSeeAlsoUris();\n\n}"
] | import java.io.OutputStream;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubUtils;
import org.nanopub.extra.index.IndexUtils;
import org.nanopub.extra.index.NanopubIndex; | package org.nanopub.extra.server;
public class FetchIndexFromDb extends FetchIndex {
public static final int maxParallelRequestsPerServer = 5;
private String indexUri;
private NanopubDb db;
private OutputStream out;
private RDFFormat format;
private boolean writeIndex, writeContent;
private int nanopubCount;
private FetchIndex.Listener listener;
public FetchIndexFromDb(String indexUri, NanopubDb db, OutputStream out, RDFFormat format, boolean writeIndex, boolean writeContent) {
this.indexUri = indexUri;
this.db = db;
this.out = out;
this.format = format;
this.writeIndex = writeIndex;
this.writeContent = writeContent;
nanopubCount = 0;
}
public void run() {
try {
getIndex(indexUri);
} catch (RDFHandlerException | MalformedNanopubException ex) {
throw new RuntimeException(ex);
}
}
private void getIndex(String indexUri) throws RDFHandlerException, MalformedNanopubException {
NanopubIndex npi = getIndex(indexUri, db);
while (npi != null) {
if (writeIndex) {
writeNanopub(npi);
}
if (writeContent) {
for (IRI elementUri : npi.getElements()) {
writeNanopub(GetNanopub.get(elementUri.toString(), db));
}
}
for (IRI subIndexUri : npi.getSubIndexes()) {
getIndex(subIndexUri.toString());
}
if (npi.getAppendedIndex() != null) {
npi = getIndex(npi.getAppendedIndex().toString(), db);
} else {
npi = null;
}
}
}
private static NanopubIndex getIndex(String indexUri, NanopubDb db) throws MalformedNanopubException {
Nanopub np = GetNanopub.get(indexUri, db);
if (!IndexUtils.isIndex(np)) {
throw new RuntimeException("NOT AN INDEX: " + np.getUri());
}
return IndexUtils.castToIndex(np);
}
private void writeNanopub(Nanopub np) throws RDFHandlerException {
nanopubCount++;
if (listener != null && nanopubCount % 100 == 0) {
listener.progress(nanopubCount);
} | NanopubUtils.writeToStream(np, out, format); | 2 |
52North/geoar-app | src/main/java/org/n52/geoar/ar/view/ARFragment.java | [
"public class CheckList<T> extends ArrayList<T> {\r\n\r\n\tpublic interface OnCheckedChangedListener<T> {\r\n\t\tvoid onCheckedChanged(T item, boolean newState);\r\n\t}\r\n\r\n\tpublic interface OnItemChangedListener<T> {\r\n\t\tvoid onItemAdded(T item);\r\n\r\n\t\tvoid onItemRemoved(T item);\r\n\t}\r\n\r\n\tpublic static abstract class OnItemChangedListenerWrapper<T> implements\r\n\t\t\tOnItemChangedListener<T> {\r\n\t\tpublic void onItemAdded(T item) {\r\n\t\t\tonItemChanged();\r\n\t\t};\r\n\r\n\t\tpublic void onItemRemoved(T item) {\r\n\t\t\tonItemChanged();\r\n\t\t};\r\n\r\n\t\tpublic void onItemChanged() {\r\n\t\t};\r\n\t}\r\n\r\n\tclass Checker {\r\n\t\tprivate T item;\r\n\r\n\t\tprivate Checker(T item) {\r\n\t\t\tthis.item = item;\r\n\t\t}\r\n\r\n\t\tvoid setChecked(boolean state) {\r\n\t\t\tcheckItem(item, state);\r\n\t\t}\r\n\r\n\t\tboolean isChecked() {\r\n\t\t\treturn CheckList.this.isChecked(item);\r\n\t\t}\r\n\t}\r\n\r\n\t@Retention(RetentionPolicy.RUNTIME)\r\n\t@Target(ElementType.FIELD)\r\n\tpublic @interface CheckManager {\r\n\t}\r\n\r\n\t@Retention(RetentionPolicy.RUNTIME)\r\n\t@Target(ElementType.METHOD)\r\n\tpublic @interface CheckedChangedListener {\r\n\t}\r\n\r\n\tprivate static final long serialVersionUID = 1L;\r\n\tprivate Method checkedChangedMethod;\r\n\r\n\tprivate BitSet checkSet = new BitSet();\r\n\tprivate Set<OnCheckedChangedListener<T>> checkedChangeListeners = new HashSet<OnCheckedChangedListener<T>>();\r\n\tprivate Set<OnItemChangedListener<T>> itemChangeListeners = new HashSet<OnItemChangedListener<T>>();\r\n\r\n\tprivate Field checkManagerField;\r\n\r\n\tpublic CheckList(Class<?> itemClass) {\r\n\t\tfor (Field field : itemClass.getDeclaredFields()) {\r\n\t\t\tif (field.isAnnotationPresent(CheckManager.class)) {\r\n\t\t\t\tfield.setAccessible(true);\r\n\t\t\t\tcheckManagerField = field;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (Method method : itemClass.getDeclaredMethods()) {\r\n\t\t\tif (method.isAnnotationPresent(CheckedChangedListener.class)) {\r\n\t\t\t\tmethod.setAccessible(true);\r\n\t\t\t\tcheckedChangedMethod = method;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic CheckList() {\r\n\r\n\t}\r\n\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic <E> List<E> ofType(Class<E> clazz) {\r\n\t\tList<E> resultList = new ArrayList<E>();\r\n\r\n\t\tfor (T item : this) {\r\n\t\t\tif (clazz.isAssignableFrom(item.getClass())) {\r\n\t\t\t\tresultList.add((E) item);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn resultList;\r\n\t}\r\n\r\n\tpublic List<T> getCheckedItems() {\r\n\t\tList<T> resultList = new ArrayList<T>();\r\n\t\tfor (int i = 0; i < size(); i++) {\r\n\t\t\tif (checkSet.get(i))\r\n\t\t\t\tresultList.add(get(i));\r\n\t\t}\r\n\t\treturn resultList;\r\n\t}\r\n\t\r\n\r\n\tpublic List<T> getUncheckedItems() {\r\n\t\tList<T> resultList = new ArrayList<T>();\r\n\t\tfor (int i = 0; i < size(); i++) {\r\n\t\t\tif (!checkSet.get(i))\r\n\t\t\t\tresultList.add(get(i));\r\n\t\t}\r\n\t\treturn resultList;\r\n\t}\r\n\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic <E> List<E> getCheckedItems(Class<E> clazz) {\r\n\t\tList<E> resultList = new ArrayList<E>();\r\n\t\tfor (int i = 0; i < size(); i++) {\r\n\t\t\tif (checkSet.get(i)) {\r\n\t\t\t\tT item = get(i);\r\n\t\t\t\tif (clazz.isAssignableFrom(item.getClass())) {\r\n\t\t\t\t\tresultList.add((E) item);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn resultList;\r\n\t}\r\n\r\n\tpublic void checkItem(int index, boolean state) {\r\n\t\tboolean changed = checkSet.get(index) != state;\r\n\t\tT item = get(index);\r\n\t\tcheckSet.set(index, state);\r\n\t\tif (changed) {\r\n\t\t\ttry {\r\n\t\t\t\tif (checkedChangedMethod != null) {\r\n\t\t\t\t\tcheckedChangedMethod.invoke(item, state);\r\n\t\t\t\t}\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tthrow new RuntimeException(e);\r\n\t\t\t}\r\n\t\t\tnotifyCheckedChanged(item, state);\t\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void add(int index, T object) {\r\n\t\tinjectFields(object);\r\n\t\tsuper.add(index, object);\r\n\t\tnotifyItemAdded(object);\r\n\t};\r\n\r\n\t@Override\r\n\tpublic boolean add(T object) {\r\n\t\tinjectFields(object);\r\n\t\tboolean changed = super.add(object);\r\n\t\tnotifyItemAdded(object);\r\n\t\treturn changed;\r\n\t};\r\n\r\n\tpublic void add(T object, boolean state) {\r\n\t\tadd(object);\r\n\t\tcheckItem(object, state);\r\n\t}\r\n\r\n\tprivate void injectFields(T object) {\r\n\t\ttry {\r\n\t\t\tif (checkManagerField != null) {\r\n\t\t\t\tif (checkManagerField.get(object) != null) {\r\n\t\t\t\t\tthrow new RuntimeException(\r\n\t\t\t\t\t\t\t\"This item is already element of a CheckList!\");\r\n\t\t\t\t}\r\n\t\t\t\tcheckManagerField.set(object, new Checker(object));\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RuntimeException(e);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void checkItem(T item, boolean state) {\r\n\t\tif (contains(item)) {\r\n\t\t\tcheckItem(this.indexOf(item), state);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void checkItem(T item) {\r\n\t\tcheckItem(item, true);\r\n\t}\r\n\r\n\tprivate void notifyCheckedChanged(T item, boolean newState) {\r\n\t\tfor (OnCheckedChangedListener<T> listener : checkedChangeListeners) {\r\n\t\t\tlistener.onCheckedChanged(item, newState);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void notifyItemAdded(T item) {\r\n\t\tfor (OnItemChangedListener<T> listener : itemChangeListeners) {\r\n\t\t\tlistener.onItemAdded(item);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void notifyItemRemoved(T item) {\r\n\t\tfor (OnItemChangedListener<T> listener : itemChangeListeners) {\r\n\t\t\tlistener.onItemRemoved(item);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void addOnCheckedChangeListener(OnCheckedChangedListener<T> listener) {\r\n\t\tcheckedChangeListeners.add(listener);\r\n\t}\r\n\r\n\tpublic void removeOnCheckedChangeListener(\r\n\t\t\tOnCheckedChangedListener<T> listener) {\r\n\t\tcheckedChangeListeners.remove(listener);\r\n\t}\r\n\r\n\tpublic void addOnItemChangeListener(OnItemChangedListener<T> listener) {\r\n\t\titemChangeListeners.add(listener);\r\n\t}\r\n\r\n\tpublic void removeOnItemChangeListener(OnItemChangedListener<T> listener) {\r\n\t\titemChangeListeners.remove(listener);\r\n\t}\r\n\r\n\tpublic boolean isChecked(T item) {\r\n\t\tint index = indexOf(item);\r\n\t\treturn isChecked(index);\r\n\t}\r\n\r\n\tpublic boolean isChecked(int index) {\r\n\t\tif (index >= 0) {\r\n\t\t\treturn checkSet.get(index);\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic T remove(int index) {\r\n\t\tfor (int i = index, len = size() - 1; i < len; i++) {\r\n\t\t\tcheckSet.set(index, checkSet.get(i + 1));\r\n\t\t}\r\n\t\tcheckSet.set(size() - 1, false);\r\n\t\tT item = super.remove(index);\r\n\t\ttry {\r\n\t\t\tif (checkManagerField != null) {\r\n\t\t\t\tcheckManagerField.set(item, null);\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RuntimeException(e);\r\n\t\t}\r\n\t\tnotifyItemRemoved(item);\r\n\t\treturn item;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean remove(Object object) {\r\n\t\tint index = indexOf(object);\r\n\t\tif (index >= 0) {\r\n\t\t\treturn remove(index) != null;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean removeAll(Collection<?> collection) {\r\n\t\tthrow new UnsupportedOperationException();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void clear() {\r\n\t\tcheckSet.clear();\r\n\t\tsuper.clear();\r\n\t\tnotifyItemRemoved(null);\r\n\t}\r\n\r\n\tpublic void checkAll(boolean state) {\r\n\t\tfor (int i = 0, len = size(); i < len; i++) {\r\n\t\t\tcheckItem(i, state);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic boolean hasChecked() {\r\n\t\treturn checkSet.cardinality() > 0;\r\n\t}\r\n\t\r\n\tpublic boolean allChecked() {\r\n\t\treturn checkSet.cardinality() == size();\r\n\t}\r\n}\r",
"public class DataSourceHolder implements Parcelable {\r\n\tpublic static final Parcelable.Creator<DataSourceHolder> CREATOR = new Parcelable.Creator<DataSourceHolder>() {\r\n\t\t@Override\r\n\t\tpublic DataSourceHolder createFromParcel(Parcel in) {\r\n\t\t\tint id = in.readInt();\r\n\t\t\t// Find DataSourceHolder with provided id\r\n\t\t\tfor (DataSourceHolder holder : PluginLoader.getDataSources()) {\r\n\t\t\t\tif (holder.id == id) {\r\n\t\t\t\t\treturn holder;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic DataSourceHolder[] newArray(int size) {\r\n\t\t\treturn new DataSourceHolder[size];\r\n\t\t}\r\n\t};\r\n\tprivate static final int CLEAR_CACHE = 1;\r\n\tprivate static final int CLEAR_CACHE_AFTER_DEACTIVATION_DELAY = 10000;\r\n\tprivate static final Logger LOG = LoggerFactory\r\n\t\t\t.getLogger(DataSourceHolder.class);\r\n\r\n\tprivate static int nextId = 0;\r\n\tprivate static Map<Class<? extends Visualization>, Visualization> visualizationMap = new HashMap<Class<? extends Visualization>, Visualization>();\r\n\tprivate byte cacheZoomLevel;\r\n\tprivate Class<? extends DataSource<? super Filter>> dataSourceClass;\r\n\r\n\tprivate Handler dataSourceHandler = new Handler(new Handler.Callback() {\r\n\t\t@Override\r\n\t\tpublic boolean handleMessage(Message msg) {\r\n\t\t\tif (msg.what == CLEAR_CACHE) {\r\n\t\t\t\t// Delayed clearing of cache after datasource has been\r\n\t\t\t\t// deactivated\r\n\t\t\t\tfor (DataSourceInstanceHolder instance : mDataSourceInstances) {\r\n\t\t\t\t\tinstance.deactivate();\r\n\t\t\t\t}\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t});\r\n\tprivate String description;\r\n\r\n\tprivate Class<? extends Filter> filterClass;\r\n\tprivate final int id = nextId++;\r\n\r\n\tprivate byte maxZoomLevel;\r\n\tprivate CheckList<DataSourceInstanceHolder> mDataSourceInstances;\r\n\r\n\tprivate long minReloadInterval;\r\n\tprivate boolean mInstanceable;\r\n\tprivate byte minZoomLevel;\r\n\tprivate InstalledPluginHolder mPluginHolder;\r\n\tprivate String name;\r\n\r\n\tprivate CheckList<Visualization> visualizations;\r\n\tprivate Method nameCallbackMethod;\r\n\r\n\t/**\r\n\t * Wrapper for a {@link DataSource}. Provides access to general settings of\r\n\t * a data source, as well as its {@link Filter} implementation and supported\r\n\t * {@link Visualization}s. This holder also maintains the state of a\r\n\t * {@link DataSource} as it automatically activates and deactivates a data\r\n\t * source and clears its {@link DataCache} if required.\r\n\t * \r\n\t * @param dataSourceClass\r\n\t * @param pluginHolder\r\n\t * {@link InstalledPluginHolder} containing this data source\r\n\t */\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic DataSourceHolder(\r\n\t\t\tClass<? extends DataSource<? super Filter>> dataSourceClass,\r\n\t\t\tInstalledPluginHolder pluginHolder) {\r\n\t\tthis.mPluginHolder = pluginHolder;\r\n\t\tthis.dataSourceClass = dataSourceClass;\r\n\t\tAnnotations.DataSource dataSourceAnnotation = dataSourceClass\r\n\t\t\t\t.getAnnotation(Annotations.DataSource.class);\r\n\t\tif (dataSourceAnnotation == null) {\r\n\t\t\tthrow new RuntimeException(\"Class not annotated as datasource\");\r\n\t\t}\r\n\t\tmInstanceable = SettingsHelper.hasSettings(dataSourceClass);\r\n\r\n\t\tif (dataSourceAnnotation.name().resId() >= 0) {\r\n\t\t\tname = pluginHolder.getPluginContext().getString(\r\n\t\t\t\t\tdataSourceAnnotation.name().resId());\r\n\t\t} else {\r\n\t\t\tname = dataSourceAnnotation.name().value();\r\n\t\t}\r\n\t\tdescription = dataSourceAnnotation.description();\r\n\t\tminReloadInterval = dataSourceAnnotation.minReloadInterval();\r\n\t\tcacheZoomLevel = dataSourceAnnotation.cacheZoomLevel();\r\n\t\tminZoomLevel = dataSourceAnnotation.minZoomLevel();\r\n\t\tmaxZoomLevel = dataSourceAnnotation.maxZoomLevel();\r\n\r\n\t\t// Find name callback\r\n\t\tfor (Method method : dataSourceClass.getMethods()) {\r\n\t\t\tif (method.isAnnotationPresent(Annotations.NameCallback.class)) {\r\n\t\t\t\tif (String.class.isAssignableFrom(method.getReturnType())) {\r\n\t\t\t\t\tnameCallbackMethod = method;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tLOG.error(\"Data source \" + name\r\n\t\t\t\t\t\t\t+ \" has an invalid NameCallback\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Find filter by getting the actual generic parameter type of the\r\n\t\t// implemented DataSource interface\r\n\r\n\t\tClass<?> currentClass = dataSourceClass;\r\n\t\twhile (currentClass != null) {\r\n\t\t\tType[] interfaces = currentClass.getGenericInterfaces();\r\n\t\t\tfor (Type interfaceType : interfaces) {\r\n\t\t\t\tParameterizedType type = (ParameterizedType) interfaceType;\r\n\t\t\t\tif (!type.getRawType().equals(DataSource.class)) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfilterClass = (Class<? extends Filter>) type\r\n\t\t\t\t\t\t.getActualTypeArguments()[0];\r\n\r\n\t\t\t}\r\n\r\n\t\t\tif (filterClass == null) {\r\n\t\t\t\tcurrentClass = currentClass.getSuperclass();\r\n\t\t\t} else {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (filterClass == null) {\r\n\t\t\tthrow new RuntimeException(\r\n\t\t\t\t\t\"Data source does not specify a filter class\");\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate void createDefaultInstances() {\r\n\t\tif (!instanceable()) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tDefaultInstances defaultInstances = dataSourceClass\r\n\t\t\t\t.getAnnotation(DefaultInstances.class);\r\n\t\tif (defaultInstances == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tsettingsSets: for (DefaultSettingsSet defaultSettingsSet : defaultInstances\r\n\t\t\t\t.value()) {\r\n\t\t\tfor (DataSourceInstanceHolder instance : getInstances()) {\r\n\t\t\t\tif (SettingsHelper.isEqualSettings(defaultSettingsSet,\r\n\t\t\t\t\t\tinstance.getDataSource())) {\r\n\t\t\t\t\tcontinue settingsSets;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tDataSourceInstanceHolder instance = addInstance();\r\n\t\t\tSettingsHelper.applyDefaultSettings(defaultSettingsSet,\r\n\t\t\t\t\tinstance.getDataSource());\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * Prevents datasource from getting unloaded. Should be called when\r\n\t * datasource is added to map/ar.\r\n\t */\r\n\t@Deprecated\r\n\tpublic void activate() {\r\n\t\tLOG.info(\"Activating data source \" + getName());\r\n\r\n\t\t// prevents clearing of cache by removing messages\r\n\t\tdataSourceHandler.removeMessages(CLEAR_CACHE);\r\n\t}\r\n\r\n\tpublic boolean areAllChecked() {\r\n\t\treturn mDataSourceInstances.allChecked();\r\n\t}\r\n\r\n\t/**\r\n\t * Queues unloading of datasource and cached data\r\n\t */\r\n\t@Deprecated\r\n\tpublic void deactivate() {\r\n\t\tLOG.info(\"Deactivating data source \" + getName());\r\n\t\tdataSourceHandler.sendMessageDelayed(\r\n\t\t\t\tdataSourceHandler.obtainMessage(CLEAR_CACHE),\r\n\t\t\t\tCLEAR_CACHE_AFTER_DEACTIVATION_DELAY);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int describeContents() {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tpublic byte getCacheZoomLevel() {\r\n\t\treturn cacheZoomLevel;\r\n\t}\r\n\r\n\tpublic String getDescription() {\r\n\t\treturn description;\r\n\t}\r\n\r\n\tpublic Class<? extends Filter> getFilterClass() {\r\n\t\treturn filterClass;\r\n\t}\r\n\r\n\tpublic String getIdentifier() {\r\n\t\treturn dataSourceClass.getSimpleName();\r\n\t}\r\n\r\n\tpublic CheckList<DataSourceInstanceHolder> getInstances() {\r\n\t\tif (mDataSourceInstances == null) {\r\n\t\t\tinitializeInstances();\r\n\t\t}\r\n\t\treturn mDataSourceInstances;\r\n\t}\r\n\t\r\n\tpublic InstalledPluginHolder getPluginHolder() {\r\n\t\treturn mPluginHolder;\r\n\t}\r\n\r\n\t/**\r\n\t * Should be called after all state initialization took place, e.g. after\r\n\t * {@link DataSourceHolder#restoreState(PluginStateInputStream)}\r\n\t */\r\n\tvoid postConstruct() {\r\n\t\tcreateDefaultInstances();\r\n\t}\r\n\r\n\tpublic byte getMaxZoomLevel() {\r\n\t\treturn maxZoomLevel;\r\n\t}\r\n\r\n\tpublic long getMinReloadInterval() {\r\n\t\treturn minReloadInterval;\r\n\t}\r\n\r\n\tpublic byte getMinZoomLevel() {\r\n\t\treturn minZoomLevel;\r\n\t}\r\n\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\r\n\tpublic Method getNameCallbackMethod() {\r\n\t\treturn nameCallbackMethod;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns {@link Visualization}s supported by this data source.\r\n\t * \r\n\t * As {@link DataSource}s get lazily initialized, this method will not\r\n\t * return any {@link Visualization}s until the underlying {@link DataSource}\r\n\t * is accessed, e.g. by {@link DataSourceHolder#getDataSource()}.\r\n\t * \r\n\t * @return\r\n\t */\r\n\tpublic CheckList<Visualization> getVisualizations() {\r\n\t\tif (visualizations == null) {\r\n\t\t\tinitializeVisualizations();\r\n\t\t}\r\n\t\treturn visualizations;\r\n\t}\r\n\r\n\t/**\r\n\t * Indicates whether the represented data source can handle multiple\r\n\t * instances\r\n\t * \r\n\t * @return\r\n\t */\r\n\tpublic boolean instanceable() {\r\n\t\treturn mInstanceable;\r\n\t}\r\n\r\n\t/**\r\n\t * Method which injects all fields with GeoAR-{@link Annotations} and\r\n\t * finally calls the {@link PostConstruct} method (if available) for any\r\n\t * object.\r\n\t * \r\n\t * @param target\r\n\t * Any object\r\n\t */\r\n\tpublic void perfomInjection(Object target) {\r\n\t\t// Field injection\r\n\t\ttry {\r\n\t\t\tClass<? extends Object> currentClass = target.getClass();\r\n\t\t\twhile (currentClass != null) {\r\n\t\t\t\tfor (Field f : currentClass.getDeclaredFields()) {\r\n\t\t\t\t\tif (f.isAnnotationPresent(SystemService.class)) {\r\n\t\t\t\t\t\tString serviceName = f.getAnnotation(\r\n\t\t\t\t\t\t\t\tSystemService.class).value();\r\n\t\t\t\t\t\tf.setAccessible(true);\r\n\t\t\t\t\t\tf.set(target, mPluginHolder.getPluginContext()\r\n\t\t\t\t\t\t\t\t.getSystemService(serviceName));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (f.isAnnotationPresent(SharedHttpClient.class)) {\r\n\t\t\t\t\t\tf.setAccessible(true);\r\n\t\t\t\t\t\tf.set(target, PluginLoader.getSharedHttpClient());\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (f.isAnnotationPresent(Annotations.PluginContext.class)) {\r\n\t\t\t\t\t\tf.setAccessible(true);\r\n\t\t\t\t\t\tf.set(target, mPluginHolder.getPluginContext());\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (f.isAnnotationPresent(Annotations.SharedGeometryFactory.class)) {\r\n\t\t\t\t\t f.setAccessible(true);\r\n\t\t\t\t\t f.set(target, PluginLoader.getGeometryFactory());\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\tcurrentClass = currentClass.getSuperclass();\r\n\t\t\t}\r\n\t\t} catch (IllegalArgumentException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t} catch (IllegalAccessException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t} catch (LinkageError e) {\r\n\t\t\tLOG.error(\"Data source \" + getName() + \" uses invalid class, \"\r\n\t\t\t\t\t+ e.getMessage());\r\n\t\t}\r\n\r\n\t\t// Post construct\r\n\t\ttry {\r\n\t\t\tClass<? extends Object> currentClass = target.getClass();\r\n\t\t\twhile (currentClass != null) {\r\n\t\t\t\tfor (Method m : currentClass.getDeclaredMethods()) {\r\n\t\t\t\t\tif (m.isAnnotationPresent(PostConstruct.class)) {\r\n\t\t\t\t\t\tm.setAccessible(true);\r\n\t\t\t\t\t\tm.invoke(target);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcurrentClass = currentClass.getSuperclass();\r\n\t\t\t}\r\n\t\t} catch (InvocationTargetException e) {\r\n\t\t\tLOG.error(\"Data source \" + getName()\r\n\t\t\t\t\t+ \" has an error in its PostConstruct method\", e);\r\n\t\t} catch (IllegalArgumentException e) {\r\n\t\t\tLOG.error(\"Data source \" + getName()\r\n\t\t\t\t\t+ \" has invalid PostConstruct arguments\", e);\r\n\t\t} catch (IllegalAccessException e) {\r\n\t\t\tLOG.error(\"Data source \" + getName()\r\n\t\t\t\t\t+ \" has an invalid PostConstruct method\", e);\r\n\t\t} catch (RuntimeException e) {\r\n\t\t\tLOG.error(\"Data source \" + getName()\r\n\t\t\t\t\t+ \" raised an exception in its PostConstruct method\", e);\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void restoreState(PluginStateInputStream objectInputStream)\r\n\t\t\tthrows IOException {\r\n\t\tobjectInputStream.setPluginClassLoader(mPluginHolder\r\n\t\t\t\t.getPluginClassLoader());\r\n\t\tif (!mInstanceable) {\r\n\t\t\tboolean checked = objectInputStream.readBoolean();\r\n\t\t\tif (checked || mDataSourceInstances != null) {\r\n\t\t\t\t// Set saved state if instance was checked or if it is already\r\n\t\t\t\t// initialized\r\n\t\t\t\tif (!getInstances().isEmpty()) {\r\n\t\t\t\t\tgetInstances().get(0).setChecked(checked);\r\n\t\t\t\t\tgetInstances().get(0).restoreState(objectInputStream);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\r\n\t\t\tint instancesCount = objectInputStream.readInt();\r\n\t\t\tfor (int i = 0; i < instancesCount; i++) {\r\n\t\t\t\tDataSourceInstanceHolder dataSourceInstance = addInstance();\r\n\t\t\t\tdataSourceInstance.restoreState(objectInputStream);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void saveState(ObjectOutputStream objectOutputStream)\r\n\t\t\tthrows IOException {\r\n\t\tif (!mInstanceable) {\r\n\t\t\t// TODO ensure size == 1\r\n\t\t\tobjectOutputStream.writeBoolean(mDataSourceInstances != null\r\n\t\t\t\t\t&& mDataSourceInstances.get(0).isChecked());\r\n\t\t\tmDataSourceInstances.get(0).saveState(objectOutputStream);\r\n\t\t} else {\r\n\t\t\tobjectOutputStream.writeInt(mDataSourceInstances.size());\r\n\t\t\tfor (DataSourceInstanceHolder dataSourceInstance : mDataSourceInstances) {\r\n\t\t\t\tdataSourceInstance.saveState(objectOutputStream);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Calling this method affects all {@link DataSourceInstanceHolder} of this\r\n\t * object\r\n\t * \r\n\t * @param state\r\n\t */\r\n\tpublic void setChecked(boolean state) {\r\n\t\tif (mDataSourceInstances != null) {\r\n\t\t\tmDataSourceInstances.checkAll(state);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void writeToParcel(Parcel dest, int flags) {\r\n\t\t// Parcel based on unique internal DataSourceHolder id\r\n\t\tdest.writeInt(id);\r\n\t}\r\n\r\n\t/**\r\n\t * Lazily loads the instances of this data source. If it is not\r\n\t * {@link DataSourceHolder#instanceable()}, a default single instance will\r\n\t * be created.\r\n\t */\r\n\tprivate void initializeInstances() {\r\n\t\tmDataSourceInstances = new CheckList<DataSourceInstanceHolder>(\r\n\t\t\t\tDataSourceInstanceHolder.class);\r\n\r\n\t\tif (!mInstanceable) {\r\n\t\t\t// data source has no instance-specific settings, create the single\r\n\t\t\t// instance\r\n\t\t\tLOG.info(\"Creating single-instance data source instance \"\r\n\t\t\t\t\t+ getName());\r\n\t\t\taddInstance();\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Lazily loads all supported {@link Visualization}s of this data source.\r\n\t * {@link Visualization} are shared for all data sources.\r\n\t */\r\n\tprivate void initializeVisualizations() {\r\n\t\tvisualizations = new CheckList<Visualization>();\r\n\r\n\t\tSupportedVisualization supportedVisualization = dataSourceClass\r\n\t\t\t\t.getAnnotation(SupportedVisualization.class);\r\n\t\tif (supportedVisualization != null) {\r\n\t\t\tClass<? extends Visualization>[] visualizationClasses = supportedVisualization\r\n\t\t\t\t\t.visualizationClasses();\r\n\r\n\t\t\ttry {\r\n\t\t\t\tfor (int i = 0; i < visualizationClasses.length; i++) {\r\n\t\t\t\t\t// Find cached instance or create new one\r\n\t\t\t\t\tVisualization v = visualizationMap\r\n\t\t\t\t\t\t\t.get(visualizationClasses[i]);\r\n\t\t\t\t\tif (v == null) {\r\n\t\t\t\t\t\t// New instance needed\r\n\t\t\t\t\t\tv = visualizationClasses[i].newInstance();\r\n\t\t\t\t\t\tperfomInjection(v);\r\n\t\t\t\t\t\tvisualizationMap.put(visualizationClasses[i], v);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tvisualizations.add(v);\r\n\t\t\t\t\tvisualizations.checkItem(v); // TODO\r\n\t\t\t\t}\r\n\t\t\t} catch (InstantiationException e) {\r\n\t\t\t\tthrow new RuntimeException(\r\n\t\t\t\t\t\t\"Referenced visualization has no appropriate constructor\");\r\n\t\t\t} catch (IllegalAccessException e) {\r\n\t\t\t\tthrow new RuntimeException(\r\n\t\t\t\t\t\t\"Referenced visualization has no appropriate constructor\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate DataSourceInstanceHolder addInstance() {\r\n\t\tif (mDataSourceInstances == null) {\r\n\t\t\tinitializeInstances();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tDataSource<? super Filter> dataSource = dataSourceClass\r\n\t\t\t\t\t.newInstance();\r\n\t\t\t// perfomInjection(dataSource);\r\n\t\t\tfinal DataSourceInstanceHolder instance = new DataSourceInstanceHolder(\r\n\t\t\t\t\tthis, dataSource);\r\n\t\t\tmDataSourceInstances.add(instance);\r\n\t\t\treturn instance;\r\n\t\t} catch (InstantiationException e) {\r\n\t\t\tthrow new RuntimeException(\"No default constructor for datasource\");\r\n\t\t} catch (IllegalAccessException e) {\r\n\t\t\tthrow new RuntimeException(\"No valid constructor for datasource\");\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void addInstance(Context context) {\r\n\t\tfinal DataSourceInstanceHolder instance = addInstance();\r\n\r\n\t\tSettingsResultListener resultListener = new SettingsResultListener() {\r\n\t\t\t@Override\r\n\t\t\tvoid onSettingsResult(int resultCode) {\r\n\t\t\t\tif (resultCode == Activity.RESULT_OK) {\r\n\t\t\t\t\tinstance.notifySettingsChanged();\r\n\t\t\t\t\tinstance.setChecked(true);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\tIntent intent = new Intent(context,\r\n\t\t\t\tDataSourceInstanceSettingsDialogActivity.class);\r\n\t\tintent.putExtra(\"dataSourceInstance\", instance);\r\n\t\tintent.putExtra(\"resultListener\", resultListener);\r\n\t\tcontext.startActivity(intent);\r\n\t}\r\n\r\n\tpublic void removeUncheckedInstances() {\r\n\t\tif (!mInstanceable) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tArrayList<DataSourceInstanceHolder> uncheckedInstances = new ArrayList<DataSourceInstanceHolder>(\r\n\t\t\t\tmDataSourceInstances.getUncheckedItems());\r\n\t\tfor (DataSourceInstanceHolder dataSourceInstance : uncheckedInstances) {\r\n\t\t\tmDataSourceInstances.remove(dataSourceInstance);\r\n\t\t}\r\n\t}\r\n\r\n}",
"public class DataSourceInstanceHolder implements Parcelable {\r\n\r\n\tpublic interface DataSourceSettingsChangedListener {\r\n\t\tvoid onDataSourceSettingsChanged();\r\n\t}\r\n\r\n\tprivate static int nextId = 0;\r\n\tprivate static final int CLEAR_CACHE = 1;\r\n\tprivate static final int CLEAR_CACHE_AFTER_DEACTIVATION_DELAY = 10000;\r\n\tprivate static final Logger LOG = LoggerFactory\r\n\t\t\t.getLogger(DataSourceInstanceHolder.class);\r\n\r\n\tprivate Handler dataSourceHandler = new Handler(new Handler.Callback() {\r\n\t\t@Override\r\n\t\tpublic boolean handleMessage(Message msg) {\r\n\t\t\tif (msg.what == CLEAR_CACHE) {\r\n\t\t\t\t// Delayed clearing of cache after datasource has been\r\n\t\t\t\t// deactivated\r\n\t\t\t\tdataCache.clearCache();\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t});\r\n\tprivate DataSource<? super Filter> dataSource;\r\n\tprivate boolean injected = false;\r\n\tprivate DataSourceHolder parentHolder;\r\n\tprivate final int id = nextId++;\r\n\tprivate DataCache dataCache;\r\n\tprivate Filter currentFilter;\r\n\tprivate Boolean hasSettings = null;\r\n\t@CheckManager\r\n\tprivate CheckList<DataSourceInstanceHolder>.Checker mChecker;\r\n\tprivate Exception lastError;\r\n\tprivate Set<DataSourceSettingsChangedListener> mSettingsChangedListeners = new HashSet<DataSourceInstanceHolder.DataSourceSettingsChangedListener>(\r\n\t\t\t0);\r\n\r\n\tpublic DataSourceInstanceHolder(DataSourceHolder parentHolder,\r\n\t\t\tDataSource<? super Filter> dataSource) {\r\n\t\tthis.parentHolder = parentHolder;\r\n\t\tthis.dataSource = dataSource;\r\n\t\ttry {\r\n\t\t\tthis.currentFilter = parentHolder.getFilterClass().newInstance();\r\n\t\t} catch (InstantiationException e) {\r\n\t\t\tthrow new RuntimeException(\r\n\t\t\t\t\t\"Referenced filter has no appropriate constructor\");\r\n\t\t} catch (IllegalAccessException e) {\r\n\t\t\tthrow new RuntimeException(\r\n\t\t\t\t\t\"Referenced filter has no appropriate constructor\");\r\n\t\t}\r\n\r\n\t\tdataCache = new DataCache(this);\r\n\t}\r\n\r\n\t@CheckedChangedListener\r\n\tpublic void checkedChanged(boolean state) {\r\n\t\tif (state) {\r\n\t\t\tactivate();\r\n\t\t} else {\r\n\t\t\tdeactivate();\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Prevents datasource from getting unloaded. Should be called when\r\n\t * datasource is added to map/ar.\r\n\t */\r\n\tpublic void activate() {\r\n\t\tLOG.info(\"Activating data source instance \" + getName());\r\n\r\n\t\t// prevents clearing of cache by removing messages\r\n\t\tdataSourceHandler.removeMessages(CLEAR_CACHE);\r\n\t\tif (!injected) {\r\n\t\t\tparentHolder.perfomInjection(dataSource);\r\n\t\t\tinjected = true;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Queues unloading of datasource and cached data\r\n\t */\r\n\tpublic void deactivate() {\r\n\t\t// Clears the cache 30s after calling this method\r\n\t\tLOG.info(\"Deactivating data source \" + getName());\r\n\t\tdataSourceHandler.sendMessageDelayed(\r\n\t\t\t\tdataSourceHandler.obtainMessage(CLEAR_CACHE),\r\n\t\t\t\tCLEAR_CACHE_AFTER_DEACTIVATION_DELAY);\r\n\t}\r\n\r\n\tpublic DataCache getDataCache() {\r\n\t\treturn dataCache;\r\n\t}\r\n\r\n\tpublic void createSettingsDialog(Context context) {\r\n\t\tSettingsResultListener resultListener = new SettingsResultListener() {\r\n\t\t\t@Override\r\n\t\t\tvoid onSettingsResult(int resultCode) {\r\n\t\t\t\tif (resultCode == Activity.RESULT_OK) {\r\n\t\t\t\t\tnotifySettingsChanged();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\tIntent intent = new Intent(context,\r\n\t\t\t\tDataSourceInstanceSettingsDialogActivity.class);\r\n\t\tintent.putExtra(\"dataSourceInstance\", this);\r\n\t\tintent.putExtra(\"resultListener\", resultListener); // unsure whether\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Intent uses weak\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// references too\r\n\t\tcontext.startActivity(intent);\r\n\t}\r\n\r\n\tpublic Filter getCurrentFilter() {\r\n\t\treturn currentFilter;\r\n\t}\r\n\r\n\tpublic DataSourceHolder getParent() {\r\n\t\treturn parentHolder;\r\n\t}\r\n\r\n\tpublic void addOnSettingsChangedListener(\r\n\t\t\tDataSourceSettingsChangedListener listener) {\r\n\t\tmSettingsChangedListeners.add(listener);\r\n\t}\r\n\r\n\tpublic void removeOnSettingsChangedListener(\r\n\t\t\tDataSourceSettingsChangedListener listener) {\r\n\t\tmSettingsChangedListeners.remove(listener);\r\n\t}\r\n\r\n\t/**\r\n\t * It does not only notify listeners, but also clears the current cache.\r\n\t * TODO\r\n\t */\r\n\tvoid notifySettingsChanged() {\r\n\t\tdataCache.setFilter(currentFilter);\r\n\t\tfor (DataSourceSettingsChangedListener listener : mSettingsChangedListeners) {\r\n\t\t\tlistener.onDataSourceSettingsChanged();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic String getName() {\r\n\t\tif (parentHolder.getNameCallbackMethod() != null) {\r\n\t\t\t// try to use name callback\r\n\t\t\ttry {\r\n\t\t\t\treturn (String) parentHolder.getNameCallbackMethod().invoke(\r\n\t\t\t\t\t\tdataSource);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tLOG.warn(\"Data Source \" + parentHolder.getName()\r\n\t\t\t\t\t\t+ \" NameCallback fails\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (parentHolder.instanceable()) {\r\n\t\t\treturn parentHolder.getName() + \" \" + id;\r\n\t\t} else {\r\n\t\t\treturn parentHolder.getName();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic DataSource<? super Filter> getDataSource() {\r\n\t\treturn dataSource;\r\n\t}\r\n\r\n\tpublic boolean hasSettings() {\r\n\t\tif (hasSettings == null) {\r\n\t\t\thasSettings = SettingsHelper.hasSettings(getCurrentFilter())\r\n\t\t\t\t\t|| SettingsHelper.hasSettings(getDataSource());\r\n\t\t}\r\n\r\n\t\treturn hasSettings;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int describeContents() {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void writeToParcel(Parcel dest, int flags) {\r\n\t\t// Parcel based on unique DataSourceHolder id\r\n\t\tdest.writeParcelable(parentHolder, 0);\r\n\t\tdest.writeInt(id);\r\n\t}\r\n\r\n\tpublic static final Parcelable.Creator<DataSourceInstanceHolder> CREATOR = new Parcelable.Creator<DataSourceInstanceHolder>() {\r\n\t\tpublic DataSourceInstanceHolder createFromParcel(Parcel in) {\r\n\t\t\tDataSourceHolder dataSource = in\r\n\t\t\t\t\t.readParcelable(DataSourceHolder.class.getClassLoader());\r\n\t\t\tint id = in.readInt();\r\n\t\t\t// Find DataSourceInstance with provided id\r\n\t\t\tfor (DataSourceInstanceHolder instance : dataSource.getInstances()) {\r\n\t\t\t\tif (instance.id == id) {\r\n\t\t\t\t\treturn instance;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tpublic DataSourceInstanceHolder[] newArray(int size) {\r\n\t\t\treturn new DataSourceInstanceHolder[size];\r\n\t\t}\r\n\t};\r\n\r\n\tpublic boolean isChecked() {\r\n\t\treturn mChecker.isChecked();\r\n\t}\r\n\r\n\tpublic void setChecked(boolean state) {\r\n\t\tmChecker.setChecked(state);\r\n\t}\r\n\r\n\tpublic void saveState(ObjectOutputStream objectOutputStream)\r\n\t\t\tthrows IOException {\r\n\r\n\t\t// Store filter, serializable\r\n\t\tobjectOutputStream.writeObject(currentFilter);\r\n\r\n\t\t// Store data source instance settings using settings framework\r\n\t\tSettingsHelper.storeSettings(objectOutputStream, this.dataSource);\r\n\r\n\t\tobjectOutputStream.writeBoolean(isChecked());\r\n\t}\r\n\r\n\tpublic void restoreState(ObjectInputStream objectInputStream)\r\n\t\t\tthrows IOException {\r\n\t\ttry {\r\n\t\t\t// restore filter, serializable\r\n\t\t\tcurrentFilter = (Filter) objectInputStream.readObject();\r\n\t\t\tdataCache.setFilter(currentFilter);\r\n\t\t} catch (ClassNotFoundException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\r\n\t\t// restore data source instance settings, settings framework\r\n\t\tSettingsHelper.restoreSettings(objectInputStream, this.dataSource);\r\n\r\n\t\tsetChecked(objectInputStream.readBoolean());\r\n\t}\r\n\r\n\tpublic void reportError(Exception e) {\r\n\t\tlastError = e;\r\n\t}\r\n\r\n\tpublic void clearError() {\r\n\t\tlastError = null;\r\n\t}\r\n\r\n\tpublic String getErrorString() {\r\n\t\tif (lastError == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tif (lastError instanceof SocketException) {\r\n\t\t\treturn GeoARApplication.applicationContext\r\n\t\t\t\t\t.getString(R.string.connection_error);\r\n\t\t} else if (lastError instanceof PluginException) {\r\n\t\t\treturn ((PluginException) lastError).getTitle();\r\n\t\t}\r\n\r\n\t\treturn GeoARApplication.applicationContext\r\n\t\t\t\t.getString(R.string.unknown_error);\r\n\t}\r\n\r\n\tpublic boolean hasErrorMessage() {\r\n\t\tif (lastError == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn lastError instanceof PluginException;\r\n\t}\r\n\r\n\tpublic String getErrorMessage() {\r\n\t\tif (lastError == null || !(lastError instanceof PluginException)) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\treturn lastError.toString();\r\n\t}\r\n}\r",
"public class PluginLoader {\r\n\r\n\t/**\r\n\t * Class to hold information about a plugin, usually obtained from its\r\n\t * plugin descriptor file. At least an identifier is required to load a\r\n\t * plugin.\r\n\t * \r\n\t */\r\n\tpublic static class PluginInfo {\r\n\t\tpublic PluginInfo(File pluginFile, String name, String description,\r\n\t\t\t\tLong version, String identifier, String publisher) {\r\n\t\t\tthis.name = name;\r\n\t\t\tthis.description = description;\r\n\t\t\tthis.version = version;\r\n\t\t\tthis.pluginFile = pluginFile;\r\n\t\t\tthis.identifier = identifier;\r\n\t\t\tthis.publisher = publisher;\r\n\t\t}\r\n\r\n\t\tFile pluginFile; // Path to the plugin\r\n\t\tString name;\r\n\t\tString description;\r\n\t\tLong version;\r\n\t\tString identifier;\r\n\t\tString publisher;\r\n\t}\r\n\r\n\tprivate static final FilenameFilter PLUGIN_FILENAME_FILTER = new FilenameFilter() {\r\n\t\t@Override\r\n\t\tpublic boolean accept(File dir, String fileName) {\r\n\t\t\treturn fileName.endsWith(\".apk\") || fileName.endsWith(\".zip\")\r\n\t\t\t\t\t|| fileName.endsWith(\".jar\");\r\n\t\t}\r\n\t};\r\n\tprivate static final String PLUGIN_STATE_PREF = \"selected_plugins\";\r\n\tprivate static final int PLUGIN_STATE_VERSION = 4;\r\n\tprivate static final File PLUGIN_DIRECTORY_PATH = GeoARApplication.applicationContext\r\n\t\t\t.getExternalFilesDir(null);\r\n\t// Pattern captures the plugin version string\r\n\tprivate static final Pattern pluginVersionPattern = Pattern\r\n\t\t\t.compile(\"-(\\\\d+(?:\\\\.\\\\d+)*)[.-]\");\r\n\t// Pattern captures the plugin name, ignoring the optional version and\r\n\t// filename ending\r\n\tprivate static final Pattern pluginNamePattern = Pattern\r\n\t\t\t.compile(\"^((?:.(?!-\\\\d+\\\\.))+.).*\\\\.[^.]+$\");\r\n\tprivate static CheckList<InstalledPluginHolder> mInstalledPlugins = new CheckList<InstalledPluginHolder>(\r\n\t\t\tInstalledPluginHolder.class);\r\n\tprivate static List<DataSourceHolder> mDataSources = new ArrayList<DataSourceHolder>();\r\n\tprivate static boolean mReloadingPlugins;\r\n\t// Listener to update the list of currently available data sources\r\n\tprivate static OnCheckedChangedListener<InstalledPluginHolder> pluginCheckedChangedListener = new OnCheckedChangedListener<InstalledPluginHolder>() {\r\n\t\t@Override\r\n\t\tpublic void onCheckedChanged(InstalledPluginHolder item,\r\n\t\t\t\tboolean newState) {\r\n\t\t\tfor (DataSourceHolder dataSource : item.getDataSources()) {\r\n\t\t\t\tif (newState == true) {\r\n\t\t\t\t\taddDataSource(dataSource);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tremoveDataSource(dataSource);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (newState && !mReloadingPlugins) {\r\n\t\t\t\titem.postConstruct();\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\tprivate static DefaultHttpClient mHttpClient;\r\n\tprivate static GeometryFactory mGeometryFactory;\r\n\r\n\tprivate static final Logger LOG = LoggerFactory\r\n\t\t\t.getLogger(PluginLoader.class);\r\n\r\n\tstatic {\r\n\t\tmInstalledPlugins\r\n\t\t\t\t.addOnCheckedChangeListener(pluginCheckedChangedListener);\r\n\t\tmReloadingPlugins = true;\r\n\t\tloadPlugins();\r\n\t\trestoreState();\r\n\t\tmReloadingPlugins = false;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns a thread safe {@link DefaultHttpClient} instance to be reused\r\n\t * among different parts of the application\r\n\t * \r\n\t * @return\r\n\t */\r\n\tpublic static DefaultHttpClient getSharedHttpClient() {\r\n\t\tif (mHttpClient == null) {\r\n\t\t\tSchemeRegistry registry = new SchemeRegistry();\r\n\t\t\tregistry.register(new Scheme(\"http\", PlainSocketFactory\r\n\t\t\t\t\t.getSocketFactory(), 80));\r\n\t\t\tregistry.register(new Scheme(\"https\", SSLSocketFactory\r\n\t\t\t\t\t.getSocketFactory(), 443));\r\n\r\n\t\t\tHttpParams httpParameters = new BasicHttpParams();\r\n\t\t\tHttpConnectionParams.setSoTimeout(httpParameters, 60000);\r\n\t\t\tHttpConnectionParams.setConnectionTimeout(httpParameters, 20000);\r\n\t\t\tClientConnectionManager cm = new ThreadSafeClientConnManager(\r\n\t\t\t\t\thttpParameters, registry);\r\n\t\t\tmHttpClient = new DefaultHttpClient(cm, httpParameters);\r\n\t\t}\r\n\r\n\t\treturn mHttpClient;\r\n\t}\r\n\t\r\n\tpublic static GeometryFactory getGeometryFactory(){\r\n\t if(mGeometryFactory == null){\r\n\t mGeometryFactory = new GeometryFactory();\r\n\t }\r\n\t return mGeometryFactory;\r\n\t}\r\n\r\n\t/**\r\n\t * Restores the state of plugins from {@link SharedPreferences}. If an error\r\n\t * occurs, e.g. if a previously selected plugin got removed, this function\r\n\t * will quit silently.\r\n\t */\r\n\tprivate static void restoreState() {\r\n\t\ttry {\r\n\t\t\tSharedPreferences preferences = GeoARApplication.applicationContext\r\n\t\t\t\t\t.getSharedPreferences(GeoARApplication.PREFERENCES_FILE,\r\n\t\t\t\t\t\t\tContext.MODE_PRIVATE);\r\n\r\n\t\t\tbyte[] data = Base64.decode(\r\n\t\t\t\t\tpreferences.getString(PLUGIN_STATE_PREF, \"\"),\r\n\t\t\t\t\tBase64.DEFAULT);\r\n\t\t\tPluginStateInputStream objectInputStream = new PluginStateInputStream(\r\n\t\t\t\t\tnew ByteArrayInputStream(data));\r\n\r\n\t\t\tint stateVersion = objectInputStream.readInt();\r\n\t\t\tif (stateVersion != PLUGIN_STATE_VERSION) {\r\n\t\t\t\t// Do not read state if preferences contains old/invalid state\r\n\t\t\t\t// information\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\t// Restore plugin state\r\n\t\t\tint count = objectInputStream.readInt();\r\n\t\t\tfor (int i = 0; i < count; i++) {\r\n\r\n\t\t\t\tInstalledPluginHolder plugin = getPluginByIdentifier(objectInputStream\r\n\t\t\t\t\t\t.readUTF());\r\n\t\t\t\tif (plugin == null) {\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\tplugin.restoreState(objectInputStream);\r\n\t\t\t\t\tplugin.postConstruct();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\tLOG.warn(\"Exception while restoring state of plugin \"\r\n\t\t\t\t\t\t\t+ plugin.getName(), e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tobjectInputStream.close();\r\n\t\t} catch (Exception e) {\r\n\t\t\tLOG.error(\"Exception while restoring state \", e);\r\n\t\t\t// TODO\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Saves the state of plugins to {@link SharedPreferences}.\r\n\t */\r\n\tpublic static void saveState() {\r\n\t\ttry {\r\n\t\t\tByteArrayOutputStream outputStream = new ByteArrayOutputStream();\r\n\t\t\tObjectOutputStream objectOutputStream = new ObjectOutputStream(\r\n\t\t\t\t\toutputStream);\r\n\r\n\t\t\t// store plugin state version\r\n\t\t\tobjectOutputStream.writeInt(PLUGIN_STATE_VERSION);\r\n\r\n\t\t\tList<InstalledPluginHolder> checkedPlugins = mInstalledPlugins\r\n\t\t\t\t\t.getCheckedItems();\r\n\t\t\tobjectOutputStream.writeInt(checkedPlugins.size());\r\n\r\n\t\t\tfor (InstalledPluginHolder plugin : checkedPlugins) {\r\n\t\t\t\tobjectOutputStream.writeUTF(plugin.getIdentifier());\r\n\t\t\t\tplugin.saveState(objectOutputStream);\r\n\t\t\t}\r\n\r\n\t\t\tSharedPreferences preferences = GeoARApplication.applicationContext\r\n\t\t\t\t\t.getSharedPreferences(GeoARApplication.PREFERENCES_FILE,\r\n\t\t\t\t\t\t\tContext.MODE_PRIVATE);\r\n\t\t\tEditor editor = preferences.edit();\r\n\t\t\tobjectOutputStream.flush();\r\n\t\t\teditor.putString(PLUGIN_STATE_PREF, Base64.encodeToString(\r\n\t\t\t\t\toutputStream.toByteArray(), Base64.DEFAULT));\r\n\t\t\teditor.commit();\r\n\t\t\tobjectOutputStream.close();\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\t// TODO\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Parses a version string to long. Assumes that each part of a version\r\n\t * string is < 100.\r\n\t * \r\n\t * @param version\r\n\t * Version string, e.g. \"1.2.3\"\r\n\t * @return long built by multiplying each version component by 100 to the\r\n\t * power of its position from the back, i.e. \"0.0.1\" -> 1, \"0.1.0\"\r\n\t * -> 100\r\n\t */\r\n\tprivate static long parseVersionNumber(String version) {\r\n\t\tString[] split = version.split(\"\\\\.\");\r\n\t\tlong versionNumber = 0;\r\n\t\tfor (int i = 0; i < split.length; i++) {\r\n\t\t\tint num = Integer.parseInt(split[i]);\r\n\t\t\tif (num < 0 || num >= 100) {\r\n\t\t\t\tthrow new NumberFormatException(\r\n\t\t\t\t\t\t\"Unable to parse version number, each part may not exceed 100\");\r\n\t\t\t}\r\n\t\t\tversionNumber += Math.pow(100, (split.length - 1) - i) * num;\r\n\t\t}\r\n\t\treturn versionNumber;\r\n\t}\r\n\r\n\t/**\r\n\t * Extracts and parses the geoar-plugin.xml plugin-descriptor to create and\r\n\t * fill a {@link PluginInfo} instance.\r\n\t * \r\n\t * @param pluginFile\r\n\t * @return\r\n\t */\r\n\tprivate static PluginInfo readPluginInfoFromPlugin(File pluginFile) {\r\n\t\ttry {\r\n\t\t\tZipFile zipFile = new ZipFile(pluginFile);\r\n\t\t\tZipEntry pluginDescriptorEntry = zipFile\r\n\t\t\t\t\t.getEntry(\"geoar-plugin.xml\");\r\n\t\t\tif (pluginDescriptorEntry == null) {\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\r\n\t\t\tDocument document = DocumentBuilderFactory.newInstance()\r\n\t\t\t\t\t.newDocumentBuilder()\r\n\t\t\t\t\t.parse(zipFile.getInputStream(pluginDescriptorEntry));\r\n\t\t\t// Find name\r\n\t\t\tString name = null;\r\n\t\t\tNodeList nodeList = document.getElementsByTagName(\"name\");\r\n\t\t\tif (nodeList != null && nodeList.getLength() >= 1) {\r\n\t\t\t\tname = nodeList.item(0).getTextContent();\r\n\t\t\t} else {\r\n\t\t\t\tLOG.warn(\"Plugin Descriptor for \" + pluginFile.getName()\r\n\t\t\t\t\t\t+ \" does not specify a name\");\r\n\t\t\t}\r\n\r\n\t\t\t// Find publisher\r\n\t\t\tString publisher = null;\r\n\t\t\tnodeList = document.getElementsByTagName(\"publisher\");\r\n\t\t\tif (nodeList != null && nodeList.getLength() >= 1) {\r\n\t\t\t\tpublisher = nodeList.item(0).getTextContent();\r\n\t\t\t} else {\r\n\t\t\t\tLOG.warn(\"Plugin Descriptor for \" + pluginFile.getName()\r\n\t\t\t\t\t\t+ \" does not specify a publisher\");\r\n\t\t\t}\r\n\r\n\t\t\t// Find description\r\n\t\t\tString description = null;\r\n\t\t\tnodeList = document.getElementsByTagName(\"description\");\r\n\t\t\tif (nodeList != null && nodeList.getLength() >= 1) {\r\n\t\t\t\tdescription = nodeList.item(0).getTextContent();\r\n\t\t\t} else {\r\n\t\t\t\tLOG.warn(\"Plugin Descriptor for \" + pluginFile.getName()\r\n\t\t\t\t\t\t+ \" does not specify a description\");\r\n\t\t\t}\r\n\r\n\t\t\t// Find identifier\r\n\t\t\tString identifier = null;\r\n\t\t\tnodeList = document.getElementsByTagName(\"identifier\");\r\n\t\t\tif (nodeList != null && nodeList.getLength() >= 1) {\r\n\t\t\t\tidentifier = nodeList.item(0).getTextContent();\r\n\t\t\t} else {\r\n\t\t\t\tLOG.warn(\"Plugin Descriptor for \" + pluginFile.getName()\r\n\t\t\t\t\t\t+ \" does not specify an identifier\");\r\n\t\t\t}\r\n\r\n\t\t\t// Find version\r\n\t\t\tLong version = null;\r\n\t\t\tnodeList = document.getElementsByTagName(\"version\");\r\n\t\t\tif (nodeList != null && nodeList.getLength() >= 1) {\r\n\t\t\t\tString versionString = \"-\" + nodeList.item(0).getTextContent();\r\n\r\n\t\t\t\tMatcher matcher = pluginVersionPattern.matcher(versionString);\r\n\t\t\t\tif (matcher.find() && matcher.group(1) != null) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tversion = parseVersionNumber(matcher.group(1));\r\n\t\t\t\t\t} catch (NumberFormatException e) {\r\n\t\t\t\t\t\tLOG.error(\"Plugin filename version invalid: \"\r\n\t\t\t\t\t\t\t\t+ matcher.group(1));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tLOG.warn(\"Plugin Descriptor for \" + pluginFile.getName()\r\n\t\t\t\t\t\t+ \" does not specify a version\");\r\n\t\t\t}\r\n\r\n\t\t\tif (identifier == null) {\r\n\t\t\t\tidentifier = name;\r\n\t\t\t}\r\n\r\n\t\t\treturn new PluginInfo(pluginFile, name, description, version,\r\n\t\t\t\t\tidentifier, publisher);\r\n\t\t} catch (SAXException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} catch (ParserConfigurationException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} catch (ZipException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * Reads {@link PluginInfo} from the path of a plugin. This will only\r\n\t * extract a name and version information\r\n\t * \r\n\t * @param pluginFile\r\n\t * @return\r\n\t */\r\n\tprivate static PluginInfo readPluginInfoFromFilename(File pluginFile) {\r\n\t\tString pluginFileName = pluginFile.getName();\r\n\r\n\t\tMatcher matcher = pluginNamePattern.matcher(pluginFileName);\r\n\t\tif (!matcher.matches()) {\r\n\t\t\tLOG.error(\"Plugin filename invalid: \" + pluginFileName);\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tString name = matcher.group(1);\r\n\r\n\t\tLong version = null;\r\n\t\tmatcher = pluginVersionPattern.matcher(pluginFileName);\r\n\t\tif (matcher.find() && matcher.group(1) != null) {\r\n\t\t\ttry {\r\n\t\t\t\tversion = parseVersionNumber(matcher.group(1));\r\n\t\t\t} catch (NumberFormatException e) {\r\n\t\t\t\tLOG.error(\"Plugin filename version invalid: \"\r\n\t\t\t\t\t\t+ matcher.group(1));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn new PluginInfo(pluginFile, name, null, version, name, null);\r\n\t}\r\n\r\n\t/**\r\n\t * Loads all plugins from SD card, compares version strings for plugins with\r\n\t * same names and loads the most recent plugin.\r\n\t * \r\n\t * The plugin name is the filename without its ending and without optional\r\n\t * version string. A version string is introduced by a hyphen, following\r\n\t * dot-separated numbers, e.g. \"-1.2.3\"\r\n\t */\r\n\tprivate static void loadPlugins() {\r\n\t\tString[] apksInDirectory = PLUGIN_DIRECTORY_PATH\r\n\t\t\t\t.list(PLUGIN_FILENAME_FILTER);\r\n\r\n\t\tif (apksInDirectory == null || apksInDirectory.length == 0){\r\n\t\t\tIntroController.startIntro(!mInstalledPlugins.isEmpty());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\t\r\n\r\n\t\t// Map to store all plugins with their versions for loading only the\r\n\t\t// newest ones\r\n\t\tHashMap<String, PluginInfo> pluginVersionMap = new HashMap<String, PluginInfo>();\r\n\r\n\t\tfor (String pluginFileName : apksInDirectory) {\r\n\r\n\t\t\tPluginInfo pluginInfo = readPluginInfoFromPlugin(new File(\r\n\t\t\t\t\tPLUGIN_DIRECTORY_PATH, pluginFileName));\r\n\t\t\tif (pluginInfo == null) {\r\n\t\t\t\tLOG.info(\"Plugin \" + pluginFileName\r\n\t\t\t\t\t\t+ \" has no plugin descriptor\");\r\n\t\t\t\tpluginInfo = readPluginInfoFromFilename(new File(\r\n\t\t\t\t\t\tPLUGIN_DIRECTORY_PATH, pluginFileName));\r\n\t\t\t}\r\n\r\n\t\t\tif (pluginInfo.identifier == null) {\r\n\t\t\t\tLOG.error(\"Plugin \"\r\n\t\t\t\t\t\t+ pluginFileName\r\n\t\t\t\t\t\t+ \" has an invalid plugin descriptor and an invalid filename. Plugin excluded from loading.\");\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif (pluginInfo.version == null) {\r\n\t\t\t\tpluginInfo.version = -1L; // Set unknown version to version -1\r\n\t\t\t}\r\n\r\n\t\t\tPluginInfo pluginInfoMapping = pluginVersionMap\r\n\t\t\t\t\t.get(pluginInfo.identifier);\r\n\t\t\tif (pluginInfoMapping == null\r\n\t\t\t\t\t|| pluginInfoMapping.version < pluginInfo.version) {\r\n\t\t\t\t// Plugin not yet known or newer\r\n\t\t\t\tpluginVersionMap.put(pluginInfo.identifier, pluginInfo);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (PluginInfo pluginInfo : pluginVersionMap.values()) {\r\n\t\t\tInstalledPluginHolder pluginHolder = new InstalledPluginHolder(\r\n\t\t\t\t\tpluginInfo);\r\n\t\t\tmInstalledPlugins.add(pluginHolder);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Reloads all plugins. The current state of the plugins are restored\r\n\t * afterwards.\r\n\t */\r\n\tpublic static void reloadPlugins() {\r\n\t\tmReloadingPlugins = true;\r\n\t\tsaveState();\r\n\t\tmInstalledPlugins.clear();\r\n\t\tmDataSources.clear();\r\n\t\tloadPlugins();\r\n\t\trestoreState();\r\n\t\tmReloadingPlugins = false;\r\n\t}\r\n\r\n\tpublic static CheckList<InstalledPluginHolder> getInstalledPlugins() {\r\n\t\treturn mInstalledPlugins;\r\n\t}\r\n\r\n\tprivate static void addDataSource(DataSourceHolder dataSource) {\r\n\t\tif (!mDataSources.contains(dataSource))\r\n\t\t\tmDataSources.add(dataSource);\r\n\t}\r\n\r\n\tprivate static void removeDataSource(DataSourceHolder dataSource) {\r\n\t\tmDataSources.remove(dataSource);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns all {@link DataSourceHolder} of currently activated plugins.\r\n\t * \r\n\t * @return\r\n\t */\r\n\tpublic static List<DataSourceHolder> getDataSources() {\r\n\t\treturn mDataSources;\r\n\t}\r\n\t\r\n\tpublic static boolean hasDataSources(){\r\n\t\treturn mInstalledPlugins == null ? false : mInstalledPlugins.size() > 0;\r\n\t}\r\n\r\n\tpublic static InstalledPluginHolder getPluginByIdentifier(String identifier) {\r\n\t\tfor (InstalledPluginHolder plugin : mInstalledPlugins) {\r\n\t\t\tif (plugin.getIdentifier().equals(identifier)) {\r\n\t\t\t\treturn plugin;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n}\r",
"public interface OnCheckedChangedListener<T> {\r\n\tvoid onCheckedChanged(T item, boolean newState);\r\n}\r",
"public class LocationHandler implements Serializable {\r\n\tprivate static final long serialVersionUID = 6337877169906901138L;\r\n\tprivate static final int DISABLE_LOCATION_UPDATES_MESSAGE = 1;\r\n\tprivate static final long DISABLE_LOCATION_UPDATES_DELAY = 12000;\r\n\tprivate static final Logger LOG = LoggerFactory\r\n\t\t\t.getLogger(LocationHandler.class);\r\n\r\n\tpublic interface OnLocationUpdateListener {\r\n\t\tvoid onLocationChanged(Location location);\r\n\t}\r\n\r\n\tprivate static LocationManager locationManager;\r\n\tprivate static final Object gpsStatusInfo = new Object();\r\n\tprivate static final Object gpsProviderInfo = new Object();\r\n\tprivate static List<OnLocationUpdateListener> listeners = new ArrayList<OnLocationUpdateListener>();\r\n\r\n\tprivate static boolean manualLocationMode;\r\n\tprivate static Location manualLocation;\r\n\r\n\tprivate static Handler disableUpdateHandler = new Handler() {\r\n\t\t@Override\r\n\t\tpublic void handleMessage(Message msg) {\r\n\t\t\tif (msg.what == DISABLE_LOCATION_UPDATES_MESSAGE) {\r\n\t\t\t\tonPause();\r\n\t\t\t} else {\r\n\t\t\t\tsuper.handleMessage(msg);\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\tstatic {\r\n\t\tlocationManager = (LocationManager) GeoARApplication.applicationContext\r\n\t\t\t\t.getSystemService(Context.LOCATION_SERVICE);\r\n\t}\r\n\r\n\tprivate static LocationListener locationListener = new LocationListener() {\r\n\r\n\t\tpublic void onProviderDisabled(String provider) {\r\n\t\t\tInfoView.setStatus(R.string.gps_nicht_aktiviert, -1,\r\n\t\t\t\t\tgpsProviderInfo);\r\n\t\t}\r\n\r\n\t\tpublic void onProviderEnabled(String provider) {\r\n\t\t\tInfoView.setStatus(R.string.gps_aktiviert, 2000, gpsProviderInfo);\r\n\t\t}\r\n\r\n\t\tpublic void onStatusChanged(String provider, int status, Bundle extras) {\r\n\t\t\tif (status != LocationProvider.AVAILABLE) {\r\n\t\t\t\tInfoView.setStatus(R.string.warte_auf_gps_verf_gbarkeit, 5000,\r\n\t\t\t\t\t\tgpsStatusInfo);\r\n\t\t\t} else {\r\n\t\t\t\tInfoView.clearStatus(gpsStatusInfo);\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void onLocationChanged(Location location) {\r\n\t\t\tfor (OnLocationUpdateListener listener : listeners) {\r\n\t\t\t\tlistener.onLocationChanged(location);\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\t/**\r\n\t * Override with a user generated location fix\r\n\t * \r\n\t * @param location\r\n\t */\r\n\tpublic static void setManualLocation(Location location) {\r\n\t\tmanualLocationMode = true;\r\n\t\tonPause();\r\n\t\tmanualLocation = location;\r\n\t\tlocationListener.onLocationChanged(manualLocation);\r\n\t\tInfoView.setStatus(R.string.manual_position, -1, manualLocation);\r\n\t}\r\n\r\n\t/**\r\n\t * Override with a user generated location fix\r\n\t * \r\n\t * @param geoPoint\r\n\t */\r\n\tpublic static void setManualLocation(GeoLocation geoPoint) {\r\n\t\tmanualLocationMode = true;\r\n\t\tonPause();\r\n\t\tif (manualLocation == null) {\r\n\t\t\tmanualLocation = new Location(\"manual\");\r\n\t\t}\r\n\t\tmanualLocation.setLatitude(geoPoint.getLatitudeE6() / 1E6f);\r\n\t\tmanualLocation.setLongitude(geoPoint.getLongitudeE6() / 1E6f);\r\n\t\tlocationListener.onLocationChanged(manualLocation);\r\n\r\n\t\tInfoView.setStatus(R.string.manual_position, -1, manualLocation);\r\n\t}\r\n\r\n\t/**\r\n\t * Reregister location updates for real location provider\r\n\t */\r\n\tpublic static void disableManualLocation() {\r\n\t\tInfoView.clearStatus(manualLocation);\r\n\t\tmanualLocationMode = false;\r\n\t\tonResume();\r\n\t}\r\n\r\n\t/**\r\n\t * Performs processes needed to enable location updates\r\n\t */\r\n\tpublic static void onResume() {\r\n\t\tif (!listeners.isEmpty()) {\r\n\t\t\tif (!locationManager\r\n\t\t\t\t\t.isProviderEnabled(LocationManager.GPS_PROVIDER)) {\r\n\t\t\t\tInfoView.setStatus(R.string.gps_nicht_aktiviert, -1,\r\n\t\t\t\t\t\tgpsProviderInfo);\r\n\t\t\t}\r\n\t\t\tlocationManager.requestLocationUpdates(\r\n\t\t\t\t\tLocationManager.GPS_PROVIDER, 5000, 0, locationListener);\r\n\t\t\tLOG.debug(\"Requesting Location Updates\");\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Should be called if activity gets paused. Removes location updates\r\n\t */\r\n\tpublic static void onPause() {\r\n\t\tlocationManager.removeUpdates(locationListener);\r\n\t\tInfoView.clearStatus(gpsProviderInfo);\r\n\t\tLOG.debug(\"Removed Location Updates\");\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the last known location. Takes user generated locations into\r\n\t * account. Returns location fix from network provider if no GPS available\r\n\t * \r\n\t * @return\r\n\t */\r\n\tpublic static Location getLastKnownLocation() {\r\n\t\tif (manualLocationMode) {\r\n\t\t\treturn manualLocation;\r\n\t\t} else if (locationManager\r\n\t\t\t\t.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {\r\n\t\t\treturn locationManager\r\n\t\t\t\t\t.getLastKnownLocation(LocationManager.GPS_PROVIDER);\r\n\t\t} else {\r\n\t\t\treturn locationManager\r\n\t\t\t\t\t.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Register listener for location updates. Gets immediately called with the\r\n\t * last known location, if available\r\n\t * \r\n\t * @param listener\r\n\t */\r\n\tpublic static void addLocationUpdateListener(\r\n\t\t\tOnLocationUpdateListener listener) {\r\n\t\tboolean shouldResume = listeners.isEmpty();\r\n\t\tif (!listeners.contains(listener)) {\r\n\t\t\tlisteners.add(listener);\r\n\t\t\tif (getLastKnownLocation() != null) {\r\n\t\t\t\tlistener.onLocationChanged(getLastKnownLocation());\r\n\t\t\t}\r\n\t\t\tdisableUpdateHandler\r\n\t\t\t\t\t.removeMessages(DISABLE_LOCATION_UPDATES_MESSAGE);\r\n\t\t}\r\n\r\n\t\tif (shouldResume) {\r\n\t\t\tonResume();\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Removes location update listener\r\n\t * \r\n\t * @param listener\r\n\t */\r\n\tpublic static void removeLocationUpdateListener(\r\n\t\t\tOnLocationUpdateListener listener) {\r\n\t\tlisteners.remove(listener);\r\n\t\tif (listeners.isEmpty()) {\r\n\t\t\tdisableUpdateHandler.sendMessageDelayed(disableUpdateHandler\r\n\t\t\t\t\t.obtainMessage(DISABLE_LOCATION_UPDATES_MESSAGE),\r\n\t\t\t\t\tDISABLE_LOCATION_UPDATES_DELAY);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static void onSaveInstanceState(Bundle outState) {\r\n\t\tif (manualLocationMode) {\r\n\t\t\toutState.putParcelable(\"manualLocation\", manualLocation);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static void onRestoreInstanceState(Bundle savedInstanceState) {\r\n\t\tif (savedInstanceState.get(\"manualLocation\") != null) {\r\n\t\t\tsetManualLocation((Location) savedInstanceState\r\n\t\t\t\t\t.getParcelable(\"manualLocation\"));\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Registers location updates to actively receive a new single location fix.\r\n\t * The provided listener will be called once or never, depending on the\r\n\t * specified timeout.\r\n\t * \r\n\t * @param listener\r\n\t * @param timeoutMillis\r\n\t * Timeout in milliseconds\r\n\t */\r\n\tpublic static void getSingleLocation(\r\n\t\t\tfinal OnLocationUpdateListener listener, int timeoutMillis) {\r\n\r\n\t\t/**\r\n\t\t * Location update listener removing itself after first fix and\r\n\t\t * canceling scheduled runnable\r\n\t\t */\r\n\t\tclass SingleLocationUpdateListener implements OnLocationUpdateListener {\r\n\r\n\t\t\tRunnable cancelSingleUpdateRunnable;\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void onLocationChanged(Location location) {\r\n\t\t\t\t// Clear updates\r\n\t\t\t\tremoveLocationUpdateListener(this);\r\n\t\t\t\tdisableUpdateHandler\r\n\t\t\t\t\t\t.removeCallbacks(this.cancelSingleUpdateRunnable);\r\n\r\n\t\t\t\t// Call actual listener\r\n\t\t\t\tlistener.onLocationChanged(location);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfinal SingleLocationUpdateListener singleUpdateListener = new SingleLocationUpdateListener();\r\n\r\n\t\t// Runnable to be called delayed by timeoutMillis to cancel location\r\n\t\t// update\r\n\t\tfinal Runnable cancelSingleUpdateRunnable = new Runnable() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tremoveLocationUpdateListener(singleUpdateListener);\r\n\t\t\t}\r\n\t\t};\r\n\t\tsingleUpdateListener.cancelSingleUpdateRunnable = cancelSingleUpdateRunnable;\r\n\r\n\t\t// init updates\r\n\t\taddLocationUpdateListener(singleUpdateListener);\r\n\t\tdisableUpdateHandler.postDelayed(cancelSingleUpdateRunnable,\r\n\t\t\t\ttimeoutMillis);\r\n\t}\r\n}\r",
"public interface OnLocationUpdateListener {\r\n\tvoid onLocationChanged(Location location);\r\n}\r"
] | import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
import java.util.HashMap;
import java.util.Map;
import org.n52.geoar.utils.GeoLocation;
import org.n52.geoar.R;
import org.n52.geoar.newdata.CheckList;
import org.n52.geoar.newdata.DataSourceHolder;
import org.n52.geoar.newdata.DataSourceInstanceHolder;
import org.n52.geoar.newdata.PluginLoader;
import org.n52.geoar.newdata.CheckList.OnCheckedChangedListener;
import org.n52.geoar.tracking.location.LocationHandler;
import org.n52.geoar.tracking.location.LocationHandler.OnLocationUpdateListener;
import android.location.Location;
import android.os.Bundle;
| /**
* Copyright 2012 52°North Initiative for Geospatial Open Source Software GmbH
*
* 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.n52.geoar.ar.view;
/**
*
* @author Arne de Wall
*
*/
public class ARFragment extends SherlockFragment implements
OnLocationUpdateListener {
| private Map<DataSourceInstanceHolder, DataSourceVisualizationHandler> mVisualizationHandlerMap = new HashMap<DataSourceInstanceHolder, DataSourceVisualizationHandler>();
| 2 |
bingyulei007/bingexcel | excel/src/test/java/com/chinamobile/excel/ReadTest3.java | [
"public class AbstractFieldConvertor implements FieldValueConverter {\n\n\t@Override\n\tpublic boolean canConvert(Class<?> clz) {\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic OutValue toObject(Object source, ConverterHandler converterHandler) {\n\t\tif(source==null){\n\t\t\treturn null;\n\t\t}\n\t\treturn new OutValue(OutValue.OutType.STRING, source.toString());\n\t}\n\n\t@Override\n\tpublic Object fromString(String cell, ConverterHandler converterHandler,\n\t\t\tType targetType) {\n\t\tif (cell == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn cell;\n\t}\n\n}",
"public final class BooleanFieldConverter extends AbstractFieldConvertor {\n\tprivate final boolean caseSensitive;\n\tprivate final String trueCaseStr;\n\tprivate final String falseCaseStr;\n\n\t/**\n\t * @param trueCaseStr 为真时候的输入\n\t * @param falseCaseStr 为家时候的输入\n\t * @param caseSensitive 是不是忽略大小写\n\t */\n\tpublic BooleanFieldConverter(String trueCaseStr, String falseCaseStr,\n\t\t\tboolean caseSensitive) {\n\t\tthis.caseSensitive = caseSensitive;\n\t\tthis.trueCaseStr = trueCaseStr;\n\t\tthis.falseCaseStr = falseCaseStr;\n\t}\n\n\t/**\n\t * 默认的boolean类型转换器,支持\"TRUE\", \"FALSE\"字符的转换\n\t */\n\tpublic BooleanFieldConverter() {\n\t\tthis(\"TRUE\", \"FALSE\", false);\n\t}\n\n\t@Override\n\tpublic boolean canConvert(Class<?> clz) {\n\t\treturn clz.equals(boolean.class) || clz.equals(Boolean.class);\n\t}\n\n\t@Override\n\tpublic OutValue toObject(Object source, ConverterHandler converterHandler) {\n\t\tif(source==null){\n\t\t\treturn null;\n\t\t}\n\t\tString re;\n\t\tif((boolean)source){\n\t\t\tre=trueCaseStr;\n\t\t}else{\n\t\t\tre=falseCaseStr;\n\t\t}\n\t\treturn OutValue.stringValue(re);\n\t}\n\n\t/*\n\t * in other case ,return false?FIXME\n\t */\n\t@Override\n\tpublic Object fromString(String cell,ConverterHandler converterHandler,Type targetType) {\n\t\tif (Strings.isNullOrEmpty(cell)) {\n\t\t\treturn null;\n\t\t}\n\t\tBoolean re;\n\t\tif (caseSensitive) {\n\t\t\tre = trueCaseStr.equals(cell) ? Boolean.TRUE : Boolean.FALSE;\n\t\t} else {\n\t\t\tre = trueCaseStr.equalsIgnoreCase(cell) ? Boolean.TRUE\n\t\t\t\t\t: Boolean.FALSE;\n\t\t}\n\t\tif (!re) {\n\t\t\tif (caseSensitive) {\n\t\t\t\tif (!falseCaseStr.equals(cell)) {\n\t\t\t\t\tthrow new ConversionException(\"Cann't parse value '\"+cell+\"' to java.lang.Boolean\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (!falseCaseStr.equalsIgnoreCase(cell)) {\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn re;\n\t}\n\n}",
"public interface BingExcel {\n\n /**\n * <p>\n * Title: readFileToList</p>\n * <p>\n * Description:读取excel 的第一个sheet页到list</p>\n *\n * @param file excel对应的文件\n * @param clazz 要转换类型的class对象\n * @param startRowNum 从第几行开始读取\n */\n <T> BingExcelImpl.SheetVo<T> readFile(File file, Class<T> clazz, int startRowNum)\n throws Exception;\n\n /**\n * 根据condition条件读取相应的sheet到list对象\n */\n <T> BingExcelImpl.SheetVo<T> readFile(File file, ReaderCondition<T> condition) throws Exception;\n\n\n /**\n * 读取所condition 对应 sheet表格,到list\n *\n * @param conditions 每个表格对应的condition,注:对于返回的条数,取conditions中 endNum的最小值\n * @return sheetVo的list对象,如果没有符合conditions的结果,返回empetyList对象\n */\n List<BingExcelImpl.SheetVo> readFileToList(File file, ReaderCondition[] conditions)\n throws Exception;\n\n\n <T> BingExcelImpl.SheetVo<T> readStream(InputStream stream, ReaderCondition<T> condition)\n throws InvalidFormatException, IOException, SQLException, OpenXML4JException, SAXException;\n\n /**\n * read sheet witch index equal 0\n */\n <T> BingExcelImpl.SheetVo<T> readStream(InputStream stream, Class<T> clazz, int startRowNum)\n throws InvalidFormatException, IOException, SQLException, OpenXML4JException, SAXException;\n\n /**\n * read sheets\n */\n List<BingExcelImpl.SheetVo> readStreamToList(InputStream stream, ReaderCondition[] condition)\n throws InvalidFormatException, IOException, SQLException, OpenXML4JException, SAXException;\n\n /**\n * 输出model集合到excel 文件。\n *\n * @param iterables 要输出到文件的集合对象,\n * @param file 文件对象\n */\n void writeExcel(File file, Iterable... iterables) throws FileNotFoundException;\n\n void writeOldExcel(File file, Iterable... iterables) throws FileNotFoundException;\n\n /**\n * 输出model集合到excel 文件。\n *\n * @param path 文件路径\n */\n void writeExcel(String path, Iterable... iterables);\n\n /**\n * 写出xls格式的excel文件\n */\n void writeOldExcel(String path, Iterable... iterables);\n\n /**\n * 写出xls格式的excel到输出流\n */\n void writeExcel(OutputStream stream, Iterable... iterables);\n\n void writeOldExcel(OutputStream stream, Iterable... iterables);\n\n void writeCSV(String path, Iterable iterable) throws IOException;\n\n void writeCSV(OutputStream os, Iterable iterable) throws IOException;\n\n /**\n * 写出指定分隔符、指定是否写header的文件到输出流\n *\n * @param os 输出流\n * @param iterable 带转换的对象\n * @param delimiter 分隔符\n * @param isWithHeader 是否写入header行\n * @param isWithBOM 是否带BOM\n */\n void writeCSV(OutputStream os, Iterable iterable, char delimiter, boolean isWithHeader,\n boolean isWithBOM) throws IOException;\n\n void modelName(Class<?> clazz, String alias);\n\n void fieldConverter(Class<?> clazz, String filedName, int index, String alias,\n FieldValueConverter converter);\n\n /**\n * 写出多sheet页的xls格式的excel文件暂时只支持xls格式,后续支持csv格式\n * \n * @param <E>\n * \n * @param path\n * @param list\n */\n void writeSheetsExcel(String path, SheetExcel... sheetExcels);\n}",
"public class BingExcelBuilder implements ExcleBuilder<BingExcel> {\n\n private final ConverterHandler localConverterHandler = new LocalConverterHandler();\n\n /**\n * bingExcel:对应的excel工具类。\n */\n private BingExcel bingExcel;\n\n /**\n * <p>\n * Title: </p>\n * <p>\n * Description: 构造新的builder对象</p>\n */\n private BingExcelBuilder() {\n\n }\n\n public static ExcleBuilder<BingExcel> toBuilder() {\n\n return new BingExcelBuilder();\n\n }\n\n /**\n * @return BingExcel 实例\n */\n public static BingExcel builderInstance() {\n return (new BingExcelBuilder()).builder();\n }\n\n @Override\n public ExcleBuilder<BingExcel> registerFieldConverter(Class<?> clazz,\n FieldValueConverter converter) {\n localConverterHandler.registerConverter(clazz, converter);\n return this;\n }\n\n @Override\n public ExcleBuilder<BingExcel> addFieldConversionMapper(Class<?> clazz,\n String filedName, int index) {\n return addFieldConversionMapper(clazz, filedName, index, filedName, null);\n\n }\n\n @Override\n public ExcleBuilder<BingExcel> addFieldConversionMapper(Class<?> clazz,\n String filedName, int index, String alias) {\n return addFieldConversionMapper(clazz, filedName, index, alias, null);\n }\n\n @Override\n public ExcleBuilder<BingExcel> addFieldConversionMapper(Class<?> clazz,\n String filedName, int index, String alias, FieldValueConverter converter) {\n getBingExcel().fieldConverter(clazz, filedName, index, alias, converter);\n return this;\n }\n\n @Override\n public ExcleBuilder<BingExcel> addClassNameAlias(Class<?> clazz,\n String alias) {\n getBingExcel().modelName(clazz, alias);\n return this;\n }\n\n\n @Deprecated\n @Override\n public BingExcel builder() {\n if (bingExcel == null) {\n bingExcel = new BingExcelImpl(localConverterHandler);\n }\n\n return this.bingExcel;\n }\n\n @Override\n public BingExcel build() {\n\n return this.getBingExcel();\n }\n\n private BingExcel getBingExcel() {\n if (bingExcel == null) {\n bingExcel = new BingExcelImpl(localConverterHandler);\n }\n return this.bingExcel;\n }\n}",
"public interface ConverterHandler {\n\n\t\n\t/**\n\t * Get default FieldConverter which is difined by <code>BaseGlobalConverterMapper</code> or user. \n\t * @param keyFieldType\n\t * @return defaultConvetter or null\n\t */\n\tFieldValueConverter getLocalConverter(Class<?> keyFieldType);\n\n\t/**\n\t * Registe converter for this {@code Class} clazz.\n\t * @param clazz\n\t * @param converter\n\t */\n\tvoid registerConverter(Class<?> clazz, FieldValueConverter converter);\n\t\n\t\n}",
"public static class SheetVo<E> {\n\n private int sheetIndex;\n private String sheetName;\n private List<E> list = new ArrayList<>();\n\n public SheetVo(int sheetIndex, String sheetName) {\n super();\n this.sheetIndex = sheetIndex;\n this.sheetName = sheetName;\n }\n\n public int getSheetIndex() {\n return sheetIndex;\n }\n\n public String getSheetName() {\n return sheetName;\n }\n\n public List<E> getObjectList() {\n return list;\n }\n\n void addObject(E obj) {\n this.list.add(obj);\n }\n\n}"
] | import java.io.File;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.bing.excel.annotation.BingConvertor;
import com.bing.excel.annotation.CellConfig;
import com.bing.excel.converter.AbstractFieldConvertor;
import com.bing.excel.converter.base.BooleanFieldConverter;
import com.bing.excel.core.BingExcel;
import com.bing.excel.core.BingExcelBuilder;
import com.bing.excel.core.handler.ConverterHandler;
import com.bing.excel.core.impl.BingExcelImpl.SheetVo;
import com.google.common.base.MoreObjects; | package com.chinamobile.excel;
public class ReadTest3 {
@Test
public void readExcelTest() throws URISyntaxException {
// InputStream in = Person.class.getResourceAsStream("/person.xlsx");
URL url = Salary.class.getResource("/salary.xlsx");
File f = new File(url.toURI());
BingExcel bing = BingExcelBuilder.toBuilder().builder();
try {
SheetVo<Salary> vo = bing.readFile(f, Salary.class, 1);
System.out.println(vo.getSheetIndex());
System.out.println(vo.getSheetName());
List<Salary> objectList = vo.getObjectList();
for (Salary salary : objectList) {
System.out.println(salary);
}
} catch (Exception e) {
e.printStackTrace();
}
}
enum Department {
develop, personnel, product;
}
public static class Salary {
@CellConfig(index = 1)
private String employNum;
@CellConfig(index = 0)
private String id;
//默认的boolean类型只支持"TRUE", "FALSE"字符的转换,但是它自带了传参数的构造方法,具体可以参考源码,
@CellConfig(index = 8)
@BingConvertor(value = BooleanFieldConverter.class, strings = { "1","0" }, booleans = { false })
private boolean allDay;
@CellConfig(index=7)
private Department department;//枚举类型
@CellConfig(index = 13)
@BingConvertor(DateTestConverter.class)
// 自定义转换器
private Date atypiaDate;
@CellConfig(index = 14)
private Date entryTime;
// 其他变量可以这样定义。
private transient String test;
public String toString() {
return MoreObjects.toStringHelper(this.getClass()).omitNullValues()
.add("id", id).add("employNum", employNum)
.add("allDay", allDay)
.add("atypiaDate", atypiaDate)
.add("department", department)
.add("entryTime", entryTime).toString();
}
}
public static class DateTestConverter extends AbstractFieldConvertor {
@Override
public boolean canConvert(Class<?> clz) {
return clz.equals(Date.class);
}
@Override | public Object fromString(String cell, ConverterHandler converterHandler,Type type) { | 4 |
rodolfodpk/myeslib | myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java | [
"public interface Command extends Serializable {\n\t\n UUID getCommandId();\n\tLong getTargetVersion();\n\t\n}",
"public interface Event extends Serializable {\n\t\n}",
"@SuppressWarnings(\"serial\")\n@Value\npublic class UnitOfWork implements Comparable<UnitOfWork>, Serializable {\n\n final UUID id;\n\tfinal Command command;\n\tfinal List<? extends Event> events;\n\tfinal long version;\n\t\n\tpublic UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) {\n\t checkNotNull(id, \"id cannot be null\");\n\t checkNotNull(command, \"command cannot be null\");\n\t\tcheckArgument(command.getTargetVersion()>=0, \"target version must be >= 0\");\n\t\tcheckArgument(version>0, \"invalid version\");\n\t\tcheckNotNull(events, \"events cannot be null\");\n\t\tfor (Event e: events){\n\t\t\tcheckNotNull(e, \"event within events list cannot be null\");\n\t\t}\n\t\tthis.id = id;\n\t\tthis.command = command;\n\t\tthis.version = version;\n\t\tthis.events = events;\n\t}\n\t\n\tpublic static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) {\n\t\tcheckNotNull(command.getTargetVersion(), \"target version cannot be null\");\n\t\tcheckArgument(command.getTargetVersion()>=0, \"target version must be >= 0\");\n\t\treturn new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents);\n\t}\n\t\n\tpublic List<Event> getEvents(){\n\t\tList<Event> result = new LinkedList<>();\n\t\tfor (Event event : events) {\n\t\t\tresult.add(event);\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic int compareTo(UnitOfWork other) {\n\t\tif (version < other.version) {\n\t\t\treturn -1;\n\t\t} else if (version > other.version) {\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic Long getTargetVersion() {\n\t\treturn command.getTargetVersion();\n\t}\n}",
"@Value\npublic static class IncreaseInventory implements Command {\n @NonNull\n UUID commandId;\n @NonNull\n UUID id;\n @NonNull\n Integer howMany;\n Long targetVersion;\n}",
"@Value\npublic static class InventoryIncreased implements Event {\n @NonNull\n UUID id;\n @NonNull\n Integer howMany;\n}",
"public interface UnitOfWorkJournalDao<K> {\n\n\tvoid append(K id, UnitOfWork uow);\n\t\n}"
] | import static org.mockito.Mockito.verify;
import java.util.Arrays;
import java.util.UUID;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.myeslib.core.Command;
import org.myeslib.core.Event;
import org.myeslib.core.data.UnitOfWork;
import org.myeslib.example.SampleDomain.IncreaseInventory;
import org.myeslib.example.SampleDomain.InventoryIncreased;
import org.myeslib.util.jdbi.UnitOfWorkJournalDao; | package org.myeslib.jdbi.storage;
@RunWith(MockitoJUnitRunner.class)
public class JdbiUnitOfWorkJournalTest {
@Mock
UnitOfWorkJournalDao<UUID> dao;
@Test
public void insert() {
JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao);
UUID id = UUID.randomUUID();
| Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l); | 0 |
skuzzle/restrict-imports-enforcer-rule | src/main/java/org/apache/maven/plugins/enforcer/RestrictImports.java | [
"public static void checkArgument(boolean condition) {\n checkArgument(condition, \"Unexpected argument\");\n}",
"public final class AnalyzeResult {\n\n private final List<MatchedFile> srcMatches;\n private final List<MatchedFile> testMatches;\n private final Duration duration;\n private final int analysedFiles;\n\n private AnalyzeResult(List<MatchedFile> srcMatches, List<MatchedFile> testMatches, long duration,\n int analysedFiles) {\n this.srcMatches = srcMatches;\n this.testMatches = testMatches;\n this.duration = Duration.ofMillis(duration);\n this.analysedFiles = analysedFiles;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * Contains all the matches that were found within the analyzed compile source files.\n *\n * @return The list of found banned imports.\n */\n public List<MatchedFile> getSrcMatches() {\n return this.srcMatches;\n }\n\n /**\n * Returns the matches that occurred in compile source files grouped by their\n * {@link BannedImportGroup}\n *\n * @return The matches grouped by {@link BannedImportGroup}\n */\n public Map<BannedImportGroup, List<MatchedFile>> srcMatchesByGroup() {\n return srcMatches.stream()\n .collect(Collectors.groupingBy(MatchedFile::getMatchedBy));\n }\n\n /**\n * Contains all the matches that were found within the analyzed test source files.\n *\n * @return The list of found banned imports.\n */\n public List<MatchedFile> getTestMatches() {\n return testMatches;\n }\n\n /**\n * Returns the matches that occurred in test source files grouped by their\n * {@link BannedImportGroup}\n *\n * @return The matches grouped by {@link BannedImportGroup}\n */\n public Map<BannedImportGroup, List<MatchedFile>> testMatchesByGroup() {\n return testMatches.stream()\n .collect(Collectors.groupingBy(MatchedFile::getMatchedBy));\n }\n\n /**\n * Returns whether at least one banned import has been found within the analyzed\n * compile OR test source files.\n *\n * @return Whether a banned import has been found.\n */\n public boolean bannedImportsFound() {\n return bannedImportsInCompileCode() || bannedImportsInTestCode();\n }\n\n /**\n * Returns whether at least one banned import has been found within the analyzed\n * compile source code.\n *\n * @return Whether a banned import has been found.\n */\n public boolean bannedImportsInCompileCode() {\n return !srcMatches.isEmpty();\n }\n\n /**\n * Returns whether at least one banned import has been found within the analyzed test\n * source code.\n *\n * @return Whether a banned import has been found.\n */\n public boolean bannedImportsInTestCode() {\n return !testMatches.isEmpty();\n }\n\n /**\n * How long the analysis took, in ms.\n *\n * @return Analysis duration in ms.\n */\n public Duration duration() {\n return this.duration;\n }\n\n /**\n * The number of files that have been analysed.\n *\n * @return Number of files.\n */\n public int analysedFiles() {\n return this.analysedFiles;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(srcMatches, testMatches);\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj == this || obj instanceof AnalyzeResult\n && Objects.equals(srcMatches, ((AnalyzeResult) obj).srcMatches)\n && Objects.equals(testMatches, ((AnalyzeResult) obj).testMatches);\n }\n\n @Override\n public String toString() {\n return StringRepresentation.ofInstance(this)\n .add(\"srcMatches\", this.srcMatches)\n .add(\"testMatches\", this.testMatches)\n .add(\"duration\", duration)\n .toString();\n }\n\n public static class Builder {\n private final List<MatchedFile> srcMatches = new ArrayList<>();\n private final List<MatchedFile> testMatches = new ArrayList<>();\n private long duration;\n private int analysedFiles;\n\n private Builder() {\n // hidden\n }\n\n public Builder withMatches(Collection<MatchedFile> matches) {\n this.srcMatches.addAll(matches);\n return this;\n }\n\n public Builder withMatches(MatchedFile.Builder... matches) {\n Arrays.stream(matches).map(MatchedFile.Builder::build)\n .forEach(this.srcMatches::add);\n return this;\n }\n\n public Builder withMatchesInTestCode(Collection<MatchedFile> matches) {\n this.testMatches.addAll(matches);\n return this;\n }\n\n public Builder withMatchesInTestCode(MatchedFile.Builder... matches) {\n Arrays.stream(matches).map(MatchedFile.Builder::build)\n .forEach(this.testMatches::add);\n return this;\n }\n\n public Builder withDuration(long duration) {\n this.duration = duration;\n return this;\n }\n\n public Builder withAnalysedFileCount(int analysedFiles) {\n this.analysedFiles = analysedFiles;\n return this;\n }\n\n public AnalyzeResult build() {\n return new AnalyzeResult(srcMatches, testMatches, duration, analysedFiles);\n }\n\n }\n}",
"public final class AnalyzerSettings {\n\n private final Charset sourceFileCharset;\n private final Collection<Path> srcDirectories;\n private final Collection<Path> testDirectories;\n private final boolean parallel;\n\n private AnalyzerSettings(Charset sourceFileCharset,\n Collection<Path> srcDirectories,\n Collection<Path> testDirectories, boolean parallel) {\n this.sourceFileCharset = sourceFileCharset;\n this.srcDirectories = srcDirectories;\n this.testDirectories = testDirectories;\n this.parallel = parallel;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public Charset getSourceFileCharset() {\n return this.sourceFileCharset;\n }\n\n public Collection<Path> getSrcDirectories() {\n return this.srcDirectories;\n }\n\n public Collection<Path> getTestDirectories() {\n return testDirectories;\n }\n\n public boolean isParallel() {\n return this.parallel;\n }\n\n /**\n * Returns the union of {@link #getSrcDirectories()} and getTestDirectories.\n *\n * @return All source directories that are subject to analysis.\n */\n public Collection<Path> getAllDirectories() {\n final Set<Path> result = new HashSet<>(srcDirectories.size() + testDirectories.size());\n result.addAll(srcDirectories);\n result.addAll(testDirectories);\n return result;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(sourceFileCharset, srcDirectories, testDirectories, parallel);\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj == this || obj instanceof AnalyzerSettings\n && Objects.equals(sourceFileCharset, ((AnalyzerSettings) obj).sourceFileCharset)\n && Objects.equals(srcDirectories, ((AnalyzerSettings) obj).srcDirectories)\n && Objects.equals(testDirectories, ((AnalyzerSettings) obj).testDirectories)\n && parallel == ((AnalyzerSettings) obj).parallel;\n }\n\n @Override\n public String toString() {\n return StringRepresentation.ofInstance(this)\n .add(\"sourceFileCharset\", sourceFileCharset)\n .add(\"srcDirectories\", srcDirectories)\n .add(\"testDirectories\", testDirectories)\n .add(\"parallel\", parallel)\n .toString();\n }\n\n public static final class Builder {\n\n private final List<Path> srcDirectories = new ArrayList<>();\n private final List<Path> testDirectories = new ArrayList<>();\n private Charset sourceFileCharset = Charset.defaultCharset();\n private boolean parallel = false;\n\n private Builder() {\n // hidden\n }\n\n public Builder withSrcDirectories(Collection<Path> srcDirectories) {\n this.srcDirectories.addAll(srcDirectories);\n return this;\n }\n\n public Builder withSrcDirectories(Path... srcDirectories) {\n this.srcDirectories.addAll(Arrays.asList(srcDirectories));\n return this;\n }\n\n public Builder withTestDirectories(Collection<Path> testDirectories) {\n this.testDirectories.addAll(testDirectories);\n return this;\n }\n\n public Builder withTestDirectories(Path... testDirectories) {\n this.testDirectories.addAll(Arrays.asList(testDirectories));\n return this;\n }\n\n public Builder withSourceFileCharset(Charset sourceFileCharset) {\n this.sourceFileCharset = sourceFileCharset;\n return this;\n }\n\n public Builder enableParallelAnalysis(boolean parallel) {\n this.parallel = parallel;\n return this;\n }\n\n public AnalyzerSettings build() {\n return new AnalyzerSettings(sourceFileCharset, srcDirectories, testDirectories, parallel);\n }\n }\n}",
"public class BannedImportDefinitionException extends RuntimeException {\n\n private static final long serialVersionUID = 8385860286515923706L;\n\n BannedImportDefinitionException(String message) {\n super(message);\n }\n}",
"public final class BannedImportGroup {\n\n private final List<PackagePattern> basePackages;\n private final List<PackagePattern> bannedImports;\n private final List<PackagePattern> allowedImports;\n private final List<PackagePattern> exclusions;\n private final String reason;\n\n private BannedImportGroup(List<PackagePattern> basePackages,\n List<PackagePattern> bannedImports,\n List<PackagePattern> allowedImports,\n List<PackagePattern> exclusions,\n String reason) {\n this.basePackages = basePackages;\n this.bannedImports = bannedImports;\n this.allowedImports = allowedImports;\n this.exclusions = exclusions;\n this.reason = reason;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public List<PackagePattern> getBasePackages() {\n return this.basePackages;\n }\n\n public boolean basePackageMatches(String fqcn) {\n return matchesAnyPattern(fqcn, basePackages);\n }\n\n public List<PackagePattern> getBannedImports() {\n return this.bannedImports;\n }\n\n public Optional<PackagePattern> ifImportIsBanned(String importName) {\n return bannedImports.stream()\n .filter(bannedImport -> bannedImport.matches(importName))\n .filter(result -> !allowedImportMatches(importName))\n .findFirst();\n }\n\n public List<PackagePattern> getAllowedImports() {\n return this.allowedImports;\n }\n\n public boolean allowedImportMatches(String importName) {\n return matchesAnyPattern(importName, allowedImports);\n }\n\n public List<PackagePattern> getExclusions() {\n return this.exclusions;\n }\n\n public boolean exclusionMatches(String fqcn) {\n return matchesAnyPattern(fqcn, exclusions);\n }\n\n private boolean matchesAnyPattern(String packageName,\n Collection<PackagePattern> patterns) {\n return patterns.stream()\n .anyMatch(pattern -> pattern.matches(packageName));\n }\n\n public Optional<String> getReason() {\n return Optional.ofNullable(this.reason).filter(s -> !s.isEmpty());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(basePackages, bannedImports, allowedImports, exclusions, reason);\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj == this || obj instanceof BannedImportGroup\n && Objects.equals(basePackages, ((BannedImportGroup) obj).basePackages)\n && Objects.equals(bannedImports, ((BannedImportGroup) obj).bannedImports)\n && Objects.equals(allowedImports, ((BannedImportGroup) obj).allowedImports)\n && Objects.equals(exclusions, ((BannedImportGroup) obj).exclusions)\n && Objects.equals(reason, ((BannedImportGroup) obj).reason);\n }\n\n @Override\n public String toString() {\n return StringRepresentation.ofInstance(this)\n .add(\"basePackages\", this.basePackages)\n .add(\"bannedImports\", this.bannedImports)\n .add(\"allowedImports\", this.allowedImports)\n .add(\"exclusions\", this.exclusions)\n .add(\"reason\", this.reason)\n .toString();\n }\n\n public static class Builder {\n private List<PackagePattern> basePackages = Collections.emptyList();\n private List<PackagePattern> bannedImports = Collections.emptyList();\n private List<PackagePattern> allowedImports = Collections.emptyList();\n private List<PackagePattern> exclusions = Collections.emptyList();\n private String reason;\n\n private Builder() {\n // hidden\n }\n\n public Builder withBasePackages(List<PackagePattern> basePackages) {\n this.basePackages = basePackages;\n return this;\n }\n\n public Builder withBasePackages(String... basePackages) {\n return withBasePackages(PackagePattern.parseAll(Arrays.asList(basePackages)));\n }\n\n public Builder withBannedImports(List<PackagePattern> bannedImports) {\n this.bannedImports = bannedImports;\n return this;\n }\n\n public Builder withBannedImports(String... bannedImports) {\n return withBannedImports(\n PackagePattern.parseAll(Arrays.asList(bannedImports)));\n }\n\n public Builder withAllowedImports(List<PackagePattern> allowedImports) {\n this.allowedImports = allowedImports;\n return this;\n }\n\n public Builder withAllowedImports(String... allowedImports) {\n return withAllowedImports(\n PackagePattern.parseAll(Arrays.asList(allowedImports)));\n }\n\n public Builder withExclusions(List<PackagePattern> exclusions) {\n this.exclusions = exclusions;\n return this;\n }\n\n public Builder withExclusions(String... exclusions) {\n return withExclusions(\n PackagePattern.parseAll(Arrays.asList(exclusions)));\n }\n\n public Builder withReason(String reason) {\n this.reason = reason;\n return this;\n }\n\n /**\n * Assembles the {@link BannedImportGroup} from this builder.\n *\n * @return The group.\n * @throws BannedImportDefinitionException If the group definition is not\n * consistent.\n */\n public BannedImportGroup build() {\n final BannedImportGroup group = new BannedImportGroup(basePackages,\n bannedImports, allowedImports,\n exclusions, reason);\n checkGroupConsistency(group);\n return group;\n }\n\n private void checkGroupConsistency(BannedImportGroup group) {\n checkAmbiguous(group);\n checkBannedImportsPresent(group);\n allowedImportMustMatchBannedPattern(group);\n checkBasePackageNotStatic(group);\n checkExclusionNotStatic(group);\n exclusionsMustMatchBasePattern(group);\n }\n\n private void checkAmbiguous(BannedImportGroup group) {\n checkAmbiguous(group.getBasePackages(), \"base package\");\n checkAmbiguous(group.getBannedImports(), \"banned import\");\n checkAmbiguous(group.getAllowedImports(), \"allowed import\");\n checkAmbiguous(group.getExclusions(), \"exclusion\");\n }\n\n private void checkAmbiguous(Collection<PackagePattern> patterns, String errorTemplate) {\n for (final PackagePattern outer : patterns) {\n for (final PackagePattern inner : patterns) {\n if (inner != outer && (inner.matches(outer))) {\n throw new BannedImportDefinitionException(String\n .format(\"There are ambiguous %s definitions: %s, %s\", errorTemplate, inner, outer));\n }\n }\n }\n }\n\n private void checkBasePackageNotStatic(BannedImportGroup group) {\n if (group.getBasePackages().stream().anyMatch(PackagePattern::isStatic)) {\n throw new BannedImportDefinitionException(\"Base packages must not be static\");\n }\n }\n\n private void checkExclusionNotStatic(BannedImportGroup group) {\n if (group.getExclusions().stream().anyMatch(PackagePattern::isStatic)) {\n throw new BannedImportDefinitionException(\"Exclusions must not be static\");\n }\n }\n\n private void checkBannedImportsPresent(BannedImportGroup group) {\n if (group.getBannedImports().isEmpty()) {\n throw new BannedImportDefinitionException(\"There are no banned imports specified\");\n }\n }\n\n private void allowedImportMustMatchBannedPattern(BannedImportGroup group) {\n for (final PackagePattern allowedImport : group.getAllowedImports()) {\n final boolean matches = group.getBannedImports().stream()\n .anyMatch(bannedPackage -> bannedPackage.matches(allowedImport));\n if (!matches) {\n throw new BannedImportDefinitionException(String.format(\n \"The allowed import pattern '%s' does not match any banned package.\",\n allowedImport));\n }\n }\n }\n\n private void exclusionsMustMatchBasePattern(BannedImportGroup group) {\n for (final PackagePattern excludedClass : group.getExclusions()) {\n final boolean matches = group.getBasePackages().stream()\n .anyMatch(basePackage -> basePackage.matches(excludedClass));\n if (!matches) {\n throw new BannedImportDefinitionException(String.format(\n \"The exclusion pattern '%s' does not match any base package.\",\n excludedClass));\n }\n }\n }\n }\n}",
"public final class BannedImportGroups {\n\n private final List<BannedImportGroup> groups;\n\n private BannedImportGroups(List<BannedImportGroup> groups) {\n this.groups = groups;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * Selects the {@link BannedImportGroup} with the most specific base package matching\n * the given full qualified class name. If the most specific match also specifies an\n * exclusion pattern for the given fqcn the result will be empty.\n *\n * @param fqcn The full qualified class name to find the group for.\n * @return The group with the most specific base package match.\n */\n public Optional<BannedImportGroup> selectGroupFor(String fqcn) {\n return groups.stream()\n .map(group -> matches(group, fqcn))\n .filter(Optional::isPresent)\n .map(Optional::get)\n .sorted()\n .map(GroupMatch::getGroup)\n .findFirst()\n .filter(group -> !group.exclusionMatches(fqcn));\n }\n\n private Optional<GroupMatch> matches(BannedImportGroup group, String fqcn) {\n return group.getBasePackages().stream()\n .filter(pattern -> pattern.matches(fqcn))\n .findFirst()\n .map(basePackage -> new GroupMatch(basePackage, group));\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(groups);\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj == this || obj instanceof BannedImportGroups\n && Objects.equals(groups, ((BannedImportGroups) obj).groups);\n }\n\n @Override\n public String toString() {\n return groups.stream().map(BannedImportGroup::toString).collect(Collectors.joining(System.lineSeparator()));\n }\n\n private static class GroupMatch implements Comparable<GroupMatch> {\n private final PackagePattern basePackage;\n private final BannedImportGroup group;\n\n public GroupMatch(PackagePattern basePackage, BannedImportGroup group) {\n this.basePackage = basePackage;\n this.group = group;\n }\n\n public BannedImportGroup getGroup() {\n return this.group;\n }\n\n @Override\n public int compareTo(GroupMatch o) {\n return o.basePackage.compareTo(basePackage);\n }\n }\n\n public static final class Builder {\n private final List<BannedImportGroup> groups = new ArrayList<>();\n\n public Builder withGroups(Collection<BannedImportGroup> groups) {\n this.groups.addAll(groups);\n return this;\n }\n\n public Builder withGroup(BannedImportGroup group) {\n this.groups.add(group);\n return this;\n }\n\n public Builder withGroup(BannedImportGroup.Builder groupBuilder) {\n groups.add(groupBuilder.build());\n return this;\n }\n\n public BannedImportGroups build() {\n Preconditions.checkArgument(!groups.isEmpty(), \"No BannedImportGroups have been specified\");\n return new BannedImportGroups(groups);\n }\n }\n}",
"public interface SourceTreeAnalyzer {\n\n /**\n * Creates a new {@link SourceTreeAnalyzer} instance.\n *\n * @return The analyzer.\n */\n static SourceTreeAnalyzer getInstance() {\n return new SourceTreeAnalyzerImpl();\n }\n\n /**\n * Analyzes all java classes found recursively in the given root directories for\n * matches of banned imports.\n *\n * @param settings Context information for performing the analysis.\n * @param groups The banned imports.\n * @return The result of analyzing the given source files.\n */\n AnalyzeResult analyze(AnalyzerSettings settings, BannedImportGroups groups);\n}",
"public interface MatchFormatter {\n\n static MatchFormatter getInstance() {\n return MatchFormatterImpl.INSTANCE;\n }\n\n String formatMatches(Collection<Path> roots, AnalyzeResult analyzeResult);\n}"
] | import static de.skuzzle.enforcer.restrictimports.util.Preconditions.checkArgument;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.maven.enforcer.rule.api.EnforcerLevel;
import org.apache.maven.enforcer.rule.api.EnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRule2;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.project.MavenProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.analyze.AnalyzeResult;
import de.skuzzle.enforcer.restrictimports.analyze.AnalyzerSettings;
import de.skuzzle.enforcer.restrictimports.analyze.BannedImportDefinitionException;
import de.skuzzle.enforcer.restrictimports.analyze.BannedImportGroup;
import de.skuzzle.enforcer.restrictimports.analyze.BannedImportGroups;
import de.skuzzle.enforcer.restrictimports.analyze.SourceTreeAnalyzer;
import de.skuzzle.enforcer.restrictimports.formatting.MatchFormatter; | package org.apache.maven.plugins.enforcer;
/**
* Enforcer rule which restricts the usage of certain packages or classes within a Java
* code base.
*/
public class RestrictImports extends BannedImportGroupDefinition implements EnforcerRule, EnforcerRule2 {
private static final Logger LOGGER = LoggerFactory.getLogger(RestrictImports.class);
private static final String SKIP_PROPERTY_NAME = "restrictimports.skip";
private static final String FAIL_BUILD_PROPERTY_NAME = "restrictimports.failBuild";
private static final String PARALLEL_ANALYSIS_PROPERTY_NAME = "restrictimports.parallel";
private final SourceTreeAnalyzer analyzer = SourceTreeAnalyzer.getInstance();
private final MatchFormatter matchFormatter = MatchFormatter.getInstance();
private List<BannedImportGroupDefinition> groups = new ArrayList<>();
private boolean includeCompileCode = true;
private boolean includeTestCode = true;
private File excludedSourceRoot = null;
private List<File> excludedSourceRoots = new ArrayList<>();
private boolean failBuild = true;
private boolean skip = false;
private boolean parallel = false;
@Override
public EnforcerLevel getLevel() {
return failBuild
? EnforcerLevel.ERROR
: EnforcerLevel.WARN;
}
@Override
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
try {
if (isSkip(helper)) {
LOGGER.info("restrict-imports-enforcer rule is skipped");
return;
}
final MavenProject project = (MavenProject) helper.evaluate("${project}");
LOGGER.debug("Checking for banned imports");
final BannedImportGroups groups = createGroupsFromPluginConfiguration();
LOGGER.debug("Banned import groups:\n{}", groups);
| final AnalyzerSettings analyzerSettings = createAnalyzerSettingsFromPluginConfiguration(helper, project); | 2 |
danijel3/KaldiJava | src/main/java/pl/edu/pjwstk/kaldi/service/tasks/KeywordSpottingTask.java | [
"public class TextGrid extends Segmentation {\n\n\tpublic TextGrid() {\n\n\t}\n\n\tpublic TextGrid(Segmentation segmentation) {\n\t\tthis.tiers = segmentation.tiers;\n\t}\n\n\tprivate String readUntil(BufferedReader reader, String prefix) throws IOException, RuntimeException {\n\t\tString line;\n\t\twhile ((line = reader.readLine()) != null) {\n\t\t\tif (line.trim().startsWith(prefix))\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (line == null)\n\t\t\tthrow new RuntimeException(\"couldn't find required line \" + prefix);\n\n\t\treturn line;\n\t}\n\n\tprivate String removeQuotes(String str) {\n\t\tif (str.charAt(0) == '\"' && str.charAt(str.length() - 1) == '\"')\n\t\t\treturn str.substring(1, str.length() - 1);\n\t\treturn str;\n\t}\n\n\t@Override\n\tpublic void read(File file) throws IOException, RuntimeException {\n\n\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), \"UTF-8\"));\n\n\t\tString line;\n\n\t\tline = readUntil(reader, \"size = \");\n\n\t\tint tierNum = Integer.parseInt(line.trim().substring(7).trim());\n\n\t\treader.readLine();\n\n\t\tfor (int t = 0; t < tierNum; t++) {\n\t\t\tTier tier = new Tier();\n\t\t\ttiers.add(tier);\n\n\t\t\tline = readUntil(reader, \"name = \");\n\n\t\t\ttier.name = removeQuotes(line.trim().substring(7).trim());\n\n\t\t\tline = readUntil(reader, \"intervals: size = \");\n\n\t\t\tint segNum = Integer.parseInt(line.trim().substring(18).trim());\n\n\t\t\tfor (int s = 0; s < segNum; s++) {\n\t\t\t\tline = reader.readLine();\n\t\t\t\tif (!line.trim().equals(\"intervals [\" + (s + 1) + \"]:\"))\n\t\t\t\t\tthrow new RuntimeException(\"error in file \" + file.getName() + \" in line \" + line);\n\n\t\t\t\tSegment segment = new Segment();\n\n\t\t\t\tline = reader.readLine();\n\t\t\t\tsegment.start_time = Double.parseDouble(line.trim().substring(7).trim());\n\t\t\t\tline = reader.readLine();\n\t\t\t\tsegment.end_time = Double.parseDouble(line.trim().substring(7).trim());\n\t\t\t\tline = reader.readLine();\n\t\t\t\tsegment.name = removeQuotes(line.trim().substring(7).trim());\n\n\t\t\t\ttier.segments.add(segment);\n\t\t\t}\n\t\t}\n\n\t\treader.close();\n\n\t}\n\n\t@Override\n\tpublic void write(File file) throws IOException {\n\n\t\tPrintWriter writer = new PrintWriter(file);\n\n\t\twriter.println(\"File type = \\\"ooTextFile\\\"\");\n\t\twriter.println(\"Object class = \\\"TextGrid\\\"\");\n\t\twriter.println();\n\t\twriter.println(\"xmin = \" + min());\n\t\twriter.println(\"xmax = \" + max());\n\t\twriter.println(\"tiers? <exists>\");\n\t\twriter.println(\"size = \" + tiers.size());\n\t\twriter.println(\"item []:\");\n\n\t\tfor (int i = 0; i < tiers.size(); i++) {\n\t\t\tTier tier = tiers.get(i);\n\n\t\t\twriter.println(\"\\titem [\" + (i + 1) + \"]:\");\n\n\t\t\twriter.println(\"\\t\\tclass = \\\"IntervalTier\\\"\");\n\t\t\twriter.println(\"\\t\\tname = \\\"\" + tier.name + \"\\\"\");\n\n\t\t\twriter.println(\"\\t\\txmin = \" + tier.min());\n\t\t\twriter.println(\"\\t\\txmax = \" + tier.max());\n\t\t\twriter.println(\"\\t\\tintervals: size = \" + tier.segments.size());\n\n\t\t\tfor (int j = 0; j < tier.segments.size(); j++) {\n\t\t\t\tSegment segment = tier.segments.get(j);\n\n\t\t\t\twriter.println(\"\\t\\tintervals [\" + (j + 1) + \"]:\");\n\t\t\t\twriter.println(\"\\t\\t\\txmin = \" + segment.start_time);\n\t\t\t\twriter.println(\"\\t\\t\\txmax = \" + segment.end_time);\n\t\t\t\twriter.println(\"\\t\\t\\ttext = \\\"\" + segment.name + \"\\\"\");\n\t\t\t}\n\t\t}\n\n\t\twriter.close();\n\n\t}\n}",
"public class KaldiKWS {\n\n\tpublic static void test() throws FileNotFoundException {\n\t\tif (!Settings.kaldi_kws_bin.exists())\n\t\t\tthrow new FileNotFoundException(Settings.kaldi_kws_bin.getAbsolutePath());\n\t}\n\n\tpublic static void get_vocab(File lattice, File vocab) throws IOException {\n\n\t\tString[] cmd = new String[] { Settings.kaldi_kws_bin.getAbsolutePath(), lattice.getAbsolutePath(),\n\t\t\t\tvocab.getAbsolutePath() };\n\n\t\tProgramLauncher launcher = new ProgramLauncher(cmd);\n\n\t\tLog.verbose(\"KWS generating vocab: \" + lattice.getAbsolutePath() + \" -> \" + vocab.getAbsolutePath());\n\t\tlauncher.run();\n\t\tLog.verbose(\"Done.\");\n\n\t}\n\n\tpublic static void detect(File lattice, File keywords, File dict, File out) throws IOException {\n\n\t\tString[] cmd = new String[] { Settings.kaldi_kws_bin.getAbsolutePath(), lattice.getAbsolutePath(),\n\t\t\t\tkeywords.getAbsolutePath(), dict.getAbsolutePath() };\n\n\t\tProgramLauncher launcher = new ProgramLauncher(cmd);\n\n\t\tlauncher.setStdoutFile(out);\n\n\t\tLog.verbose(\"KWS detecting keywords: \" + lattice.getAbsolutePath() + \" + \" + keywords.getAbsolutePath() + \" + \"\n\t\t\t\t+ dict.getAbsolutePath() + \" -> \" + out.getAbsolutePath());\n\t\tlauncher.run();\n\t\tLog.verbose(\"Done.\");\n\n\t}\n\n\tpublic static void main(String[] args) {\n\t\ttry {\n\t\t\tLocale.setDefault(Locale.ENGLISH);\n\n\t\t\tLog.init(\"debug\", true);\n\n\t\t\tget_vocab(new File(\"/home/guest/Desktop/lucas_kws/paris/130514_NWSU_120A0_O.txt\"),\n\t\t\t\t\tnew File(\"/home/guest/Desktop/lucas_kws/paris/vocab.txt\"));\n\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n}",
"public class KaldiUtils {\n\n private static File utils_dir;\n private static File openfst_dir;\n\n private static File compute_mfcc_feats;\n private static File compute_cmvn_stats;\n private static File splice_feats;\n private static File transform_feats;\n private static File apply_cmvn;\n private static File add_deltas;\n private static File gmm_decode_faster;\n private static File gmm_latgen_faster;\n private static File gmm_align;\n private static File copy_int_vector;\n private static File lattice_copy;\n private static File lattice_oracle;\n private static File lattice_align_words;\n private static File lattice_to_ctm_conf;\n private static File lattice_to_fst;\n private static File lattice_best_path;\n private static File lattice_1best;\n private static File nbest_to_ctm;\n private static File show_alignments;\n private static File lattice_to_phone_lattice;\n private static File linear_to_nbest;\n\n private static File lattice_to_post;\n private static File weight_silence_post;\n private static File gmm_post_to_gpost;\n private static File gmm_est_fmllr_gpost;\n private static File lattice_determinize_pruned;\n private static File gmm_est_fmllr;\n private static File compose_transforms;\n private static File gmm_rescore_lattice;\n\n private static File arpa2fst;\n private static File fstcompile;\n private static File fstarcsort;\n private static File fstrmepsilon;\n private static File fstrandgen;\n private static File fstprint;\n private static File fstdraw;\n private static File fstcompose;\n private static File fstaddselfloops;\n private static File fsttablecompose;\n private static File fstdeterminizestar;\n private static File fstminimizeencoded;\n private static File fstisstochastic;\n private static File fstcomposecontext;\n private static File make_h_transducer;\n private static File fstrmsymbols;\n private static File fstrmepslocal;\n private static File add_self_loops;\n private static File online_wav_gmm_decode_faster;\n\n private static File fst_lib;\n\n private static File eps2disambig;\n private static File s2eps;\n private static File int2sym;\n private static File sym2int;\n private static File add_lex_disambig;\n private static File make_lexicon_fst;\n\n private static File prepare_lang;\n\n private static ArrayList<File> fstlibs;\n\n public static void init() {\n utils_dir = new File(Settings.kaldi_root, \"egs/wsj/s5/utils\");\n openfst_dir = new File(Settings.kaldi_root, \"tools/openfst-1.3.4\");\n\n compute_mfcc_feats = new File(Settings.kaldi_root, \"src/featbin/compute-mfcc-feats\");\n compute_cmvn_stats = new File(Settings.kaldi_root, \"src/featbin/compute-cmvn-stats\");\n splice_feats = new File(Settings.kaldi_root, \"src/featbin/splice-feats\");\n transform_feats = new File(Settings.kaldi_root, \"src/featbin/transform-feats\");\n apply_cmvn = new File(Settings.kaldi_root, \"src/featbin/apply-cmvn\");\n add_deltas = new File(Settings.kaldi_root, \"src/featbin/add-deltas\");\n gmm_decode_faster = new File(Settings.kaldi_root, \"src/gmmbin/gmm-decode-faster\");\n gmm_latgen_faster = new File(Settings.kaldi_root, \"src/gmmbin/gmm-latgen-faster\");\n gmm_align = new File(Settings.kaldi_root, \"src/gmmbin/gmm-align\");\n copy_int_vector = new File(Settings.kaldi_root, \"src/bin/copy-int-vector\");\n lattice_copy = new File(Settings.kaldi_root, \"src/latbin/lattice-copy\");\n lattice_oracle = new File(Settings.kaldi_root, \"src/latbin/lattice-oracle\");\n lattice_align_words = new File(Settings.kaldi_root, \"src/latbin/lattice-align-words\");\n lattice_to_ctm_conf = new File(Settings.kaldi_root, \"src/latbin/lattice-to-ctm-conf\");\n lattice_to_fst = new File(Settings.kaldi_root, \"src/latbin/lattice-to-fst\");\n lattice_1best = new File(Settings.kaldi_root, \"src/latbin/lattice-1best\");\n lattice_best_path = new File(Settings.kaldi_root, \"src/latbin/lattice-best-path\");\n nbest_to_ctm = new File(Settings.kaldi_root, \"src/latbin/nbest-to-ctm\");\n show_alignments = new File(Settings.kaldi_root, \"src/bin/show-alignments\");\n lattice_to_phone_lattice = new File(Settings.kaldi_root, \"src/latbin/lattice-to-phone-lattice\");\n linear_to_nbest = new File(Settings.kaldi_root, \"src/latbin/linear-to-nbest\");\n lattice_to_post = new File(Settings.kaldi_root, \"src/latbin/lattice-to-post\");\n weight_silence_post = new File(Settings.kaldi_root, \"src/bin/weight-silence-post\");\n gmm_post_to_gpost = new File(Settings.kaldi_root, \"src/gmmbin/gmm-post-to-gpost\");\n gmm_est_fmllr_gpost = new File(Settings.kaldi_root, \"src/gmmbin/gmm-est-fmllr-gpost\");\n lattice_determinize_pruned = new File(Settings.kaldi_root, \"src/latbin/lattice-determinize-pruned\");\n gmm_est_fmllr = new File(Settings.kaldi_root, \"src/gmmbin/gmm-est-fmllr\");\n compose_transforms = new File(Settings.kaldi_root, \"src/featbin/compose-transforms\");\n gmm_rescore_lattice = new File(Settings.kaldi_root, \"src/gmmbin/gmm-rescore-lattice\");\n arpa2fst = new File(Settings.kaldi_root, \"src/bin/arpa2fst\");\n fstcompile = new File(openfst_dir, \"bin/fstcompile\");\n fstarcsort = new File(openfst_dir, \"bin/fstarcsort\");\n fstrmepsilon = new File(openfst_dir, \"bin/fstrmepsilon\");\n fstprint = new File(openfst_dir, \"bin/fstprint\");\n fstrandgen = new File(openfst_dir, \"bin/fstrandgen\");\n fstdraw = new File(openfst_dir, \"bin/fstdraw\");\n fstcompose = new File(openfst_dir, \"bin/fstcompose\");\n fstaddselfloops = new File(Settings.kaldi_root, \"src/fstbin/fstaddselfloops\");\n fsttablecompose = new File(Settings.kaldi_root, \"src/fstbin/fsttablecompose\");\n fstdeterminizestar = new File(Settings.kaldi_root, \"src/fstbin/fstdeterminizestar\");\n fstminimizeencoded = new File(Settings.kaldi_root, \"src/fstbin/fstminimizeencoded\");\n fstisstochastic = new File(Settings.kaldi_root, \"src/fstbin/fstisstochastic\");\n fstcomposecontext = new File(Settings.kaldi_root, \"src/fstbin/fstcomposecontext\");\n make_h_transducer = new File(Settings.kaldi_root, \"src/bin/make-h-transducer\");\n fstrmsymbols = new File(Settings.kaldi_root, \"src/fstbin/fstrmsymbols\");\n fstrmepslocal = new File(Settings.kaldi_root, \"src/fstbin/fstrmepslocal\");\n add_self_loops = new File(Settings.kaldi_root, \"src/bin/add-self-loops\");\n online_wav_gmm_decode_faster = new File(Settings.kaldi_root, \"src/onlinebin/online-wav-gmm-decode-faster\");\n\n fst_lib = new File(openfst_dir, \"lib\");\n\n eps2disambig = new File(utils_dir, \"eps2disambig.pl\");\n s2eps = new File(utils_dir, \"s2eps.pl\");\n int2sym = new File(utils_dir, \"int2sym.pl\");\n sym2int = new File(utils_dir, \"sym2int.pl\");\n make_lexicon_fst = new File(utils_dir, \"make_lexicon_fst.pl\");\n add_lex_disambig = new File(utils_dir, \"add_lex_disambig.pl\");\n\n prepare_lang = new File(utils_dir, \"prepare_lang.sh\");\n\n fstlibs = new ArrayList<File>();\n fstlibs.add(fst_lib);\n }\n\n public static void test() throws FileNotFoundException {\n\n Field fields[] = KaldiUtils.class.getDeclaredFields();\n for (Field field : fields) {\n if (Modifier.isStatic(field.getModifiers()) && field.getType().getName().equals(\"java.io.File\")) {\n\n try {\n\n File file = (File) field.get(null);\n\n if (file == null || !file.exists())\n throw new FileNotFoundException(\"\" + file);\n\n } catch (IllegalArgumentException | IllegalAccessException e) {\n Log.error(\"Internal error\", e);\n }\n }\n }\n\n for (File file : fstlibs) {\n if (!file.exists())\n throw new FileNotFoundException(file.getAbsolutePath());\n }\n\n }\n\n public static void generateWordsMapping(File vocab, String vocab_enc, File mapping, String mapping_enc)\n throws IOException {\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(vocab), vocab_enc));\n PrintWriter writer = new PrintWriter(mapping, mapping_enc);\n\n writer.println(\"<eps> 0\");\n writer.println(\"!SIL 1\");\n writer.println(\"SIL 2\");\n writer.println(\"<UNK> 3\");\n\n int i = 4;\n String line;\n while ((line = reader.readLine()) != null) {\n\n if (line.equals(\"<s>\"))\n continue;\n if (line.equals(\"</s>\"))\n continue;\n\n writer.println(line + \" \" + i);\n i++;\n }\n\n writer.println(\"#0 \" + i);\n\n reader.close();\n writer.close();\n\n }\n\n public static void compute_mfcc_feats(File config, File scp, File out) {\n\n String[] cmd = new String[]{compute_mfcc_feats.getAbsolutePath(), \"--config=\" + config.getAbsolutePath(),\n \"scp:\" + scp.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"compute_mfcc_feats: \" + scp.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void compute_cmvn_stats(File in, File out) {\n\n String[] cmd = new String[]{compute_cmvn_stats.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(),\n \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"compute_cmvn_stats: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void apply_cmvn(File stats, File in, File out) {\n\n String[] cmd = new String[]{apply_cmvn.getAbsolutePath(), \"ark:\" + stats.getAbsolutePath(),\n \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"apply_cmvn: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void add_deltas(File in, File out) {\n\n String[] cmd = new String[]{add_deltas.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(),\n \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"add_deltas: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void splice_feats(File in, File out) {\n\n String[] cmd = new String[]{splice_feats.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(),\n \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"splice_feats: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void transform_feats(File trans, boolean trans_ark, File in, File out) {\n\n String trans_ark_str = \"\";\n if (trans_ark)\n trans_ark_str = \"ark:\";\n\n String[] cmd = new String[]{transform_feats.getAbsolutePath(), trans_ark_str + trans.getAbsolutePath(),\n \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"transform_feats: \" + in.getName() + \"->{\" + trans.getName() + \"}->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void gmm_decode_faster(File word_symbol_table, File model, File fst, File feat, File out)\n throws RuntimeException {\n\n String[] cmd = new String[]{gmm_decode_faster.getAbsolutePath(),\n \"--word-symbol-table=\" + word_symbol_table.getAbsolutePath(), model.getAbsolutePath(),\n fst.getAbsolutePath(), \"ark:\" + feat.getAbsolutePath(), \"ark:\" + out};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"gmm_decode_faster: \" + feat.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n\n }\n\n public static void gmm_latgen_faster(File model, File fst, File feat, File lattice, File words, File alignment)\n throws RuntimeException {\n\n /*String[] cmd = new String[]{gmm_latgen_faster.getAbsolutePath(), model.getAbsolutePath(),\n fst.getAbsolutePath(), \"ark:\" + feat.getAbsolutePath(), \"ark:\" + lattice.getAbsolutePath(),\n \"ark:\" + words.getAbsolutePath(), \"ark:\" + alignment.getAbsolutePath()};*/\n\n String[] cmd = new String[]{gmm_latgen_faster.getAbsolutePath(),\n /*\"--verbose=100\", \"--max-active=7000\", \"--beam=64.0\", \"--lattice-beam=36.0\", \"--acoustic-scale=0.083333\",*/\n //\"--allow-partial=true\",\n //\"--determinize-lattice=false\",\n model.getAbsolutePath(), fst.getAbsolutePath(), \"ark:\" + feat.getAbsolutePath(), \"ark:\" + lattice.getAbsolutePath(),\n \"ark:\" + words.getAbsolutePath(), \"ark:\" + alignment.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"gmm_latgen_faster: \" + feat.getName() + \"->\" + lattice.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n\n }\n\n public static void gmm_align(double beam, double retry_beam, File tree, File model, File lexicon, File feat,\n File transcription, File alignment) throws RuntimeException {\n\n String[] cmd = new String[]{gmm_align.getAbsolutePath(), \"--beam=\" + beam, \"--retry-beam=\" + retry_beam,\n tree.getAbsolutePath(), model.getAbsolutePath(), lexicon.getAbsolutePath(),\n \"ark:\" + feat.getAbsolutePath(), \"ark:\" + transcription.getAbsolutePath(),\n \"ark:\" + alignment.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"gmm_align: \" + feat.getName() + \"->\" + alignment.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n\n }\n\n public static void copy_int_vector(String in_type, File in, String out_type, File out) {\n\n String[] cmd = new String[]{copy_int_vector.getAbsolutePath(), in_type + \":\" + in.getAbsolutePath(),\n out_type + \":\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"copy_int_vector: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void lattice_1best(File in, File out) {\n\n String[] cmd = new String[]{lattice_1best.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(),\n \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_1best: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void lattice_copy(String input_opts, File input_lattice, String output_opts, File output_lattice,\n boolean write_compact) {\n\n String wc_str = \"false\";\n if (write_compact)\n wc_str = \"true\";\n\n String[] cmd = new String[]{lattice_copy.getAbsolutePath(), \"--write-compact=\" + wc_str,\n input_opts + \":\" + input_lattice.getAbsolutePath(),\n output_opts + \":\" + output_lattice.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_copy: \" + input_opts + \":\" + input_lattice.getAbsolutePath() + \" -> \" + output_opts + \":\"\n + output_lattice.getAbsolutePath());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void lattice_oracle(File lattice, File input_txt, File output_lattice, File word_symbol_table) {\n\n String[] cmd = new String[]{lattice_oracle.getAbsolutePath(),\n \"--write-lattices=ark:\" + output_lattice.getAbsolutePath(),\n \"--word-symbol-table=\" + word_symbol_table.getAbsolutePath(), \"ark:\" + lattice.getAbsolutePath(),\n \"ark:\" + input_txt.getAbsolutePath(), \"ark,t:-\"};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_oracle: \" + lattice.getName() + \"->\" + output_lattice.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void lattice_align_words(File word_boundaries, File model, File in, File out) {\n\n String[] cmd = new String[]{lattice_align_words.getAbsolutePath(), word_boundaries.getAbsolutePath(),\n model.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_align_words: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void nbest_to_ctm(File in, File out) {\n\n String[] cmd = new String[]{nbest_to_ctm.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(),\n out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"nbest_to_ctm: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void lattice_to_ctm_conf(File in, File out) {\n\n String[] cmd = new String[]{lattice_to_ctm_conf.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(),\n out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_to_ctm_conf: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void lattice_to_fst(File in, File out_txt) {\n\n String[] cmd = new String[]{lattice_to_fst.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(),\n \"ark,t:\" + out_txt.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_to_fst: \" + in.getName() + \"->\" + out_txt.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void show_alignments(File phone_sym_table, File model, File alignment, File out)\n throws FileNotFoundException {\n\n String[] cmd = new String[]{show_alignments.getAbsolutePath(), phone_sym_table.getAbsolutePath(),\n model.getAbsolutePath(), \"ark:\" + alignment.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutFile(out);\n\n Log.verbose(\"show_alignments: \" + alignment.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void lattice_to_phone_lattice(File model, File in, File out) {\n\n String[] cmd = new String[]{lattice_to_phone_lattice.getAbsolutePath(), model.getAbsolutePath(),\n \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_to_phone_lattice: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void linear_to_nbest(File alignment, File transcription, File nbest) {\n\n String[] cmd = new String[]{linear_to_nbest.getAbsolutePath(), \"ark:\" + alignment.getAbsolutePath(),\n \"ark:\" + transcription.getAbsolutePath(), \"\", \"\", \"ark:\" + nbest.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"linear_to_nbest: \" + alignment.getName() + \"->\" + nbest.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void lattice_best_path(File lat, File tra, File ali) {\n\n String[] cmd = new String[]{lattice_best_path.getAbsolutePath(), \"ark:\" + lat.getAbsolutePath(),\n \"ark:\" + tra.getAbsolutePath(), \"ark:\" + ali.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_best_path: \" + lat.getName() + \"->\" + tra.getName());\n\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void lattice_to_post(double acoustic_scale, File in, File out) throws RuntimeException {\n\n String[] cmd = new String[]{lattice_to_post.getAbsolutePath(), \"--acoustic-scale=\" + acoustic_scale,\n \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_to_post: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n }\n\n public static void weight_silence_post(double silence_weight, String silence_list, File mdl, File in, File out)\n throws RuntimeException {\n\n String[] cmd = new String[]{weight_silence_post.getAbsolutePath(), \"\" + silence_weight, silence_list,\n mdl.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"weight_silence_post: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n }\n\n public static void gmm_post_to_gpost(File model, File feat, File in, File out) throws RuntimeException {\n\n String[] cmd = new String[]{gmm_post_to_gpost.getAbsolutePath(), model.getAbsolutePath(),\n \"ark:\" + feat.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"gmm_post_to_gpost: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n }\n\n public static enum FMLLRUpdateType {\n full, diag, offset, none\n }\n\n public static void gmm_est_fmllr_gpost(FMLLRUpdateType update_type, File spk2utt, File model, File feat, File in,\n File out) throws RuntimeException {\n\n String updTypStr = \"--fmllr-update-type=\";\n\n switch (update_type) {\n case diag:\n updTypStr += \"diag\";\n break;\n default:\n case full:\n updTypStr += \"full\";\n break;\n case none:\n updTypStr += \"none\";\n break;\n case offset:\n updTypStr += \"offset\";\n break;\n }\n\n String[] cmd = new String[]{gmm_est_fmllr_gpost.getAbsolutePath(), updTypStr, model.getAbsolutePath(),\n \"ark:\" + feat.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n if (spk2utt != null) {\n cmd = new String[]{gmm_est_fmllr_gpost.getAbsolutePath(), updTypStr,\n \"--spk2utt=ark:\" + spk2utt.getAbsolutePath(), model.getAbsolutePath(),\n \"ark:\" + feat.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n }\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"gmm_est_fmllr_gpost: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n }\n\n public static void lattice_determinize_pruned(double acoustic_scale, double beam, File in, File out)\n throws RuntimeException {\n\n String[] cmd = new String[]{lattice_determinize_pruned.getAbsolutePath(),\n \"--acoustic-scale=\" + acoustic_scale, \"--beam=\" + beam, \"ark:\" + in.getAbsolutePath(),\n \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"lattice_determinize_pruned: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n }\n\n public static void gmm_est_fmllr(FMLLRUpdateType update_type, File spk2utt, File model, File feat, File in,\n File out) throws RuntimeException {\n\n String updTypStr = \"--fmllr-update-type=\";\n\n switch (update_type) {\n case diag:\n updTypStr += \"diag\";\n break;\n default:\n case full:\n updTypStr += \"full\";\n break;\n case none:\n updTypStr += \"none\";\n break;\n case offset:\n updTypStr += \"offset\";\n break;\n }\n\n String[] cmd = new String[]{gmm_est_fmllr.getAbsolutePath(), updTypStr, model.getAbsolutePath(),\n \"ark:\" + feat.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n if (spk2utt != null) {\n cmd = new String[]{gmm_est_fmllr.getAbsolutePath(), updTypStr,\n \"--spk2utt=ark:\" + spk2utt.getAbsolutePath(), model.getAbsolutePath(),\n \"ark:\" + feat.getAbsolutePath(), \"ark:\" + in.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n }\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"gmm_est_fmllr: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n }\n\n public static void compose_transforms(boolean bIsAffine, File in_a, File in_b, File out) throws RuntimeException {\n\n String bIsAffineStr = \"--b-is-affine=\";\n if (bIsAffine)\n bIsAffineStr += \"true\";\n else\n bIsAffineStr += \"false\";\n\n String[] cmd = new String[]{compose_transforms.getAbsolutePath(), bIsAffineStr,\n \"ark:\" + in_a.getAbsolutePath(), \"ark:\" + in_b.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"compose_transforms: \" + in_a.getName() + \"+\" + in_b.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n }\n\n public static void gmm_rescore_lattice(File model, File in, File feat, File out) throws RuntimeException {\n\n String[] cmd = new String[]{gmm_rescore_lattice.getAbsolutePath(), model.getAbsolutePath(),\n \"ark:\" + in.getAbsolutePath(), \"ark:\" + feat.getAbsolutePath(), \"ark:\" + out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"gmm_rescore_lattice: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n }\n\n public static void arpa2fst(File arpa, File fst) {\n\n String[] cmd = new String[]{arpa2fst.getAbsolutePath(), arpa.getAbsolutePath(), fst.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"arpa2fst: \" + arpa.getName() + \"->\" + fst.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void fstprint(File fst, File txt) {\n\n String[] cmd = new String[]{fstprint.getAbsolutePath(), fst.getAbsolutePath(), txt.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstprint: \" + fst.getName() + \"->\" + txt.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstprint(File fst, File txt, File input_symbols, File output_symbols) {\n\n String[] cmd = new String[]{fstprint.getAbsolutePath(),\n \"--isymbols=\" + input_symbols.getAbsolutePath(), \"--osymbols=\" + output_symbols.getAbsolutePath(),\n fst.getAbsolutePath(), txt.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstprint: \" + fst.getName() + \"->\" + txt.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstrandgen(File fst, File rand, int seed) {\n\n String[] cmd = new String[]{fstrandgen.getAbsolutePath(), \"--seed=\" + seed, fst.getAbsolutePath(), rand.getAbsolutePath(),};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstrandgen: \" + fst.getName() + \"->\" + rand.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstdraw(File fst, File dot, File isyms, File osyms, boolean acceptor) {\n\n String[] cmd = new String[]{fstdraw.getAbsolutePath(),\n \"--isymbols=\" + isyms.getAbsolutePath(), \"--osymbols=\" + osyms.getAbsolutePath(),\n fst.getAbsolutePath(), dot.getAbsolutePath()};\n\n if (acceptor) {\n cmd = new String[]{fstdraw.getAbsolutePath(), \"--acceptor\",\n \"--isymbols=\" + isyms.getAbsolutePath(), \"--osymbols=\" + osyms.getAbsolutePath(),\n fst.getAbsolutePath(), dot.getAbsolutePath()};\n }\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstdraw: \" + fst.getName() + \"->\" + dot.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstcompose(File fsta, File fstb, File fstout) {\n\n String[] cmd = new String[]{fstcompose.getAbsolutePath(),\n fsta.getAbsolutePath(), fstb.getAbsolutePath(), fstout.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstcompose: \" + fsta.getName() + \" + \" + fstb.getAbsolutePath() + \"->\" + fstout.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void eps2disambig(File fst_in, File fst_out) throws FileNotFoundException {\n String[] cmd = new String[]{Settings.perl_bin.getAbsolutePath(), eps2disambig.getAbsolutePath(),\n fst_in.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setStdoutFile(fst_out);\n\n Log.verbose(\"eps2disambig: \" + fst_in.getName() + \"->\" + fst_out.getName());\n Log.verbose(\"<SUPRESSING OUTPUT>\");\n launcher.run();\n Log.verbose(\"Done.\");\n\n }\n\n public static void s2eps(File fst_in, File fst_out) throws FileNotFoundException {\n String[] cmd = new String[]{Settings.perl_bin.getAbsolutePath(), s2eps.getAbsolutePath(),\n fst_in.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setStdoutFile(fst_out);\n\n Log.verbose(\"s2eps: \" + fst_in.getName() + \"->\" + fst_out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void int2sym(String field, File string_table, File in, File out) throws FileNotFoundException {\n String[] cmd = new String[]{Settings.perl_bin.getAbsolutePath(), int2sym.getAbsolutePath(), \"-f\", field,\n string_table.getAbsolutePath(), in.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setStdoutFile(out);\n\n Log.verbose(\"int2sym: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void sym2int(String field, File string_table, File in, File out) throws FileNotFoundException {\n String[] cmd = new String[]{Settings.perl_bin.getAbsolutePath(), sym2int.getAbsolutePath(), \"-f\", field, \"--map-oov\", \"<UNK>\",\n string_table.getAbsolutePath(), in.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setStdoutFile(out);\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"sym2int: \" + in.getName() + \"->\" + out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstcompile(File isymbols, File osymbols, boolean keep_isymbols, boolean keep_osymbols,\n File fst_in, File fst_out) {\n\n String keep_isymbols_str = \"true\";\n if (!keep_isymbols)\n keep_isymbols_str = \"false\";\n String keep_osymbols_str = \"true\";\n if (!keep_osymbols)\n keep_osymbols_str = \"false\";\n\n String[] cmd = new String[]{fstcompile.getAbsolutePath(), \"--isymbols=\" + isymbols.getAbsolutePath(),\n \"--osymbols=\" + osymbols.getAbsolutePath(), \"--keep_isymbols=\" + keep_isymbols_str,\n \"--keep_osymbols=\" + keep_osymbols_str, fst_in.getAbsolutePath(), fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstcompile: \" + fst_in.getName() + \"->\" + fst_out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstarcsort(String sort_type, File fst_in, File fst_out) {\n\n String[] cmd = new String[]{fstarcsort.getAbsolutePath(), \"--sort_type=\" + sort_type, fst_in.getAbsolutePath(), fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstarcsort: \" + fst_in.getName() + \"->\" + fst_out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstaddselfloops(File in_disambig_list, File out_disambig_list, File fst_in, File fst_out) {\n\n String[] cmd = new String[]{fstaddselfloops.getAbsolutePath(), in_disambig_list.getAbsolutePath(), out_disambig_list.getAbsolutePath(),\n fst_in.getAbsolutePath(), fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstaddselfloops: \" + fst_in.getName() + \"->\" + fst_out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n\n public static void prepareLexicon(File dict_dir, File lang_dir) {\n\n String[] cmd = new String[]{Settings.bash_bin.getAbsolutePath(), prepare_lang.getAbsolutePath(),\n dict_dir.getAbsolutePath(), \"<UNK>\", lang_dir.getAbsolutePath(), dict_dir.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setCwd(utils_dir.getParentFile());\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"prepareLexicon...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static int add_lex_disambig(boolean sil_probs, boolean pron_probs, File lex_in, File lex_out) {\n Vector<String> cmd_vec = new Vector<String>();\n cmd_vec.add(Settings.perl_bin.getAbsolutePath());\n cmd_vec.add(add_lex_disambig.getAbsolutePath());\n if (sil_probs)\n cmd_vec.add(\"--sil-probs\");\n if (pron_probs)\n cmd_vec.add(\"--pron-probs\");\n cmd_vec.add(lex_in.getAbsolutePath());\n cmd_vec.add(lex_out.getAbsolutePath());\n\n String[] cmd = cmd_vec.toArray(new String[]{});\n\n ByteArrayOutputStream ostr = new ByteArrayOutputStream();\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setStdoutStream(ostr);\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"add_lex_disambig: \" + lex_in.getName() + \" -> \" + lex_out.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n\n String ret = new String(ostr.toByteArray()).trim();\n return Integer.parseInt(ret);\n }\n\n public static void make_lexicon_fst(boolean pron_prob, File lex, double silprob, String silphone, int ndisambig, File fst) throws FileNotFoundException {\n Vector<String> cmd_vec = new Vector<String>();\n cmd_vec.add(Settings.perl_bin.getAbsolutePath());\n cmd_vec.add(make_lexicon_fst.getAbsolutePath());\n if (pron_prob)\n cmd_vec.add(\"--pron-probs\");\n cmd_vec.add(lex.getAbsolutePath());\n cmd_vec.add(\"\" + silprob);\n cmd_vec.add(silphone);\n if (ndisambig > 0)\n cmd_vec.add(\"#\" + ndisambig);\n\n String[] cmd = cmd_vec.toArray(new String[]{});\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setStdoutFile(fst);\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"make_lexicon_fst: \" + lex.getName() + \" -> \" + fst.getName());\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fsttablecompose(File fst_one, File fst_two, File fst_out) {\n String[] cmd = new String[]{fsttablecompose.getAbsolutePath(), fst_one.getAbsolutePath(),\n fst_two.getAbsolutePath(), fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\n \"fsttablecompose: \" + fst_one.getName() + \"+\" + fst_two.getName() + \"=\" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstdeterminizestar(File fst_in, File fst_out, boolean use_log) {\n\n String strUseLog = \"true\";\n if (!use_log)\n strUseLog = \"false\";\n\n String[] cmd = new String[]{fstdeterminizestar.getAbsolutePath(), \"--use-log=\" + strUseLog,\n fst_in.getAbsolutePath(), fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstdeterminizestar: \" + fst_in.getName() + \" -> \" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstminimizeencoded(File fst_in, File fst_out) {\n String[] cmd = new String[]{fstminimizeencoded.getAbsolutePath(), fst_in.getAbsolutePath(),\n fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstminimizeencoded: \" + fst_in.getName() + \" -> \" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static boolean fstisstochastic(File fst) {\n\n String[] cmd = new String[]{fstisstochastic.getAbsolutePath(), fst.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstisstochastic: \" + fst.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() == 0)\n return true;\n else\n return false;\n }\n\n public static void fstcomposecontext(int context_size, int central_position, File disamb_syms_in,\n File disamb_syms_out, File ilabels_out, File fst_in, File fst_out) {\n\n String[] cmd = new String[]{fstcomposecontext.getAbsolutePath(), \"--context-size=\" + context_size,\n \"--central-position=\" + central_position, \"--read-disambig-syms=\" + disamb_syms_in.getAbsolutePath(),\n \"--write-disambig-syms=\" + disamb_syms_out.getAbsolutePath(), ilabels_out.getAbsolutePath(),\n fst_in.getAbsolutePath(), fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstcomposecontext: \" + fst_in.getName() + \" -> \" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void make_h_transducer(File disamb_syms_out, float trans_scale, File ilabels, File tree, File mdl_in,\n File fst_out) {\n\n String[] cmd = new String[]{make_h_transducer.getAbsolutePath(),\n \"--disambig-syms-out=\" + disamb_syms_out.getAbsolutePath(), \"--transition-scale=\" + trans_scale,\n ilabels.getAbsolutePath(), tree.getAbsolutePath(), mdl_in.getAbsolutePath(),\n fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"make_h_transducer: \" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstrmsymbols(File syms, File fst_in, File fst_out) {\n\n String[] cmd = new String[]{fstrmsymbols.getAbsolutePath(), syms.getAbsolutePath(), fst_in.getAbsolutePath(),\n fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstrmsymbols: \" + fst_in.getName() + \" -> \" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstrmepslocal(File fst_in, File fst_out) {\n\n String[] cmd = new String[]{fstrmepslocal.getAbsolutePath(), fst_in.getAbsolutePath(),\n fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstrmsymbols: \" + fst_in.getName() + \" -> \" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void fstrmepsilon(File fst_in, File fst_out) {\n\n String[] cmd = new String[]{fstrmepsilon.getAbsolutePath(), fst_in.getAbsolutePath(),\n fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"fstrmepsilon: \" + fst_in.getName() + \" -> \" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n\n public static void add_self_loops(float loop_scale, boolean reorder, File mdl_in, File fst_in, File fst_out)\n throws RuntimeException {\n\n String strReorder = \"true\";\n if (!reorder)\n strReorder = \"false\";\n\n String[] cmd = new String[]{add_self_loops.getAbsolutePath(), \"--self-loop-scale=\" + loop_scale,\n \"--reorder=\" + strReorder, mdl_in.getAbsolutePath(), fst_in.getAbsolutePath(),\n fst_out.getAbsolutePath()};\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"add_self_loops: \" + fst_in.getName() + \" -> \" + fst_out.getName() + \"...\");\n launcher.run();\n Log.verbose(\"Done.\");\n\n if (launcher.getReturnValue() != 0)\n throw new RuntimeException(\"Retval: \" + launcher.getReturnValue());\n\n }\n\n public static void online_wav_gmm_decode_faster(float rt_min, float rt_max, int max_active, float beam,\n float acoustic_scale, File wav_scp, File mdl_file, File HCLG_fst, File words_list, File trans, File ali,\n File lda_matrix) {\n\n String[] cmd;\n\n if (lda_matrix != null) {\n cmd = new String[]{online_wav_gmm_decode_faster.getAbsolutePath(), \"--verbose=1\", \"--rt-min=\" + rt_min,\n \"--rt-max=\" + rt_max, \"--max-active=\" + max_active, \"--beam=\" + beam,\n \"--acoustic-scale=\" + acoustic_scale, \"scp:\" + wav_scp.getAbsolutePath(),\n mdl_file.getAbsolutePath(), HCLG_fst.getAbsolutePath(), words_list.getAbsolutePath(), \"1:2:3:4:5\",\n \"ark,t:\" + trans.getAbsolutePath(), \"ark,t:\" + ali.getAbsolutePath(),\n lda_matrix.getAbsolutePath()};\n } else {\n cmd = new String[]{online_wav_gmm_decode_faster.getAbsolutePath(), \"--verbose=1\", \"--rt-min=\" + rt_min,\n \"--rt-max=\" + rt_max, \"--max-active=\" + max_active, \"--beam=\" + beam,\n \"--acoustic-scale=\" + acoustic_scale, \"scp:\" + wav_scp.getAbsolutePath(),\n mdl_file.getAbsolutePath(), HCLG_fst.getAbsolutePath(), words_list.getAbsolutePath(), \"1:2:3:4:5\",\n \"ark,t:\" + trans.getAbsolutePath(), \"ark,t:\" + ali.getAbsolutePath()};\n }\n\n ProgramLauncher launcher = new ProgramLauncher(cmd);\n launcher.setLibraries(fstlibs);\n launcher.setStdoutStream(new Log.Stream());\n launcher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n Log.verbose(\"online_wav_gmm_decode_faster...\");\n launcher.run();\n Log.verbose(\"Done.\");\n }\n}",
"public class Transcriber {\n\n\tprivate static File transcriber_bin;\n\tprivate static File rules;\n\tprivate static File replacement;\n\n\tpublic static void init() {\n\t\ttranscriber_bin = new File(Settings.transcriber_dir, \"transcriber\");\n\t\trules = new File(Settings.transcriber_dir, \"transcription.rules\");\n\t\treplacement = new File(Settings.transcriber_dir, \"replacement.rules\");\n\t}\n\n\tpublic static void test() throws FileNotFoundException {\n\t\tif (!Settings.transcriber_dir.exists())\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\tSettings.transcriber_dir.getAbsolutePath());\n\t\tif (!transcriber_bin.exists())\n\t\t\tthrow new FileNotFoundException(transcriber_bin.getAbsolutePath());\n\t\tif (!rules.exists())\n\t\t\tthrow new FileNotFoundException(rules.getAbsolutePath());\n\t\tif (!replacement.exists())\n\t\t\tthrow new FileNotFoundException(replacement.getAbsolutePath());\n\t}\n\n\tpublic static void transcribe(File vocab, String vocab_enc, File dict,\n\t\t\tString dict_enc, boolean add_sent_boundaries) throws IOException {\n\n\t\tFile temp_vocab = File.createTempFile(\"voc\", \".txt\");\n\t\tFile temp_dic = File.createTempFile(\"dic\", \".txt\");\n\n\t\tArrayList<String> sent = new ArrayList<String>();\n\t\tsent.add(\"<s>\");\n\t\tsent.add(\"</s>\");\n\t\tsent.add(\"<unk>\");\n\t\tsent.add(\"<UNK>\");\n\t\tsent.add(\"sil\");\n\t\tsent.add(\"SIL\");\n\t\tsent.add(\"-pau-\");\n\n\t\tFileUtils.removeLines(vocab, vocab_enc, temp_vocab, vocab_enc, sent,\n\t\t\t\ttrue);\n\n\t\tString[] cmd = new String[] { transcriber_bin.getAbsolutePath(), \"-r\",\n\t\t\t\trules.getAbsolutePath(), \"-w\", replacement.getAbsolutePath(),\n\t\t\t\t\"-i\", temp_vocab.getAbsolutePath(), \"-ie\", vocab_enc, \"-o\",\n\t\t\t\ttemp_dic.getAbsolutePath(), \"-oe\", dict_enc };\n\n\t\tProgramLauncher launcher = new ProgramLauncher(cmd);\n\n\t\tlauncher.setStdoutStream(new Log.Stream());\n\t\tlauncher.setStderrStream(new Log.Stream(\"ERR>>\"));\n\n\t\tLog.verbose(\"Transcribing...\");\n\t\tlauncher.run();\n\t\tLog.verbose(\"Done.\");\n\n\t\tArrayList<String> dic = new ArrayList<String>();\n\t\tdic.add(\"SIL sil\");\n\t\tdic.add(\"<UNK> sil\");\n\n\t\tif (add_sent_boundaries) {\n\t\t\tdic.add(\"<s> sil\");\n\t\t\tdic.add(\"</s> sil\");\n\t\t}\n\n\t\tFileUtils.appendLines(temp_dic, dict_enc, dict, dict_enc, dic, true);\n\n\t\ttemp_vocab.delete();\n\t\ttemp_dic.delete();\n\t}\n\n}",
"public class FileUtils {\n\n /**\n * Convert encoding of files.\n *\n * @param input input file\n * @param input_enc encoding of input file\n * @param output output file\n * @param output_enc encoding of output file\n * @throws IOException\n */\n\n public static void iconv(File input, String input_enc, File output, String output_enc) throws IOException {\n\n InputStreamReader reader = new InputStreamReader(new FileInputStream(input), input_enc);\n OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(output), output_enc);\n\n char buf[] = new char[512];\n\n int ret;\n while ((ret = reader.read(buf)) >= 0)\n writer.write(buf, 0, ret);\n\n reader.close();\n writer.close();\n }\n\n /**\n * Removes lines from file based on a set of conditions.\n *\n * @param input input file\n * @param input_enc input file encoding\n * @param output output file\n * @param output_enc output file encoding\n * @param lines lines removed from the file\n * @param equals if true remove only of lines are equal; if false remove if\n * file line contains line given as argument\n * @throws IOException\n */\n\n public static void removeLines(File input, String input_enc, File output, String output_enc, List<String> lines,\n boolean equals) throws IOException {\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input), input_enc));\n PrintWriter writer = new PrintWriter(output, output_enc);\n\n String line;\n while ((line = reader.readLine()) != null) {\n\n boolean print = true;\n for (String l : lines)\n if (equals) {\n if (line.equals(l)) {\n print = false;\n break;\n }\n } else {\n if (line.contains(l)) {\n print = false;\n break;\n }\n }\n\n if (print)\n writer.println(line);\n }\n\n reader.close();\n writer.close();\n }\n\n /**\n * Append lines to a file at end or start of file.\n *\n * @param input input file\n * @param input_enc input file encoding\n * @param output output file\n * @param output_enc output file encoding\n * @param lines lines being appended\n * @param prepend if true add to beginning; if false add to end of file\n * @throws IOException\n */\n\n public static void appendLines(File input, String input_enc, File output, String output_enc, List<String> lines,\n boolean prepend) throws IOException {\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input), input_enc));\n PrintWriter writer = new PrintWriter(output, output_enc);\n\n String line;\n\n if (prepend) {\n for (String l : lines)\n writer.println(l);\n }\n\n while ((line = reader.readLine()) != null)\n writer.println(line);\n\n if (!prepend) {\n for (String l : lines)\n writer.println(l);\n }\n\n reader.close();\n writer.close();\n }\n\n /**\n * Writes a list with file paths into a SCP file.\n *\n * @param scp_file the file containing the paths\n * @param file_list a list of paths to save\n * @param prepend_name if true a name is prepended before each file\n * @throws IOException\n */\n\n public static void makeSCPFile(File scp_file, File[] file_list, boolean prepend_name) throws IOException {\n PrintWriter writer = new PrintWriter(scp_file);\n\n for (File file : file_list) {\n if (prepend_name)\n writer.print(file.getName() + \" \");\n writer.println(file.getAbsolutePath());\n }\n\n writer.close();\n }\n\n /**\n * Reads a file into a string.\n *\n * @param file file to read\n * @param delim delimiter to use instead of new-lines\n * @return string\n * @throws IOException\n */\n public static String readFile(File file, String delim) throws IOException {\n String ret = \"\";\n BufferedReader reader = new BufferedReader(new FileReader(file));\n\n String line;\n while ((line = reader.readLine()) != null) {\n ret += line + delim;\n }\n\n reader.close();\n\n return ret;\n\n }\n\n public static void writelnFile(File file, String string) throws IOException {\n PrintWriter writer = new PrintWriter(file);\n writer.println(string);\n writer.close();\n }\n\n public static void appendName(String name, File input, File output) throws IOException {\n\n PrintWriter writer = new PrintWriter(output);\n\n writer.print(name + \" \");\n\n BufferedReader reader = new BufferedReader(new FileReader(input));\n\n String line = reader.readLine();\n\n writer.println(line);\n\n writer.close();\n reader.close();\n\n }\n\n public static void makeVocab(File input_file, File vocab_file) throws IOException {\n HashSet<String> words = new HashSet<String>();\n\n BufferedReader reader = new BufferedReader(new FileReader(input_file));\n\n String line;\n while ((line = reader.readLine()) != null) {\n String[] tok = line.split(\"\\\\s+\");\n for (String w : tok)\n words.add(w);\n }\n\n reader.close();\n\n PrintWriter writer = new PrintWriter(vocab_file);\n\n for (String w : words) {\n writer.println(w);\n }\n\n writer.close();\n }\n\n /**\n * Cleans the contenst of a directory.\n *\n * @param dir directory to clean\n * @param exclude files and folders to skip\n * @param max_depth maximum depth\n */\n public static void cleanup(File dir, File[] exclude, int max_depth) {\n if (max_depth < 0)\n return;\n\n Log.verbose(\"Cleaning up \" + dir.getName() + \" dir...\");\n\n for (File file : dir.listFiles()) {\n boolean skip = false;\n for (File exc : exclude) {\n if (file.getAbsolutePath().equals(exc.getAbsolutePath())) {\n Log.verbose(\"Skipping \" + file.getName());\n skip = true;\n break;\n }\n }\n\n if (!skip) {\n\n if (file.isDirectory())\n cleanup(file, exclude, max_depth - 1);\n\n Log.verbose(\"Deleting \" + file.getName());\n file.delete();\n }\n }\n }\n\n public static void reverse(File input, File output) throws IOException {\n\n LinkedList<String> words = new LinkedList<String>();\n\n BufferedReader reader = new BufferedReader(new FileReader(input));\n\n String line;\n while ((line = reader.readLine()) != null) {\n StringTokenizer strtok = new StringTokenizer(line);\n while (strtok.hasMoreTokens()) {\n words.addFirst(strtok.nextToken());\n }\n }\n reader.close();\n\n PrintWriter writer = new PrintWriter(output);\n\n for (String w : words) {\n writer.print(w + \" \");\n }\n writer.println();\n writer.close();\n }\n\n public static void bracket(String prepend, File file, String postpend, File out) throws IOException {\n\n PrintWriter writer = new PrintWriter(out);\n\n BufferedReader reader = new BufferedReader(new FileReader(file));\n String line;\n while ((line = reader.readLine()) != null) {\n writer.print(prepend);\n writer.print(line);\n writer.println(postpend);\n }\n\n reader.close();\n writer.close();\n }\n\n public static void sort_uniq(File input, File output, String encoding) throws IOException {\n HashSet<String> lines = new HashSet<String>();\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input), encoding));\n\n String line;\n while ((line = reader.readLine()) != null)\n lines.add(line);\n\n reader.close();\n\n PrintWriter writer = new PrintWriter(output, encoding);\n\n for (String line2 : lines) {\n writer.println(line2);\n }\n\n writer.close();\n\n }\n\n public static Vector<String> readLines(File file, String encoding) throws IOException {\n Vector<String> ret = new Vector<String>();\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));\n\n String line;\n while ((line = reader.readLine()) != null)\n ret.add(line);\n\n reader.close();\n\n return ret;\n }\n\n public static Vector<String> readTokens(File file, String encoding) throws IOException {\n Vector<String> ret = new Vector<String>();\n\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));\n ) {\n\n String line;\n while ((line = reader.readLine()) != null) {\n String tok[] = line.split(\"\\\\s+\");\n for (String word : tok)\n ret.add(word);\n }\n\n }\n\n return ret;\n }\n\n\n public static void writeLines(Vector<String> lines, File file, String encoding) throws IOException {\n\n PrintWriter writer = new PrintWriter(file, encoding);\n\n for (String line : lines)\n writer.println(line);\n writer.close();\n\n }\n\n public static void mergeFiles(File[] input_files, File output, String encoding, boolean skip_blanks)\n throws IOException {\n PrintWriter writer = new PrintWriter(output, encoding);\n for (File file : input_files) {\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));\n\n String line;\n while ((line = reader.readLine()) != null) {\n if (skip_blanks && line.isEmpty())\n continue;\n writer.println(line);\n }\n\n reader.close();\n\n }\n\n writer.close();\n }\n\n private static Pattern pClean = Pattern\n .compile(\"[^a-zA-Z0-9ąĄćĆęĘłŁńŃóÓśŚżŻźŹšŠťŤžŽşŞľĽŕŔáÁâÂăĂäÄĺĹçÇčČéÉëËěĚíÍîÎďĎđĐňŇôÔőŐöÖřŘůŮúÚűŰüÜýÝţŢ ]\");\n private static Pattern pCleanNl = Pattern\n .compile(\"[^a-zA-Z0-9ąĄćĆęĘłŁńŃóÓśŚżŻźŹšŠťŤžŽşŞľĽŕŔáÁâÂăĂäÄĺĹçÇčČéÉëËěĚíÍîÎďĎđĐňŇôÔőŐöÖřŘůŮúÚűŰüÜýÝţŢ \\n]\");\n private static Pattern pCleanDs = Pattern.compile(\"\\\\s+\");\n\n public static void cleanChars(File input, File output, boolean leave_newlines, boolean remove_doublespace,\n String encoding) throws IOException {\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input), encoding));\n PrintWriter writer = new PrintWriter(output, encoding);\n\n Pattern p = pClean;\n if (leave_newlines)\n p = pCleanNl;\n Matcher m;\n\n String line;\n while ((line = reader.readLine()) != null) {\n m = p.matcher(line);\n line = m.replaceAll(\"\");\n\n if (remove_doublespace) {\n m = pCleanDs.matcher(line);\n line = m.replaceAll(\" \");\n }\n\n if (leave_newlines)\n writer.println(line);\n else\n writer.print(line + \" \");\n }\n\n reader.close();\n writer.close();\n }\n\n public static void add_probs_to_lexicon(File lex_in, File lex_out) throws IOException {\n\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(lex_in)));\n PrintWriter writer = new PrintWriter(lex_out);\n ) {\n String line;\n while ((line = reader.readLine()) != null) {\n int i = line.indexOf(' ');\n writer.println(line.substring(0, i).trim() + \" 1.0 \" + line.substring(i + 1).trim());\n }\n }\n }\n\n public static void add_besi_to_lexicon(File lex_in, File lex_out) throws IOException {\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(lex_in)));\n PrintWriter writer = new PrintWriter(lex_out);\n ) {\n String line;\n while ((line = reader.readLine()) != null) {\n String[] tok = line.split(\"\\\\s+\");\n\n if (tok.length < 3)\n throw new IOException(\"Error reading lexicon - line has <3 tokens: \" + line);\n\n String w = tok[0];\n String p = tok[1];\n\n if (tok.length == 3) {\n writer.println(w + \" \" + p + \" \" + tok[2] + \"_S\");\n } else {\n writer.print(w + \" \" + p + \" \" + tok[2] + \"_B \");\n for (int i = 3; i < tok.length - 1; i++)\n writer.print(tok[i] + \"_I \");\n writer.println(tok[tok.length - 1] + \"_E\");\n }\n }\n }\n }\n\n public static void make_words_list(File vocab, File words) throws IOException {\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(vocab)));\n PrintWriter writer = new PrintWriter(words);\n ) {\n writer.println(\"<eps> 0\");\n int cnt = 1;\n String line;\n while ((line = reader.readLine()) != null) {\n if (line.equals(\"<s>\") || line.equals(\"</s>\")) continue;\n if (line.equals(\"-pau-\")) line = \"SIL\";\n writer.println(line + \" \" + (cnt++));\n }\n writer.println(\"#0 \" + (cnt++));\n writer.println(\"<s> \" + (cnt++));\n writer.println(\"</s> \" + (cnt++));\n }\n }\n\n public static void make_phones_list(File silence_phones, File nonsilence_phones, int disambig_num, File phones) throws IOException {\n try (\n BufferedReader silreader = new BufferedReader(new InputStreamReader(new FileInputStream(silence_phones)));\n BufferedReader nonsilreader = new BufferedReader(new InputStreamReader(new FileInputStream(nonsilence_phones)));\n PrintWriter writer = new PrintWriter(phones);\n ) {\n writer.println(\"<eps> 0\");\n int cnt = 1;\n String line;\n\n while ((line = silreader.readLine()) != null) {\n writer.println(line + \" \" + (cnt++));\n writer.println(line + \"_B \" + (cnt++));\n writer.println(line + \"_E \" + (cnt++));\n writer.println(line + \"_S \" + (cnt++));\n writer.println(line + \"_I \" + (cnt++));\n }\n\n while ((line = nonsilreader.readLine()) != null) {\n writer.println(line + \"_B \" + (cnt++));\n writer.println(line + \"_E \" + (cnt++));\n writer.println(line + \"_S \" + (cnt++));\n writer.println(line + \"_I \" + (cnt++));\n }\n\n for (int i = 0; i <= disambig_num; i++) {\n writer.println(\"#\" + i + \" \" + (cnt++));\n }\n }\n }\n\n public static int get_id_from_table(File table, String key) throws IOException, NumberFormatException {\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(table)));\n ) {\n key = key.trim();\n String line;\n while ((line = reader.readLine()) != null)\n if (line.startsWith(key)) {\n return Integer.parseInt(line.substring(key.length() + 1).trim());\n }\n }\n\n return -1;\n }\n\n public static Vector<String> get_ids_from_table(File table, String key_regex) throws IOException, NumberFormatException {\n Vector<String> ret = new Vector<String>();\n\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(table)));\n ) {\n String line;\n while ((line = reader.readLine()) != null)\n if (line.matches(key_regex)) {\n ret.add(line.split(\"\\\\s+\")[1].trim());\n }\n }\n\n return ret;\n }\n\n public static void convert_besi_to_desc(File besi, File desc) throws IOException {\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(besi)));\n PrintWriter writer = new PrintWriter(desc);\n ) {\n\n String line;\n while ((line = reader.readLine()) != null) {\n String tok[] = line.split(\"\\\\s\");\n String k = tok[0];\n String id = tok[1];\n\n if (k.equals(\"<eps>\")) continue;\n if (k.charAt(0) == '#') continue;\n\n String d = \"nonword\";\n if (k.endsWith(\"_B\")) d = \"begin\";\n if (k.endsWith(\"_E\")) d = \"end\";\n if (k.endsWith(\"_S\")) d = \"singleton\";\n if (k.endsWith(\"_I\")) d = \"internal\";\n\n writer.println(id + \" \" + d);\n }\n\n }\n }\n\n public static void getSymsFromList(File syms, File out, Set<String> skip) throws IOException {\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(syms)));\n PrintWriter writer = new PrintWriter(out);\n ) {\n String line;\n while ((line = reader.readLine()) != null) {\n String tok[] = line.split(\"\\\\s\");\n\n if (skip.contains(tok[0])) continue;\n\n writer.println(tok[0]);\n }\n }\n }\n\n public static void tail(File in, File out, int skip_num) throws IOException {\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(in)));\n PrintWriter writer = new PrintWriter(out);\n ) {\n String line;\n while ((line = reader.readLine()) != null) {\n if (skip_num > 0) {\n skip_num--;\n continue;\n }\n writer.println(line);\n }\n }\n }\n\n public static Vector<String> cut(File in, int field) throws IOException {\n Vector<String> ret = new Vector<String>();\n try (\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(in)));\n ) {\n String line;\n while ((line = reader.readLine()) != null) {\n String tok[] = line.split(\"\\\\s+\");\n if (tok.length > field) {\n ret.add(tok[field]);\n }\n }\n }\n\n return ret;\n }\n}",
"public class Log {\n\n public static class Stream extends OutputStream {\n\n private StringBuffer str = new StringBuffer();\n\n private String prefix = \"OUT>>\";\n\n public Stream() {\n }\n\n public Stream(String prefix) {\n this.prefix = prefix;\n }\n\n @Override\n public void write(int b) throws IOException {\n if (b == '\\n' || b == '\\r') {\n Log.verbose(prefix + str.toString());\n str.setLength(0);\n } else\n str.append((char) b);\n }\n\n }\n\n private static class FileLog extends Handler {\n\n private PrintWriter fileWriter;\n\n public FileLog(String prog_name, boolean append)\n throws FileNotFoundException {\n\n this(new File(Settings.log_dir, prog_name + \"_main.log\"), append);\n }\n\n public FileLog(File logFile, boolean append)\n throws FileNotFoundException {\n\n Settings.log_dir.mkdirs();\n\n fileWriter = new PrintWriter(new FileOutputStream(logFile, append));\n }\n\n @Override\n public void close() throws SecurityException {\n fileWriter.close();\n\n }\n\n @Override\n public void flush() {\n fileWriter.flush();\n }\n\n private SimpleDateFormat sdf = new SimpleDateFormat(\n \"[yyyy-MM-dd HH:mm:ss]\");\n\n @Override\n public void publish(LogRecord lr) {\n\n String loglevel = lr.getLevel().getName();\n if (lr.getLevel() == Level.SEVERE)\n loglevel = \"ERROR\";\n\n String line = sdf.format(new Date(lr.getMillis())) + \" <\"\n + loglevel + \"> \" + lr.getMessage();\n\n fileWriter.println(line);\n fileWriter.flush();\n\n Throwable th = lr.getThrown();\n if (th != null) {\n fileWriter.println(\"Exception: \" + th.toString());\n\n fileWriter.println(\"Stack trace:\");\n\n for (StackTraceElement el : th.getStackTrace()) {\n fileWriter.println(\"**\" + el.getFileName() + \":\"\n + el.getLineNumber() + \" in \" + el.getClassName()\n + \":\" + el.getMethodName());\n }\n\n fileWriter.flush();\n }\n\n }\n }\n\n public static class SimpleConsoleLog extends Handler {\n\n @Override\n public void close() throws SecurityException {\n }\n\n @Override\n public void flush() {\n System.out.flush();\n System.err.flush();\n }\n\n private SimpleDateFormat sdf = new SimpleDateFormat(\n \"[yyyy-MM-dd HH:mm:ss]\");\n\n @Override\n public void publish(LogRecord lr) {\n\n String loglevel = lr.getLevel().getName();\n if (lr.getLevel() == Level.SEVERE)\n loglevel = \"ERROR\";\n\n String line = sdf.format(new Date(lr.getMillis())) + \" <\"\n + loglevel + \"> \" + lr.getMessage();\n\n if (lr.getLevel() == Level.SEVERE)\n System.err.println(line);\n else\n System.out.println(line);\n\n Throwable th = lr.getThrown();\n if (th != null) {\n th.printStackTrace();\n }\n\n }\n\n }\n\n private static Logger logger = null;\n private static boolean suppress_output = false;\n\n public static void init(String prog_name, boolean append)\n throws SecurityException, FileNotFoundException {\n\n initFile(prog_name, append);\n\n logger.addHandler(new SimpleConsoleLog());\n }\n\n public static void initFile(String prog_name, boolean append)\n throws SecurityException, FileNotFoundException {\n\n logger = Logger.getLogger(Log.class.getPackage().getName());\n\n logger.setUseParentHandlers(false);\n\n logger.addHandler(new FileLog(prog_name, append));\n\n logger.setLevel(Level.ALL);\n }\n\n public static void setLevel(Level level) {\n if (logger != null)\n logger.setLevel(level);\n }\n\n public static void disableOutput() {\n suppress_output=true;\n }\n\n public static void enableOutput() {\n suppress_output=false;\n }\n\n public static void verbose(String message) {\n\n if(suppress_output) return;\n\n if (logger == null) {\n System.out.println(\"V:\" + message);\n return;\n }\n\n logger.log(Level.FINE, message);\n }\n\n public static void info(String message) {\n\n if(suppress_output) return;\n\n if (logger == null) {\n System.out.println(\"I:\" + message);\n return;\n }\n\n logger.log(Level.INFO, message);\n }\n\n public static void warn(String message) {\n\n if(suppress_output) return;\n\n if (logger == null) {\n System.out.println(\"W:\" + message);\n return;\n }\n\n logger.log(Level.WARNING, message);\n }\n\n public static void error(String message) {\n\n if(suppress_output) return;\n\n if (logger == null) {\n System.out.println(\"E:\" + message);\n return;\n }\n\n logger.log(Level.SEVERE, message);\n }\n\n public static void error(String message, Throwable e) {\n\n if(suppress_output) return;\n\n if (logger == null) {\n System.out.println(\"E:\" + message);\n e.printStackTrace();\n return;\n }\n\n logger.log(Level.SEVERE, message, e);\n }\n\n public static void addHandler(Handler h) {\n if (logger != null)\n logger.addHandler(h);\n }\n\n}",
"public class Settings {\n\n\t/**************************************************************************************************************************/\n\n\tpublic static File kaldi_root = new File(\"/home/guest/kaldi\");\n\n\tpublic static File perl_bin = new File(\"/usr/bin/perl\");\n\n\tpublic static File python_bin = new File(\"/usr/bin/python\");\n\n\tpublic static File bash_bin = new File(\"/bin/bash\");\n\n\tpublic static File transcriber_dir = new File(\"/home/guest/transcriber\");\n\t\n\tpublic static File kaldi_kws_bin= new File(\"/usr/local/bin/kaldi_kws\");\n\n\tpublic static File essentia_pitch_bin = new File(\"/home/guest/essentia/build/src/examples/standard_pitchyinfft\");\n\n\tpublic static File estimate_ngram_bin = new File(\"/home/guest/mitlm/estimate-ngram\");\n\n\tpublic static File ngram_count_bin = new File(\"/home/guest/kaldi/tools/srilm/lm/bin/i686-m64/ngram-count\");\n\n\tpublic static File praat_bin = new File(\"/home/guest/praat/sources_5384/praat\");\n\n\tpublic static File shout_dir = new File(\"/home/guest/shout/release/src\");\n\n\tpublic static File shout_models = new File(\"/home/guest/shout/\");\n\n\tpublic static File lium_models = new File(\"lium_model\");\n\n\tpublic static File julius_bin = new File(\"/usr/local/bin/julius\");\n\n\tpublic static File julius_mklm_bin = new File(\"/usr/local/bin/mkbingram\");\n\n\tpublic static File ffmpeg_bin = new File(\"/usr/bin/ffmpeg\");\n\n\tpublic static double julius_win_offset = 0.01;\n\n\tpublic static String julius_default_encoding = \"utf8\";\n\n\tpublic static File java_lib_dir = new File(\"JAR\");\n\n\tpublic static File python_scripts_dir = new File(\"Python\");\n\n\tpublic static File daemon_pid = new File(\"daemon.pid\");\n\n\tpublic static int daemon_slots = 4;\n\n\tpublic static int daemon_startup_timer_ms = 10000;\n\n\tpublic static File daemon_status = new File(\"daemon_status.xml\");\n\n\tpublic static File tasks_dir = new File(\"tasks\");\n\n\tpublic static File curr_task_dir = null;\n\n\tpublic static File log_dir = new File(\"logs\");\n\n\tpublic static File temp_dir = new File(\"tmp\");\n\tpublic static File temp_dir2 = new File(\"tmp2\");\n\n\tpublic static double align_beam = 500;\n\n\tpublic static double align_retry_beam = 1000;\n\n\tpublic static boolean removeTempFile = true;\n\n\tpublic static String default_encoding = \"utf8\";\n\n\tpublic static String db_username = \"test\";\n\n\t@Hidden(password = true)\n\tpublic static String db_password = \"test\";\n\n\tpublic static String db_name = \"speech_services\";\n\n\t/**************************************************************************************************************************/\n\n\t@Target(ElementType.FIELD)\n\t@Retention(RetentionPolicy.RUNTIME)\n\tpublic @interface Hidden {\n\t\tboolean password() default false;\n\t}\n\n\tpublic static void loadSettings(File settingsFile) throws IOException {\n\n\t\tBufferedReader reader = new BufferedReader(\n\t\t\t\tnew InputStreamReader(new FileInputStream(settingsFile), default_encoding));\n\n\t\tString line, key, value, type;\n\t\tString[] values = null;\n\t\tboolean array;\n\t\tField field;\n\t\tint pos;\n\t\twhile ((line = reader.readLine()) != null) {\n\n\t\t\tif (line.length() == 0)\n\t\t\t\tcontinue;\n\n\t\t\tpos = line.indexOf(';');\n\t\t\tif (pos >= 0) {\n\t\t\t\tline = line.substring(0, pos).trim();\n\t\t\t}\n\n\t\t\tif (line.length() == 0)\n\t\t\t\tcontinue;\n\n\t\t\tpos = line.indexOf('=');\n\n\t\t\tkey = line.substring(0, pos).trim();\n\t\t\tvalue = line.substring(pos + 1).trim();\n\n\t\t\ttry {\n\t\t\t\tfield = Settings.class.getField(key);\n\t\t\t} catch (NoSuchFieldException | SecurityException e) {\n\t\t\t\tSystem.err.println(\"Cannot find key \" + key + \" to configure!\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!Modifier.isStatic(field.getModifiers())) {\n\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <not static>!\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttype = field.getType().getName();\n\n\t\t\tHidden annotation = field.getAnnotation(Hidden.class);\n\t\t\tif (annotation != null && annotation.password()) {\n\t\t\t\tif (!type.equals(\"java.lang.String\")) {\n\t\t\t\t\tSystem.err.println(\"Only String types can be deobfuscated! Skipping \" + key + \"!\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (field.getType().isArray()) {\n\t\t\t\tvalues = value.split(\",\");\n\t\t\t\ttype = field.getType().getComponentType().getName();\n\t\t\t\tarray = true;\n\t\t\t} else {\n\t\t\t\tarray = false;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (type.equals(\"java.lang.String\")) {\n\n\t\t\t\t\tif (array) {\n\t\t\t\t\t\tString obj[] = new String[values.length];\n\t\t\t\t\t\tfield.set(null, obj);\n\t\t\t\t\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\t\t\t\t\tvalue = values[i].trim();\n\n\t\t\t\t\t\t\tif (annotation != null && annotation.password())\n\t\t\t\t\t\t\t\tvalue = PasswordObfuscator.deobfuscatePassword(value);\n\n\t\t\t\t\t\t\tArray.set(obj, i, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (annotation != null && annotation.password())\n\t\t\t\t\t\t\tvalue = PasswordObfuscator.deobfuscatePassword(value);\n\t\t\t\t\t\tfield.set(null, value);\n\t\t\t\t\t}\n\n\t\t\t\t} else if (type.equals(\"int\")) {\n\t\t\t\t\tif (array) {\n\t\t\t\t\t\tint[] obj = new int[values.length];\n\t\t\t\t\t\tfield.set(null, obj);\n\t\t\t\t\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\t\t\t\t\tvalue = values[i].trim();\n\t\t\t\t\t\t\tint iv;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tiv = Integer.parseInt(value);\n\t\t\t\t\t\t\t} catch (NumberFormatException ne) {\n\t\t\t\t\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <integer parse exc>!\");\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tobj[i] = iv;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tint iv;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tiv = Integer.parseInt(value);\n\t\t\t\t\t\t} catch (NumberFormatException ne) {\n\t\t\t\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <integer parse exc>!\");\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfield.setInt(null, iv);\n\t\t\t\t\t}\n\n\t\t\t\t} else if (type.equals(\"char\")) {\n\t\t\t\t\tif (array) {\n\t\t\t\t\t\tchar[] obj = new char[values.length];\n\t\t\t\t\t\tfield.set(null, obj);\n\t\t\t\t\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\t\t\t\t\tvalue = values[i].trim();\n\t\t\t\t\t\t\tif (value.length() == 0) {\n\t\t\t\t\t\t\t\tSystem.err.println(\"WARNING: using space as value for \" + key);\n\t\t\t\t\t\t\t\tobj[i] = ' ';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (value.length() > 1) {\n\t\t\t\t\t\t\t\tSystem.err.println(\"WARNING: using only first char in \" + key);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tobj[i] = value.charAt(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (value.length() == 0) {\n\t\t\t\t\t\t\tSystem.err.println(\"WARNING: using space as value for \" + key);\n\t\t\t\t\t\t\tfield.set(null, ' ');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value.length() > 1) {\n\t\t\t\t\t\t\tSystem.err.println(\"WARNING: using only first char in \" + key);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfield.set(null, value.charAt(0));\n\t\t\t\t\t}\n\t\t\t\t} else if (type.equals(\"float\")) {\n\t\t\t\t\tif (array) {\n\t\t\t\t\t\tfloat[] obj = new float[values.length];\n\t\t\t\t\t\tfield.set(null, obj);\n\t\t\t\t\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\t\t\t\t\tvalue = values[i].trim();\n\t\t\t\t\t\t\tfloat f;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tf = Float.parseFloat(value);\n\t\t\t\t\t\t\t} catch (NumberFormatException ne) {\n\t\t\t\t\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <float parse exc>!\");\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tobj[i] = f;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfloat f;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tf = Float.parseFloat(value);\n\t\t\t\t\t\t} catch (NumberFormatException ne) {\n\t\t\t\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <float parse exc>!\");\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfield.setFloat(null, f);\n\t\t\t\t\t}\n\t\t\t\t} else if (type.equals(\"double\")) {\n\t\t\t\t\tif (array) {\n\t\t\t\t\t\tdouble[] obj = new double[values.length];\n\t\t\t\t\t\tfield.set(null, obj);\n\t\t\t\t\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\t\t\t\t\tvalue = values[i].trim();\n\t\t\t\t\t\t\tdouble d;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\td = Double.parseDouble(value);\n\t\t\t\t\t\t\t} catch (NumberFormatException ne) {\n\t\t\t\t\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <double parse exc>!\");\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tobj[i] = d;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdouble d;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\td = Double.parseDouble(value);\n\t\t\t\t\t\t} catch (NumberFormatException ne) {\n\t\t\t\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <double parse exc>!\");\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfield.setDouble(null, d);\n\t\t\t\t\t}\n\t\t\t\t} else if (type.equals(\"boolean\")) {\n\t\t\t\t\tif (array) {\n\t\t\t\t\t\tboolean[] obj = new boolean[values.length];\n\t\t\t\t\t\tfield.set(null, obj);\n\t\t\t\t\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\t\t\t\t\tvalue = values[i].trim().toLowerCase();\n\t\t\t\t\t\t\tif (value.equals(\"true\") || value.equals(\"yes\") || value.equals(\"1\"))\n\t\t\t\t\t\t\t\tobj[i] = true;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tobj[i] = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalue = value.toLowerCase();\n\t\t\t\t\t\tif (value.equals(\"true\") || value.equals(\"yes\") || value.equals(\"1\"))\n\t\t\t\t\t\t\tfield.setBoolean(null, true);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tfield.setBoolean(null, false);\n\t\t\t\t\t}\n\t\t\t\t} else if (type.equals(\"java.io.File\")) {\n\t\t\t\t\tif (array) {\n\t\t\t\t\t\tFile[] obj = new File[values.length];\n\t\t\t\t\t\tfield.set(null, obj);\n\t\t\t\t\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\t\t\t\t\tvalue = values[i].trim();\n\t\t\t\t\t\t\tArray.set(obj, i, new File(value));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfield.set(null, new File(value));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <unknown type>!\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tSystem.err.println(\"The key \" + key + \" cannot be configured <access exc>!\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\treader.close();\n\t}\n\n\tpublic static void dumpSettings() {\n\n\t\tField[] fields = Settings.class.getFields();\n\n\t\tLog.info(\"Settings dump:\");\n\n\t\tfor (Field field : fields) {\n\n\t\t\tif (!Modifier.isStatic(field.getModifiers()))\n\t\t\t\tcontinue;\n\n\t\t\tif (field.getAnnotation(Hidden.class) != null) {\n\t\t\t\tLog.info(field.getName() + \" = <hidden>\");\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tif (field.getType().isArray()) {\n\t\t\t\t\t\tObject obj = field.get(null);\n\t\t\t\t\t\tint length = Array.getLength(obj);\n\t\t\t\t\t\tStringBuffer buf = new StringBuffer();\n\t\t\t\t\t\tbuf.append(\"{\");\n\t\t\t\t\t\tfor (int i = 0; i < length; i++) {\n\t\t\t\t\t\t\tbuf.append(\"\" + Array.get(obj, i));\n\t\t\t\t\t\t\tif (i < length - 1)\n\t\t\t\t\t\t\t\tbuf.append(\",\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbuf.append(\"}\");\n\t\t\t\t\t\tLog.info(field.getName() + \" = \" + buf);\n\t\t\t\t\t} else\n\t\t\t\t\t\tLog.info(field.getName() + \" = \" + field.get(null));\n\t\t\t\t} catch (IllegalArgumentException | IllegalAccessException e) {\n\t\t\t\t\tLog.info(field.getName() + \" = <cannot access>\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void dumpSettings(File file) throws IOException {\n\n\t\tPrintWriter writer = new PrintWriter(file);\n\n\t\tField[] fields = Settings.class.getFields();\n\n\t\twriter.println(\";; Autogenerated settings file...\");\n\n\t\tfor (Field field : fields) {\n\n\t\t\tif (!Modifier.isStatic(field.getModifiers()))\n\t\t\t\tcontinue;\n\n\t\t\tHidden a = field.getAnnotation(Hidden.class);\n\t\t\ttry {\n\t\t\t\tif (a != null && a.password()) {\n\t\t\t\t\twriter.println(\n\t\t\t\t\t\t\tfield.getName() + \" = \" + PasswordObfuscator.obfuscatePassword(\"\" + field.get(null)));\n\t\t\t\t} else {\n\t\t\t\t\tif (field.getType().isArray()) {\n\t\t\t\t\t\tObject obj = field.get(null);\n\t\t\t\t\t\tint length = Array.getLength(obj);\n\t\t\t\t\t\tStringBuffer buf = new StringBuffer();\n\t\t\t\t\t\tfor (int i = 0; i < length; i++) {\n\t\t\t\t\t\t\tbuf.append(\"\" + Array.get(obj, i));\n\t\t\t\t\t\t\tif (i < length - 1)\n\t\t\t\t\t\t\t\tbuf.append(\",\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twriter.println(field.getName() + \" = \" + buf);\n\t\t\t\t\t} else\n\t\t\t\t\t\twriter.println(field.getName() + \" = \" + field.get(null));\n\t\t\t\t}\n\t\t\t} catch (IllegalArgumentException | IllegalAccessException e) {\n\t\t\t\twriter.println(field.getName() + \" = <cannot access>\");\n\t\t\t}\n\n\t\t}\n\n\t\twriter.close();\n\n\t}\n}"
] | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.Vector;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Element;
import pl.edu.pjwstk.kaldi.files.TextGrid;
import pl.edu.pjwstk.kaldi.programs.KaldiKWS;
import pl.edu.pjwstk.kaldi.programs.KaldiUtils;
import pl.edu.pjwstk.kaldi.programs.Transcriber;
import pl.edu.pjwstk.kaldi.utils.FileUtils;
import pl.edu.pjwstk.kaldi.utils.Log;
import pl.edu.pjwstk.kaldi.utils.Settings; | package pl.edu.pjwstk.kaldi.service.tasks;
public class KeywordSpottingTask extends Task {
private File input_keywords;
private File words_table;
@Override
public void run() {
state = State.RUNNING;
try {
File lattice = new File(Settings.curr_task_dir, "aligned_lattice");
File lattice_int = new File(Settings.curr_task_dir, "kws_lattice.int");
File lattice_txt = new File(Settings.curr_task_dir, "kws_lattice.txt");
File kw_clean = new File(Settings.curr_task_dir, "kws_clean_words");
File lat_vocab = new File(Settings.curr_task_dir, "kws_lat_vocab");
File vocab = new File(Settings.curr_task_dir, "kws_vocab");
File dict = new File(Settings.curr_task_dir, "kws_dict");
File kws_out = new File(Settings.curr_task_dir, "kws.txt");
File tg_out = new File(Settings.curr_task_dir, "out.TextGrid");
if (!lattice.canRead()) {
Log.error("Cannot read lattice for task: " + Settings.curr_task_dir);
Log.error("Keyword spotting HAS to be run after decoding the file first!");
state = State.FAILED;
return;
}
cleanKeywords(input_keywords, kw_clean, Settings.default_encoding);
| KaldiUtils.lattice_copy("ark", lattice, "ark,t", lattice_int, true); | 2 |
GeneFeng/CircView | src/cn/edu/whu/ui/ComparisonFrame.java | [
"public class CircRna implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * circRNA ID\n\t */\n\tprivate String circRnaID;\n\n\t/**\n\t * Chromosome name\n\t */\n\tprivate String chrom;\n\n\t/**\n\t * circRNA start point;\n\t */\n\tprivate long startPoint;\n\n\t/**\n\t * circRNA end point;\n\t */\n\tprivate long endPoint;\n\n\t/**\n\t * strand\n\t */\n\tprivate String strand;\n\n\t/**\n\t * junction reads\n\t */\n\tprivate int junctionReads;\n\n\t/**\n\t * \"geneName transcriptName\" \"geneName transcriptName\" pair\n\t */\n\tprivate TreeMap<String, String> geneTranscrpits;\n\n\t/**\n\t * Repeat Times\n\t */\n\t// private int repeat;\n\n\tprivate TreeMap<String, Integer> samples;\n\tprivate TreeMap<String, Integer> circTools;\n\tprivate TreeMap<String, Integer> files;\n\n\t/**\n\t * exon or intron or intergenic\n\t */\n\tprivate String region;\n\n\t/**\n\t * mRNA or lncRNA or unknown\n\t */\n\tprivate String circRnaType;\n\n\t/**\n\t * Constructor of CircRna\n\t * \n\t * @param geneName\n\t */\n\tpublic CircRna(String circRnaID) {\n\t\tthis.circRnaID = circRnaID;\n\t\tgeneTranscrpits = new TreeMap<String, String>();\n\t\tsamples = new TreeMap<String, Integer>();\n\t\tcircTools = new TreeMap<String, Integer>();\n\t\tfiles = new TreeMap<String, Integer>();\n\t}\n\n\tpublic String getCircRnaID() {\n\t\treturn circRnaID;\n\t}\n\n\tpublic void setCircRnaID(String circRnaID) {\n\t\tthis.circRnaID = circRnaID;\n\t}\n\n\tpublic String getChrom() {\n\t\treturn chrom;\n\t}\n\n\tpublic void setChrom(String chrom) {\n\t\tthis.chrom = chrom;\n\t}\n\n\tpublic long getStartPoint() {\n\t\treturn startPoint;\n\t}\n\n\tpublic void setStartPoint(long startPoint) {\n\t\tthis.startPoint = startPoint;\n\t}\n\n\tpublic long getEndPoint() {\n\t\treturn endPoint;\n\t}\n\n\tpublic void setEndPoint(long endPoint) {\n\t\tthis.endPoint = endPoint;\n\t}\n\n\tpublic String getStrand() {\n\t\treturn strand;\n\t}\n\n\tpublic void setStrand(String strand) {\n\t\tthis.strand = strand;\n\t}\n\n\tpublic int getJunctionReads() {\n\t\treturn junctionReads;\n\t}\n\n\tpublic void setJunctionReads(int junctionReads) {\n\t\tthis.junctionReads = junctionReads;\n\t}\n\n\tpublic String getRegion() {\n\t\treturn region;\n\t}\n\n\tpublic void setRegion(String region) {\n\t\tthis.region = region;\n\t}\n\n\tpublic String getCircRnaType() {\n\t\treturn circRnaType;\n\t}\n\n\tpublic void setCircRnaType(String circRnaType) {\n\t\tthis.circRnaType = circRnaType;\n\t}\n\n\t/**\n\t * @return the geneTranscrpits\n\t */\n\tpublic TreeMap<String, String> getGeneTranscrpits() {\n\t\treturn geneTranscrpits;\n\t}\n\n\t/**\n\t * @param geneTranscrpits\n\t * the geneTranscrpits to set\n\t */\n\tpublic void setGeneTranscrpits(TreeMap<String, String> geneTranscrpits) {\n\t\tthis.geneTranscrpits = geneTranscrpits;\n\t}\n\n\t/**\n\t * @return the samples\n\t */\n\tpublic TreeMap<String, Integer> getSamples() {\n\t\treturn samples;\n\t}\n\n\t/**\n\t * @param samples\n\t * the samples to set\n\t */\n\tpublic void setSamples(TreeMap<String, Integer> samples) {\n\t\tthis.samples = samples;\n\t}\n\n\t/**\n\t * @return the circTools\n\t */\n\tpublic TreeMap<String, Integer> getCircTools() {\n\t\treturn circTools;\n\t}\n\n\t/**\n\t * @param circTools\n\t * the circTools to set\n\t */\n\tpublic void setCircTools(TreeMap<String, Integer> circTools) {\n\t\tthis.circTools = circTools;\n\t}\n\n\t/**\n\t * @return the files\n\t */\n\tpublic TreeMap<String, Integer> getFiles() {\n\t\treturn files;\n\t}\n\n\t/**\n\t * @param files\n\t * the files to set\n\t */\n\tpublic void setFiles(TreeMap<String, Integer> files) {\n\t\tthis.files = files;\n\t}\n\n\t// /**\n\t// * @return the repeat\n\t// */\n\t// public int getRepeat() {\n\t// return repeat;\n\t// }\n\t//\n\t// /**\n\t// * @param repeat the repeat to set\n\t// */\n\t// public void setRepeat(int repeat) {\n\t// this.repeat = repeat;\n\t// }\n}",
"public class CircView {\n\n\tpublic static JFrame frame;\n\tprivate JPanel imagePanel;\n\tprivate static JComboBox<String> cbSpecies;\n\tprivate static JComboBox<String> cbCircRnaTool;\n\tprivate static JComboBox<String> cbSample;\n\tprivate static JComboBox<String> cbChrom;\n\tprivate static Vector<String> geneTransName;\n\tprivate static JList<String> geneTransList;\n\tprivate static JComboBox<String> cbCircRnaSelect;\n\tprivate CircRnaImagePanel circRnaImage;\n\n\tprivate static JCheckBox cbRbp;\n\tprivate static JCheckBox cbMre;\n\n\tprivate static Connection conn;\n\tpublic static Logger log;\n\n\tprivate static TreeMap<String, Gene> genes;\n\tprivate boolean cbChromInit;\n\n\tprivate static JTextArea tipsTA;\n\n\t/**\n\t * Launch the application.\n\t */\n\tpublic static void main(String[] args) {\n\t\tinitLogConfig(Constant.LOG_FILE);\n\t\tlog = Logger.getLogger(CircView.class);\n\t\tPropertyConfigurator.configure(Constant.LOG_FILE);\n\t\tEventQueue.invokeLater(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tlong mem = RuntimeUtils.getAvailableMemory();\n\t\t\t\t\tint MB = 1000000;\n\t\t\t\t\tif (mem < 400 * MB) {\n\t\t\t\t\t\tint mb = (int) (mem / MB);\n\t\t\t\t\t\tJOptionPane.showMessageDialog(null,\n\t\t\t\t\t\t\t\t\"Warning: CircView is running with low available memory (\" + mb + \" mb)\");\n\t\t\t\t\t}\n\t\t\t\t\tnew CircView();\n\t\t\t\t\tframe.setVisible(true);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate static void initLogConfig(String logFile) {\n\t\tFile file = new File(Constant.LOG_FILE);\n\t\tif (!file.exists()) {\n\t\t\tProperties logPro = new Properties();\n\t\t\ttry {\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_ROOTLOGGER, Constant.LOG4J_ROOTLOGGER_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_CONSOLE, Constant.LOG4J_APPENDER_CONSOLE_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_CONSOLE_TARGET,\n\t\t\t\t\t\tConstant.LOG4J_APPENDER_CONSOLE_TARGET_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_CONSOLE_LAYOUT,\n\t\t\t\t\t\tConstant.LOG4J_APPENDER_CONSOLE_LAYOUT_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_CONSOLE_LAYOUT_CONV_PATT,\n\t\t\t\t\t\tConstant.LOG4J_APPENDER_CONSOLE_LAYOUT_CONV_PATT_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_FILE, Constant.LOG4J_APPENDER_FILE_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_FILE_FILE, Constant.LOG4J_APPENDER_FILE_FILE_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_FILE_MAXFILESIZE,\n\t\t\t\t\t\tConstant.LOG4J_APPENDER_FILE_MAXFILESIZE_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_FILE_THRESHOLD,\n\t\t\t\t\t\tConstant.LOG4J_APPENDER_FILE_THRESHOLD_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_FILE_LAYOUT, Constant.LOG4J_APPENDER_FILE_LAYOUT_VALUE);\n\t\t\t\tlogPro.setProperty(Constant.LOG4J_APPENDER_FILE_LAYOUT_CONV_PATT,\n\t\t\t\t\t\tConstant.LOG4J_APPENDER_FILE_LAYOUT_CONV_PATT_VALUE);\n\n\t\t\t\t// Write LogConfig File\n\t\t\t\tOutputStream os = new FileOutputStream(Constant.LOG_FILE);\n\t\t\t\tlogPro.store(os, \"Save LogConfig File\");\n\t\t\t} catch (IOException e) {\n\t\t\t\tCircView.log.error(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Create the application.\n\t */\n\tpublic CircView() {\n\t\t// Init Config\n\t\tinitData();\n\t\t// Connect to DB\n\t\tconnectDB();\n\t\t// Initialize Interface\n\t\tinitInterface();\n\t\t// Auto Resize\n\t\tframe.addComponentListener(new ComponentListener() {\n\t\t\tpublic void componentResized(ComponentEvent e) {\n\t\t\t\tdisplay();\n\t\t\t}\n\n\t\t\tpublic void componentMoved(ComponentEvent e) {\n\t\t\t}\n\n\t\t\tpublic void componentShown(ComponentEvent e) {\n\t\t\t}\n\n\t\t\tpublic void componentHidden(ComponentEvent e) {\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate void initData() {\n\t\tnew MainData();\n\t\tgeneTransName = new Vector<String>();\n\t}\n\n\tprivate void initInterface() {\n\t\tcbChromInit = true;\n\t\tinitComponent();\n\t\tinitFrame();\n\t\tinitMenu();\n\t\tinitToolBar();\n\t\tinitMainPanel();\n\t}\n\n\tprivate void initComponent() {\n\t\tframe = new JFrame(\"CircRNA Viewer\");\n\t\tcbSpecies = new JComboBox<String>();\n\t\tcbCircRnaTool = new JComboBox<String>();\n\t\tcbSample = new JComboBox<String>();\n\t\tcbChrom = new JComboBox<String>();\n\t\tgeneTransList = new JList<String>();\n\t}\n\n\tprivate void connectDB() {\n\t\ttry {\n\t\t\tconn = DbUtil.connectDb();\n\t\t\tDbUtil.createDb(conn);\n\t\t} catch (ClassNotFoundException | SQLException e) {\n\t\t\tlog.warn(e.getMessage());\n\t\t}\n\t\ttry {\n\t\t\tDbUtil.useDb(conn);\n\t\t} catch (ClassNotFoundException | SQLException e) {\n\t\t\tlog.warn(e.getMessage());\n\t\t}\n\t}\n\n\tprivate void initFrame() {\n\t\t// TODO Auto-generated method stub\n\t\tDimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n\t\tframe.setBounds(0, 0, (int) screenSize.getWidth(), (int) screenSize.getHeight());\n\t\tframe.setMinimumSize(new Dimension(800, 600));\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t}\n\n\tprivate void initMenu() {\n\t\t// Add MenuBar to Frame\n\t\tJMenuBar menuBar = new JMenuBar();\n\t\tframe.setJMenuBar(menuBar);\n\t\t// Add Menu to MenuBar\n\t\tJMenu mnFile = new JMenu(\"File\");\n\t\tJMenu mnCircRna = new JMenu(\"CircRNA\");\n\t\tJMenu mnAnalysis = new JMenu(\"Analysis\");\n\t\tJMenu mnSpecies = new JMenu(\"Species\");\n\t\tJMenu mnDbLink = new JMenu(\"Database\");\n\t\tJMenu mnMre = new JMenu(\"MRE\");\n\t\tJMenu mnRbp = new JMenu(\"RBP\");\n\t\tJMenu mnHelp = new JMenu(\"Help\");\n\t\tmenuBar.add(mnFile);\n\t\tmenuBar.add(mnCircRna);\n\t\tmenuBar.add(mnAnalysis);\n\t\tmenuBar.add(mnSpecies);\n\t\tmenuBar.add(mnDbLink);\n\t\tmenuBar.add(mnMre);\n\t\tmenuBar.add(mnRbp);\n\t\tmenuBar.add(mnHelp);\n\t\t// Add MenuItem to File Menu\n\t\tJMenuItem mntmQuit = new JMenuItem(\"Quit\");\n\t\tmnFile.add(mntmQuit);\n\t\t// Add MenuItem to CircRNA Menu\n\t\tJMenuItem mntmCircRnaLoad = new JMenuItem(\"Load Data\");\n\t\tJMenuItem mntmCircRnaClear = new JMenuItem(\"Clear Data\");\n\t\tJMenuItem mntmCircRnaAdd = new JMenuItem(\"Add Tool\");\n\t\tJMenuItem mntmCircRnaDel = new JMenuItem(\"Delete Tool\");\n\t\tmnCircRna.add(mntmCircRnaLoad);\n\t\tmnCircRna.add(mntmCircRnaClear);\n\t\tmnCircRna.addSeparator();\n\t\tmnCircRna.add(mntmCircRnaAdd);\n\t\tmnCircRna.add(mntmCircRnaDel);\n\t\t// Add MenuItem to Analysis Menu\n\t\tJMenuItem mntmCompare = new JMenuItem(\"Comparison\");\n\t\tmnAnalysis.add(mntmCompare);\n\t\t// Add MenuItem to Species Menu\n\t\tJMenuItem mntmSpeciesAdd = new JMenuItem(\"Add Species\");\n\t\tJMenuItem mntmSpeciesDel = new JMenuItem(\"Delete Species\");\n\t\tmnSpecies.add(mntmSpeciesAdd);\n\t\tmnSpecies.add(mntmSpeciesDel);\n\t\t// Add MenuItem to MRE Menu\n\t\tJMenuItem mntmMreLoad = new JMenuItem(\"Load Data\");\n\t\tJMenuItem mntmMreClear = new JMenuItem(\"Clear\");\n\t\tmnMre.add(mntmMreLoad);\n\t\tmnMre.add(mntmMreClear);\n\t\t// Add MenuItem to RBP Menu\n\t\tJMenuItem mntmRbpLoad = new JMenuItem(\"Load Data\");\n\t\tJMenuItem mntmRbpClear = new JMenuItem(\"Clear\");\n\t\tmnRbp.add(mntmRbpLoad);\n\t\tmnRbp.add(mntmRbpClear);\n\t\t// Add MenuItem to Database Link Menu\n\t\tJMenuItem mntmLink1 = new JMenuItem(\"Circ2Traits\");\n\t\tJMenuItem mntmLink2 = new JMenuItem(\"CircBase\");\n\t\tJMenuItem mntmLink3 = new JMenuItem(\"CircInteractome\");\n\t\tJMenuItem mntmLink4 = new JMenuItem(\"CircNet\");\n\t\tJMenuItem mntmLink5 = new JMenuItem(\"CircRNADb\");\n\t\tJMenuItem mntmLink6 = new JMenuItem(\"StarBase\");\n\t\tJMenuItem mntmLink7 = new JMenuItem(\"TSCD\");\n\t\tmnDbLink.add(mntmLink1);\n\t\tmnDbLink.add(mntmLink2);\n\t\tmnDbLink.add(mntmLink3);\n\t\tmnDbLink.add(mntmLink4);\n\t\tmnDbLink.add(mntmLink5);\n\t\tmnDbLink.add(mntmLink6);\n\t\tmnDbLink.add(mntmLink7);\n\t\t// Add MenuItem to Help\n\t\tJMenuItem mntmAbout = new JMenuItem(\"About\");\n\t\tmnHelp.add(mntmAbout);\n\t\t//\n\t\tif (null == conn) {\n\t\t\tmntmRbpLoad.setEnabled(false);\n\t\t\tmntmRbpClear.setEnabled(false);\n\t\t\tmntmMreLoad.setEnabled(false);\n\t\t\tmntmMreClear.setEnabled(false);\n\t\t\t// JOptionPane.showMessageDialog(CircView.frame, \"Can NOT Connect to\n\t\t\t// Database!\");\n\t\t}\n\n\t\t// Add ActionListener to Quit MenuItem\n\t\tmntmQuit.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tSystem.exit(0);\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to CircRNA Load MenuItem\n\t\tmntmCircRnaLoad.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew CircRnaDataLoadDialog();\n\t\t\t}\n\t\t});\n\n\t\tmntmCircRnaClear.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew CircRnaDataClearDialog();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to CircRNA Tool Name Add MenuItem\n\t\tmntmCircRnaAdd.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew CircRnaToolAddDialog();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to CircRNA Tool Name Delete MenuItem\n\t\tmntmCircRnaDel.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew CircRnaToolDelDialog();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to CircRNA Tool Name Delete MenuItem\n\t\tmntmCompare.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew ComparisonFrame();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to Species Name Add MenuItem\n\t\tmntmSpeciesAdd.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew SpeciesAddDialog();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to Species Name Delete MenuItem\n\t\tmntmSpeciesDel.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew SpeciesDelDialog();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to MRE Load Data MenuItem\n\t\tmntmMreLoad.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew MreLoadDialog(conn);\n\t\t\t}\n\t\t});\n\t\t// Add ActionListener to MRE Clear Data MenuItem\n\t\tmntmMreClear.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew MreClearDialog(conn);\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to RBP Load Data MenuItem\n\t\tmntmRbpLoad.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew RbpLoadDialog(conn);\n\t\t\t}\n\t\t});\n\t\t// Add ActionListener to RBP Clear Data MenuItem\n\t\tmntmRbpClear.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew RbpClearDialog(conn);\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to Database Link MenuItem\n\t\tmntmLink1.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\ttry {\n\t\t\t\t\tURI uri = new URI(\"http://gyanxet-beta.com/circdb/\");\n\t\t\t\t\tDesktop dtp = Desktop.getDesktop();\n\t\t\t\t\tif (Desktop.isDesktopSupported() && dtp.isSupported(Desktop.Action.BROWSE)) {\n\t\t\t\t\t\tdtp.browse(uri);\n\t\t\t\t\t}\n\t\t\t\t} catch (URISyntaxException | IOException e1) {\n\t\t\t\t\tCircView.log.warn(e1.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tmntmLink2.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\ttry {\n\t\t\t\t\tURI uri = new URI(\"http://circbase.org\");\n\t\t\t\t\tDesktop dtp = Desktop.getDesktop();\n\t\t\t\t\tif (Desktop.isDesktopSupported() && dtp.isSupported(Desktop.Action.BROWSE)) {\n\t\t\t\t\t\tdtp.browse(uri);\n\t\t\t\t\t}\n\t\t\t\t} catch (URISyntaxException | IOException e1) {\n\t\t\t\t\tCircView.log.warn(e1.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tmntmLink3.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\ttry {\n\t\t\t\t\tURI uri = new URI(\"https://circinteractome.nia.nih.gov\");\n\t\t\t\t\tDesktop dtp = Desktop.getDesktop();\n\t\t\t\t\tif (Desktop.isDesktopSupported() && dtp.isSupported(Desktop.Action.BROWSE)) {\n\t\t\t\t\t\tdtp.browse(uri);\n\t\t\t\t\t}\n\t\t\t\t} catch (URISyntaxException | IOException e1) {\n\t\t\t\t\tCircView.log.warn(e1.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tmntmLink4.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\ttry {\n\t\t\t\t\tURI uri = new URI(\"http://circnet.mbc.nctu.edu.tw\");\n\t\t\t\t\tDesktop dtp = Desktop.getDesktop();\n\t\t\t\t\tif (Desktop.isDesktopSupported() && dtp.isSupported(Desktop.Action.BROWSE)) {\n\t\t\t\t\t\tdtp.browse(uri);\n\t\t\t\t\t}\n\t\t\t\t} catch (URISyntaxException | IOException e1) {\n\t\t\t\t\tCircView.log.warn(e1.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tmntmLink5.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\ttry {\n\t\t\t\t\tURI uri = new URI(\"http://reprod.njmu.edu.cn/circrnadb\");\n\t\t\t\t\tDesktop dtp = Desktop.getDesktop();\n\t\t\t\t\tif (Desktop.isDesktopSupported() && dtp.isSupported(Desktop.Action.BROWSE)) {\n\t\t\t\t\t\tdtp.browse(uri);\n\t\t\t\t\t}\n\t\t\t\t} catch (URISyntaxException | IOException e1) {\n\t\t\t\t\tCircView.log.warn(e1.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tmntmLink6.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\ttry {\n\t\t\t\t\tURI uri = new URI(\"http://starbase.sysu.edu.cn\");\n\t\t\t\t\tDesktop dtp = Desktop.getDesktop();\n\t\t\t\t\tif (Desktop.isDesktopSupported() && dtp.isSupported(Desktop.Action.BROWSE)) {\n\t\t\t\t\t\tdtp.browse(uri);\n\t\t\t\t\t}\n\t\t\t\t} catch (URISyntaxException | IOException e1) {\n\t\t\t\t\tCircView.log.warn(e1.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tmntmLink7.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\ttry {\n\t\t\t\t\tURI uri = new URI(\"http://gb.whu.edu.cn/TSCD/\");\n\t\t\t\t\tDesktop dtp = Desktop.getDesktop();\n\t\t\t\t\tif (Desktop.isDesktopSupported() && dtp.isSupported(Desktop.Action.BROWSE)) {\n\t\t\t\t\t\tdtp.browse(uri);\n\t\t\t\t\t}\n\t\t\t\t} catch (URISyntaxException | IOException e1) {\n\t\t\t\t\tCircView.log.warn(e1.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to About MenuItem\n\t\tmntmAbout.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew AboutDialog();\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate void initToolBar() {\n\t\t// Add ToolBar to Frame\n\t\tJToolBar toolBar = new JToolBar();\n\t\tframe.getContentPane().add(toolBar, BorderLayout.NORTH);\n\n\t\t// Add Species JComboBox to ToolBar\n\t\tcbSpecies.setPreferredSize(new Dimension(180, 28));\n\t\ttoolBar.add(cbSpecies);\n\t\t// Add CircRnaTool JComboBox to ToolBar\n\t\tcbCircRnaTool.setPreferredSize(new Dimension(180, 28));\n\t\ttoolBar.add(cbCircRnaTool);\n\t\t// Add Sample JComboBox to ToolBar\n\t\tcbSample.setPreferredSize(new Dimension(180, 28));\n\t\ttoolBar.add(cbSample);\n\t\t// Add Chrom JComboBox to ToolBar\n\t\tcbChrom.setPreferredSize(new Dimension(100, 28));\n\t\ttoolBar.add(cbChrom);\n\n\t\t// Init Species ComboBox\n\t\tupdateSpeciesCombo();\n\t\t// Init CircRna ComboBox\n\t\tupdateCircRnaToolsCombo();\n\t\t// Init Sample ComboBox\n\t\tupdateSamplesCombo();\n\t\t// Init Chrom ComboBox\n\t\tupdateCbChrom();\n\t\t// Init GeneTranscript List\n\t\tupdateGeneTransList();\n\n\t\t// Add ItemListener to Species\n\t\tcbSpecies.addItemListener(new ItemListener() {\n\t\t\tpublic void itemStateChanged(ItemEvent e) {\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED) {\n\t\t\t\t\tString species = (String) cbSpecies.getSelectedItem();\n\t\t\t\t\tgenes = MainData.getSpeciesData().get(species);\n\t\t\t\t\tupdateCircRnaToolsCombo();\n\t\t\t\t\tupdateSamplesCombo();\n\t\t\t\t\tupdateCbChrom();\n\t\t\t\t\tupdateGeneTransList();\n\t\t\t\t\tupdateRbpMreStatus();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Add ItemListener to CircRnaTool\n\t\tcbCircRnaTool.addItemListener(new ItemListener() {\n\t\t\tpublic void itemStateChanged(ItemEvent e) {\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED) {\n\t\t\t\t\tupdateSamplesCombo();\n\t\t\t\t\tupdateGeneTransList();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t// Add ItemListener to Sample\n\t\tcbSample.addItemListener(new ItemListener() {\n\t\t\tpublic void itemStateChanged(ItemEvent e) {\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED) {\n\t\t\t\t\tupdateGeneTransList();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Add ItemListener to Chrom\n\t\tcbChrom.addItemListener(new ItemListener() {\n\t\t\tpublic void itemStateChanged(ItemEvent e) {\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED) {\n\t\t\t\t\tif (cbChromInit) {\n\t\t\t\t\t\tcbChromInit = false;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tupdateGeneTransList();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tcbChrom.addItem(\"Chrom\");\n\n\t\t// Search\n\t\tJLabel lbGeneName = new JLabel(\"Gene Name:\", JLabel.RIGHT);\n\t\tfinal JTextField tfGeneName = new JTextField();\n\t\ttfGeneName.setPreferredSize(new Dimension(100, 20));\n\t\tJLabel lbLocation = new JLabel(\" or Location:\", JLabel.RIGHT);\n\t\tfinal JTextField tfLocStart = new JTextField();\n\t\ttfLocStart.setPreferredSize(new Dimension(100, 20));\n\t\tJLabel lbTo = new JLabel(\"-\", JLabel.LEFT);\n\t\tfinal JTextField tfLocEnd = new JTextField();\n\t\ttfLocEnd.setPreferredSize(new Dimension(100, 20));\n\t\t// JButton btSearch = new JButton(\"Search\");\n\t\tJButton btReset = new JButton(\"Reset\");\n\t\t// Add to ToolBar\n\t\ttoolBar.addSeparator();\n\t\ttoolBar.add(lbGeneName);\n\t\ttoolBar.add(tfGeneName);\n\t\ttoolBar.add(lbLocation);\n\t\ttoolBar.add(tfLocStart);\n\t\ttoolBar.add(lbTo);\n\t\ttoolBar.add(tfLocEnd);\n\t\t// toolBar.add(btSearch);\n\t\ttoolBar.add(btReset);\n\n\t\ttfGeneName.getDocument().addDocumentListener(new DocumentListener() {\n\t\t\tpublic void insertUpdate(DocumentEvent e) {\n\t\t\t\tsearchByGeneName();\n\t\t\t}\n\n\t\t\tpublic void removeUpdate(DocumentEvent e) {\n\t\t\t\tsearchByGeneName();\n\t\t\t}\n\n\t\t\tpublic void changedUpdate(DocumentEvent e) {\n\t\t\t}\n\n\t\t\tprivate void searchByGeneName() {\n\t\t\t\tString searchGeneName = tfGeneName.getText();\n\t\t\t\tgeneTransName.removeAllElements();\n\t\t\t\tif (genes != null) {\n\t\t\t\t\tfor (String geneName : genes.keySet()) {\n\t\t\t\t\t\tGene gene = genes.get(geneName);\n\t\t\t\t\t\tfor (String transName : gene.getGeneTranscripts().keySet()) {\n\t\t\t\t\t\t\tGeneTranscript geneTrans = gene.getGeneTranscripts().get(transName);\n\t\t\t\t\t\t\tif (geneTrans.getGeneName().toLowerCase().contains(searchGeneName.toLowerCase())\n\t\t\t\t\t\t\t\t\t|| searchGeneName.equalsIgnoreCase(\"\")) {\n\t\t\t\t\t\t\t\tif (geneTrans.getCircRnas().size() > 0) {\n\t\t\t\t\t\t\t\t\tgeneTransName.addElement(gene.getGeneName() + \" [\" + geneTrans.getTranscriptName()\n\t\t\t\t\t\t\t\t\t\t\t+ \"] \" + \"(\" + geneTrans.getCircRnas().size() + \")\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tgeneTransList.setListData(geneTransName);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\ttfLocStart.getDocument().addDocumentListener(new DocumentListener() {\n\t\t\tpublic void insertUpdate(DocumentEvent e) {\n\t\t\t\tsearchByLocation();\n\t\t\t}\n\n\t\t\tpublic void removeUpdate(DocumentEvent e) {\n\t\t\t\tsearchByLocation();\n\t\t\t}\n\n\t\t\tpublic void changedUpdate(DocumentEvent e) {\n\n\t\t\t}\n\n\t\t\tprivate void searchByLocation() {\n\t\t\t\tlong start = 0;\n\t\t\t\tlong end = Long.MAX_VALUE;\n\t\t\t\tif (tfLocStart.getText().matches(\"[0-9]+\")) {\n\t\t\t\t\tString str = tfLocStart.getText();\n\t\t\t\t\tstart = Long.parseLong(str);\n\t\t\t\t}\n\t\t\t\tif (tfLocEnd.getText().matches(\"[0-9]+\")) {\n\t\t\t\t\tString str = tfLocEnd.getText();\n\t\t\t\t\tend = Long.parseLong(str);\n\t\t\t\t}\n\t\t\t\tgeneTransName.removeAllElements();\n\t\t\t\tif (genes != null) {\n\t\t\t\t\tfor (String geneName : genes.keySet()) {\n\t\t\t\t\t\tGene gene = genes.get(geneName);\n\t\t\t\t\t\tfor (String transName : gene.getGeneTranscripts().keySet()) {\n\t\t\t\t\t\t\tGeneTranscript geneTrans = gene.getGeneTranscripts().get(transName);\n\t\t\t\t\t\t\tif ((start <= geneTrans.getTxStart()) && (geneTrans.getTxEnd() <= end)) {\n\t\t\t\t\t\t\t\tif (geneTrans.getCircRnas().size() > 0) {\n\t\t\t\t\t\t\t\t\tgeneTransName.addElement(gene.getGeneName() + \" [\" + geneTrans.getTranscriptName()\n\t\t\t\t\t\t\t\t\t\t\t+ \"] \" + \"(\" + geneTrans.getCircRnas().size() + \")\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tgeneTransList.setListData(geneTransName);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\ttfLocEnd.getDocument().addDocumentListener(new DocumentListener() {\n\t\t\tpublic void insertUpdate(DocumentEvent e) {\n\t\t\t\tsearchByLocation();\n\t\t\t}\n\n\t\t\tpublic void removeUpdate(DocumentEvent e) {\n\t\t\t\tsearchByLocation();\n\t\t\t}\n\n\t\t\tpublic void changedUpdate(DocumentEvent e) {\n\n\t\t\t}\n\n\t\t\tprivate void searchByLocation() {\n\t\t\t\tlong start = 0;\n\t\t\t\tlong end = Long.MAX_VALUE;\n\t\t\t\tif (tfLocStart.getText().matches(\"[0-9]+\")) {\n\t\t\t\t\tString str = tfLocStart.getText();\n\t\t\t\t\tstart = Long.parseLong(str);\n\t\t\t\t}\n\t\t\t\tif (tfLocEnd.getText().matches(\"[0-9]+\")) {\n\t\t\t\t\tString str = tfLocEnd.getText();\n\t\t\t\t\tend = Long.parseLong(str);\n\t\t\t\t}\n\t\t\t\tgeneTransName.removeAllElements();\n\t\t\t\tif (genes != null) {\n\t\t\t\t\tfor (String geneName : genes.keySet()) {\n\t\t\t\t\t\tGene gene = genes.get(geneName);\n\t\t\t\t\t\tfor (String transName : gene.getGeneTranscripts().keySet()) {\n\t\t\t\t\t\t\tGeneTranscript geneTrans = gene.getGeneTranscripts().get(transName);\n\t\t\t\t\t\t\tif ((start <= geneTrans.getTxStart()) && (geneTrans.getTxEnd() <= end)) {\n\t\t\t\t\t\t\t\tif (geneTrans.getCircRnas().size() > 0) {\n\t\t\t\t\t\t\t\t\tgeneTransName.addElement(gene.getGeneName() + \" [\" + geneTrans.getTranscriptName()\n\t\t\t\t\t\t\t\t\t\t\t+ \"] \" + \"(\" + geneTrans.getCircRnas().size() + \")\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tgeneTransList.setListData(geneTransName);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to Reset Button\n\t\tbtReset.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tupdateGeneTransList();\n\t\t\t\ttfGeneName.setText(\"\");\n\t\t\t\ttfLocStart.setText(\"\");\n\t\t\t\ttfLocEnd.setText(\"\");\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate void initMainPanel() {\n\t\t// Add MainPanel to Frame\n\t\tJPanel mainPanel = new JPanel(new BorderLayout());\n\t\tmainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));\n\t\tframe.getContentPane().add(mainPanel, BorderLayout.CENTER);\n\n\t\t// Touch geneTransList to ScrollPane, Add ScrollPane to MainPanel\n\t\tJPanel geneTransPanel = new JPanel(new BorderLayout());\n\t\tfinal JComboBox<String> cbSort = new JComboBox<String>();\n\t\tcbSort.setPreferredSize(new Dimension(mainPanel.getWidth(), 28));\n\t\tcbSort.addItem(\"sort name by asc\");\n\t\tcbSort.addItem(\"sort name by desc\");\n\t\tcbSort.addItem(\"sort position by asc\");\n\t\tcbSort.addItem(\"sort position by desc\");\n\t\tcbSort.addItem(\"sort abundance by asc\");\n\t\tcbSort.addItem(\"sort abundance by desc\");\n\t\tgeneTransPanel.add(cbSort, BorderLayout.NORTH);\n\n\t\tJScrollPane geneTransScrollPane = new JScrollPane(geneTransList);\n\t\tgeneTransScrollPane.setPreferredSize(new Dimension(250, mainPanel.getHeight()));\n\t\tgeneTransPanel.add(geneTransScrollPane, BorderLayout.CENTER);\n\t\tmainPanel.add(geneTransPanel, BorderLayout.WEST);\n\n\t\t// Add ImagePanel to MainPanel\n\t\timagePanel = new JPanel(new BorderLayout());\n\t\tmainPanel.add(imagePanel, BorderLayout.CENTER);\n\n\t\t// Add ImageToolBar to ImagePanel\n\t\tJPanel imageToolBar = new JPanel();\n\t\timageToolBar.setLayout(new FlowLayout());\n\t\timageToolBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));\n\t\timagePanel.add(imageToolBar, BorderLayout.NORTH);\n\n\t\t// Add Buttons to ImageToolBar\n\t\tJButton btHome = new JButton(\"Home\");\n\t\tcbCircRnaSelect = new JComboBox<String>();\n\t\tJButton btZoomIn = new JButton(\"Zoom In\");\n\t\tJButton btZoomOut = new JButton(\"Zoom Out\");\n\t\tcbRbp = new JCheckBox(\"RBP\", null, false);\n\t\tcbMre = new JCheckBox(\"MRE\", null, false);\n\t\tJButton btDetails = new JButton(\"Details\");\n\t\tJButton btSaveImage = new JButton(\"Save Image\");\n\t\tcbCircRnaSelect.setPreferredSize(new Dimension(200, 28));\n\t\timageToolBar.add(btHome);\n\t\timageToolBar.add(cbCircRnaSelect);\n\t\timageToolBar.add(btZoomIn);\n\t\timageToolBar.add(btZoomOut);\n\t\timageToolBar.add(cbRbp);\n\t\timageToolBar.add(cbMre);\n\t\timageToolBar.add(btDetails);\n\t\timageToolBar.add(btSaveImage);\n\n\t\tif ((null == conn) || (null == cbSpecies.getSelectedItem()) || (null == circRnaImage.getGt())) {\n\t\t\tcbRbp.setEnabled(false);\n\t\t\tcbMre.setEnabled(false);\n\t\t}\n\n\t\t// Add Image to ImageScrollPane, Add ImageSchollPane to ImagePanel\n\t\tcircRnaImage = new CircRnaImagePanel();\n\t\tfinal JScrollPane imageScrollPane = new JScrollPane(circRnaImage);\n\t\timagePanel.add(imageScrollPane, BorderLayout.CENTER);\n\n\t\t// Mouse Tips\n\t\ttipsTA = new JTextArea();\n\t\ttipsTA.setLineWrap(true);\n\t\ttipsTA.setWrapStyleWord(true);\n\t\tcircRnaImage.add(tipsTA);\n\t\tcircRnaImage.setLayout(null);\n\n\t\t// Add ItemListener to Sort ComboBox\n\t\tcbSort.addItemListener(new ItemListener() {\n\t\t\tpublic void itemStateChanged(ItemEvent e) {\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED) {\n\t\t\t\t\tString sortType = cbSort.getSelectedItem().toString();\n\t\t\t\t\tupdateGeneTransList(sortType);\n\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Add ListSelectionListener to GeneTransList\n\t\tgeneTransList.addListSelectionListener(new ListSelectionListener() {\n\t\t\tpublic void valueChanged(ListSelectionEvent e) {\n\t\t\t\tcbRbp.setSelected(false);\n\t\t\t\tcbMre.setSelected(false);\n\t\t\t\tif (e.getValueIsAdjusting()) {\n\t\t\t\t\tcircRnaImage.clearRbp();\n\t\t\t\t\tcircRnaImage.clearMre();\n\t\t\t\t\tpreDisplay();\n\t\t\t\t\tdisplay();\n\t\t\t\t\tupdateCircRnasCheckList();\n\t\t\t\t\tupdateRbpMreStatus();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tgeneTransList.addKeyListener(new KeyAdapter() {\n\t\t\tpublic void keyReleased(KeyEvent key) {\n\t\t\t\tcbRbp.setSelected(false);\n\t\t\t\tcbMre.setSelected(false);\n\t\t\t\tcircRnaImage.clearRbp();\n\t\t\t\tcircRnaImage.clearMre();\n\t\t\t\tpreDisplay();\n\t\t\t\tdisplay();\n\t\t\t\tupdateCircRnasCheckList();\n\t\t\t\tupdateRbpMreStatus();\n\t\t\t}\n\t\t});\n\n\t\tbtHome.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tif (cbCircRnaSelect.getItemCount() > 0\n\t\t\t\t\t\t&& !cbCircRnaSelect.getSelectedItem().toString().equalsIgnoreCase(\"All\")) {\n\t\t\t\t\tcbCircRnaSelect.setSelectedIndex(0);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to CircRnaSelect\n\t\tcbCircRnaSelect.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString circRnaId = \"\";\n\t\t\t\tif (null != cbCircRnaSelect.getSelectedItem()) {\n\t\t\t\t\tcircRnaId = cbCircRnaSelect.getSelectedItem().toString();\n\t\t\t\t} else {\n\t\t\t\t\tcircRnaId = \"All\";\n\t\t\t\t}\n\t\t\t\tif (circRnaId.equalsIgnoreCase(\"All\")) {\n\t\t\t\t\tcircRnaImage.selectAllCircRnas();\n\t\t\t\t} else {\n\t\t\t\t\tcircRnaImage.selectOneCircRna(circRnaId);\n\t\t\t\t}\n\t\t\t\tdisplay();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to Zoom In Button\n\t\tbtZoomIn.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tcircRnaImage.zoomIn();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to Zoom Out Button\n\t\tbtZoomOut.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tcircRnaImage.zoomOut();\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to RBP CheckBox\n\t\tcbRbp.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tboolean selected = cbRbp.isSelected();\n\t\t\t\tif (selected) {\n\t\t\t\t\tif (null != conn) {\n\t\t\t\t\t\tif ((null != cbSpecies.getSelectedItem()) && (null != circRnaImage.getGt())) {\n\t\t\t\t\t\t\tDataLoadingDialog dataLoadingDialog = new DataLoadingDialog(frame, \"Loading RBP Data ...\");\n\t\t\t\t\t\t\tcircRnaImage.queryRbpData(cbSpecies.getSelectedItem().toString(), circRnaImage.getGt());\n\t\t\t\t\t\t\tdataLoadingDialog.setVisible(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tJOptionPane.showMessageDialog(CircView.frame, \"Can NOT connect to the Server!\");\n\t\t\t\t\t\tcbRbp.setSelected(false);\n\t\t\t\t\t}\n\t\t\t\t\tdisplay();\n\t\t\t\t} else {\n\t\t\t\t\tcircRnaImage.clearRbp();\n\t\t\t\t\tdisplay();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to MRE CheckBox\n\t\tcbMre.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tboolean selected = cbMre.isSelected();\n\t\t\t\tif (selected) {\n\t\t\t\t\tif (null != conn) {\n\t\t\t\t\t\tif ((null != cbSpecies.getSelectedItem()) && (null != circRnaImage.getGt())) {\n\t\t\t\t\t\t\tDataLoadingDialog dataLoadingDialog = new DataLoadingDialog(frame, \"Loading MRE Data ...\");\n\t\t\t\t\t\t\tcircRnaImage.queryMreData(cbSpecies.getSelectedItem().toString(), circRnaImage.getGt());\n\t\t\t\t\t\t\tdataLoadingDialog.setVisible(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tJOptionPane.showMessageDialog(CircView.frame, \"Can NOT connect to the Server!\");\n\t\t\t\t\t\tcbMre.setSelected(false);\n\t\t\t\t\t}\n\t\t\t\t\tdisplay();\n\t\t\t\t} else {\n\t\t\t\t\tcircRnaImage.clearMre();\n\t\t\t\t\tdisplay();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to View the Details\n\t\tbtDetails.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew DetailsResultDialog(circRnaImage.getDetails(circRnaImage.getGt()));\n\t\t\t}\n\t\t});\n\n\t\t// Add ActionListener to Save Image Button\n\t\tbtSaveImage.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tnew SaveImageDialog(circRnaImage);\n\t\t\t}\n\t\t});\n\n\t\t// Add MouseListener to\n\t\tcircRnaImage.addMouseListener(new MouseListener() {\n\t\t\tpublic void mouseClicked(MouseEvent e) {\n\t\t\t\tif (0 == cbCircRnaSelect.getItemCount()) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!cbCircRnaSelect.getSelectedItem().equals(\"All\")) {\n\t\t\t\t\tcbCircRnaSelect.setSelectedItem(\"All\");\n\t\t\t\t\tcircRnaImage.selectAllCircRnas();\n\t\t\t\t\ttipsTA.setVisible(false);\n\t\t\t\t\tdisplay();\n\t\t\t\t} else {\n\t\t\t\t\tint circRnaIndex = -1;\n\t\t\t\t\tfor (int i = 0; i < circRnaImage.getCircX().size(); i++) {\n\t\t\t\t\t\tif (hitCirc(circRnaImage.getCircX().get(i), circRnaImage.getCircY().get(i),\n\t\t\t\t\t\t\t\tcircRnaImage.getCircR(), e.getX(), e.getY())) {\n\t\t\t\t\t\t\tcircRnaIndex = i;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (circRnaIndex >= 0) {\n\t\t\t\t\t\tcircRnaIndex++;\n\t\t\t\t\t\tcbCircRnaSelect.setSelectedIndex(circRnaIndex);\n\t\t\t\t\t\tcircRnaImage.selectOneCircRna(cbCircRnaSelect.getItemAt(circRnaIndex));\n\t\t\t\t\t\ttipsTA.setVisible(false);\n\t\t\t\t\t\tdisplay();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpublic void mousePressed(MouseEvent e) {\n\t\t\t}\n\n\t\t\tpublic void mouseReleased(MouseEvent e) {\n\t\t\t}\n\n\t\t\tpublic void mouseEntered(MouseEvent e) {\n\t\t\t}\n\n\t\t\tpublic void mouseExited(MouseEvent e) {\n\t\t\t}\n\t\t});\n\t\t// Add MouseMotionListener\n\t\tcircRnaImage.addMouseMotionListener(new MouseMotionListener() {\n\t\t\tpublic void mouseDragged(MouseEvent e) {\n\t\t\t}\n\n\t\t\tpublic void mouseMoved(MouseEvent e) {\n\t\t\t\tint tipsTop = 0;\n\t\t\t\tint tipsLeft = 0;\n\t\t\t\tif (0 == cbCircRnaSelect.getItemCount()) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tint circRnaIndex = -1;\n\t\t\t\tfor (int i = 0; i < circRnaImage.getCircX().size(); i++) {\n\t\t\t\t\tif (hitCirc(circRnaImage.getCircX().get(i), circRnaImage.getCircY().get(i), circRnaImage.getCircR(),\n\t\t\t\t\t\t\te.getX(), e.getY())) {\n\t\t\t\t\t\ttipsLeft = (int) Math.round(circRnaImage.getCircX().get(i) - circRnaImage.getCircR());\n\t\t\t\t\t\ttipsTop = (int) Math.round(circRnaImage.getCircY().get(i) + circRnaImage.getCircR() * 2);\n\t\t\t\t\t\tcircRnaIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Display the information of the circRnaIndex CircRna\n\t\t\t\tif (circRnaIndex >= 0) {\n\t\t\t\t\tString info = \"\";\n\t\t\t\t\tif (cbCircRnaSelect.getSelectedItem().equals(\"All\")) {\n\t\t\t\t\t\tinfo = circRnaImage.getCircRnaInfo(cbCircRnaSelect.getItemAt(circRnaIndex + 1));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinfo = circRnaImage.getCircRnaInfo(cbCircRnaSelect.getSelectedItem().toString());\n\t\t\t\t\t}\n\t\t\t\t\tint fontSize = (int) Math.round(circRnaImage.getHeight() / 80.0) < (int) Math\n\t\t\t\t\t\t\t.round(imageScrollPane.getHeight() / 60.0)\n\t\t\t\t\t\t\t\t\t? (int) Math.round(circRnaImage.getHeight() / 80.0)\n\t\t\t\t\t\t\t\t\t: (int) Math.round(imageScrollPane.getHeight() / 60.0);\n\t\t\t\t\ttipsTA.setFont(new Font(\"TimeRomes\", Font.PLAIN, fontSize));\n\n\t\t\t\t\tint tipsLength = imageScrollPane.getWidth() / 2;\n\t\t\t\t\tint tipsHeight = imageScrollPane.getHeight() / 4;\n\t\t\t\t\tif ((tipsLeft + tipsLength) > circRnaImage.getWidth()) {\n\t\t\t\t\t\ttipsLeft = circRnaImage.getWidth() - tipsLength;\n\t\t\t\t\t}\n\t\t\t\t\ttipsTA.setBounds(tipsLeft, tipsTop, tipsLength, tipsHeight);\n\t\t\t\t\ttipsTA.setRows(12);\n\t\t\t\t\ttipsTA.setColumns(150);\n\t\t\t\t\ttipsTA.setText(info);\n\t\t\t\t\ttipsTA.setVisible(true);\n\t\t\t\t}\n\t\t\t\t// Destory the tip dialog\n\t\t\t\telse {\n\t\t\t\t\ttipsTA.setVisible(false);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate boolean hitCirc(double circX, double circY, double circR, int x, int y) {\n\t\tboolean ret = false;\n\t\tif ((circX - circR <= x) && (x <= circX + circR) && (circY - circR <= y) && (y <= circY + circR)) {\n\t\t\tret = true;\n\t\t}\n\t\treturn ret;\n\t}\n\n\tprivate void preDisplay() {\n\t\tString geneTransName = geneTransList.getSelectedValue();\n\t\tString[] tmp = geneTransName.split(\" \");\n\t\tString gName = tmp[0];\n\t\tString trName = tmp[1].substring(1, tmp[1].length() - 1);\n\t\tGeneTranscript geneTranscript = null;\n\t\tOUTER: for (String geneName : genes.keySet()) {\n\t\t\tif (geneName.equalsIgnoreCase(gName)) {\n\t\t\t\tGene gene = genes.get(geneName);\n\t\t\t\tfor (String gtName : gene.getGeneTranscripts().keySet()) {\n\t\t\t\t\tif (gtName.equalsIgnoreCase(trName)) {\n\t\t\t\t\t\tgeneTranscript = gene.getGeneTranscripts().get(gtName);\n\t\t\t\t\t\tbreak OUTER;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tString species = (String) cbSpecies.getSelectedItem();\n\t\tTreeMap<String, String> sampleName = new TreeMap<String, String>();\n\t\tTreeMap<String, String> toolName = new TreeMap<String, String>();\n\t\tfor (Vector<String> rowData : MainData.getCircRnaFilesInfo()) {\n\t\t\tString sname = rowData.get(0);\n\t\t\tString tname = rowData.get(1);\n\t\t\tString fname = rowData.get(2);\n\t\t\tif (species.equalsIgnoreCase(sname)) {\n\t\t\t\ttoolName.put(tname, tname);\n\t\t\t\tint tmpP = fname.lastIndexOf(\".\");\n\t\t\t\tsampleName.put(fname.substring(0, tmpP), fname);\n\t\t\t}\n\t\t}\n\t\tcircRnaImage.setGt(geneTranscript, sampleName.size(), toolName.size());\n\t}\n\n\tprivate void updateCircRnasCheckList() {\n\t\tcbCircRnaSelect.removeAllItems();\n\t\tcbCircRnaSelect.addItem(\"All\");\n\t\tfor (String circRnaId : circRnaImage.getGtBackup().getCircRnas().keySet()) {\n\t\t\tcbCircRnaSelect.addItem(circRnaId);\n\t\t}\n\t}\n\n\tpublic static void updateRbpMreStatus() {\n\t\tif (null != cbSpecies.getSelectedItem()) {\n\t\t\tString species = cbSpecies.getSelectedItem().toString();\n\t\t\tString rbpTableName = \"rbp_\" + DbUtil.species2TableName(species);\n\t\t\tString mreTableName = \"mre_\" + DbUtil.species2TableName(species);\n\t\t\ttry {\n\t\t\t\tif (DbUtil.existTable(conn, rbpTableName)) {\n\t\t\t\t\tcbRbp.setEnabled(true);\n\t\t\t\t} else {\n\t\t\t\t\tcbRbp.setEnabled(false);\n\t\t\t\t}\n\n\t\t\t\tif (DbUtil.existTable(conn, mreTableName)) {\n\t\t\t\t\tcbMre.setEnabled(true);\n\t\t\t\t} else {\n\t\t\t\t\tcbMre.setEnabled(false);\n\t\t\t\t}\n\t\t\t} catch (ClassNotFoundException | SQLException e) {\n\t\t\t\tCircView.log.warn(e.getMessage());\n\t\t\t}\n\t\t} else {\n\t\t\tcbRbp.setEnabled(false);\n\t\t\tcbMre.setEnabled(false);\n\t\t}\n\t}\n\n\tprivate void display() {\n\t\tcircRnaImage.createOneImage(imagePanel.getWidth(), imagePanel.getHeight(), conn);\n\t\tcircRnaImage.repaint();\n\t}\n\n\tpublic static void updateGeneTransList() {\n\t\tgeneTransName.removeAllElements();\n\t\tif (genes != null) {\n\t\t\tString toolName = (String) cbCircRnaTool.getSelectedItem();\n\t\t\tString sampleName = (String) cbSample.getSelectedItem();\n\t\t\tString chrom = (String) cbChrom.getSelectedItem();\n\t\t\tfor (String geneName : genes.keySet()) {\n\t\t\t\tGene gene = genes.get(geneName);\n\t\t\t\tfor (String transName : gene.getGeneTranscripts().keySet()) {\n\t\t\t\t\tGeneTranscript geneTrans = gene.getGeneTranscripts().get(transName);\n\t\t\t\t\tif ((geneTrans.getCircRnas().size() > 0)\n\t\t\t\t\t\t\t&& ((chrom.equalsIgnoreCase(\"Chrom\")) || (geneTrans.getChrom().equalsIgnoreCase(chrom)))) {\n\t\t\t\t\t\tif (toolName.equalsIgnoreCase(\"Tool\") && sampleName.equalsIgnoreCase(\"Sample\")) {\n\t\t\t\t\t\t\tgeneTransName.addElement(gene.getGeneName() + \" [\" + geneTrans.getTranscriptName() + \"] \"\n\t\t\t\t\t\t\t\t\t+ \"(\" + geneTrans.getCircRnas().size() + \")\");\n\t\t\t\t\t\t} else if (toolName.equalsIgnoreCase(\"Tool\")) {\n\t\t\t\t\t\t\tboolean sign = false;\n\t\t\t\t\t\t\tfor (String circRnaName : geneTrans.getCircRnas().keySet()) {\n\t\t\t\t\t\t\t\tCircRna circRna = geneTrans.getCircRnas().get(circRnaName);\n\t\t\t\t\t\t\t\tfor (String sname : circRna.getFiles().keySet()) {\n\t\t\t\t\t\t\t\t\tif (sampleName.equalsIgnoreCase(sname)) {\n\t\t\t\t\t\t\t\t\t\tsign = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (sign) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (sign) {\n\t\t\t\t\t\t\t\tgeneTransName.addElement(gene.getGeneName() + \" [\" + geneTrans.getTranscriptName()\n\t\t\t\t\t\t\t\t\t\t+ \"] \" + \"(\" + geneTrans.getCircRnas().size() + \")\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (sampleName.equalsIgnoreCase(\"Sample\")) {\n\t\t\t\t\t\t\tboolean sign = false;\n\t\t\t\t\t\t\tfor (String circRnaName : geneTrans.getCircRnas().keySet()) {\n\t\t\t\t\t\t\t\tCircRna circRna = geneTrans.getCircRnas().get(circRnaName);\n\t\t\t\t\t\t\t\tfor (String tname : circRna.getCircTools().keySet()) {\n\t\t\t\t\t\t\t\t\tif (toolName.equalsIgnoreCase(tname)) {\n\t\t\t\t\t\t\t\t\t\tsign = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (sign) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (sign) {\n\t\t\t\t\t\t\t\tgeneTransName.addElement(gene.getGeneName() + \" [\" + geneTrans.getTranscriptName()\n\t\t\t\t\t\t\t\t\t\t+ \"] \" + \"(\" + geneTrans.getCircRnas().size() + \")\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tboolean sign = false;\n\t\t\t\t\t\t\tfor (String circRnaName : geneTrans.getCircRnas().keySet()) {\n\t\t\t\t\t\t\t\tCircRna circRna = geneTrans.getCircRnas().get(circRnaName);\n\t\t\t\t\t\t\t\tfor (String sname : circRna.getFiles().keySet()) {\n\t\t\t\t\t\t\t\t\tif (sampleName.equalsIgnoreCase(sname)) {\n\t\t\t\t\t\t\t\t\t\tsign = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (sign) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!sign) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsign = false;\n\t\t\t\t\t\t\tfor (String circRnaName : geneTrans.getCircRnas().keySet()) {\n\t\t\t\t\t\t\t\tCircRna circRna = geneTrans.getCircRnas().get(circRnaName);\n\t\t\t\t\t\t\t\tfor (String tname : circRna.getCircTools().keySet()) {\n\t\t\t\t\t\t\t\t\tif (toolName.equalsIgnoreCase(tname)) {\n\t\t\t\t\t\t\t\t\t\tsign = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (sign) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (sign) {\n\t\t\t\t\t\t\t\tgeneTransName.addElement(gene.getGeneName() + \" [\" + geneTrans.getTranscriptName()\n\t\t\t\t\t\t\t\t\t\t+ \"] \" + \"(\" + geneTrans.getCircRnas().size() + \")\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgeneTransList.setListData(geneTransName);\n\t}\n\n\tpublic static void updateGeneTransList(String sort) {\n\n\t\t// TreeMap Key sort\n\t\tComparator<String> keyComparator = null;\n\t\t// TreeMap Value sort\n\t\tComparator<Map.Entry<String, Long>> positionValueComparator = null;\n\t\tComparator<Map.Entry<String, Integer>> abundanceValueComparator = null;\n\n\t\tif (sort.contains(\"name\")) {\n\t\t\tif (sort.contains(\"asc\")) {\n\t\t\t\tkeyComparator = new Comparator<String>() {\n\t\t\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t} else if (sort.contains(\"desc\")) {\n\t\t\t\tkeyComparator = new Comparator<String>() {\n\t\t\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\t\t\treturn o2.compareToIgnoreCase(o1);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (sort.contains(\"position\")) {\n\t\t\tif (sort.contains(\"asc\")) {\n\t\t\t\tpositionValueComparator = new Comparator<Map.Entry<String, Long>>() {\n\t\t\t\t\tpublic int compare(Entry<String, Long> o1, Entry<String, Long> o2) {\n\t\t\t\t\t\treturn (int) (o1.getValue() - o2.getValue());\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t} else if (sort.contains(\"desc\")) {\n\t\t\t\tpositionValueComparator = new Comparator<Map.Entry<String, Long>>() {\n\t\t\t\t\tpublic int compare(Entry<String, Long> o1, Entry<String, Long> o2) {\n\t\t\t\t\t\treturn (int) (o2.getValue() - o1.getValue());\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (sort.contains(\"abundance\")) {\n\t\t\tif (sort.contains(\"asc\")) {\n\t\t\t\tabundanceValueComparator = new Comparator<Map.Entry<String, Integer>>() {\n\t\t\t\t\tpublic int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {\n\t\t\t\t\t\treturn (o1.getValue() - o2.getValue());\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t} else if (sort.contains(\"desc\")) {\n\t\t\t\tabundanceValueComparator = new Comparator<Map.Entry<String, Integer>>() {\n\t\t\t\t\tpublic int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {\n\t\t\t\t\t\treturn (o2.getValue() - o1.getValue());\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tTreeMap<String, Integer> geneTrans_juncReads;\n\t\tTreeMap<String, Long> geneTrans_position;\n\t\tif (sort.contains(\"name\")) {\n\t\t\tgeneTrans_juncReads = new TreeMap<String, Integer>(keyComparator);\n\t\t\tgeneTrans_position = new TreeMap<String, Long>(keyComparator);\n\n\t\t} else {\n\t\t\tgeneTrans_juncReads = new TreeMap<String, Integer>();\n\t\t\tgeneTrans_position = new TreeMap<String, Long>();\n\t\t}\n\n\t\tfor (String name : geneTransName) {\n\t\t\tString[] tmp = name.split(\" \\\\[\");\n\t\t\tString geneName = tmp[0];\n\t\t\tString[] tmp2 = tmp[1].split(\"\\\\]\");\n\t\t\tString transName = tmp2[0];\n\t\t\tGene gene = genes.get(geneName);\n\t\t\tif (null != gene) {\n\t\t\t\tGeneTranscript geneTrans = gene.getGeneTranscripts().get(transName);\n\t\t\t\tgeneTrans_juncReads.put(name, geneTrans.getTotalJunctionReads());\n\t\t\t\tgeneTrans_position.put(name, geneTrans.getCdsStart());\n\t\t\t} else {\n\t\t\t\tSystem.out.println(\"Gene Transcript Name error \" + name);\n\t\t\t}\n\t\t}\n\n\t\tgeneTransName.removeAllElements();\n\t\tif (sort.contains(\"name\")) {\n\t\t\tfor (Map.Entry<String, Integer> entry : geneTrans_juncReads.entrySet()) {\n\t\t\t\tgeneTransName.addElement(entry.getKey());\n\t\t\t}\n\t\t} else if (sort.contains(\"position\")) {\n\t\t\tList<Map.Entry<String, Long>> positionList = new ArrayList<Map.Entry<String, Long>>(\n\t\t\t\t\tgeneTrans_position.entrySet());\n\t\t\tCollections.sort(positionList, positionValueComparator);\n\t\t\tfor (Map.Entry<String, Long> entry : positionList) {\n\t\t\t\tgeneTransName.addElement(entry.getKey());\n\t\t\t}\n\t\t} else if (sort.contains(\"abundance\")) {\n\t\t\tList<Map.Entry<String, Integer>> junctionReadsList = new ArrayList<Map.Entry<String, Integer>>(\n\t\t\t\t\tgeneTrans_juncReads.entrySet());\n\t\t\tCollections.sort(junctionReadsList, abundanceValueComparator);\n\t\t\tfor (Map.Entry<String, Integer> entry : junctionReadsList) {\n\t\t\t\tgeneTransName.addElement(entry.getKey());\n\t\t\t}\n\t\t}\n\n\t\tgeneTransList.setListData(geneTransName);\n\t}\n\n\tpublic static void updateCbChrom() {\n\t\tcbChrom.removeAllItems();\n\t\tcbChrom.addItem(\"Chrom\");\n\t\tif (genes == null) {\n\t\t} else {\n\t\t\tTreeMap<String, String> chrom = new TreeMap<String, String>();\n\t\t\tfor (String geneName : genes.keySet()) {\n\t\t\t\tGene gene = genes.get(geneName);\n\t\t\t\tfor (String transcriptName : gene.getGeneTranscripts().keySet()) {\n\t\t\t\t\tGeneTranscript transcript = gene.getGeneTranscripts().get(transcriptName);\n\t\t\t\t\tif (transcript.getCircRnas().size() > 0) {\n\t\t\t\t\t\tchrom.put(transcript.getChrom(), transcript.getChrom());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (String chr : chrom.keySet()) {\n\t\t\t\tcbChrom.addItem(chr);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void setSpeciesCombo(String species) {\n\t\tcbSpecies.setSelectedItem(species);\n\t}\n\n\tpublic static void setCircRnaToolsCombo(String circRnaTool) {\n\t\tcbCircRnaTool.setSelectedItem(circRnaTool);\n\t}\n\n\tpublic static void updateSpeciesCombo() {\n\t\tcbSpecies.removeAllItems();\n\t\tfor (String speciesName : MainData.getSpeciesData().keySet()) {\n\t\t\tcbSpecies.addItem(speciesName);\n\t\t}\n\t\tString sname = (String) cbSpecies.getSelectedItem();\n\t\tif (null == sname) {\n\t\t\tgenes = null;\n\t\t} else {\n\t\t\tgenes = MainData.getSpeciesData().get(sname);\n\t\t}\n\t}\n\n\tpublic static void updateCircRnaToolsCombo() {\n\t\tcbCircRnaTool.removeAllItems();\n\t\tcbCircRnaTool.addItem(\"Tool\");\n\n\t\tif (null == cbSpecies.getSelectedItem()) {\n\t\t\treturn;\n\t\t}\n\n\t\tString speciesName = cbSpecies.getSelectedItem().toString();\n\t\tTreeMap<String, String> tools = new TreeMap<String, String>();\n\t\tfor (Vector<String> rowData : MainData.getCircRnaFilesInfo()) {\n\t\t\tString sname = rowData.get(0);\n\t\t\tString tname = rowData.get(1);\n\t\t\tif (speciesName.equalsIgnoreCase(sname)) {\n\t\t\t\ttools.put(tname, tname);\n\t\t\t}\n\t\t}\n\t\tfor (String toolName : tools.keySet()) {\n\t\t\tcbCircRnaTool.addItem(toolName);\n\t\t}\n\t}\n\n\tpublic static void updateSamplesCombo() {\n\t\tcbSample.removeAllItems();\n\t\tcbSample.addItem(\"Sample\");\n\n\t\tif (null == cbSpecies.getSelectedItem()) {\n\t\t\treturn;\n\t\t}\n\t\tif (null == cbCircRnaTool.getSelectedItem()) {\n\t\t\treturn;\n\t\t}\n\t\tString speciesName = cbSpecies.getSelectedItem().toString();\n\t\tString circRnaTool = cbCircRnaTool.getSelectedItem().toString();\n\n\t\tTreeMap<String, String> samples = new TreeMap<String, String>();\n\t\tfor (Vector<String> rowData : MainData.getCircRnaFilesInfo()) {\n\t\t\tString sname = rowData.get(0);\n\t\t\tString tname = rowData.get(1);\n\t\t\tString fname = rowData.get(2);\n\t\t\tif (speciesName.equalsIgnoreCase(sname)\n\t\t\t\t\t&& ((circRnaTool.equalsIgnoreCase(tname)) || (circRnaTool.equalsIgnoreCase(\"Tool\")))) {\n\t\t\t\tsamples.put(fname, fname);\n\t\t\t}\n\t\t}\n\t\tfor (String sampleName : samples.keySet()) {\n\t\t\tcbSample.addItem(sampleName);\n\t\t}\n\t}\n\n\tpublic TreeMap<String, Gene> getMainData() {\n\t\treturn genes;\n\t}\n\n\tpublic static JComboBox<String> getCbCircRnaSelect() {\n\t\treturn cbCircRnaSelect;\n\t}\n\n\tpublic static void setCbCircRnaSelect(JComboBox<String> cbCircRnaSelect) {\n\t\tCircView.cbCircRnaSelect = cbCircRnaSelect;\n\t}\n}",
"public class Gene implements Serializable{\n\t\n\tprivate static final long serialVersionUID = 1L;\n\t/**\n\t * gene's name\n\t */\n\tprivate String geneName;\n\t/**\n\t * gene's transcripts\n\t */\n\tprivate TreeMap<String, GeneTranscript> geneTranscripts;\n\t/**\n\t * gene's circRNA samples\n\t */\n\t\n\tprivate Vector<Exon> allExons;\n\t/**\n\t * gene's reference\n\t */\n\tprivate GeneTranscript geneReference;\n\n\t/**\n\t * Constructor of Gene\n\t * \n\t * @param geneName\n\t */\n\tpublic Gene(String geneName) {\n\t\tthis.setGeneName(geneName);\n\t\tgeneTranscripts = new TreeMap<String, GeneTranscript>();\n\t\tallExons = new Vector<Exon>();\n\t\tgeneReference = new GeneTranscript(geneName);\n\t}\n\n\t/**\n\t * get Gene's name\n\t * \n\t * @return geneName\n\t */\n\tpublic String getGeneName() {\n\t\treturn geneName;\n\t}\n\n\t/**\n\t * set Gene's name\n\t * \n\t * @param geneName\n\t */\n\tpublic void setGeneName(String geneName) {\n\t\tthis.geneName = geneName;\n\t}\n\n\t/**\n\t * get gene's transcripts\n\t * \n\t * @return geneTranscripts\n\t */\n\tpublic TreeMap<String, GeneTranscript> getGeneTranscripts() {\n\t\treturn geneTranscripts;\n\t}\n\n\t/**\n\t * set gene's transcripts\n\t * \n\t * @param geneTranscripts\n\t */\n\tpublic void setGeneTranscripts(TreeMap<String, GeneTranscript> geneTranscripts) {\n\t\tthis.geneTranscripts = geneTranscripts;\n\t}\n\n\t/**\n\t * get all exons\n\t * \n\t * @return allExons\n\t */\n\tpublic Vector<Exon> getAllExons() {\n\t\treturn allExons;\n\t}\n\n\t/**\n\t * set all exons\n\t * \n\t * @param allExons\n\t */\n\tpublic void setAllExons(Vector<Exon> allExons) {\n\t\tthis.allExons = allExons;\n\t}\n\n\t/**\n\t * get gene's reference\n\t * \n\t * @return geneReference\n\t */\n\tpublic GeneTranscript getGeneReference() {\n\t\treturn geneReference;\n\t}\n\n\t/**\n\t * set gene's reference\n\t * \n\t * @param geneReference\n\t */\n\tpublic void setGeneReference(GeneTranscript geneReference) {\n\t\tthis.geneReference = geneReference;\n\t}\n\n}",
"public class GeneTranscript implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\t/**\n\t * Name of gene as it appears in Genome Browser\n\t */\n\tprivate String geneName;\n\t/**\n\t * Name of gene\n\t */\n\tprivate String transcriptName;\n\t/**\n\t * Chromosome name\n\t */\n\tprivate String chrom;\n\t/**\n\t * + or - for strand\n\t */\n\tprivate String strand;\n\t/**\n\t * Transcription start position\n\t */\n\tprivate Long txStart;\n\t/**\n\t * Transcription end position\n\t */\n\tprivate Long txEnd;\n\t/**\n\t * Coding region start\n\t */\n\tprivate Long cdsStart;\n\t/**\n\t * Coding region end\n\t */\n\tprivate Long cdsEnd;\n\t/**\n\t * Number of exons\n\t */\n\tprivate Integer exonCount;\n\t/**\n\t * Exon start postions\n\t */\n\tprivate Vector<Long> exonStarts;\n\t/**\n\t * Exon end positons\n\t */\n\tprivate Vector<Long> exonEnds;\n\n\tprivate TreeMap<String, CircRna> circRnas;\n\tprivate TreeMap<String, Integer> circRnasNum;\n\tprivate int totalJunctionReads;\n\n\t/**\n\t * Constructor of class GeneTranscript\n\t * \n\t * @param geneName\n\t */\n\tpublic GeneTranscript(String geneName) {\n\t\tthis.setGeneName(geneName);\n\t\texonStarts = new Vector<Long>();\n\t\texonEnds = new Vector<Long>();\n\t\tsetCircRnas(new TreeMap<String, CircRna>());\n\t\tsetCircRnasNum(new TreeMap<String, Integer>());\n\t\tsetTotalJunctionReads(0);\n\t}\n\n\t/**\n\t * get gene name\n\t * \n\t * @return geneName\n\t */\n\tpublic String getGeneName() {\n\t\treturn geneName;\n\t}\n\n\t/**\n\t * set gene name\n\t * \n\t * @param geneName\n\t */\n\tpublic void setGeneName(String geneName) {\n\t\tthis.geneName = geneName;\n\t}\n\n\t/**\n\t * get transcript name\n\t * \n\t * @return transcriptName\n\t */\n\tpublic String getTranscriptName() {\n\t\treturn transcriptName;\n\t}\n\n\t/**\n\t * set transcript name\n\t * \n\t * @param transcriptName\n\t */\n\tpublic void setTranscriptName(String transcriptName) {\n\t\tthis.transcriptName = transcriptName;\n\t}\n\n\t/**\n\t * get chrom\n\t * \n\t * @return chrom\n\t */\n\tpublic String getChrom() {\n\t\treturn chrom;\n\t}\n\n\t/**\n\t * set chrom\n\t * \n\t * @param chrom\n\t */\n\tpublic void setChrom(String chrom) {\n\t\tthis.chrom = chrom;\n\t}\n\n\t/**\n\t * get strand\n\t * \n\t * @return strand\n\t */\n\tpublic String getStrand() {\n\t\treturn strand;\n\t}\n\n\t/**\n\t * set strand\n\t * \n\t * @param strand\n\t */\n\tpublic void setStrand(String strand) {\n\t\tthis.strand = strand;\n\t}\n\n\t/**\n\t * get Tx start\n\t * \n\t * @return txStart\n\t */\n\tpublic Long getTxStart() {\n\t\treturn txStart;\n\t}\n\n\t/**\n\t * set Tx start\n\t * \n\t * @param txStart\n\t */\n\tpublic void setTxStart(Long txStart) {\n\t\tthis.txStart = txStart;\n\t}\n\n\t/**\n\t * get Tx end\n\t * \n\t * @return txEnd\n\t */\n\tpublic Long getTxEnd() {\n\t\treturn txEnd;\n\t}\n\n\t/**\n\t * set Tx end\n\t * \n\t * @param txEnd\n\t */\n\tpublic void setTxEnd(Long txEnd) {\n\t\tthis.txEnd = txEnd;\n\t}\n\n\t/**\n\t * get CDS start\n\t * \n\t * @return cdsStart\n\t */\n\tpublic Long getCdsStart() {\n\t\treturn cdsStart;\n\t}\n\n\t/**\n\t * set CDS start\n\t * \n\t * @param cdsStart\n\t */\n\tpublic void setCdsStart(Long cdsStart) {\n\t\tthis.cdsStart = cdsStart;\n\t}\n\n\t/**\n\t * get CDS end\n\t * \n\t * @return cdsEnd\n\t */\n\tpublic Long getCdsEnd() {\n\t\treturn cdsEnd;\n\t}\n\n\t/**\n\t * set CDS end\n\t * \n\t * @param cdsEnd\n\t */\n\tpublic void setCdsEnd(Long cdsEnd) {\n\t\tthis.cdsEnd = cdsEnd;\n\t}\n\n\t/**\n\t * get exon count\n\t * \n\t * @return exonCount\n\t */\n\tpublic Integer getExonCount() {\n\t\treturn exonCount;\n\t}\n\n\t/**\n\t * set exon count\n\t * \n\t * @param exonCount\n\t */\n\tpublic void setExonCount(Integer exonCount) {\n\t\tthis.exonCount = exonCount;\n\t}\n\n\t/**\n\t * get exon starts\n\t * \n\t * @return exonStarts\n\t */\n\tpublic Vector<Long> getExonStarts() {\n\t\treturn exonStarts;\n\t}\n\n\t/**\n\t * set exon starts\n\t * \n\t * @param exonStarts\n\t */\n\tpublic void setExonStarts(Vector<Long> exonStarts) {\n\t\tthis.exonStarts = exonStarts;\n\t}\n\n\t/**\n\t * get exon ends\n\t * \n\t * @return exonEnds\n\t */\n\tpublic Vector<Long> getExonEnds() {\n\t\treturn exonEnds;\n\t}\n\n\t/**\n\t * set exon ends\n\t * \n\t * @param exonEnds\n\t */\n\tpublic void setExonEnds(Vector<Long> exonEnds) {\n\t\tthis.exonEnds = exonEnds;\n\t}\n\n\t/**\n\t * @return the circRnaNum\n\t */\n\tpublic TreeMap<String, Integer> getCircRnasNum() {\n\t\treturn circRnasNum;\n\t}\n\n\t/**\n\t * @param circRnaNum\n\t * the circRnaNum to set\n\t */\n\tpublic void setCircRnasNum(TreeMap<String, Integer> circRnasNum) {\n\t\tthis.circRnasNum = circRnasNum;\n\t}\n\t\n\t/**\n\t * @return the totalJunctionReads\n\t */\n\tpublic int getTotalJunctionReads() {\n\t\treturn totalJunctionReads;\n\t}\n\n\t/**\n\t * @param totalJunctionReads the totalJunctionReads to set\n\t */\n\tpublic void setTotalJunctionReads(int totalJunctionReads) {\n\t\tthis.totalJunctionReads = totalJunctionReads;\n\t}\n\n\t/**\n\t * @return the circRnas\n\t */\n\tpublic TreeMap<String, CircRna> getCircRnas() {\n\t\treturn circRnas;\n\t}\n\n\t/**\n\t * @param circRnas\n\t * the circRnas to set\n\t */\n\tpublic void setCircRnas(TreeMap<String, CircRna> circRnas) {\n\t\tthis.circRnas = circRnas;\n\t}\n\n\tpublic GeneTranscript deepClone() {\n\t\tByteArrayOutputStream byteOut = null;\n\t\tObjectOutputStream objOut = null;\n\t\tByteArrayInputStream byteIn = null;\n\t\tObjectInputStream objIn = null;\n\n\t\ttry {\n\t\t\tbyteOut = new ByteArrayOutputStream();\n\t\t\tobjOut = new ObjectOutputStream(byteOut);\n\t\t\tobjOut.writeObject(this);\n\n\t\t\tbyteIn = new ByteArrayInputStream(byteOut.toByteArray());\n\t\t\tobjIn = new ObjectInputStream(byteIn);\n\n\t\t\treturn (GeneTranscript) objIn.readObject();\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(\"Clone Object failed in IO.\", e);\n\t\t} catch (ClassNotFoundException e) {\n\t\t\tthrow new RuntimeException(\"Class not found.\", e);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tbyteIn = null;\n\t\t\t\tbyteOut = null;\n\t\t\t\tif (objOut != null)\n\t\t\t\t\tobjOut.close();\n\t\t\t\tif (objIn != null)\n\t\t\t\t\tobjIn.close();\n\t\t\t} catch (IOException e) {\n\t\t\t}\n\t\t}\n\t}\n\n}",
"public class MainData {\n\tprivate static TreeMap<String, String> speciesFile; // SpeciesName - Species\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Data File Path\n\tprivate static TreeMap<String, TreeMap<String, Gene>> speciesData; // SpeciesName\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// -\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Loaded\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Species\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Data\n\tprivate static Vector<String> speciesNames;\t\t// Tool Names\n\tprivate static Vector<String> circRnaToolNames; // Tool Names\n\tprivate static Vector<Vector<String>> circRnaFilesInfo;\n\tprivate static Properties properties;\n\tprivate static DbConfig dbConfig;\n\n\tpublic MainData() {\n\t\tspeciesFile = new TreeMap<String, String>();\n\t\tspeciesData = new TreeMap<String, TreeMap<String, Gene>>();\n\t\tspeciesNames = new Vector<String>();\n\t\tcircRnaToolNames = new Vector<String>();\n\t\tcircRnaFilesInfo = new Vector<Vector<String>>();\n\t\tproperties = new Properties();\n\t\tdbConfig = new DbConfig();\n\t\tconfigure();\n\t}\n\n\tprivate void configure() {\n\t\tFile file = new File(Constant.CONFIG_FILE);\n\t\tif (file.exists()) {\n\t\t\treadDbConfig();\n\t\t} else {\n\t\t\tinitDbConfig();\n\t\t\twriteDbConfig();\n\t\t}\n\t\tinitSpeciesFile();\n\t\tinitTools();\n\t}\n\n\tprivate void initSpeciesFile() {\n\t\t// Init Default Species Config\n\t\tfor (String speciesName : Constant.SPECIES) {\n\t\t\tFile file = new File(Constant.SPECIES_FILE.get(speciesName));\n\t\t\tif (file.exists()) {\n\t\t\t\tspeciesNames.add(speciesName);\n\t\t\t\tspeciesFile.put(speciesName, Constant.SPECIES_FILE.get(speciesName));\n\t\t\t} else {\n\t\t\t\tCircView.log.info(\"Can not find annotation file \" + file.getName());\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void initTools() {\n\t\t// Init Default CircRNA Tools Config\n\t\tfor (String circRnaToolName : Constant.CIRCRNA_TOOLS) {\n\t\t\tcircRnaToolNames.add(circRnaToolName);\n\t\t}\n\t}\n\n\tprivate void initDbConfig() {\n\t\tCircView.log.info(\"Init Default Config\");\n\t\t// Init Default Database Config\n\t\tdbConfig.setDbServer(Constant.DEFAULT_DB_SERVER);\n\t\tdbConfig.setDbPort(Constant.DEFAULT_DB_PORT);\n\t\tdbConfig.setDbUser(Constant.DEFAULT_DB_USER);\n\t\tdbConfig.setDbPasswd(Constant.DEFAULT_DB_PASSWD);\n\t\tdbConfig.setDbName(Constant.DEFAULT_DB_NAME);\n\t}\n\n\tpublic static void readDbConfig() {\n\t\t// Read Configure File\n\t\tCircView.log.info(Constant.CONFIG_FILE + \" is loaded\");\n\t\ttry {\n\t\t\tInputStream in = new FileInputStream(Constant.CONFIG_FILE);\n\t\t\tproperties.load(in);\n\t\t\tdbConfig.setDbServer(properties.getProperty(Constant.CONFIG_DB_SERVER));\n\t\t\tdbConfig.setDbPort(properties.getProperty(Constant.CONFIG_DB_PORT));\n\t\t\tdbConfig.setDbUser(properties.getProperty(Constant.CONFIG_DB_USER));\n\t\t\tdbConfig.setDbPasswd(properties.getProperty(Constant.CONFIG_DB_PASSWD));\n\t\t\tdbConfig.setDbName(properties.getProperty(Constant.CONFIG_DB_NAME));\n\t\t} catch (IOException e) {\n\t\t\tCircView.log.info(e.getMessage());\n\t\t}\n\t}\n\n\tpublic static void writeDbConfig() {\n\t\ttry {\n\t\t\tproperties.setProperty(Constant.CONFIG_DB_SERVER, Constant.DEFAULT_DB_SERVER);\n\t\t\tproperties.setProperty(Constant.CONFIG_DB_PORT, Constant.DEFAULT_DB_PORT);\n\t\t\tproperties.setProperty(Constant.CONFIG_DB_USER, Constant.DEFAULT_DB_USER);\n\t\t\tproperties.setProperty(Constant.CONFIG_DB_PASSWD, Constant.DEFAULT_DB_PASSWD);\n\t\t\tproperties.setProperty(Constant.CONFIG_DB_NAME, Constant.DEFAULT_DB_NAME);\n\t\t\t// Write Config File\n\t\t\tOutputStream os = new FileOutputStream(Constant.CONFIG_FILE);\n\t\t\tproperties.store(os, \"Save Config File\");\n\t\t} catch (IOException e) {\n\t\t\tCircView.log.error(e.getMessage());\n\t\t}\n\t}\n\n\tpublic static TreeMap<String, TreeMap<String, Gene>> getSpeciesData() {\n\t\treturn speciesData;\n\t}\n\n\tpublic static void setSpeciesData(TreeMap<String, TreeMap<String, Gene>> speciesData) {\n\t\tMainData.speciesData = speciesData;\n\t}\n\n\tpublic static TreeMap<String, String> getSpeciesFile() {\n\t\treturn speciesFile;\n\t}\n\n\tpublic static void setSpeciesFile(TreeMap<String, String> speciesFile) {\n\t\tMainData.speciesFile = speciesFile;\n\t}\n\n\tpublic static Vector<String> getSpeciesNames() {\n\t\treturn speciesNames;\n\t}\n\n\tpublic static void setSpeciesNames(Vector<String> speciesNames) {\n\t\tMainData.speciesNames = speciesNames;\n\t}\n\n\tpublic static Vector<String> getCircRnaToolNames() {\n\t\treturn circRnaToolNames;\n\t}\n\n\tpublic static void setCircRnaToolNames(Vector<String> circRnaToolNames) {\n\t\tMainData.circRnaToolNames = circRnaToolNames;\n\t}\n\n\tpublic static Vector<Vector<String>> getCircRnaFilesInfo() {\n\t\treturn circRnaFilesInfo;\n\t}\n\n\tpublic static void setCircRnaFilesInfo(Vector<Vector<String>> circRnaFilesInfo) {\n\t\tMainData.circRnaFilesInfo = circRnaFilesInfo;\n\t}\n\n\tpublic static Properties getProperties() {\n\t\treturn properties;\n\t}\n\n\tpublic static void setProperties(Properties properties) {\n\t\tMainData.properties = properties;\n\t}\n\n\tpublic static DbConfig getDbConfig() {\n\t\treturn dbConfig;\n\t}\n\n\tpublic static void setDbConfig(DbConfig dbConfig) {\n\t\tMainData.dbConfig = dbConfig;\n\t}\n\n}",
"public class Constant {\n\tpublic final static String TOOL_CIRCEXPLORER = \"CIRCexplorer\";\n\tpublic final static String TOOL_CIRCRNAFINDER = \"circRNA_finder\";\n\tpublic final static String TOOL_CIRI = \"CIRI\";\n\tpublic final static String TOOL_FIND_CIRC = \"find_circ\";\n\tpublic final static String TOOL_MAPSPLICE = \"Mapsplice\";\n\tpublic final static String TOOL_UROBORUS = \"UROBORUS\";\n\tpublic final static Vector<String> CIRCRNA_TOOLS = new Vector<String>() {\n\t\tprivate static final long serialVersionUID = 1L;\n\n\t\t{\n\t\t\tadd(TOOL_CIRCEXPLORER);\n\t\t\tadd(TOOL_CIRCRNAFINDER);\n\t\t\tadd(TOOL_CIRI);\n\t\t\tadd(TOOL_FIND_CIRC);\n\t\t\tadd(TOOL_MAPSPLICE);\n\t\t\tadd(TOOL_UROBORUS);\n\t\t}\n\t};\n\n\tpublic final static String HUMAN_HG38 = \"human (hg38)\";\n\tpublic final static String HUMAN_HG19 = \"human (hg19)\";\n\tpublic final static String MOUSE_MM10 = \"mouse (mm10)\";\n\tpublic final static String MOUSE_MM9 = \"mouse (mm9)\";\n\tpublic final static String ZEBRAFISH = \"zebrafish (zv9)\";\n\tpublic final static String FLY = \"fly (dm6)\";\n\tpublic final static String C_ELEGANS = \"c.elegans (ce10)\";\n\tpublic final static Vector<String> SPECIES = new Vector<String>() {\n\t\tprivate static final long serialVersionUID = 1L;\n\t\t{\n\t\t\tadd(HUMAN_HG38);\n\t\t\tadd(HUMAN_HG19);\n\t\t\tadd(MOUSE_MM10);\n\t\t\tadd(MOUSE_MM9);\n\t\t\tadd(ZEBRAFISH);\n\t\t\tadd(FLY);\n\t\t\tadd(C_ELEGANS);\n\t\t}\n\t};\n\n\tpublic final static String HUMAN_HG38_FILE = \"annotation\" + File.separator + \"Human_hg38.txt\";\n\tpublic final static String HUMAN_HG19_FILE = \"annotation\" + File.separator + \"Human_hg19.txt\";\n\tpublic final static String MOUSE_MM10_FILE = \"annotation\" + File.separator + \"Mouse_mm10.txt\";\n\tpublic final static String MOUSE_MM9_FILE = \"annotation\" + File.separator + \"Mouse_mm9.txt\";\n\tpublic final static String ZEBRAFISH_FILE = \"annotation\" + File.separator + \"Zebrafish_zv9.txt\";\n\tpublic final static String FLY_FILE = \"annotation\" + File.separator + \"Fly_dm6.txt\";\n\tpublic final static String C_ELEGANS_FILE = \"annotation\" + File.separator + \"C_elegans_ce10.txt\";\n\tpublic final static TreeMap<String, String> SPECIES_FILE = new TreeMap<String, String>() {\n\t\tprivate static final long serialVersionUID = 1L;\n\t\t{\n\t\t\tput(HUMAN_HG38, HUMAN_HG38_FILE);\n\t\t\tput(HUMAN_HG19, HUMAN_HG19_FILE);\n\t\t\tput(MOUSE_MM10, MOUSE_MM10_FILE);\n\t\t\tput(MOUSE_MM9, MOUSE_MM9_FILE);\n\t\t\tput(ZEBRAFISH, ZEBRAFISH_FILE);\n\t\t\tput(FLY, FLY_FILE);\n\t\t\tput(C_ELEGANS, C_ELEGANS_FILE);\n\t\t}\n\t};\n\n\tpublic final static String SEPERATER = \"==>\";\n\tpublic final static int ASSIGN_TOLERATION = 2;\n\tpublic final static int BP_MATCH_TOLERATE = 10;\n\t// RBP tables;\n\tpublic final static String RBP_TABLE_STRUCTS = \"(chr varchar(10), start int, end int, rbp varchar(512), detail varchar(1024))\";\n\n\t// MRE tables;\n\tpublic static final String MRE_TABLE_STRUCTS = \"(chr varchar(10), start int, end int, mre varchar(512), detail varchar(1024))\";\n\n\t// Default Database Configure\n\tpublic final static String DEFAULT_DB_SERVER = \"127.0.0.1\";\n\tpublic final static String DEFAULT_DB_PORT = \"3306\";\n\tpublic final static String DEFAULT_DB_USER = \"root\";\n\tpublic final static String DEFAULT_DB_PASSWD = \"12345\";\n\tpublic final static String DEFAULT_DB_NAME = \"mre_rbp\";\n\n\t// Data Configure\n\tpublic final static String CONFIG_FILE = \"config.properties\";\n\tpublic final static String CONFIG_DB_SERVER = \"dbserver\";\n\tpublic final static String CONFIG_DB_PORT = \"dbport\";\n\tpublic final static String CONFIG_DB_USER = \"dbuser\";\n\tpublic final static String CONFIG_DB_PASSWD = \"dbpasswd\";\n\tpublic final static String CONFIG_DB_NAME = \"dbname\";\n\tpublic final static String CONFIG_SPECIES = \"species\";\n\tpublic final static String CONFIG_CIRCRNA_TOOLS = \"circrnatools\";\n\n\t// Logfile Configure\n\tpublic final static String LOG_FILE = \"log4j.properties\";\n\tpublic final static String LOG4J_ROOTLOGGER = \"log4j.rootLogger\";\n\tpublic final static String LOG4J_APPENDER_CONSOLE = \"log4j.appender.Console\";\n\tpublic final static String LOG4J_APPENDER_CONSOLE_TARGET = \"log4j.appender.Console.Target\";\n\tpublic final static String LOG4J_APPENDER_CONSOLE_LAYOUT = \"log4j.appender.Console.layout\";\n\tpublic final static String LOG4J_APPENDER_CONSOLE_LAYOUT_CONV_PATT = \"log4j.appender.Console.layout.ConversionPattern\";\n\tpublic final static String LOG4J_APPENDER_FILE = \"log4j.appender.File\";\n\tpublic final static String LOG4J_APPENDER_FILE_FILE = \"log4j.appender.File.File\";\n\tpublic final static String LOG4J_APPENDER_FILE_MAXFILESIZE = \"log4j.appender.File.MaxFileSize\";\n\tpublic final static String LOG4J_APPENDER_FILE_THRESHOLD = \"log4j.appender.File.Threshold\";\n\tpublic final static String LOG4J_APPENDER_FILE_LAYOUT = \"log4j.appender.File.layout\";\n\tpublic final static String LOG4J_APPENDER_FILE_LAYOUT_CONV_PATT = \"log4j.appender.File.layout.ConversionPattern\";\n\n\tpublic final static String LOG4J_ROOTLOGGER_VALUE = \"INFO,Console,File\";\n\tpublic final static String LOG4J_APPENDER_CONSOLE_VALUE = \"org.apache.log4j.ConsoleAppender\";\n\tpublic final static String LOG4J_APPENDER_CONSOLE_TARGET_VALUE = \"System.out\";\n\tpublic final static String LOG4J_APPENDER_CONSOLE_LAYOUT_VALUE = \"org.apache.log4j.PatternLayout\";\n\tpublic final static String LOG4J_APPENDER_CONSOLE_LAYOUT_CONV_PATT_VALUE = \"[%c] - %m%n\";\n\tpublic final static String LOG4J_APPENDER_FILE_VALUE = \"org.apache.log4j.RollingFileAppender\";\n\tpublic final static String LOG4J_APPENDER_FILE_FILE_VALUE = \"logs/circview.log\";\n\tpublic final static String LOG4J_APPENDER_FILE_MAXFILESIZE_VALUE = \"10MB\";\n\tpublic final static String LOG4J_APPENDER_FILE_THRESHOLD_VALUE = \"ALL\";\n\tpublic final static String LOG4J_APPENDER_FILE_LAYOUT_VALUE = \"org.apache.log4j.PatternLayout\";\n\tpublic final static String LOG4J_APPENDER_FILE_LAYOUT_CONV_PATT_VALUE = \"[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n\";\n\n\t// About Content\n\tpublic static final String ABOUT = \"Circular RNAs Viewer\";\n\tpublic static final String VERSION = \"version 1.0.0\";\n\tpublic static final String AUTHOR = \"Report bug to: [email protected]\";\n}",
"public class EvenOddRenderer implements TableCellRenderer {\n\n\tpublic static final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();\n\n\tpublic Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,\n\t\t\tint row, int column) {\n\t\tComponent renderer = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,\n\t\t\t\tcolumn);\n\t\tColor foreground, background;\n\t\tif (isSelected) {\n\t\t\tforeground = Color.YELLOW;\n\t\t\tbackground = Color.GREEN;\n\t\t} else {\n\t\t\tif (row % 2 == 0) {\n\t\t\t\tforeground = Color.GRAY;\n\t\t\t\tbackground = Color.WHITE;\n\t\t\t} else {\n\t\t\t\tforeground = Color.WHITE;\n\t\t\t\tbackground = Color.GRAY;\n\t\t\t}\n\t\t}\n\t\trenderer.setForeground(foreground);\n\t\trenderer.setBackground(background);\n\t\treturn renderer;\n\t}\n}"
] | import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.TreeMap;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import cn.edu.whu.CircRna;
import cn.edu.whu.CircView;
import cn.edu.whu.Gene;
import cn.edu.whu.GeneTranscript;
import cn.edu.whu.MainData;
import cn.edu.whu.util.Constant;
import cn.edu.whu.util.EvenOddRenderer; | }
}
unSelected.addElement(slct);
jlUnSelected.removeAll();
jlSelected.removeAll();
jlUnSelected.setListData(unSelected);
jlSelected.setListData(selected);
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
btCompare.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String species = (String) cbSpecies.getSelectedItem();
if (null == species || species.equals("")) {
return;
}
fillTable();
}
});
btReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
unSelected.removeAllElements();
selected.removeAllElements();
jlUnSelected.setListData(unSelected);
jlSelected.setListData(selected);
tableData.removeAllElements();
model.setDataVector(tableData, colName);
}
});
btSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CsvSaveFileChooser saveFile = new CsvSaveFileChooser("Save as ...");
saveFile.setFileSelectionMode(JFileChooser.FILES_ONLY);
saveFile.setMultiSelectionEnabled(false);
int returnValue = saveFile.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File fileOut = saveFile.getSelectedFile();
String type = "csv";
String fileName = fileOut.getAbsolutePath() + "." + type;
try {
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
for (int i = 0; i < tbResult.getColumnCount(); i++) {
out.write(tbResult.getColumnName(i) + "\t");
}
out.newLine();
for (int i = 0; i < tbResult.getRowCount(); i++) {
for (int j = 0; j < tbResult.getColumnCount(); j++) {
out.write(tbResult.getValueAt(i, j).toString() + "\t");
}
out.newLine();
}
out.close();
JOptionPane.showMessageDialog(null, "Export Data Successfully!");
} catch (IOException e1) {
CircView.log.warn(e1.getMessage());
}
}
}
});
tbResult.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
int row = tbResult.rowAtPoint(e.getPoint());
int col = tbResult.columnAtPoint(e.getPoint());
if (row >= 0 && col >= 0) {
Object value = tbResult.getValueAt(row, col);
if (null != value && !value.equals("")) {
tbResult.setToolTipText(value.toString());
} else {
tbResult.setToolTipText(null);
}
}
}
});
for (String speciesName : MainData.getSpeciesData().keySet()) {
cbSpecies.addItem(speciesName);
}
for (int i = 0; i <= Constant.BP_MATCH_TOLERATE; i++) {
cbTolerate.addItem(i + "");
}
}
private void fillTable() {
tableData.removeAllElements();
if (selected.size() > 0) {
fillTableOr();
}
model.setDataVector(tableData, colName);
}
private void fillTableOr() {
int tolerate = Integer.parseInt((String) cbTolerate.getSelectedItem());
int num = 0;
String species = (String) cbSpecies.getSelectedItem();
if ((null == species) || (species.equals(""))) {
return;
}
TreeMap<String, Gene> genes = MainData.getSpeciesData().get(species);
for (String geneName : genes.keySet()) {
Gene gene = genes.get(geneName);
TreeMap<String, GeneTranscript> geneTrans = gene.getGeneTranscripts();
for (String geneTransName : geneTrans.keySet()) {
GeneTranscript gt = geneTrans.get(geneTransName); | TreeMap<String, CircRna> circRnas = gt.getCircRnas(); | 0 |
TheCookieLab/poloniex-api-java | src/test/java/com/cf/data/map/poloniex/PoloniexDataMapperTest.java | [
"public class PoloniexChartData {\n\n public final ZonedDateTime date;\n public final BigDecimal high;\n public final BigDecimal low;\n public final BigDecimal open;\n public final BigDecimal close;\n public final BigDecimal volume;\n public final BigDecimal quoteVolume;\n public final BigDecimal weightedAverage;\n\n public PoloniexChartData(ZonedDateTime date, BigDecimal high, BigDecimal low, BigDecimal open, BigDecimal close, BigDecimal volume, BigDecimal quoteVolume, BigDecimal weightedAverage) {\n this.date = date;\n this.high = high;\n this.low = low;\n this.open = open;\n this.close = close;\n this.volume = volume;\n this.quoteVolume = quoteVolume;\n this.weightedAverage = weightedAverage;\n }\n\n @Override\n public String toString() {\n return new Gson().toJson(this);\n }\n}",
"public class PoloniexFeeInfo\n{\n public final BigDecimal makerFee;\n public final BigDecimal takerFee;\n public final BigDecimal thirtyDayVolume;\n public final BigDecimal nextTier;\n\n public PoloniexFeeInfo(BigDecimal makerFee, BigDecimal takerFee, BigDecimal thirtyDayVolume, BigDecimal nextTier)\n {\n this.makerFee = makerFee;\n this.takerFee = takerFee;\n this.thirtyDayVolume = thirtyDayVolume;\n this.nextTier = nextTier;\n }\n\n @Override\n public String toString()\n {\n return new Gson().toJson(this);\n }\n}",
"public class PoloniexOpenOrder\n{\n public final String orderNumber;\n public final String type;\n public final BigDecimal rate;\n public final BigDecimal amount;\n public final BigDecimal total;\n\n public PoloniexOpenOrder(String orderNumber, String type, BigDecimal rate, BigDecimal amount, BigDecimal total)\n {\n this.orderNumber = orderNumber;\n this.type = type;\n this.rate = rate;\n this.amount = amount;\n this.total = total;\n }\n\n @Override\n public String toString()\n {\n return new Gson().toJson(this);\n }\n}",
"public class PoloniexOrderResult\n{\n public final Long orderNumber;\n public final String error;\n public final List<PoloniexTradeHistory> resultingTrades;\n\n public PoloniexOrderResult(Long orderNumber, List<PoloniexTradeHistory> resultingTrades, String error)\n {\n this.orderNumber = orderNumber;\n this.resultingTrades = resultingTrades;\n this.error = error;\n }\n\n @Override\n public String toString()\n {\n return new Gson().toJson(this);\n }\n}",
"public class PoloniexTradeHistory\n{\n public final Long globalTradeID;\n public final String tradeID;\n public final ZonedDateTime date;\n public final BigDecimal rate;\n public final BigDecimal amount;\n public final BigDecimal total;\n public final BigDecimal fee;\n public final String orderNumber;\n public final String type;\n public final String category;\n\n public PoloniexTradeHistory(Long globalTradeID, String tradeID, ZonedDateTime date, BigDecimal rate, BigDecimal amount, BigDecimal total, BigDecimal fee, String orderNumber, String type, String category)\n {\n this.globalTradeID = globalTradeID;\n this.tradeID = tradeID;\n this.date = date;\n this.rate = rate;\n this.amount = amount;\n this.total = total;\n this.fee = fee;\n this.orderNumber = orderNumber;\n this.type = type;\n this.category = category;\n }\n\n @Override\n public String toString()\n {\n return new Gson().toJson(this);\n }\n}",
"public class PoloniexOrderTrade {\n\n public final Long globalTradeID;\n public final Long tradeID;\n public final String currencyPair;\n public final String type;\n public final BigDecimal rate;\n public final BigDecimal amount;\n public final BigDecimal total;\n public final BigDecimal fee;\n public final ZonedDateTime date;\n\n public PoloniexOrderTrade(Long globalTradeID, Long tradeID, String currencyPair, String type, BigDecimal rate, BigDecimal amount, BigDecimal total, BigDecimal fee, ZonedDateTime date) {\n this.globalTradeID = globalTradeID;\n this.tradeID = tradeID;\n this.currencyPair = currencyPair;\n this.type = type;\n this.rate = rate;\n this.amount = amount;\n this.total = total;\n this.fee = fee;\n this.date = date;\n }\n\n @Override\n public String toString() {\n return new Gson().toJson(this);\n }\n}"
] | import com.cf.data.model.poloniex.PoloniexChartData;
import com.cf.data.model.poloniex.PoloniexFeeInfo;
import com.cf.data.model.poloniex.PoloniexOpenOrder;
import com.cf.data.model.poloniex.PoloniexOrderResult;
import com.cf.data.model.poloniex.PoloniexTradeHistory;
import com.cf.data.model.poloniex.PoloniexOrderTrade;
import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test; | package com.cf.data.map.poloniex;
/**
*
* @author David
*/
public class PoloniexDataMapperTest {
private final PoloniexDataMapper mapper = new PoloniexDataMapper();
@Test
public void mapValidPoloniexChartData() {
String results = "[{\"date\":1512777600,\"high\":487.0422141,\"low\":436.6987279,\"open\":441.81031703,\"close\":461.04968807,\"volume\":29389672.275876,\"quoteVolume\":63412.76665555,\"weightedAverage\":463.46617291},{\"date\":1512864000,\"high\":461.05014912,\"low\":412.0088,\"open\":461.05014912,\"close\":428.95845809,\"volume\":15297660.06622,\"quoteVolume\":35159.74815454,\"weightedAverage\":435.09014908},{\"date\":1512950400,\"high\":463.39998999,\"low\":428.95845926,\"open\":430,\"close\":461.83896992,\"volume\":8204186.3775461,\"quoteVolume\":18163.96559478,\"weightedAverage\":451.67374573}]"; | List<PoloniexChartData> chartDataList = mapper.mapChartData(results); | 0 |
dmillett/prank | src/test/java/net/prank/example/ExampleScoreCard.java | [
"public class Indices\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n /** A collection of indices for any object that is subject to multiple sorts */\n private final List<Integer> _indices;\n\n public Indices(int originalIndex) {\n _indices = new ArrayList<>();\n _indices.add(originalIndex);\n }\n\n public int getOriginalIndex() {\n return _indices.get(0);\n }\n\n public int getLastIndex() {\n return _indices.get(_indices.size() - 1);\n }\n\n public List<Integer> getIndices() {\n return new ArrayList<>(_indices);\n }\n\n public void updateWithCurrentIndex(int currentIndex) {\n _indices.add(currentIndex);\n }\n\n @Override\n public boolean equals(Object o) {\n\n if ( this == o )\n {\n return true;\n }\n\n if ( o == null || getClass() != o.getClass() )\n {\n return false;\n }\n\n Indices indices = (Indices) o;\n return _indices.equals(indices._indices);\n }\n\n @Override\n public int hashCode() {\n return _indices.hashCode();\n }\n\n @Override\n public String toString() {\n return \"Indices{\" +\n \"_indices=\" + _indices +\n '}';\n }\n}",
"public class RequestOptions {\n\n /** Defaults to 0.0 */\n private final double _minPoints;\n /** Defaults to 10.0 */\n private final double _maxPoints;\n /** Defaults to 10 */\n private final int _bucketCount;\n /** Defaults to 'true' */\n private final boolean _enabled;\n /** Defaults to 50 milliseconds */\n private final long _timeoutMillis;\n\n public RequestOptions(double minPoints, double maxPoints, int bucketCount, boolean enabled, long timeoutMillis) {\n _minPoints = minPoints;\n _maxPoints = maxPoints;\n _bucketCount = bucketCount;\n _enabled = enabled;\n _timeoutMillis = timeoutMillis;\n }\n\n public double getMinPoints() {\n return _minPoints;\n }\n\n public double getMaxPoints() {\n return _maxPoints;\n }\n\n public int getBucketCount() {\n return _bucketCount;\n }\n\n public boolean isEnabled() {\n return _enabled;\n }\n\n public long getTimeoutMillis() {\n return _timeoutMillis;\n }\n\n /**\n * Use this if any of the defaults are acceptable, otherwise specify every value\n * in the RequestOptions constructor. This could be renamed to something simpler,\n * such as Builder, since it is statically referenced from RequestOptions (todo: 2.0)\n */\n public static class RequestOptionsBuilder {\n\n private double _minPointsB = 0.0;\n private double _maxPointsB = 10.0;\n private int _bucketCountB = 10;\n private boolean _enabledB = true;\n private long _timeoutMillisB = 50;\n\n public RequestOptionsBuilder setMinPointsB(double minPointsB) {\n _minPointsB = minPointsB;\n return this;\n }\n\n public RequestOptionsBuilder setMaxPointsB(double maxPointsB) {\n _maxPointsB = maxPointsB;\n return this;\n }\n\n public RequestOptionsBuilder setBucketCountB(int bucketCountB) {\n _bucketCountB = bucketCountB;\n return this;\n }\n\n public RequestOptionsBuilder setEnabledB(boolean enabledB) {\n _enabledB = enabledB;\n return this;\n }\n\n public RequestOptionsBuilder setTimeoutMillisB(long timeoutMillisB) {\n _timeoutMillisB = timeoutMillisB;\n return this;\n }\n\n public RequestOptions build() {\n return new RequestOptions(_minPointsB, _maxPointsB, _bucketCountB, _enabledB, _timeoutMillisB);\n }\n }\n}",
"public class Result<T>\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n /**\n * ORIGINAL - setupScoring per original scoring\n * ADJUSTED - indicates that an adjustment (+/-/*) may have occurred\n */\n public enum ResultScoreType {\n\n ORIGINAL,\n NORMALIZED,\n ADJUSTED\n }\n\n /** Name of the ScoreCard for this result, corresponds to Prankster 'key' */\n private final String _scoreCardName;\n /** The value to score on (price, shipping time, etc) */\n private final T _scoredValue;\n /** Initial position prior to scoring and ranking */\n private final Indices _indices;\n\n /** Encapsulating score, adjusted score, max points, min points, number of buckets, etc */\n private final ScoreData _score;\n /** Capture average and deviations (mean, median, standard) */\n private final Statistics _statistics;\n\n /**\n * Instantiate directly or use the Builder\n * @param scoreCardName The name of the score card that produced a result\n * @param scoredValue The value that the score card produced\n * @param indices Original index order position\n * @param score The score data specifics\n * @param stats Any statistical measurements for the collection\n */\n public Result(String scoreCardName, T scoredValue, Indices indices, ScoreData score, Statistics stats) {\n\n _scoreCardName = scoreCardName;\n _scoredValue = scoredValue;\n _indices = indices;\n _score = score;\n _statistics = stats;\n }\n\n public String getScoreCardName() {\n return _scoreCardName;\n }\n\n public T getScoredValue() {\n return _scoredValue;\n }\n\n public Indices getPosition() {\n return _indices;\n }\n\n public ScoreData getScoreData() {\n return _score;\n }\n\n public Statistics getStatistics() {\n return _statistics;\n }\n\n @Override\n public boolean equals(Object o) {\n\n if ( this == o )\n {\n return true;\n }\n\n if ( o == null || getClass() != o.getClass() )\n {\n return false;\n }\n\n Result result = (Result) o;\n\n if ( _indices != null ? !_indices.equals(result._indices) : result._indices != null )\n {\n return false;\n }\n\n if ( _score != null ? !_score.equals(result._score) : result._score != null )\n {\n return false;\n }\n\n if ( _scoreCardName != null ? !_scoreCardName.equals(result._scoreCardName) : result._scoreCardName != null )\n {\n return false;\n }\n\n if ( _scoredValue != null ? !_scoredValue.equals(result._scoredValue) : result._scoredValue != null )\n {\n return false;\n }\n\n if ( _statistics != null ? !_statistics.equals(result._statistics) : result._statistics != null )\n {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n\n int result = _scoreCardName != null ? _scoreCardName.hashCode() : 0;\n result = 31 * result + (_scoredValue != null ? _scoredValue.hashCode() : 0);\n result = 31 * result + (_indices != null ? _indices.hashCode() : 0);\n result = 31 * result + (_score != null ? _score.hashCode() : 0);\n result = 31 * result + (_statistics != null ? _statistics.hashCode() : 0);\n\n return result;\n }\n\n @Override\n public String toString() {\n return \"Result{\" +\n \"_scoreCardName='\" + _scoreCardName + '\\'' +\n \", _scoredValue=\" + _scoredValue +\n \", _position=\" + _indices +\n \", _score=\" + _score +\n \", _statistics=\" + _statistics +\n '}';\n }\n\n /**\n * A helper since the constructor is large.\n */\n public static class Builder<T> {\n\n private String _bCardName;\n private T _bOriginal;\n private Indices _bIndices;\n private ScoreData _bScore;\n private Statistics _bStatistics;\n\n public Builder() {}\n\n public Builder(Result<T> original) {\n\n if (original != null)\n {\n _bCardName = original._scoreCardName;\n _bOriginal = original._scoredValue;\n _bIndices = original._indices;\n _bScore = original._score;\n _bStatistics = original._statistics;\n }\n }\n\n public Builder(String name, ScoreData score) {\n _bCardName = name;\n _bScore = score;\n }\n\n public Builder setPosition(Indices bPosition) {\n _bIndices = bPosition;\n return this;\n }\n\n public Builder setOriginal(T bOriginal) {\n _bOriginal = bOriginal;\n return this;\n }\n\n public Builder setScore(ScoreData bScore) {\n _bScore = bScore;\n return this;\n }\n\n public Builder setStatistics(Statistics bStatistics) {\n _bStatistics = bStatistics;\n return this;\n }\n\n public Builder setCardName(String bCardName) {\n _bCardName = bCardName;\n return this;\n }\n\n public Result build() {\n return new Result<>(_bCardName, _bOriginal, _bIndices, _bScore, _bStatistics);\n }\n }\n}",
"public interface ScoreCard<T> {\n\n /**\n * Score a single object with default options\n * @param scoringObject The object to score\n * @return The score summary after scoring\n */\n public ScoreSummary score(T scoringObject);\n /**\n * Score a single object with specified options, otherwise use defaults\n * @param scoringObject The object to score\n * @param options The request specific options to use for scoring\n * @return The score summary\n */\n public ScoreSummary scoreWith(T scoringObject, RequestOptions options);\n\n /**\n * Score and update an object or collection of objects with default options\n * @param scoringObject The object to score\n */\n public void updateObjectsWithScore(T scoringObject);\n /**\n * Score and update an object or collection of objects with specific options\n * @param scoringObject The object to score\n * @param options The request specific scoring parameters\n */\n public void updateObjectsWithScore(T scoringObject, RequestOptions options);\n\n /**\n * A setupScoring card name to use as a key in ScoreSummary\n * The name of the ScoreCard for reporting, applying, etc\n *\n * @return The name of the ScoreCard\n */\n public String getName();\n}",
"public class ScoreData\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n\n /** The value given by a ScoreCard */\n private final BigDecimal _score;\n /** The value of adjusting '_score' */\n private final BigDecimal _adjustedScore;\n /** A normalized score (if necessary) */\n private final BigDecimal _normalizedScore;\n /** The number of buckets allocated across the range given by '_minPoints' and '_maxPoints' */\n private final int _buckets;\n /** The maximum possible score */\n private final BigDecimal _maxPoints;\n /** The minimum possible score */\n private final BigDecimal _minPoints;\n\n /**\n * Use this or the builder to create a ScoreData object in your ScoreCard\n * implementation. It represents the details/state of a specific Score\n *\n * @param score The score value\n * @param adjustedScore The adjusted score value\n * @param normalizedScore The normalized score\n * @param buckets The number of scoring buckets between min and max\n * @param maxPoints The maximum points in a group\n * @param minPoints The minimum points in a group\n */\n public ScoreData(BigDecimal score, BigDecimal adjustedScore, BigDecimal normalizedScore, int buckets,\n BigDecimal maxPoints, BigDecimal minPoints) {\n\n _score = score;\n _adjustedScore = adjustedScore;\n _normalizedScore = normalizedScore;\n _buckets = buckets;\n _maxPoints = maxPoints;\n _minPoints = minPoints;\n }\n\n @Override\n public boolean equals(Object o) {\n\n if ( this == o )\n {\n return true;\n }\n\n if ( o == null || getClass() != o.getClass() )\n {\n return false;\n }\n\n ScoreData score = (ScoreData) o;\n\n if ( _buckets != score._buckets )\n {\n return false;\n }\n\n if ( _adjustedScore != null ? !_adjustedScore.equals(score._adjustedScore) : score._adjustedScore != null )\n {\n return false;\n }\n\n if ( _normalizedScore != null ? !_normalizedScore.equals(score._normalizedScore) :\n score._normalizedScore != null )\n {\n return false;\n }\n\n if ( _maxPoints != null ? !_maxPoints.equals(score._maxPoints) : score._maxPoints != null )\n {\n return false;\n }\n\n if ( _minPoints != null ? !_minPoints.equals(score._minPoints) : score._minPoints != null )\n {\n return false;\n }\n\n if ( _score != null ? !_score.equals(score._score) : score._score != null )\n {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n\n int result = _score != null ? _score.hashCode() : 0;\n result = 31 * result + (_adjustedScore != null ? _adjustedScore.hashCode() : 0);\n result = 31 * result + (_normalizedScore != null ? _normalizedScore.hashCode() : 0);\n result = 31 * result + _buckets;\n result = 31 * result + (_maxPoints != null ? _maxPoints.hashCode() : 0);\n result = 31 * result + (_minPoints != null ? _minPoints.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"ScoreData{\" +\n \"_score=\" + _score +\n \", _adjustedScore=\" + _adjustedScore +\n \", _normalizedScore=\" + _normalizedScore +\n \", _buckets=\" + _buckets +\n \", _maxPoints=\" + _maxPoints +\n \", _minPoints=\" + _minPoints +\n '}';\n }\n\n /**\n * Multiplies the '_score' by a multiplier and returns a new ScoreData object,\n * otherwise returns this\n *\n * @param multiplier A multiplier applied to '_score' if not null\n * @return A new ScoreData object with adjusted score or this\n */\n public ScoreData adjustScore(BigDecimal multiplier) {\n\n if ( multiplier == null || _score == null )\n {\n return this;\n }\n\n BigDecimal adjustedScore = _score.multiply(multiplier);\n return new ScoreData(_score, adjustedScore, _normalizedScore, _buckets, _maxPoints, _minPoints);\n }\n\n /**\n *\n * @return score:adjustedScore:maxPoints:minPoints:buckets\n */\n public String dump() {\n\n ScoreFormatter formatter = new ScoreFormatter();\n return formatter.dumpScoreData(this);\n }\n\n public BigDecimal getScore() {\n return _score;\n }\n\n public BigDecimal getAdjustedScore() {\n return _adjustedScore;\n }\n\n public BigDecimal getNormalizedScore() {\n return _normalizedScore;\n }\n\n public int getBuckets() {\n return _buckets;\n }\n\n public BigDecimal getMaxPoints() {\n return _maxPoints;\n }\n\n public BigDecimal getMinPoints() {\n return _minPoints;\n }\n\n public static class Builder {\n\n private BigDecimal _bScore;\n private BigDecimal _bAdjustedScore;\n private BigDecimal _bNormalizedScore;\n private int _bBuckets;\n private BigDecimal _bMaxPoints;\n private BigDecimal _bMinPoints;\n\n public ScoreData build() {\n return new ScoreData(_bScore, _bAdjustedScore, _bNormalizedScore, _bBuckets, _bMaxPoints, _bMinPoints);\n }\n\n public Builder setScore(BigDecimal score) {\n _bScore = score;\n return this;\n }\n\n public Builder setAdjustedScore(BigDecimal adjustedScore) {\n _bAdjustedScore = adjustedScore;\n return this;\n }\n\n public Builder setNormalizedScore(BigDecimal normalizedScore) {\n _bNormalizedScore = normalizedScore;\n return this;\n }\n\n public Builder setBuckets(int buckets) {\n _bBuckets = buckets;\n return this;\n }\n\n public Builder setMaxPoints(BigDecimal maxPoints) {\n _bMaxPoints = maxPoints;\n return this;\n }\n\n public Builder setMinPoints(BigDecimal minPoints) {\n _bMinPoints = minPoints;\n return this;\n }\n }\n}",
"public class ScoreSummary\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n private final Map<String, Result> _results;\n private final String _name;\n\n public ScoreSummary(String name) {\n _name = name;\n _results = new HashMap<>();\n }\n\n public void addResult(String key, Result result) {\n _results.put(key, result);\n }\n\n public Result getResultByScoreCard(String scoreCardName) {\n return _results.get(scoreCardName);\n }\n\n public Map<String, Result> getResults() {\n return _results;\n }\n\n public String getName() {\n return _name;\n }\n\n /**\n * Add up all the scores for each Result.\n *\n * @return The sum of all Result.getScore() or null\n */\n public BigDecimal tallyScore() {\n return tallyScore(_results.keySet(), Result.ResultScoreType.ORIGINAL);\n }\n\n public BigDecimal tallyScore(Result.ResultScoreType scoreType) {\n return tallyScore(_results.keySet(), scoreType);\n }\n\n /**\n * Get the setupScoring for a subset of ScoreCards by name.\n *\n * @param scoreCardNames The names of score cards to apply\n * @return The tallied BigDecimal score\n */\n public BigDecimal tallyScoreFor(Set<String> scoreCardNames) {\n return tallyScoreFor(scoreCardNames, Result.ResultScoreType.ORIGINAL);\n }\n\n /**\n * Tally score based on score cards, by name, and scoring type\n * @param scoreCardNames The score cards to apply\n * @param scoreType The scoring type to use\n * @return The score or 'null'\n */\n // todo: use ScoringTool.tallyScoreFor()?\n public BigDecimal tallyScoreFor(Set<String> scoreCardNames, Result.ResultScoreType scoreType) {\n\n if (scoreCardNames == null)\n {\n return null;\n }\n\n Set<String> scoreCards = findScoreCardsByName(scoreCardNames);\n return tallyScore(scoreCards, scoreType);\n }\n\n /**\n * todo: use ScoringTool.tallyScoreFor()?\n *\n * @param scoreCardNames The names of score cards to apply\n * @param scoreType The score type to use when calculating the score\n * @return null if there are no matching ScoreCards, otherwise the tally(+)\n */\n public BigDecimal tallyScore(Set<String> scoreCardNames, Result.ResultScoreType scoreType) {\n\n if (scoreCardNames.isEmpty())\n {\n return null;\n }\n\n BigDecimal tally = null;\n\n for (String scoreCardName : scoreCardNames)\n {\n if (scoreCardName == null)\n {\n continue;\n }\n\n tally = updateTallyFromResult(scoreType, tally, scoreCardName);\n }\n\n return tally;\n }\n\n private BigDecimal updateTallyFromResult(Result.ResultScoreType scoreType, BigDecimal tally,\n String scoreCardName) {\n\n Result result = _results.get(scoreCardName);\n\n if (result == null) { return tally; }\n\n if (tally == null)\n {\n tally = new BigDecimal(\"0.0\");\n }\n\n if (scoreType.equals(Result.ResultScoreType.ORIGINAL))\n {\n if (result.getScoreData().getScore() != null)\n {\n tally = tally.add(result.getScoreData().getScore());\n }\n }\n else if (scoreType.equals(Result.ResultScoreType.ADJUSTED))\n {\n if (result.getScoreData().getAdjustedScore() != null)\n {\n tally = tally.add(result.getScoreData().getAdjustedScore());\n }\n }\n\n return tally;\n }\n\n /**\n * Flexible way of determining which scores to tally\n *\n * @param scoreCards The names of score cards to apply\n * @return The BigDecimal score result\n */\n public BigDecimal tallyScoreFor(String... scoreCards) {\n return tallyScoreFor(Result.ResultScoreType.ORIGINAL, scoreCards);\n }\n\n /**\n * Flexible way of determining which adjusted scores to tally based on setupScoring type\n * (original or adjusted)\n *\n * @param scoreType Original or Adjusted\n * @param scoreCards The score card names to apply\n * @return The resulting score\n */\n public BigDecimal tallyScoreFor(Result.ResultScoreType scoreType, String... scoreCards) {\n\n if (scoreCards == null || scoreCards.length == 0)\n {\n return null;\n }\n\n return tallyScore(new HashSet<>(Arrays.asList(scoreCards)), scoreType);\n }\n\n /**\n * Find any of these that are currently part of the summary\n */\n private Set<String> findScoreCardsByName(Set<String> scoreCardNames) {\n\n Set<String> scoreCards = new HashSet<>();\n\n for (String scoreCardName : _results.keySet())\n {\n if (scoreCardNames.contains(scoreCardName))\n {\n scoreCards.add(scoreCardName);\n }\n }\n\n return scoreCards;\n }\n\n @Override\n public String toString() {\n return \"ScoreSummary{\" +\n \"_results=\" + _results +\n \", _name='\" + _name + '\\'' +\n '}';\n }\n\n /**\n * Uses ScoreFormatter.dumpResult() for each ScoreCard result.\n * @return A formatted score\n */\n public String dump() {\n\n ScoreFormatter scf = new ScoreFormatter();\n return scf.dumpScoreSummary(this);\n }\n\n @Override\n public boolean equals(Object o) {\n\n if (this == o)\n {\n return true;\n }\n\n if (o == null || getClass() != o.getClass())\n {\n return false;\n }\n\n ScoreSummary that = (ScoreSummary) o;\n\n if (_name != null ? !_name.equals(that._name) : that._name != null)\n {\n return false;\n }\n\n if (_results != null ? !_results.equals(that._results) : that._results != null)\n {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n\n int result = _results != null ? _results.hashCode() : 0;\n result = 31 * result + (_name != null ? _name.hashCode() : 0);\n return result;\n }\n}",
"public class Statistics\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n /** The minimum value within a collection */\n private final BigDecimal _min;\n /** The maximum value within a collection */\n private final BigDecimal _max;\n /** The sample size */\n private final int _sampleSize;\n /** Use your favorite stats library or NumericTools */\n private final BigDecimal _average;\n /** Use your favorite stats library or NumericTools */\n private final BigDecimal _meanDeviation;\n /** Use your favorite stats library or NumericTools */\n private final BigDecimal _medianDeviation;\n /** Use your favorite stats library or NumericTools */\n private final BigDecimal _standardDeviation;\n\n public Statistics(BigDecimal min, BigDecimal max, int sampleSize, BigDecimal average,\n BigDecimal meanAbsoluteDeviation,BigDecimal medianAbsoluteDeviation,\n BigDecimal standardDeviation) {\n\n _min = min;\n _max = max;\n _sampleSize = sampleSize;\n _average = average;\n _meanDeviation = meanAbsoluteDeviation;\n _medianDeviation = medianAbsoluteDeviation;\n _standardDeviation = standardDeviation;\n }\n\n public BigDecimal getMin() {\n return _min;\n }\n\n public BigDecimal getMax() {\n return _max;\n }\n\n public int getSampleSize() {\n return _sampleSize;\n }\n\n public BigDecimal getAverage() {\n return _average;\n }\n\n public BigDecimal getMeanDeviation() {\n return _meanDeviation;\n }\n\n public BigDecimal getMedianDeviation() {\n return _medianDeviation;\n }\n\n public BigDecimal getStandardDeviation() {\n return _standardDeviation;\n }\n\n /**\n *\n * Builds a String representation of these values with their\n * original scale. If value is null, then just appends a \":\" delimiter.\n *\n * min:max:sample size:average:mean deviation:median devation:standard deviation\n *\n * Example:\n * :::: // all values are null\n * 40.00:5.31:: // average, mean devation not null\n * 5.10:1.144:1.00:1.654 // no null values\n *\n * Option:\n * Use a custom Formatter and the Statistics object\n *\n * @return A formatted score, statistics, etc\n */\n public String dump() {\n return dump(-1, RoundingMode.UNNECESSARY);\n }\n\n /**\n * Same as dump(), but with a specified scale and RoundingMode.HALF_EVEN\n * @param scale will truncate to value\n * @return A formatted score, statistics, etc\n */\n public String dump(int scale) {\n return dump(scale, null);\n }\n\n /**\n * Same as dump() but with both scale and rounding mode\n * @param scale The scale to use for score format printer\n * @param roundingMode The rounding mode for the score format printer\n * @return A formatted score, statistics, etc\n */\n public String dump(int scale, RoundingMode roundingMode) {\n\n ScoreFormatter formatter = new ScoreFormatter();\n return formatter.dumpStatistics(this, scale, roundingMode);\n }\n\n @Override\n public boolean equals(Object o) {\n\n if ( this == o )\n {\n return true;\n }\n\n if ( o == null || getClass() != o.getClass() )\n {\n return false;\n }\n\n Statistics that = (Statistics) o;\n\n if ( _sampleSize != that._sampleSize )\n {\n return false;\n }\n\n if ( _average != null ? !_average.equals(that._average) : that._average != null )\n {\n return false;\n }\n\n if ( _max != null ? !_max.equals(that._max) : that._max != null )\n {\n return false;\n }\n\n if ( _meanDeviation != null ? !_meanDeviation.equals(that._meanDeviation) : that._meanDeviation != null )\n {\n return false;\n }\n\n if ( _medianDeviation != null ? !_medianDeviation.equals(that._medianDeviation) :\n that._medianDeviation != null )\n {\n return false;\n }\n\n if ( _min != null ? !_min.equals(that._min) : that._min != null )\n {\n return false;\n }\n\n if ( _standardDeviation != null ? !_standardDeviation.equals(that._standardDeviation) :\n that._standardDeviation != null )\n {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n\n int result = _min != null ? _min.hashCode() : 0;\n result = 31 * result + (_max != null ? _max.hashCode() : 0);\n result = 31 * result + _sampleSize;\n result = 31 * result + (_average != null ? _average.hashCode() : 0);\n\n result = 31 * result + (_meanDeviation != null ? _meanDeviation.hashCode() : 0);\n result = 31 * result + (_medianDeviation != null ? _medianDeviation.hashCode() : 0);\n result = 31 * result + (_standardDeviation != null ? _standardDeviation.hashCode() : 0);\n return result;\n }\n\n /** More flexibility for creating a Statistics object. */\n public static class Builder {\n\n private BigDecimal _bMin;\n private BigDecimal _bMax;\n private int _bSampleSize;\n /** Use your favorite stats library or NumericTools */\n private BigDecimal _bAverage;\n /** Use your favorite stats library or NumericTools */\n private BigDecimal _bMeanDeviation;\n /** Use your favorite stats library or NumericTools */\n private BigDecimal _bMedianDeviation;\n /** Use your favorite stats library or NumericTools */\n private BigDecimal _bStandardDeviation;\n\n public Statistics build() {\n return new Statistics(_bMin, _bMax, _bSampleSize, _bAverage, _bMeanDeviation, _bMedianDeviation,\n _bStandardDeviation);\n }\n\n public Builder setMin(BigDecimal bMin) {\n _bMin = bMin;\n return this;\n }\n\n public Builder setSampleSize(int bSampleSize) {\n _bSampleSize = bSampleSize;\n return this;\n }\n\n public Builder setMax(BigDecimal bMax) {\n _bMax = bMax;\n return this;\n }\n\n public Builder setStandardDeviation(BigDecimal bStandardDeviation) {\n _bStandardDeviation = bStandardDeviation;\n return this;\n }\n\n public Builder setAverage(BigDecimal bAverage) {\n _bAverage = bAverage;\n return this;\n }\n\n public Builder setMeanDeviation(BigDecimal bMeanDeviation) {\n _bMeanDeviation = bMeanDeviation;\n return this;\n }\n\n public Builder setMedianDeviation(BigDecimal bMedianDeviation) {\n _bMedianDeviation = bMedianDeviation;\n return this;\n }\n\n }\n}"
] | import net.prank.core.Indices;
import net.prank.core.RequestOptions;
import net.prank.core.Result;
import net.prank.core.ScoreCard;
import net.prank.core.ScoreData;
import net.prank.core.ScoreSummary;
import net.prank.core.Statistics;
import java.math.BigDecimal; | package net.prank.example;
/**
* A very simple example of a setupScoring card. More complex examples should still be stateless for
* thread safety. Typically, the higher the setupScoring, the better the result.
* <p/>
* The adjustments are just examples of how scoring might be adjusted to make some
* setupScoring cards more/less important than other setupScoring cards. If machine learning (ML)
* indicates that price is the most important factor for all customers (or individual),
* then it should have "heavier" weighting and it's setupScoring should be adjusted (+)
* <p/>
* Examples:
* Price: the lowest price has the highest setupScoring.
* Shipping cost: how much to ship the item
* Shipping time: how long it takes an item to ship
*
*
* @author dmillett
*
* Copyright 2012 David Millett
* 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.
*/
public class ExampleScoreCard
implements ScoreCard<ExampleObject> {
private final String _name = "SolutionPriceScoreCard";
// Mutable state (single threaded only) -- D
private final int _scoreAdjustment;
private final int _positionAdjustment;
private final double _averageAdjustment;
private final double _standardDeviationAdjustment;
public ExampleScoreCard() {
_scoreAdjustment = 5;
_positionAdjustment = 3;
_averageAdjustment = 2;
_standardDeviationAdjustment = 1.0;
}
public ExampleScoreCard(int scoreAdjustment, int positionAdjustment, double averageAdjustment,
double standardDeviationAdjustment) {
_scoreAdjustment = scoreAdjustment;
_positionAdjustment = positionAdjustment;
_averageAdjustment = averageAdjustment;
_standardDeviationAdjustment = standardDeviationAdjustment;
}
public ScoreSummary score(ExampleObject scoringObject) {
// Ignore the summary for now
performScoring(scoringObject);
return null;
}
@Override
public ScoreSummary scoreWith(ExampleObject scoringObject, RequestOptions options) {
return score(scoringObject);
}
@Override
public void updateObjectsWithScore(ExampleObject scoringObject) {
performScoring(scoringObject);
}
@Override
public void updateObjectsWithScore(ExampleObject scoringObject, RequestOptions options) {
performScoring(scoringObject);
}
private void performScoring(ExampleObject scoringObject) {
int score = scoringObject.getAverageShippingTime() + _scoreAdjustment;
int position = _positionAdjustment;
double average = scoringObject.getShippingCost().doubleValue() + _averageAdjustment;
double standardDeviation = _standardDeviationAdjustment;
// Calculate stats with primitives for performance | ScoreData.Builder scoreBuilder = new ScoreData.Builder(); | 4 |
leobm/teavm-jquery | core/src/main/java/de/iterable/teavm/jquery/ajax/JQueryAjaxSettingsObject.java | [
"@JSFunctor\npublic interface AjaxBeforeSendHandler extends JSObject {\n void onBeforeSend(JQueryXHR jqXHR, JQueryAjaxSettingsObject settings);\n}",
"@JSFunctor\npublic interface AjaxCompleteHandler extends JSObject {\n\t\n\tvoid onComplete(JQueryXHR jqXHR, String textStatus);\n\n}",
"@JSFunctor\npublic interface AjaxErrorHandler extends JSObject {\n\n void onError(JQueryXHR jqXHR, JSString textStatus, JSString errorThrow);\n\n}",
"@JSFunctor\npublic interface AjaxFilterHandler extends JSObject {\n\n\tpublic abstract JSObject apply(JSObject data, String dataType);\n\n}",
"@JSFunctor\npublic interface AjaxSuccessHandler<T extends JSObject> extends JSObject {\n\n\tvoid onSuccess(T data, JSString textStatus, JQueryXHR jqXHR);\n\n}",
"public interface AjaxXhrFunctionHandler extends JSObject {\n\n JSFunction onXhr();\n\n}",
"@JSFunctor\npublic interface JSFunctor0<R extends JSObject> extends JSFunctorBase{\n\n\tpublic R apply();\n\n}",
"public abstract class JSDictonary implements JSObject {\n\n private JSDictonary() {\n }\n\n @JSIndexer\n public abstract <V extends JSObject> V get(String key);\n\n @JSIndexer\n public abstract <V extends JSObject> void put(String key, V value);\n\n public <V extends JSObject> JSDictonary with(String key, V value) {\n this.put(key, value);\n return this;\n }\n\n public JSDictonary with(String key, String value) {\n return this.with(key, JSString.valueOf(value));\n }\n\n public JSDictonary with(String key, JSDictonary value) {\n return this.with(key, (JSObject) value);\n }\n\n public JSDictonary with(String key, Integer value) {\n return this.with(key, JSNumber.valueOf(value));\n }\n\n public JSDictonary with(String key, Float value) {\n return this.with(key, JSNumber.valueOf(value));\n }\n\n public JSDictonary with(String key, Double value) {\n return this.with(key, JSNumber.valueOf(value));\n }\n\n public JSDictonary with(String key, Boolean value) {\n return this.with(key, JSBoolean.valueOf(value));\n }\n\n public JSObject remove(String key) {\n if (JSObjectUtils.hasOwnProperty(this, key)) {\n final JSObject value = get(key);\n JSObjectUtils.delete(this, key);\n return value;\n }\n return null;\n }\n\n public String[] keys() {\n return JSObjectUtils.keys(this);\n }\n\n public boolean has(String key) {\n return JSObjectUtils.hasOwnProperty(this, key);\n }\n\n public static <V extends JSObject> JSDictonary create() {\n return JSObjectUtils.create();\n }\n\n}"
] | import org.teavm.jso.JSBody;
import org.teavm.jso.JSObject;
import org.teavm.jso.JSProperty;
import org.teavm.jso.core.JSArray;
import org.teavm.jso.core.JSString;
import de.iterable.teavm.jquery.ajax.handler.AjaxBeforeSendHandler;
import de.iterable.teavm.jquery.ajax.handler.AjaxCompleteHandler;
import de.iterable.teavm.jquery.ajax.handler.AjaxErrorHandler;
import de.iterable.teavm.jquery.ajax.handler.AjaxFilterHandler;
import de.iterable.teavm.jquery.ajax.handler.AjaxSuccessHandler;
import de.iterable.teavm.jquery.ajax.handler.AjaxXhrFunctionHandler;
import de.iterable.teavm.utils.functor.JSFunctor0;
import de.iterable.teavm.utils.jso.JSDictonary; | /*
* Copyright 2015 Jan-Felix Wittmann.
*
* 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 de.iterable.teavm.jquery.ajax;
/**
*
* @author Jan-Felix Wittmann
*/
public abstract class JQueryAjaxSettingsObject implements JSObject {
private JQueryAjaxSettingsObject() {
}
@JSBody(params = {}, script = "return {}")
public static native final JQueryAjaxSettingsObject create();
@JSProperty
public abstract void setAccepts(JSDictonary obj);
@JSProperty
public abstract void setAsync(boolean isAsync);
@JSProperty("beforeSend") | public abstract void setBeforeSendHandler(AjaxBeforeSendHandler handler); | 0 |
curtisullerich/attendance | src/main/java/edu/iastate/music/marching/attendance/servlets/AuthServlet.java | [
"public class Lang {\n\n\tpublic static final String ERROR_MESSAGE_NO_DIRECTOR = \"There is no director registered. You cannot register for an account yet.\";\n\tpublic static final String ERROR_INVALID_PRIMARY_REGISTER_EMAIL= \"Not a valid email, try logging in with your student account\";\n\tpublic static final String ERROR_ABSENCE_FOR_NULL_USER = \"Tried to create absence for null user\";\n}",
"public class AuthManager implements Serializable {\n\n\tprivate static final long serialVersionUID = -962768931131670649L;\n\n\tprivate static final String SESSION_USER_ATTRIBUTE = \"authenticated_user\";\n\n\tprivate static final Logger LOG = Logger.getLogger(AuthManager.class\n\t\t\t.getName());\n\n\tpublic static String getGoogleLoginURL(String redirect_url) {\n\t\tUserService userService = UserServiceFactory.getUserService();\n\n\t\tif (userService == null)\n\t\t\treturn null;\n\n\t\treturn userService.createLoginURL(redirect_url);\n\t}\n\n\tpublic static String getGoogleLogoutURL(String redirect_url) {\n\t\tUserService userService = UserServiceFactory.getUserService();\n\n\t\tif (userService == null)\n\t\t\treturn null;\n\n\t\treturn userService.createLogoutURL(redirect_url);\n\t}\n\n\tpublic static com.google.appengine.api.users.User getGoogleUser() {\n\t\tUserService userService = UserServiceFactory.getUserService();\n\n\t\treturn userService.getCurrentUser();\n\t}\n\n\tprivate static User getUserFromSession(HttpSession session) {\n\t\tif (session == null)\n\t\t\treturn null;\n\n\t\tObject u = session.getAttribute(SESSION_USER_ATTRIBUTE);\n\n\t\tif (!(u instanceof User))\n\t\t\treturn null;\n\t\telse\n\t\t\treturn (User) u;\n\t}\n\n\tpublic static boolean isAdminLoggedIn() {\n\t\ttry {\n\t\t\tUserService userService = UserServiceFactory.getUserService();\n\t\t\treturn userService.isUserAdmin();\n\t\t} catch (IllegalStateException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic static boolean isLoggedIn(HttpSession session,\n\t\t\tUser.Type... allowed_types) {\n\t\tUser u = getUserFromSession(session);\n\n\t\tif (u == null)\n\t\t\treturn false;\n\n\t\tif (allowed_types == null || allowed_types.length == 0)\n\t\t\treturn true;\n\n\t\tfor (User.Type type : allowed_types) {\n\t\t\tif (u.getType() == type)\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic static void logout(HttpSession session) {\n\t\tsession.removeAttribute(SESSION_USER_ATTRIBUTE);\n\t}\n\n\tprivate static void putUserInSession(User u, HttpSession session) {\n\t\tif (session != null)\n\t\t\tsession.setAttribute(SESSION_USER_ATTRIBUTE, u);\n\t}\n\n\tpublic void updateCurrentUser(User user, HttpSession session) {\n\t\tputUserInSession(user, session);\n\t}\n\n\tprivate DataTrain train;\n\n\tprivate User currentUser = null;\n\n\tpublic AuthManager(DataTrain dataTrain) {\n\t\tthis.train = dataTrain;\n\t}\n\n\tpublic User getCurrentUser(HttpSession session) {\n\t\tif (this.currentUser == null) {\n\t\t\tthis.currentUser = getUserFromSession(session);\n\t\t\ttrain.getDataStore().activate(this.currentUser);\n\t\t}\n\n\t\tif (this.currentUser != null\n\t\t\t\t&& !train.getDataStore().isAssociated(this.currentUser)) {\n\t\t\ttry {\n\t\t\t\ttrain.getDataStore().associate(this.currentUser);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.log(Level.WARNING, \"Error associating current user: \"\n\t\t\t\t\t\t+ this.currentUser.getId(), e);\n\t\t\t}\n\t\t}\n\n\t\tif (null != this.currentUser\n\t\t\t\t&& !train.getDataStore().isActivated(this.currentUser)) {\n\t\t\ttry {\n\t\t\t\ttrain.getDataStore().activate(this.currentUser);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.log(Level.WARNING, \"Error activating current user: \"\n\t\t\t\t\t\t+ this.currentUser.getId(), e);\n\t\t\t}\n\t\t}\n\n\t\treturn currentUser;\n\t}\n\n\tpublic boolean login(HttpSession session) {\n\n\t\tcom.google.appengine.api.users.User google_user = getGoogleUser();\n\n\t\tif (google_user == null) {\n\t\t\t// No google user logged in at all\n\t\t\tthrow new GoogleAccountException(\"No google user logged in at all\",\n\t\t\t\t\tGoogleAccountException.Type.None);\n\t\t}\n\n\t\tEmail google_users_email = Util.makeEmail(google_user.getEmail());\n\n\t\tUser matchedUser = null;\n\n\t\t// Some kind of google user logged in, check it against the\n\t\t// primary email's of all users\n\t\tif (ValidationUtil.isValidPrimaryEmail(google_users_email, this.train)) {\n\n\t\t\t// Check if there is a user in the system already for this\n\t\t\t// google user\n\t\t\tmatchedUser = train.users().get(google_users_email);\n\n\t\t} else if (ValidationUtil.isValidSecondaryEmail(google_users_email,\n\t\t\t\tthis.train)) {\n\t\t\t// Maybe the secondary email will match a user in the database\n\n\t\t\t// Check if there is a user in the system already for this\n\t\t\t// google user\n\t\t\tmatchedUser = train.users().getSecondary(google_users_email);\n\t\t} else {\n\t\t\tthrow new GoogleAccountException(\"Not a valid google account\",\n\t\t\t\t\tGoogleAccountException.Type.Invalid);\n\t\t}\n\n\t\tif (matchedUser == null) {\n\t\t\t// Still need to register\n\t\t\treturn false;\n\t\t} else {\n\t\t\t// Did successful login\n\t\t\tupdateCurrentUser(matchedUser, session);\n\t\t\treturn true;\n\t\t}\n\t}\n\n}",
"public class DataTrain {\n\n\tprivate static class CacheKey implements Serializable {\n\n\t\t/**\n\t\t * \n\t\t */\n\t\tprivate static final long serialVersionUID = -8879640511900898415L;\n\n\t\t@SuppressWarnings(\"unused\")\n\t\tpublic String clazz;\n\n\t\t@SuppressWarnings(\"unused\")\n\t\tpublic int id;\n\n\t\tpublic CacheKey(Class<?> clazz, int id) {\n\t\t\tthis.clazz = clazz.getName();\n\t\t\tthis.id = id;\n\t\t}\n\t}\n\n\t/**\n\t * Transaction wrapper to keep in the train theme\n\t * \n\t * For internal use in controllers when the outside code has already started\n\t * a transaction when the controller tries to start one\n\t * \n\t * Thus to deal with this nested transaction problem, we just linearize\n\t * everything and let the outside code call the actual commit to commit\n\t * everything.\n\t * \n\t */\n\tprivate class InternalTrack extends Track {\n\n\t\tprotected InternalTrack(Track t) {\n\t\t\tsuper(t.getTransaction());\n\t\t}\n\n\t\t/**\n\t\t * Does nothing, this is a nested transaction\n\t\t */\n\t\t@Override\n\t\tpublic void bendIronBack() {\n\t\t\t// Do nothing, this is a nested transaction\n\t\t}\n\n\t\t/**\n\t\t * Does nothing, this is a nested transaction\n\t\t */\n\t\t@Override\n\t\tpublic Future<Void> bendIronBackAsync() {\n\t\t\t// Do nothing, this is a nested transaction\n\t\t\treturn null;\n\t\t}\n\n\t}\n\n\t/**\n\t * Transaction wrapper to keep in the train theme\n\t * \n\t */\n\tpublic class Track {\n\n\t\tprivate Transaction transaction;\n\n\t\tprotected Track(Transaction t) {\n\t\t\tthis.transaction = t;\n\t\t}\n\n\t\t/**\n\t\t * Commits this transaction to the datastore\n\t\t */\n\t\tpublic void bendIronBack() {\n\t\t\tthis.transaction.commit();\n\t\t}\n\n\t\t/**\n\t\t * Commits this transaction to the datastore asynchronously\n\t\t */\n\t\tpublic Future<Void> bendIronBackAsync() {\n\t\t\treturn this.transaction.commitAsync();\n\t\t}\n\n\t\t/**\n\t\t * End this transaction without committing any of the changes made\n\t\t */\n\t\tpublic void derail() {\n\t\t\tthis.transaction.rollback();\n\t\t}\n\n\t\t/**\n\t\t * End this transaction asynchronously without committing any of the\n\t\t * changes made\n\t\t */\n\t\tpublic Future<Void> derailAsync() {\n\t\t\treturn this.transaction.rollbackAsync();\n\t\t}\n\n\t\t/**\n\t\t * \n\t\t * @return The application id for the Transaction.\n\t\t */\n\t\tpublic String getApp() {\n\t\t\treturn this.transaction.getApp();\n\t\t}\n\n\t\t/**\n\t\t * \n\t\t * @return The globally unique identifier for the Transaction.\n\t\t */\n\t\tpublic String getId() {\n\t\t\treturn this.transaction.getId();\n\t\t}\n\n\t\tprotected Transaction getTransaction() {\n\t\t\treturn this.transaction;\n\t\t}\n\n\t\tpublic boolean isActive() {\n\t\t\treturn this.transaction.isActive();\n\t\t}\n\n\t}\n\n\tpublic static DataTrain depart() {\n\t\tDataTrain train = new DataTrain();\n\t\treturn train;\n\t}\n\n\tprivate StandardObjectDatastore datastore = null;\n\n\tprivate Cache cache = null;\n\n\t/**\n\t * Current transaction\n\t */\n\tprivate Track track = null;\n\n\tpublic DataTrain() {\n\t\tdatastore = ModelFactory.newObjectDatastore();\n\t}\n\n\t<T> RootFindCommand<T> find(Class<T> type) {\n\t\treturn getDataStore().find().type(type);\n\t}\n\n\tpublic AbsenceManager absences() {\n\t\treturn new AbsenceManager(this);\n\t}\n\n\tpublic AppDataManager appData() {\n\t\treturn new AppDataManager(this);\n\t}\n\n\tpublic AuthManager auth() {\n\t\treturn new AuthManager(this);\n\t}\n\n\tpublic DataManager data() {\n\t\treturn new DataManager(this);\n\t}\n\n\tStandardObjectDatastore getDataStore() {\n\t\treturn this.datastore;\n\t}\n\n\tpublic EventManager events() {\n\t\treturn new EventManager(this);\n\t}\n\n\tpublic FormManager forms() {\n\t\treturn new FormManager(this);\n\t}\n\n\tCache getMemCache() {\n\t\tif (this.cache == null) {\n\t\t\ttry {\n\t\t\t\tCacheFactory cacheFactory = CacheManager.getInstance()\n\t\t\t\t\t\t.getCacheFactory();\n\t\t\t\tthis.cache = cacheFactory.createCache(Collections.emptyMap());\n\t\t\t} catch (CacheException e) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\treturn this.cache;\n\t}\n\n\tpublic MobileDataManager mobileData() {\n\t\treturn new MobileDataManager(this);\n\t}\n\n\t// For implementing transaction support\n\t// Object getAncestor() {\n\t// return getVersionController().getCurrent();\n\t// }\n\n\tKey getTie(Class<?> type, long id) {\n\t\treturn new KeyFactory.Builder(this.datastore.getConfiguration()\n\t\t\t\t.typeToKind(type), id).getKey();\n\t}\n\n\tKey getTie(Class<?> type, String id) {\n\t\treturn new KeyFactory.Builder(this.datastore.getConfiguration()\n\t\t\t\t.typeToKind(type), id).getKey();\n\t}\n\n\tpublic UserManager users() {\n\t\treturn new UserManager(this);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t<CachedType> CachedType loadFromCache(Class<CachedType> clazz, int id) {\n\t\tCache cache = getMemCache();\n\n\t\tif (cache != null)\n\t\t\treturn (CachedType) cache.get(new CacheKey(clazz, id));\n\t\telse\n\t\t\treturn null;\n\t}\n\n\t/**\n\t * Starts a new data store transaction\n\t * \n\t * Note that only one transaction can be active at a time\n\t */\n\tpublic Track switchTracks() {\n\n\t\tthis.track = new Track(getDataStore().beginTransaction());\n\t\treturn this.track;\n\t}\n\n\t/**\n\t * Non-recursive begin transaction\n\t * \n\t * Starts a new data store transaction if none is running, or simply reuses\n\t * the existing one in a wrapper if it is active.\n\t * \n\t * This is because only one transaction can be running at a time\n\t * \n\t * @return Internal transaction for use in a controller. Must either be\n\t * committed to or canceled within the controller and never be\n\t * passed out of the controller\n\t */\n\tTrack switchTracksInternal() {\n\t\tif (this.track != null && this.track.isActive())\n\t\t\treturn new InternalTrack(this.track);\n\t\telse\n\t\t\treturn switchTracks();\n\t}\n\n\t<CachedType> boolean updateCache(int id, CachedType object) {\n\n\t\tif (object == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tClass<?> clazz = object.getClass();\n\n\t\tCache cache = getMemCache();\n\n\t\tif (cache != null) {\n\t\t\tcache.put(new CacheKey(clazz, id), object);\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n}",
"@Entity(kind = \"User\", allocateIdsBy = 0)\npublic class User implements Serializable {\n\n\tpublic enum Grade {\n\t\tA, B, C, D, F;\n\t\tprivate String mDisplayString;\n\n\t\tprivate Grade() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tprivate Grade(String display_string) {\n\t\t\tmDisplayString = display_string;\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\t}\n\n\tpublic enum Section {\n\t\tPiccolo, Clarinet, AltoSax(\"Alto Sax\"), TenorSax(\"Tenor Sax\"), Trumpet, Trombone, Bass_Trombone(\n\t\t\t\t\"Bass trombone\"), Mellophone, Baritone, Sousaphone, Guard, DrumMajor(\n\t\t\t\t\"Drum Major\"), Staff, Drumline_Cymbals(\"Drumline: Cymbals\"), Drumline_Tenors(\n\t\t\t\t\"Drumline: Tenors\"), Drumline_Snare(\"Drumline: Snare\"), Drumline_Bass(\n\t\t\t\t\"Drumline: Bass\"), Twirler;\n\n\t\tprivate String mDisplayString;\n\n\t\tprivate Section() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tprivate Section(String display_string) {\n\t\t\tmDisplayString = display_string;\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\t}\n\n\tpublic enum Type {\n\t\tStudent, TA, Director;\n\n\t\tpublic boolean isDirector() {\n\t\t\treturn this.equals(Director);\n\t\t}\n\n\t\tpublic boolean isStudent() {\n\t\t\treturn this.equals(Student);\n\t\t}\n\n\t\tpublic boolean isTa() {\n\t\t\treturn this.equals(TA);\n\t\t}\n\t}\n\n\tprivate static final long serialVersionUID = 1421557192976557704L;\n\n\tpublic static final String FIELD_TYPE = \"type\";\n\n\tpublic static final String FIELD_ID = \"id\";\n\n\tpublic static final String FIELD_PRIMARY_EMAIL = \"email\";\n\n\tpublic static final String FIELD_SECONDARY_EMAIL = \"secondEmail\";\n\n\tpublic static final String FIELD_UNIVERSITY_ID = \"universityID\";\n\n\tprivate Type type;\n\n\tprivate Grade grade;\n\n\t@Id\n\tprivate String id;\n\n\tprivate Email email;\n\n\tprivate Email secondEmail;\n\n\tprivate String universityID;\n\n\tprivate Section section;\n\n\tprivate String firstName;\n\n\tprivate String lastName;\n\n\tprivate int year;\n\n\tprivate String major;\n\n\tprivate String rank;\n\n\tprivate boolean showApproved;\n\n\t// number of minutes available from submitted TimeWorked forms\n\tprivate int minutesAvailable;\n\n\t// number of unexcused minutes absent so far this semester\n\tprivate int minutesMissed;\n\n\t/**\n\t * Create users through UserController (DataModel.users().create(...)\n\t */\n\tUser() {\n\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o == null)\n\t\t\treturn false;\n\n\t\t// emails are unique, so compare based on them\n\t\tif (o instanceof User) {\n\t\t\tUser u = (User) o;\n\n\t\t\tif (this.email == null || this.email.getEmail() == null\n\t\t\t\t\t|| u.email == null || u.email.getEmail() == null) {\n\t\t\t\tif (this.email == null && u.email == null) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (this.email.getEmail() == null\n\t\t\t\t\t\t&& u.email.getEmail() == null) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.email.equals(u.email))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\tpublic Grade getGrade() {\n\n\t\treturn this.grade;\n\t}\n\n\tpublic String getId() {\n\t\treturn this.id;\n\t}\n\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\tpublic String getMajor() {\n\t\treturn major;\n\t}\n\n\tpublic int getMinutesAvailable() {\n\t\treturn minutesAvailable;\n\t}\n\n\tpublic String getName() {\n\t\treturn this.getFirstName() + \" \" + this.getLastName();\n\t}\n\n\t/**\n\t * Iowa State specific, instead use getId()\n\t * \n\t * @return net id of the user\n\t */\n\t@Deprecated\n\tpublic String getNetID() {\n\t\treturn this.id;\n\t}\n\n\tpublic Email getPrimaryEmail() {\n\t\treturn this.email;\n\t}\n\n\tpublic String getRank() {\n\t\treturn this.rank;\n\t}\n\n\tpublic Email getSecondaryEmail() {\n\t\treturn this.secondEmail;\n\t}\n\n\tpublic Section getSection() {\n\t\treturn section;\n\t}\n\n\tpublic Type getType() {\n\t\treturn this.type;\n\t}\n\n\tpublic String getUniversityID() {\n\t\treturn universityID;\n\t}\n\n\tpublic int getYear() {\n\t\treturn year;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tif (this.email == null || this.email.getEmail() == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn this.email.hashCode();\n\t}\n\n\tpublic boolean isShowApproved() {\n\t\treturn this.showApproved;\n\t}\n\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\tpublic void setGrade(Grade grade) {\n\t\tthis.grade = grade;\n\t}\n\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\tpublic void setMajor(String major) {\n\t\tthis.major = major;\n\t}\n\n\tpublic void setMinutesAvailable(int minutesAvailable) {\n\t\tthis.minutesAvailable = minutesAvailable;\n\t}\n\n\tpublic void setPrimaryEmail(Email email) {\n\t\tthis.email = email;\n\t\t// TODO https://github.com/curtisullerich/attendance/issues/170\n\t\t// This shouldn't be in the model, it should happen in the controllers\n\t\t// somehow\n\t\tif (email.getEmail().indexOf('%') == -1) {\n\t\t\tthis.id = email.getEmail().substring(0,\n\t\t\t\t\temail.getEmail().indexOf('@'));\n\t\t} else {\n\t\t\tthis.id = email.getEmail().substring(0,\n\t\t\t\t\temail.getEmail().indexOf('%'));\n\t\t}\n\t}\n\n\tpublic void setRank(String rank) {\n\t\tthis.rank = rank;\n\t}\n\n\tpublic void setSecondaryEmail(Email email) {\n\t\tthis.secondEmail = email;\n\t}\n\n\tpublic void setSection(Section section) {\n\t\tthis.section = section;\n\t}\n\n\tpublic void setShowApproved(boolean show) {\n\t\tthis.showApproved = show;\n\t}\n\n\tpublic void setType(Type type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic void setUniversityID(String new_universityID) {\n\t\tthis.universityID = new_universityID;\n\t}\n\n\tpublic void setYear(int year) {\n\t\tthis.year = year;\n\t}\n\n\tpublic void setMinutesMissed(int minutes) {\n\t\tthis.minutesMissed = minutes;\n\t}\n\n\tpublic int getMinutesMissed() {\n\t\treturn this.minutesMissed;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getName();\n\t}\n\n}",
"public class GoogleAccountException extends IllegalArgumentException {\n\n\tpublic enum Type {\n\t\tNone, Invalid\n\t}\n\n\tprivate Type type;\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 5059826102465006401L;\n\n\tpublic GoogleAccountException(String message, Type type) {\n\t\tsuper(message);\n\t\tthis.type = type;\n\t}\n\n\tpublic Type getType() {\n\t\treturn this.type;\n\t}\n\n}",
"public class PageBuilder {\n\n\tprivate static final String JSP_PATH_PRE = \"/WEB-INF/\";\n\n\tprivate static final String JSP_PATH_POST = \".jsp\";\n\n\tprivate static final String ATTR_SUCCESS_MESSAGE = \"success_message\";\n\n\tpublic static final String PARAM_SUCCESS_MESSAGE = \"success_message\";\n\n\tprivate static final String ATTR_REDIRECT_URL = \"redirect_url\";\n\n\tpublic static final String PARAM_REDIRECT_URL = \"redirect\";\n\n\tprivate String mJSPPath;\n\n\tprivate Map<String, Object> attribute_map;\n\tprivate PageTemplateBean mPageTemplateBean;\n\n\tprivate AppData mAppData;\n\n\tprivate DataTrain mDataTrain;\n\n\tprivate PageBuilder() {\n\t\tattribute_map = new HashMap<String, Object>();\n\t}\n\n\tprivate PageBuilder(String jsp_simple_path, DataTrain train) {\n\t\tthis();\n\n\t\t// Save parameters\n\t\tmJSPPath = JSP_PATH_PRE + jsp_simple_path + JSP_PATH_POST;\n\n\t\tmDataTrain = train;\n\n\t\tmAppData = mDataTrain.appData().get();\n\n\t\tmPageTemplateBean = new PageTemplateBean(jsp_simple_path, mAppData,\n\t\t\t\tmDataTrain.auth());\n\n\t\tmPageTemplateBean.setTitle(mAppData.getTitle());\n\t}\n\n\tpublic <T extends Enum<T>> PageBuilder(T page, String jsp_servlet_path) {\n\t\tthis(jsp_servlet_path + \"/\" + page.name(), DataTrain.depart());\n\t}\n\n\tpublic <T extends Enum<T>> PageBuilder(T page, String jsp_servlet_path,\n\t\t\tDataTrain dataTrain) {\n\t\tthis(jsp_servlet_path + \"/\" + page.name(), dataTrain);\n\t}\n\n\tprivate void initialPageSetup(HttpServletRequest req,\n\t\t\tHttpServletResponse resp) {\n\t\t// Copy over any success message or redirect url\n\t\treq.setAttribute(ATTR_SUCCESS_MESSAGE,\n\t\t\t\treq.getParameter((PARAM_SUCCESS_MESSAGE)));\n\t\treq.setAttribute(ATTR_REDIRECT_URL,\n\t\t\t\treq.getParameter((PARAM_REDIRECT_URL)));\n\t}\n\n\tpublic void passOffToJsp(HttpServletRequest req, HttpServletResponse resp)\n\t\t\tthrows ServletException, IOException {\n\n\t\t// Set some default attributes\n\t\tinitialPageSetup(req, resp);\n\n\t\t// Apply all saved attributes\n\t\tfor (Entry<String, Object> entry : attribute_map.entrySet())\n\t\t\treq.setAttribute(entry.getKey(), entry.getValue());\n\n\t\t// Insert page template data bean\n\t\tmPageTemplateBean.apply(req);\n\n\t\t// Insert authentication data bean\n\t\tAuthBean.getBean(req.getSession(), mDataTrain).apply(req);\n\n\t\t// Do actual forward\n\t\tRequestDispatcher d = req.getRequestDispatcher(mJSPPath);\n\t\td.forward(req, resp);\n\t}\n\n\tpublic PageBuilder setAttribute(String name, Object value) {\n\t\tattribute_map.put(name, value);\n\n\t\treturn this;\n\t}\n\n\tpublic PageBuilder setPageTitle(String title) {\n\t\tmPageTemplateBean.setTitle(title + \" - \" + mAppData.getTitle());\n\n\t\treturn this;\n\t}\n\n\tpublic void setErrors(List<String> errors) {\n\t\tsetAttribute(\"error_messages\", errors);\n\t}\n\n}",
"public class Util {\n\n\tprivate static final DateTimeFormatter DATEFORMAT = DateTimeFormat\n\t\t\t.forPattern(\"MM/dd/yyyy\");\n\tprivate static final DateTimeFormatter TIMEFORMAT = DateTimeFormat\n\t\t\t.forPattern(\"h:mm aa\");\n\tprivate static final DateTimeFormatter DATETIMEFORMAT = DateTimeFormat\n\t\t\t.forPattern(\"MM/dd/yyyy h:mm aa\");\n\n\tpublic static String formatDateOnly(DateTime datetime, DateTimeZone zone) {\n\t\treturn DATEFORMAT.withZone(zone).print(datetime);\n\t}\n\n\tpublic static String formatDateOnly(LocalDate date) {\n\t\tif (date == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn DATEFORMAT.print(date);\n\t}\n\n\tpublic static String formatDateTime(DateTime datetime, DateTimeZone zone) {\n\t\tif (datetime == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn DATETIMEFORMAT.withZone(zone).print(datetime);\n\t}\n\n\tpublic static String formatTimeOnly(DateTime datetime, DateTimeZone zone) {\n\t\tif (datetime == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn TIMEFORMAT.withZone(zone).print(datetime);\n\t}\n\n\tpublic static String formatTimeOnly(LocalTime datetime) {\n\t\treturn TIMEFORMAT.print(datetime);\n\t}\n\n\tpublic static boolean overlapDays(ReadableInterval interval1,\n\t\t\tReadableInterval interval2) {\n\t\t// Expand one interval to be full days\n\t\tDateTime start = interval1.getStart().toDateMidnight().toDateTime();\n\t\tDateTime end = interval1.getEnd().toDateMidnight().toInterval()\n\t\t\t\t.getEnd();\n\t\tInterval interval1FullDays = new Interval(start, end);\n\n\t\t// Simply compare for any overlap\n\t\treturn interval1FullDays.overlaps(interval2);\n\t}\n\n\tpublic static LocalDate parseDateOnly(String text, DateTimeZone zone) {\n\t\treturn DATEFORMAT.parseLocalDate(text);\n\t}\n\n\tpublic static DateTime parseDateTime(String text, DateTimeZone zone) {\n\t\treturn DATETIMEFORMAT.withZone(zone).parseDateTime(text);\n\t}\n\n\tpublic static LocalTime parseTimeOnly(String text, DateTimeZone zone) {\n\t\treturn TIMEFORMAT.parseLocalTime(text);\n\t}\n\n\tpublic static Interval datesToFullDaysInterval(LocalDate startDate,\n\t\t\tLocalDate endDate, DateTimeZone zone) {\n\t\tDateTime startOfFirstDay = startDate.toInterval(zone).getStart();\n\t\tDateTime endOfFirstDay = endDate.toInterval(zone).getEnd();\n\t\treturn new Interval(startOfFirstDay, endOfFirstDay);\n\t}\n\n\tpublic static Email makeEmail(String emailString) {\n\t\tif(null == emailString || \"\".equals(emailString.trim())) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn new Email(emailString.toLowerCase());\n\t\t}\n\t}\n\n\tpublic static String emailToString(Email email) {\n\t\tif(null == email) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn email.getEmail();\n\t\t}\n\t}\n}",
"public class ValidationUtil {\n\n\tprivate static final Pattern PATTERN_NAME = Pattern\n\t\t\t.compile(\"^[\\\\w\\\\. -]+$\");\n\n\tprivate static final Pattern PATTERN_EMAIL = Pattern\n\t\t\t.compile(\"^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,4})$\");\n\n\tprivate static final Pattern PATTERN_GTEMPEMAIL = Pattern\n\t\t\t.compile(\"^([a-zA-Z0-9._%+-]+)%([a-zA-Z0-9.-]+)@gtempaccount.com$\");\n\n\tprivate static final int MAX_TEXT_LENGTH = 50000;\n\n\tpublic static boolean isPost(HttpServletRequest req) {\n\t\treturn \"POST\".equals(req.getMethod());\n\t}\n\n\tpublic static boolean isUniqueId(String id, Email primary) {\n\t\treturn DataTrain.depart().users().isUniqueId(id, primary);\n\t}\n\n\tpublic static boolean isUniqueSecondaryEmail(Email checkEmail,\n\t\t\tEmail excludedUserPrimaryEmail, DataTrain train) {\n\t\treturn train.users().isUniqueSecondaryEmail(checkEmail,\n\t\t\t\texcludedUserPrimaryEmail);\n\t}\n\n\tpublic static boolean isValidMajor(String major) {\n\t\treturn isValidText(major, false);\n\t}\n\n\t// private static boolean validEmailDomain(String domain, DataTrain train) {\n\n\t// AppData app = train.getAppDataController().get();\n\n\t// }\n\n\tpublic static boolean isValidName(String name) {\n\t\t// Names are composed of characters (\\w) and dashes\n\t\treturn PATTERN_NAME.matcher(name).matches();\n\t}\n\n\tpublic static boolean isValidRank(String rank) {\n\t\treturn true;\n\t}\n\n\tpublic static boolean isValidSection(User.Section section) {\n\t\tboolean ret = false;\n\t\tfor (User.Section sect : User.Section.values()) {\n\t\t\tif (section == sect) {\n\t\t\t\tret = true;\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\n\tpublic static boolean isValidText(String text, boolean canBeEmpty) {\n\n\t\tif (text == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (\"\".equals(text.trim())) {\n\t\t\treturn canBeEmpty;\n\t\t}\n\n\t\tif (text.length() > MAX_TEXT_LENGTH) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic static boolean isValidUniversityID(String uId) {\n\t\tif (uId.length() != 9) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tInteger.parseInt(uId);\n\t\t\t\treturn true;\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static boolean isValidYear(int year) {\n\t\tboolean ret = false;\n\t\tfor (int i = 1; i <= 10; ++i) {\n\t\t\tif (year == i) {\n\t\t\t\tret = true;\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\n\tpublic static boolean isValidPrimaryEmail(Email email, DataTrain train) {\n\n\t\t// TODO https://github.com/curtisullerich/attendance/issues/122\n\t\t// This should be an application setting\n\t\tString domain = App.DOMAIN;\n\n\t\tif (null == email)\n\t\t\treturn true;\n\n\t\tif (\"\".equals(email.getEmail()))\n\t\t\treturn false;\n\n\t\tif (null == email.getEmail())\n\t\t\treturn false;\n\n\t\tMatcher emailMatcher = PATTERN_EMAIL.matcher(email.getEmail());\n\n\t\t// Check for valid email\n\t\tif (!emailMatcher.matches()) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Allow address@domain email's\n\t\tif (domain.equals(emailMatcher.group(2))) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Allow address%[email protected] email's\n\t\tMatcher gTempMatcher = PATTERN_GTEMPEMAIL.matcher(email.getEmail());\n\t\tif (gTempMatcher.matches() && domain.equals(gTempMatcher.group(2))) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic static boolean isValidSecondaryEmail(Email email, DataTrain train) {\n\n\t\t// Null or empty emails are okay for the secondary\n\t\tif (email == null)\n\t\t\treturn true;\n\n\t\tif (email.getEmail() == null || email.getEmail().equals(\"\"))\n\t\t\treturn false;\n\n\t\treturn PATTERN_EMAIL.matcher(email.getEmail()).matches();\n\t}\n\n}"
] | import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.Email;
import edu.iastate.music.marching.attendance.Lang;
import edu.iastate.music.marching.attendance.model.interact.AuthManager;
import edu.iastate.music.marching.attendance.model.interact.DataTrain;
import edu.iastate.music.marching.attendance.model.store.User;
import edu.iastate.music.marching.attendance.util.GoogleAccountException;
import edu.iastate.music.marching.attendance.util.PageBuilder;
import edu.iastate.music.marching.attendance.util.Util;
import edu.iastate.music.marching.attendance.util.ValidationUtil; | package edu.iastate.music.marching.attendance.servlets;
public class AuthServlet extends AbstractBaseServlet {
private enum Page {
index, login, login_callback, logout, welcome, register, register_post, login_fail;
}
private static final long serialVersionUID = -4587683490944456397L;
private static final String SERVLET_PATH = "auth";
public static final String URL_LOGOUT = pageToUrl(Page.logout, SERVLET_PATH);
public static final String URL_LOGIN = pageToUrl(Page.login, SERVLET_PATH);
private static final String URL_REGISTER = pageToUrl(Page.register,
SERVLET_PATH);
private static final Logger LOG = Logger.getLogger(AuthServlet.class
.getName());
private static String getLoginCallback(HttpServletRequest request) {
String url = pageToUrl(Page.login_callback, SERVLET_PATH);
try { | if (null != request.getParameter(PageBuilder.PARAM_REDIRECT_URL)) | 5 |
xcsp3team/XCSP3-Java-Tools | src/main/java/org/xcsp/parser/entries/XVariables.java | [
"public static enum TypeVar {\n\tinteger, symbolic, real, stochastic, symbolic_stochastic, set, symbolic_set, undirected_graph, directed_graph, point, interval, region;\n\n\t/** Returns true if the constant corresponds to integer, symbolic, real or (symbolic) stochastic. */\n\tpublic boolean isBasic() {\n\t\treturn this == integer || this == symbolic || this == real || isStochastic();\n\t}\n\n\tpublic boolean isStochastic() {\n\t\treturn this == stochastic || this == symbolic_stochastic;\n\t}\n\n\tpublic boolean isSet() {\n\t\treturn this == set || this == symbolic_set;\n\t}\n\n\tpublic boolean isGraph() {\n\t\treturn this == undirected_graph || this == directed_graph;\n\t}\n\n\tpublic boolean isComplex() {\n\t\treturn isSet() || isGraph();\n\t}\n\n\tpublic boolean isQualitative() {\n\t\treturn this == point || this == interval || this == region;\n\t}\n}",
"public class Utilities {\n\n\tpublic static final Comparator<int[]> lexComparatorInt = (t1, t2) -> {\n\t\tfor (int i = 0; i < t1.length; i++)\n\t\t\tif (t1[i] < t2[i])\n\t\t\t\treturn -1;\n\t\t\telse if (t1[i] > t2[i])\n\t\t\t\treturn +1;\n\t\treturn 0;\n\t};\n\n\tpublic static final Comparator<String[]> lexComparatorString = (t1, t2) -> {\n\t\tfor (int i = 0; i < t1.length; i++) {\n\t\t\tint res = t1[i].compareTo(t2[i]);\n\t\t\tif (res != 0)\n\t\t\t\treturn res;\n\t\t}\n\t\treturn 0;\n\t};\n\n\tpublic static <T> T[] buildArray(Class<?> cl, int length) {\n\t\treturn (T[]) Array.newInstance(cl, length);\n\t}\n\n\tpublic static <T> T[][] buildArray(Class<?> cl, int length1, int length2) {\n\t\treturn (T[][]) Array.newInstance(cl, length1, length2);\n\t}\n\n\tpublic static Object firstNonNull(Object array) {\n\t\tif (array != null && array.getClass().isArray())\n\t\t\treturn IntStream.range(0, Array.getLength(array)).mapToObj(i -> firstNonNull(Array.get(array, i))).filter(o -> o != null).findFirst().orElse(null);\n\t\treturn array;\n\t}\n\n\t/**\n\t * Builds a one-dimensional array of T with the objects of the specified list. If the list does not contain any\n\t * object other than null, null is returned.\n\t */\n\tpublic static <T> T[] convert(Collection<T> list) {\n\t\tObject firstObject = list.stream().filter(o -> o != null).findFirst().orElse(null);\n\t\tif (firstObject == null)\n\t\t\treturn null;\n\t\tT[] ts = buildArray(firstObject.getClass(), list.size());\n\t\tint i = 0;\n\t\tfor (T x : list)\n\t\t\tts[i++] = x;\n\t\treturn ts;\n\t}\n\n\t/**\n\t * Builds a one-dimensional array of T with the objects of the specified stream. If the stream does not contain any\n\t * object other than null, null is returned.\n\t */\n\tpublic static <T> T[] convert(Stream<T> stream) {\n\t\treturn convert(stream.collect(Collectors.toList()));\n\t}\n\n\tpublic static <T> T[] convert(Object[] t) {\n\t\tObject firstObject = Stream.of(t).filter(o -> o != null).findFirst().orElse(null);\n\t\tClass<?> clazz = firstObject == null ? null\n\t\t\t\t: Stream.of(t).noneMatch(o -> o != null && o.getClass() != firstObject.getClass()) ? firstObject.getClass() : null;\n\t\tif (clazz == null)\n\t\t\treturn null; // null is returned if the array has only null or elements of several types\n\t\tT[] ts = buildArray(firstObject.getClass(), t.length);\n\t\tint i = 0;\n\t\tfor (Object x : t)\n\t\t\tts[i++] = (T) x;\n\t\treturn ts;\n\t}\n\n\tpublic static <T> T[][] convert(Object[][] t) {\n\t\tcontrol(isRegular(t), \" pb\");\n\t\t// other controls to add\n\t\tT[][] m = buildArray(t[0][0].getClass(), t.length, t[0].length);\n\t\tfor (int i = 0; i < t.length; i++)\n\t\t\tfor (int j = 0; j < t[i].length; j++)\n\t\t\t\tm[i][j] = (T) t[i][j];\n\t\treturn m;\n\t}\n\n\tpublic static Object[] specificArrayFrom(List<Object> list) {\n\t\tObject firstObject = list.stream().filter(o -> o != null).findFirst().orElse(null);\n\t\tClass<?> clazz = firstObject == null ? null\n\t\t\t\t: list.stream().noneMatch(o -> o != null && o.getClass() != firstObject.getClass()) ? firstObject.getClass() : null;\n\t\treturn clazz == null ? list.toArray() : list.toArray((Object[]) Array.newInstance(clazz, list.size()));\n\t}\n\n\tpublic static Object[][] specificArray2DFrom(List<Object[]> list) {\n\t\tClass<?> clazz = list.stream().noneMatch(o -> o.getClass() != list.get(0).getClass()) ? list.get(0).getClass() : null;\n\t\treturn clazz == null ? list.toArray(new Object[0][]) : list.toArray((Object[][]) Array.newInstance(clazz, list.size()));\n\t}\n\n\tprivate static <T> List<T> collectRec(Class<T> clazz, List<T> list, Object src) {\n\t\tif (src != null) {\n\t\t\tif (src instanceof Collection)\n\t\t\t\tcollectRec(clazz, list, ((Collection<?>) src).stream());\n\t\t\telse if (src instanceof Stream)\n\t\t\t\t((Stream<?>) src).forEach(o -> collectRec(clazz, list, o));\n\t\t\telse if (src.getClass().isArray())\n\t\t\t\tIntStream.range(0, Array.getLength(src)).forEach(i -> collectRec(clazz, list, Array.get(src, i)));\n\t\t\telse if (clazz.isAssignableFrom(src.getClass()))\n\t\t\t\tlist.add(clazz.cast(src));\n\t\t\telse if (src instanceof IntStream)\n\t\t\t\t((IntStream) src).forEach(o -> collectRec(clazz, list, o));\n\t\t\telse if (src.getClass() == Range.class)\n\t\t\t\tcollectRec(clazz, list, ((Range) src).toArray()); // in order to deal with clazz being Integer.class\n\t\t}\n\t\treturn list;\n\t}\n\n\t/**\n\t * Returns a 1-dimensional array of objects of the specified type after collecting any object of this type being\n\t * present in the specified objects. The specified objects can be stream (and IntStream), collections and arrays.\n\t * The collecting process is made recursively.\n\t * \n\t * @param clazz\n\t * the class of the objects to be collected\n\t * @param src\n\t * the objects where to collect the objects\n\t * @return a 1-dimensional array of objects of the specified type after collecting any object of this type being\n\t * present in the specified objects\n\t */\n\tpublic static <T> T[] collect(Class<T> clazz, Object... src) {\n\t\tList<T> list = new ArrayList<>();\n\t\tStream.of(src).forEach(o -> collectRec(clazz, list, o));\n\t\treturn convert(list.stream().collect(Collectors.toList()));\n\t}\n\n\t/**\n\t * Builds a 1-dimensional array of integers (int) from the specified sequence of parameters. Each parameter can be\n\t * an integer, a Range, an array, a stream, a collection, etc. All integers are collected and concatenated to form a\n\t * 1-dimensional array.\n\t *\n\t * @param src\n\t * the objects where to collect the integers\n\t * @return a 1-dimensional array of integers after collecting any encountered integer in the specified objects\n\t */\n\tpublic static int[] collectInt(Object... src) {\n\t\tInteger[] t = collect(Integer.class, src);\n\t\treturn t == null ? new int[0] : Stream.of(t).filter(i -> i != null).mapToInt(i -> i).toArray();\n\t}\n\n\tpublic static boolean isNumeric(String token) {\n\t\treturn token.matches(\"-?\\\\d+(\\\\.\\\\d+)?\"); // match a number with optional '-' and decimal.\n\t}\n\n\tpublic static boolean isNumericInterval(String token) {\n\t\treturn token.matches(\"-?\\\\d+\\\\.\\\\.-?\\\\d+\");\n\t}\n\n\tpublic static int[] splitToInts(String s, String regex) {\n\t\treturn Arrays.stream(s.trim().split(regex)).filter(tok -> tok.length() > 0).mapToInt(tok -> Integer.parseInt(tok)).toArray();\n\t}\n\n\tpublic static int[] splitToInts(String s) {\n\t\treturn splitToInts(s, Constants.REG_WS);\n\t}\n\n\tpublic static int splitToInt(String s, String regex) {\n\t\tint[] t = splitToInts(s, regex);\n\t\tcontrol(t.length > 0, \"Not possible to extract an int from this call\");\n\t\treturn t[0];\n\t}\n\n\tpublic static int[] wordAsIntArray(String s) {\n\t\tassert s.chars().allMatch(c -> ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'));\n\t\tint[] t = new int[s.length()]; // We don't use streams here for efficiency reasons (when dealing with large sets\n\t\t\t\t\t\t\t\t\t\t// of words)\n\t\tfor (int i = 0; i < s.length(); i++)\n\t\t\tt[i] = s.charAt(i) - (Character.isUpperCase(s.charAt(i)) ? 'A' : 'a');\n\t\treturn t;\n\t}\n\n\tpublic static Boolean toBoolean(String s) {\n\t\ts = s.toLowerCase();\n\t\tif (s.equals(\"yes\") || s.equals(\"y\") || s.equals(\"true\") || s.equals(\"t\") || s.equals(\"1\"))\n\t\t\treturn Boolean.TRUE;\n\t\tif (s.equals(\"no\") || s.equals(\"n\") || s.equals(\"false\") || s.equals(\"f\") || s.equals(\"0\"))\n\t\t\treturn Boolean.FALSE;\n\t\treturn null;\n\t}\n\n\tpublic static boolean isInteger(String token) {\n\t\ttry {\n\t\t\tInteger.parseInt(token);\n\t\t\treturn true;\n\t\t} catch (NumberFormatException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic static boolean isLong(String token) {\n\t\ttry {\n\t\t\tLong.parseLong(token);\n\t\t\treturn true;\n\t\t} catch (NumberFormatException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic static Integer toInteger(String token, Predicate<Integer> p) {\n\t\ttry {\n\t\t\tInteger i = Integer.parseInt(token);\n\t\t\tUtilities.control(p == null || p.test(i), \"Value \" + i + \" not accepted by \" + p);\n\t\t\treturn i;\n\t\t} catch (RuntimeException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static Integer toInteger(String token) {\n\t\treturn toInteger(token, null);\n\t}\n\n\tpublic static int[] toIntegers(String[] tokens) {\n\t\tif (tokens == null || tokens.length == 0)\n\t\t\treturn null;\n\t\treturn Stream.of(tokens).map(tok -> toInteger(tok)).mapToInt(i -> i).toArray();\n\t}\n\n\tpublic static Double toDouble(String token, Predicate<Double> p) {\n\t\ttry {\n\t\t\tDouble d = Double.parseDouble(token);\n\t\t\tUtilities.control(p == null || p.test(d), \"Value \" + d + \" not accepted by \" + p);\n\t\t\treturn d;\n\t\t} catch (RuntimeException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static double toDouble(String token) {\n\t\treturn toDouble(token, null);\n\t}\n\n\tpublic static BigInteger powerBig(long a, int b) {\n\t\treturn BigInteger.valueOf(a).pow(b);\n\t}\n\n\tpublic static int power(long a, int b) {\n\t\treturn powerBig(a, b).intValueExact();\n\t}\n\n\tprivate static BigInteger recursiveFactorial(long start, long n) {\n\t\tlong i;\n\t\tif (n <= 16) {\n\t\t\tBigInteger r = BigInteger.valueOf(start);\n\t\t\tfor (i = start + 1; i < start + n; i++)\n\t\t\t\tr = r.multiply(BigInteger.valueOf(i));\n\t\t\treturn r;\n\t\t}\n\t\ti = n / 2;\n\t\treturn recursiveFactorial(start, i).multiply(recursiveFactorial(start + i, n - i));\n\t}\n\n\tpublic static BigInteger factorialBig(int n) {\n\t\treturn recursiveFactorial(1, n);\n\t}\n\n\tpublic static int factorial(int n) {\n\t\treturn factorialBig(n).intValueExact();\n\t}\n\n\tpublic static BigInteger binomialBig(int n, int k) {\n\t\tif (k < 0 || n < k)\n\t\t\treturn BigInteger.ZERO;\n\t\tif (k > n - k)\n\t\t\tk = n - k;\n\t\tBigInteger i = BigInteger.ONE;\n\t\tfor (int v = 0; v < k; v++)\n\t\t\ti = i.multiply(BigInteger.valueOf(n - v)).divide(BigInteger.valueOf(v + 1));\n\t\treturn i;\n\t}\n\n\tpublic static int binomial(int n, int k) {\n\t\treturn binomialBig(n, k).intValueExact();\n\t}\n\n\tpublic static BigInteger nArrangementsFor(int[] nValues) {\n\t\treturn IntStream.of(nValues).mapToObj(v -> BigInteger.valueOf(v)).reduce(BigInteger.ONE, (acc, v) -> acc.multiply(v));\n\t}\n\n\tpublic static boolean contains(int[] tab, int v, int from, int to) {\n\t\treturn IntStream.rangeClosed(from, to).anyMatch(i -> tab[i] == v);\n\t}\n\n\tpublic static boolean contains(int[] tab, int v) {\n\t\treturn contains(tab, v, 0, tab.length - 1);\n\t}\n\n\tpublic static int indexOf(String s, String... t) {\n\t\treturn IntStream.range(0, t.length).filter(i -> t[i].equals(s)).findFirst().orElse(-1);\n\t}\n\n\tpublic static int indexOf(String s, List<Object> list) {\n\t\treturn IntStream.range(0, list.size()).filter(i -> list.get(i).equals(s)).findFirst().orElse(-1);\n\t}\n\n\tpublic static int indexOf(int value, int[] t) {\n\t\tfor (int i = 0; i < t.length; i++)\n\t\t\tif (value == t[i])\n\t\t\t\treturn i;\n\t\treturn -1;\n\t\t// return IntStream.range(0, t.length).filter(i -> t[i] == value).findFirst().orElse(-1);\n\t}\n\n\tpublic static int indexOf(Object value, Object[] t) {\n\t\treturn IntStream.range(0, t.length).filter(i -> t[i] == value).findFirst().orElse(-1);\n\t}\n\n\t/**\n\t * Returns true is the array is regular and matches exactly the specified size. For example, if size is [5,4] then\n\t * the specified array must be a 2-dimensional array of 5 x 4 squares.\n\t */\n\tpublic static boolean hasSize(Object array, int... size) {\n\t\tboolean b1 = array != null && array.getClass().isArray(), b2 = size.length > 0;\n\t\tif (!b1 && !b2)\n\t\t\treturn true;\n\t\tif (b1 && !b2 || !b1 && b2 || Array.getLength(array) != size[0])\n\t\t\treturn false;\n\t\treturn IntStream.range(0, size[0]).noneMatch(i -> !hasSize(Array.get(array, i), Arrays.stream(size).skip(1).toArray()));\n\t}\n\n\t/**\n\t * Returns true is the array is regular, that is to say has the form of a rectangle for a 2-dimensional array, a\n\t * cube for a 3-dimensional array... For example, if the specified array is a 2-dimensional array of 5 x 4 squares,\n\t * then it is regular. But it has 3 squares for the first row, and 4 squares for the second row, then it is not\n\t * regular.\n\t */\n\tpublic static boolean isRegular(Object array) {\n\t\tList<Integer> list = new ArrayList<>();\n\t\tfor (Object a = array; a != null && a.getClass().isArray(); a = Array.getLength(a) == 0 ? null : Array.get(a, 0))\n\t\t\tlist.add(Array.getLength(a));\n\t\treturn hasSize(array, list.stream().mapToInt(i -> i).toArray());\n\t}\n\n\t/**\n\t * Method that controls that the specified condition is verified. If it is not the case, a message is displayed and\n\t * the program is stopped.\n\t */\n\tpublic static Object control(boolean condition, String message) {\n\t\tif (!condition) {\n\t\t\tSystem.out.println(\"\\n\\nFatal Error: \" + message);\n\t\t\tthrow new RuntimeException();\n\t\t\t// System.exit(1);\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Object exit(String message) {\n\t\treturn control(false, message);\n\t}\n\n\t/**\n\t * Checks if the specified {@code Runnable} object raises an {@code ArithmeticException} object, when run. The value\n\t * {@code true} is returned iff no such exception is raised.\n\t * \n\t * @param r\n\t * a {@code Runnable} object to be run\n\t * @return {@code true} iff no {@code ArithmeticException} is raised when running the specified code\n\t */\n\tpublic static boolean checkSafeArithmeticOperation(Runnable r) {\n\t\ttry {\n\t\t\tr.run();\n\t\t\treturn true;\n\t\t} catch (ArithmeticException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Method that parses the specified string as a long integer. If the value is too small or too big, an exception is\n\t * raised. The specified boolean allows us to indicate if some special values (such as +infinity) must be checked.\n\t */\n\tpublic static Long safeLong(String s, boolean checkSpecialValues) {\n\t\tif (checkSpecialValues) {\n\t\t\tif (s.equals(PLUS_INFINITY_STRING))\n\t\t\t\treturn PLUS_INFINITY;\n\t\t\tif (s.equals(MINUS_INFINITY_STRING))\n\t\t\t\treturn MINUS_INFINITY;\n\t\t}\n\t\tif (s.length() > 18) { // 18 because MAX_LONG and MIN_LONG are composed of at most 19 characters\n\t\t\tBigInteger big = new BigInteger(s);\n\t\t\tcontrol(big.compareTo(BIG_MIN_SAFE_LONG) >= 0 && big.compareTo(BIG_MAX_SAFE_LONG) <= 0, \"Too small or big value for this parser : \" + s);\n\t\t\treturn big.longValue();\n\t\t} else\n\t\t\treturn Long.parseLong(s);\n\t}\n\n\t/**\n\t * Method that parses the specified string as a long integer. If the value is too small or too big, an exception is\n\t * raised.\n\t */\n\tpublic static Long safeLong(String s) {\n\t\treturn safeLong(s, false);\n\t}\n\n\tpublic static boolean isSafeInt(long l, boolean useMargin) {\n\t\treturn (useMargin ? Constants.MIN_SAFE_INT : Integer.MIN_VALUE) <= l && l <= (useMargin ? Constants.MAX_SAFE_INT : Integer.MAX_VALUE);\n\t}\n\n\tpublic static boolean isSafeInt(long l) {\n\t\treturn isSafeInt(l, true);\n\t}\n\n\t/**\n\t * Converts the specified long number to int if it is safe to do it. When the specified boolean is set to true, we\n\t * control that it is safe according to the constants MIN_SAFE_INT and MAX_SAFE_INT.\n\t */\n\tpublic static int safeInt(Long l, boolean useMargin) {\n\t\tcontrol(isSafeInt(l, useMargin), \"Too big integer value \" + l);\n\t\treturn l.intValue();\n\t\t// return safeLong2Int(number.longValue(), useMargin);\n\t}\n\n\t/**\n\t * Converts the specified long to int if it is safe to do it. We control that it is safe according to the constants\n\t * MIN_SAFE_INT and MAX_SAFE_INT.\n\t */\n\tpublic static int safeInt(Long l) {\n\t\treturn safeInt(l, true);\n\t}\n\n\t/**\n\t * Converts the specified long to int if it is safe to do it. Note that VAL_MINUS_INFINITY will be translated to\n\t * VAL_MINUS_INFINITY_INT and that VAL_PLUS_INFINITY will be translated to VAL_PLUS_INFINITY_INT . We control that\n\t * it is safe according to the constants MIN_SAFE_INT and MAX_SAFE_INT.\n\t */\n\tpublic static int safeIntWhileHandlingInfinity(long l) {\n\t\tif (l == Constants.MINUS_INFINITY)\n\t\t\treturn Constants.MINUS_INFINITY_INT;\n\t\tif (l == Constants.PLUS_INFINITY)\n\t\t\treturn Constants.PLUS_INFINITY_INT;\n\t\treturn safeInt(l);\n\t}\n\n\tpublic static <T> T[] swap(T[] t, int i, int j) {\n\t\tT tmp = t[i];\n\t\tt[i] = t[j];\n\t\tt[j] = tmp;\n\t\treturn t;\n\t}\n\n\t/** Method that joins the elements of the specified array, using the specified delimiter to separate them. */\n\tpublic static String join(Object array, String delimiter) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (int i = 0, length = Array.getLength(array); i < length; i++) {\n\t\t\tObject item = Array.get(array, i);\n\t\t\tif (item != null && item.getClass().isArray())\n\t\t\t\tsb.append(\"[\").append(join(item, delimiter)).append(\"]\");\n\t\t\telse\n\t\t\t\tsb.append(item != null ? item.toString() : \"null\").append(i < length - 1 ? delimiter : \"\");\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\t/** Method that joins the elements of the specified array, using a white-space as delimiter. */\n\tpublic static String join(Object array) {\n\t\treturn join(array, \" \");\n\t}\n\n\tpublic static String join(Collection<? extends Object> c) {\n\t\treturn join(c.toArray());\n\t}\n\n\t/** Method that joins the elements of the specified map, using the specified separator and delimiter. */\n\tpublic static <K, V> String join(Map<K, V> m, String separator, String delimiter) {\n\t\treturn m.entrySet().stream().map(e -> e.getKey() + separator + e.getValue()).reduce(\"\", (n, p) -> n + (n.length() == 0 ? \"\" : delimiter) + p);\n\t}\n\n\t/**\n\t * Method that joins the elements of the specified two-dimensional array, using the specified separator and\n\t * delimiter.\n\t */\n\tpublic static String join(Object[][] m, String separator, String delimiter) {\n\t\treturn Arrays.stream(m).map(t -> join(t, delimiter)).reduce(\"\", (n, p) -> n + (n.length() == 0 ? \"\" : separator) + p);\n\t}\n\n\tpublic static String join(int[][] m, String separator, String delimiter) {\n\t\treturn Arrays.stream(m).map(t -> join(t, delimiter)).reduce(\"\", (n, p) -> n + (n.length() == 0 ? \"\" : separator) + p);\n\t}\n\n\t/**\n\t * Returns the specified string in camel case form (with the first letter of the first word in lower case).\n\t */\n\tpublic static String toCamelCase(String s) {\n\t\tString[] words = s.split(\"_\");\n\t\treturn IntStream.range(0, words.length)\n\t\t\t\t.mapToObj(i -> i == 0 ? words[i].toLowerCase() : words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase())\n\t\t\t\t.collect(Collectors.joining());\n\t}\n\n\t/**\n\t * Returns the specified string in kebab case form.\n\t */\n\tpublic static String toKebabCase(String s) {\n\t\tString[] words = s.split(\"_\");\n\t\treturn Stream.of(words).map(w -> w.toLowerCase()).collect(Collectors.joining(\"-\"));\n\t}\n\n\t/** Method for converting an array into a string. */\n\tpublic static String arrayToString(Object array, final char LEFT, final char RIGHT, final String SEP) {\n\t\tassert array.getClass().isArray();\n\n\t\tif (array instanceof boolean[])\n\t\t\treturn Arrays.toString((boolean[]) array);\n\t\tif (array instanceof byte[])\n\t\t\treturn Arrays.toString((byte[]) array);\n\t\tif (array instanceof short[])\n\t\t\treturn Arrays.toString((short[]) array);\n\t\tif (array instanceof int[])\n\t\t\treturn Arrays.toString((int[]) array);\n\t\tif (array instanceof long[])\n\t\t\treturn Arrays.toString((long[]) array);\n\t\tif (array instanceof String[])\n\t\t\treturn LEFT + String.join(SEP, (String[]) array) + RIGHT;\n\t\tif (array instanceof IVar[])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((IVar[]) array).map(x -> x.toString()).toArray(String[]::new)) + RIGHT;\n\n\t\tif (array instanceof boolean[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((boolean[][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof byte[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((byte[][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof short[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((short[][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof int[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((int[][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof long[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((long[][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof String[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((String[][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\n\t\tif (array instanceof boolean[][][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((boolean[][][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof byte[][][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((byte[][][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof short[][][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((short[][][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof int[][][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((int[][][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof long[][][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((long[][][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\t\tif (array instanceof String[][][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((String[][][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\n\t\tif (array instanceof Long[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((Long[][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\n\t\tif (array instanceof IVar[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((IVar[][]) array).map(t -> arrayToString(t, LEFT, RIGHT, SEP)).toArray(String[]::new)) + RIGHT;\n\n\t\tif (array instanceof Object[][])\n\t\t\treturn LEFT + String.join(SEP, Stream.of((Object[][]) array).map(t -> arrayToString(t)).toArray(String[]::new)) + RIGHT;\n\t\t// return \"(\" + String.join(\")(\", Stream.of((Object[][]) array).map(t ->\n\t\t// simplify(Arrays.toString(t))).toArray(String[]::new)) +\n\t\t// \")\";\n\t\tif (array instanceof Object[])\n\t\t\treturn String.join(SEP,\n\t\t\t\t\tStream.of((Object[]) array).map(t -> t.getClass().isArray() ? LEFT + arrayToString(t) + RIGHT : t.toString()).toArray(String[]::new));\n\t\treturn null;\n\t}\n\n\t/** Method for converting an array into a string. */\n\tpublic static String arrayToString(Object array) {\n\t\treturn arrayToString(array, '[', ']', \", \");\n\t}\n\n\t/**\n\t * Returns true if inside the specified object, there is an element that checks the predicate. If syntactic trees\n\t * are encountered, we check the leaves only.\n\t */\n\tpublic static boolean check(Object obj, Predicate<Object> p) {\n\t\tif (obj instanceof Object[])\n\t\t\treturn IntStream.range(0, Array.getLength(obj)).anyMatch(i -> check(Array.get(obj, i), p));\n\t\tif (obj instanceof XNode)\n\t\t\treturn ((XNode<?>) obj).firstNodeSuchThat(n -> n instanceof XNodeLeaf && p.test(((XNodeLeaf<?>) n).value)) != null;\n\t\t// if (obj instanceof XNode)\n\t\t// return ((XNode<?>) obj).containsLeafSuchThat(leaf -> p.test(leaf.value));\n\t\treturn p.test(obj);\n\t}\n\n\tpublic static class ModifiableBoolean {\n\t\tpublic Boolean value;\n\n\t\tpublic ModifiableBoolean(Boolean value) {\n\t\t\tthis.value = value;\n\t\t}\n\t}\n\n\t// ************************************************************************\n\t// ***** Methods for XML\n\t// ************************************************************************\n\n\t/** Method that loads an XML document, using the specified file name. */\n\tpublic static Document loadDocument(String fileName) throws Exception {\n\t\tUtilities.control(new File(fileName).exists(), \"Filename \" + fileName + \" not found\\n\");\n\t\tif (fileName.endsWith(\"xml.bz2\") || fileName.endsWith(\"xml.lzma\")) {\n\t\t\tProcess p = Runtime.getRuntime().exec((fileName.endsWith(\"xml.bz2\") ? \"bunzip2 -c \" : \"lzma -c -d \") + fileName);\n\t\t\tDocument document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(p.getInputStream());\n\t\t\tp.waitFor();\n\t\t\treturn document;\n\t\t} else\n\t\t\treturn DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(new File(fileName)));\n\t}\n\n\tpublic static void save(Document document, PrintWriter out) {\n\t\ttry {\n\t\t\tTransformer transformer = TransformerFactory.newInstance().newTransformer();\n\t\t\ttransformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n\t\t\ttransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"yes\");\n\t\t\ttransformer.transform(new DOMSource(document), new StreamResult(out));\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static String save(Document document, String fileName) {\n\t\ttry (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)))) {\n\t\t\tsave(document, out);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn fileName;\n\t}\n\n\t/** Method that returns an array with the child elements of the specified element. */\n\tpublic static Element[] childElementsOf(Element element) {\n\t\tNodeList childs = element.getChildNodes();\n\t\treturn IntStream.range(0, childs.getLength()).mapToObj(i -> childs.item(i)).filter(e -> e.getNodeType() == Node.ELEMENT_NODE).toArray(Element[]::new);\n\t}\n\n\t/** Determines whether the specified element has the specified type as tag name. */\n\tpublic static boolean isTag(Element elt, TypeChild type) {\n\t\treturn elt.getTagName().equals(type.name());\n\t}\n\n\tpublic static Element element(Document doc, String tag, List<Element> sons) {\n\t\tElement elt = doc.createElement(tag);\n\t\tsons.stream().forEach(c -> elt.appendChild(c));\n\t\treturn elt;\n\t}\n\n\tpublic static Element element(Document doc, String tag, Element son) {\n\t\treturn element(doc, tag, Arrays.asList(son));\n\t}\n\n\tpublic static Element element(Document doc, String tag, Element son, Element... otherSons) {\n\t\treturn element(doc, tag, IntStream.range(0, 1 + otherSons.length).mapToObj(i -> i == 0 ? son : otherSons[i - 1]).collect(Collectors.toList()));\n\t}\n\n\tpublic static Element element(Document doc, String tag, Element son, Stream<Element> otherSons) {\n\t\treturn element(doc, tag, Stream.concat(Stream.of(son), otherSons).collect(Collectors.toList()));\n\t}\n\n\tpublic static Element element(Document doc, String tag, Object textContent) {\n\t\tElement elt = doc.createElement(tag);\n\t\telt.setTextContent(\" \" + textContent + \" \");\n\t\treturn elt;\n\t}\n\n\tpublic static Element element(Document doc, String tag, String attName, String attValue, Object textContent) {\n\t\tElement elt = element(doc, tag, textContent);\n\t\telt.setAttribute(attName, attValue);\n\t\treturn elt;\n\t}\n\n\tpublic static Element element(Document doc, String tag, String attName, String attValue) {\n\t\tElement elt = doc.createElement(tag);\n\t\telt.setAttribute(attName, attValue);\n\t\treturn elt;\n\t}\n\n\tpublic static Element element(Document doc, String tag, String attName1, String attValue1, String attName2, String attValue2) {\n\t\tElement elt = doc.createElement(tag);\n\t\telt.setAttribute(attName1, attValue1);\n\t\telt.setAttribute(attName2, attValue2);\n\t\treturn elt;\n\t}\n\n\tpublic static Element element(Document doc, String tag, Stream<Entry<String, Object>> attributes) {\n\t\tElement elt = doc.createElement(tag);\n\t\tif (attributes != null)\n\t\t\tattributes.forEach(e -> elt.setAttribute(e.getKey(), e.getValue().toString()));\n\t\treturn elt;\n\t}\n\n\tpublic static Element element(Document doc, String tag, Collection<Entry<String, Object>> attributes) {\n\t\treturn element(doc, tag, attributes != null ? attributes.stream() : null);\n\t}\n\n}",
"public static final class Dom extends DomBasic {\n\n\tpublic static String compactFormOf(int[] values) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tif (values.length == 2)\n\t\t\treturn values[0] + \" \" + values[1];\n\t\tint prevVal = values[0], startInterval = prevVal;\n\t\tfor (int i = 1; i < values.length; i++) {\n\t\t\tint currVal = values[i];\n\t\t\tif (currVal != prevVal + 1) {\n\t\t\t\tsb.append(prevVal == startInterval ? prevVal : startInterval + (prevVal == startInterval + 1 ? \" \" : \"..\") + prevVal).append(\" \");\n\t\t\t\t// when only two values, no need for an interval\n\t\t\t\tstartInterval = currVal;\n\t\t\t}\n\t\t\tprevVal = currVal;\n\t\t}\n\t\treturn sb.append(prevVal == startInterval ? prevVal : startInterval + (prevVal == startInterval + 1 ? \" \" : \"..\") + prevVal).toString();\n\t}\n\n\t/**\n\t * Builds an integer domain, with the integer values (entities that are either integers or integer intervals) obtained by parsing the\n\t * specified string.\n\t */\n\tprotected Dom(String seq) {\n\t\tsuper(IntegerEntity.parseSeq(seq)); // must be already sorted.\n\t}\n\n\t/** Builds an integer domain, with the specified integer values. */\n\tpublic Dom(int[] values) {\n\t\tsuper(IntStream.of(values).mapToObj(v -> new IntegerValue(v)).toArray(IntegerEntity[]::new));\n\t}\n\n\t/** Builds an integer domain, with the specified integer interval. */\n\tpublic Dom(int min, int max) {\n\t\tsuper(new IntegerEntity[] { new IntegerInterval(min, max) });\n\t}\n\n\t/** Returns the first (smallest) value of the domain. It may be VAL_M_INFINITY for -infinity. */\n\tpublic long firstValue() {\n\t\treturn ((IntegerEntity) values[0]).smallest();\n\t}\n\n\t/** Returns the last (greatest) value of the domain. It may be VAL_P_INFINITY for +infinity. */\n\tpublic long lastValue() {\n\t\treturn ((IntegerEntity) values[values.length - 1]).greatest();\n\t}\n\n\t/** Returns true iff the domain contains the specified value. */\n\tpublic boolean contains(long v) {\n\t\tfor (int left = 0, right = values.length - 1; left <= right;) {\n\t\t\tint center = (left + right) / 2;\n\t\t\tint res = ((IntegerEntity) values[center]).compareContains(v);\n\t\t\tif (res == 0)\n\t\t\t\treturn true;\n\t\t\tif (res == -1)\n\t\t\t\tleft = center + 1;\n\t\t\telse\n\t\t\t\tright = center - 1;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate Object cacheAllValues; // cache for lazy initialization\n\n\t/** Returns the number of values in the domain, if the domain is finite. Returns -1 otherwise. */\n\tpublic long nValues() {\n\t\tif (cacheAllValues == null)\n\t\t\tcacheAllValues = allValues();\n\t\treturn cacheAllValues == null ? -1 : cacheAllValues instanceof Range ? ((Range) cacheAllValues).length() : ((int[]) cacheAllValues).length;\n\t}\n\n\t/**\n\t * Returns the values of the integer domain, either as an object Range or as an array of integers. Returns null if the domain is infinite (or\n\t * too large).\n\t **/\n\tpublic Object allValues() {\n\t\tif (cacheAllValues == null) {\n\t\t\tIntegerEntity[] vs = (IntegerEntity[]) values;\n\t\t\tif (values.length == 1 && values[0] instanceof IntegerInterval) {\n\t\t\t\tIntegerInterval ii = (IntegerInterval) values[0];\n\t\t\t\tcacheAllValues = ii.width() == -1 ? null : new Range(ii);\n\t\t\t} else\n\t\t\t\tcacheAllValues = IntegerEntity.toIntArray(vs, Integer.MAX_VALUE);\n\t\t}\n\t\tassert !(cacheAllValues instanceof int[])\n\t\t\t\t|| IntStream.range(0, ((int[]) cacheAllValues).length - 1).allMatch(i -> ((int[]) cacheAllValues)[i] < ((int[]) cacheAllValues)[i + 1]);\n\t\treturn cacheAllValues;\n\t}\n\n\t/**\n\t * Returns this object if the condition is evaluated to {@code true}, {@code null} otherwise.\n\t * \n\t * @param condition\n\t * a Boolean expression\n\t * @return this object if the condition is evaluated to {@code true}, {@code null} otherwise\n\t */\n\tpublic Dom when(boolean condition) {\n\t\treturn condition ? this : null;\n\t}\n}",
"public static interface IDom {\n}",
"public static interface IntegerEntity extends Comparable<IntegerEntity> {\n\t/** Returns an integer entity (integer value or integer interval) obtained by parsing the specified string. */\n\tpublic static IntegerEntity parse(String s) {\n\t\tString[] t = s.split(\"\\\\.\\\\.\");\n\t\treturn t.length == 1 ? new IntegerValue(safeLong(t[0])) : new IntegerInterval(safeLong(t[0], true), safeLong(t[1], true));\n\t}\n\n\t/** Returns an array of integer entities (integer values or integer intervals) obtained by parsing the specified string. */\n\tpublic static IntegerEntity[] parseSeq(String seq) {\n\t\treturn Stream.of(seq.split(\"\\\\s+\")).map(tok -> IntegerEntity.parse(tok)).toArray(IntegerEntity[]::new);\n\t}\n\n\t/**\n\t * Returns the number of values in the specified array of integer entities. Importantly, note that -1 is returned if this number is infinite, or simply\n\t * greater than {@code Long.MAX_VALUE}.\n\t */\n\tpublic static long nValues(IntegerEntity[] pieces) {\n\t\tassert IntStream.range(0, pieces.length - 1).noneMatch(i -> pieces[i].greatest() >= pieces[i + 1].smallest());\n\t\tif (Stream.of(pieces).anyMatch(p -> p.width() == -1))\n\t\t\treturn -1L; // the number of values does not fit within a long\n\t\tlong cnt = 0;\n\t\ttry {\n\t\t\tfor (IntegerEntity piece : pieces)\n\t\t\t\tcnt = Math.addExact(cnt, piece.width());\n\t\t} catch (ArithmeticException e) {\n\t\t\treturn -1L;\n\t\t}\n\t\treturn cnt;\n\t}\n\n\t/**\n\t * Returns an array of integers with all values represented by the specified integer entities. Note that null is returned if the number of values is\n\t * infinite or greater than the specified limit value.\n\t */\n\tpublic static int[] toIntArray(IntegerEntity[] pieces, int limit) {\n\t\tlong l = nValues(pieces);\n\t\tif (l == -1L || l > limit)\n\t\t\treturn null;\n\t\tint[] values = new int[(int) l];\n\t\tint i = 0;\n\t\tfor (IntegerEntity piece : pieces)\n\t\t\tif (piece instanceof IntegerValue)\n\t\t\t\tvalues[i++] = Utilities.safeInt(((IntegerValue) piece).v);\n\t\t\telse {\n\t\t\t\tint min = Utilities.safeInt(((IntegerInterval) piece).inf), max = Utilities.safeInt(((IntegerInterval) piece).sup);\n\t\t\t\tfor (int v = min; v <= max; v++)\n\t\t\t\t\tvalues[i++] = v;\n\t\t\t}\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns an array of integers with all values represented by the specified integer entities. Note that null is returned if the number of values is\n\t * infinite or greater than Integer.MAX_VALUE\n\t */\n\tpublic static int[] toIntArray(IntegerEntity[] pieces) {\n\t\treturn toIntArray(pieces, Integer.MAX_VALUE);\n\t}\n\n\t@Override\n\tpublic default int compareTo(IntegerEntity p) {\n\t\tlong l1 = this instanceof IntegerValue ? ((IntegerValue) this).v : ((IntegerInterval) this).inf;\n\t\tlong l2 = p instanceof IntegerValue ? ((IntegerValue) p).v : ((IntegerInterval) p).inf;\n\t\treturn l1 < l2 ? -1 : l1 > l2 ? 1 : 0; // correct because pieces do not overlap\n\t}\n\n\t/** Returns true iff the entity is an integer value or an integer interval containing only one value */\n\tpublic boolean isSingleton();\n\n\t/** Returns the smallest value of the entity (the value itself or the lower bound of the interval). */\n\tpublic long smallest();\n\n\t/** Returns the greatest value of the entity (the value itself or the upper bound of the interval). */\n\tpublic long greatest();\n\n\t/** Returns the number of values represented by the entity, or -1 if this number does not fit within a {@code long}. */\n\tpublic long width();\n\n\t/**\n\t * Returns 0 if the entity contains the specified value, -1 if the values of the entity are strictly smaller than the specified value, and +1 if the\n\t * values of the entity are strictly greater than the specified value.\n\t */\n\tpublic int compareContains(long l);\n\n}",
"public static final class IntegerInterval implements IntegerEntity {\n\t/** The bounds of the interval. */\n\tpublic final long inf, sup;\n\n\tprivate final long width;\n\n\t/** Builds an IntegerInterval object with the specified bounds. */\n\tpublic IntegerInterval(long inf, long sup) {\n\t\tthis.inf = inf;\n\t\tthis.sup = sup;\n\t\tUtilities.control(inf <= sup, \"Interval problem \" + this);\n\t\twidth = inf == MINUS_INFINITY || sup == PLUS_INFINITY || !Utilities.checkSafeArithmeticOperation(() -> Math.subtractExact(sup + 1, inf)) ? -1\n\t\t\t\t: sup + 1 - inf;\n\t}\n\n\tpublic IntegerInterval(long singleton) {\n\t\tthis(singleton, singleton);\n\t}\n\n\t@Override\n\tpublic boolean isSingleton() {\n\t\treturn inf == sup;\n\t}\n\n\t@Override\n\tpublic long smallest() {\n\t\treturn inf;\n\t}\n\n\t@Override\n\tpublic long greatest() {\n\t\treturn sup;\n\t}\n\n\t@Override\n\tpublic long width() {\n\t\treturn width;\n\t}\n\n\t@Override\n\tpublic int compareContains(long l) {\n\t\treturn sup < l ? -1 : inf > l ? 1 : 0;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn inf == sup - 1 ? inf + \" \" + sup : inf + \"..\" + sup;\n\t}\n}",
"public static enum TypePrimitive {\n\tBYTE, SHORT, INT, LONG;\n\n\t/**\n\t * Returns the smallest primitive that can be used for representing values lying within the specified bounds.\n\t */\n\tpublic static TypePrimitive whichPrimitiveFor(long inf, long sup) {\n\t\tif (MIN_SAFE_BYTE <= inf && sup <= MAX_SAFE_BYTE)\n\t\t\treturn BYTE;\n\t\tif (MIN_SAFE_SHORT <= inf && sup <= MAX_SAFE_SHORT)\n\t\t\treturn SHORT;\n\t\tif (MIN_SAFE_INT <= inf && sup <= MAX_SAFE_INT)\n\t\t\treturn INT;\n\t\t// if (MIN_SAFE_LONG <= inf && sup <= MAX_SAFE_LONG)\n\t\treturn LONG; // else return null;\n\t}\n\n\t/** Returns the smallest primitive that can be used for representing the specified value. */\n\tpublic static TypePrimitive whichPrimitiveFor(long val) {\n\t\treturn whichPrimitiveFor(val, val);\n\t}\n\n\t/**\n\t * Returns the smallest primitive that can be used for representing any value of the domains of the specified\n\t * variables. If one variable is not integer, null is returned.\n\t */\n\tstatic TypePrimitive whichPrimitiveFor(XVar[] vars) {\n\t\tif (Stream.of(vars).anyMatch(x -> x.type != TypeVar.integer))\n\t\t\treturn null;\n\t\treturn TypePrimitive.values()[Stream.of(vars).mapToInt(x -> ((XVarInteger) x).whichPrimitive().ordinal()).max()\n\t\t\t\t.orElse(TypePrimitive.LONG.ordinal())];\n\t}\n\n\t/**\n\t * Returns the smallest primitive that can be used for representing any value of the domains of the specified\n\t * variables. If one variable is not integer, null is returned.\n\t */\n\tstatic TypePrimitive whichPrimitiveFor(XVar[][] varss) {\n\t\tif (whichPrimitiveFor(varss[0]) == null)\n\t\t\treturn null;\n\t\treturn TypePrimitive.values()[Stream.of(varss).mapToInt(t -> whichPrimitiveFor(t).ordinal()).max().orElse(TypePrimitive.LONG.ordinal())];\n\t}\n\n\t/** Returns true iff the primitive can represent the specified value. */\n\tprivate boolean canRepresent(long val) {\n\t\treturn this.ordinal() >= whichPrimitiveFor(val).ordinal();\n\t}\n\n\t/**\n\t * Parse the specified string that denotes a sequence of values. In case we have at least one interval, we just\n\t * return an array of IntegerEntity (as for integer domains), and no validity test on values is performed.\n\t * Otherwise, we return an array of integer (either long[] or int[]). It is possible that some values are\n\t * discarded because either they do not belong to the specified domain (test performed if this domain is not\n\t * null), or they cannot be represented by the primitive.\n\t */\n\tObject parseSeq(String s, Dom dom) {\n\t\tif (s.indexOf(\"..\") != -1)\n\t\t\treturn IntegerEntity.parseSeq(s);\n\t\tint nbDiscarded = 0;\n\t\tList<Long> list = new ArrayList<>();\n\t\tfor (String tok : s.split(\"\\\\s+\")) {\n\t\t\tassert !tok.equals(\"*\") : \"STAR not handled in unary lists\";\n\t\t\tlong l = Utilities.safeLong(tok);\n\t\t\tif (canRepresent(l) && (dom == null || dom.contains(l)))\n\t\t\t\tlist.add(l);\n\t\t\telse\n\t\t\t\tnbDiscarded++;\n\t\t}\n\t\tif (nbDiscarded > 0)\n\t\t\tSystem.out.println(nbDiscarded + \" discarded values in the unary list \" + s);\n\t\tif (this == LONG)\n\t\t\treturn list.stream().mapToLong(i -> i).toArray();\n\t\telse\n\t\t\treturn list.stream().mapToInt(i -> i.intValue()).toArray();\n\t\t// TODO possible refinement for returning byte[] and short[]\n\t}\n\n\t/**\n\t * Parse the specified string, and builds a tuple of (long) integers put in the specified array t. If the tuple\n\t * is not valid wrt the specified domains or the primitive, false is returned, in which case, the tuple can be\n\t * discarded. If * is encountered, the specified modifiable boolean is set to true.\n\t */\n\tboolean parseTuple(String s, long[] t, DomBasic[] doms, AtomicBoolean ab) {\n\t\tString[] toks = s.split(\"\\\\s*,\\\\s*\");\n\t\tassert toks.length == t.length : toks.length + \" \" + t.length;\n\t\tboolean starred = false;\n\t\tfor (int i = 0; i < toks.length; i++) {\n\t\t\tif (toks[i].equals(\"*\")) {\n\t\t\t\tt[i] = this == BYTE ? Constants.STAR_BYTE : this == SHORT ? Constants.STAR_SHORT : this == INT ? Constants.STAR : Constants.STAR_LONG;\n\t\t\t\tstarred = true;\n\t\t\t} else {\n\t\t\t\tlong l = Utilities.safeLong(toks[i]);\n\t\t\t\tif (canRepresent(l) && (doms == null || ((Dom) doms[i]).contains(l)))\n\t\t\t\t\tt[i] = l;\n\t\t\t\telse\n\t\t\t\t\treturn false; // because the tuple can be discarded\n\t\t\t}\n\t\t}\n\t\tif (starred)\n\t\t\tab.set(true);\n\t\treturn true;\n\t}\n}",
"public static abstract class VEntry extends ParsingEntry {\n\t/** The type of the entry. */\n\tpublic final TypeVar type;\n\n\t/** Returns the type of the entry. We need an accessor for Scala. */\n\tpublic final TypeVar getType() {\n\t\treturn type;\n\t}\n\n\t/** Builds an entry with the specified id and type. */\n\tprotected VEntry(String id, TypeVar type) {\n\t\tsuper(id);\n\t\tthis.type = type;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn id + \":\" + type;\n\t}\n}"
] | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.xcsp.common.IVar;
import org.xcsp.common.IVar.Var;
import org.xcsp.common.IVar.VarSymbolic;
import org.xcsp.common.Types.TypeVar;
import org.xcsp.common.Utilities;
import org.xcsp.common.domains.Domains.Dom;
import org.xcsp.common.domains.Domains.IDom;
import org.xcsp.common.domains.Values.IntegerEntity;
import org.xcsp.common.domains.Values.IntegerInterval;
import org.xcsp.parser.XParser.TypePrimitive;
import org.xcsp.parser.entries.ParsingEntry.VEntry; | /*
* Copyright (c) 2016 XCSP3 Team ([email protected])
*
* 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 org.xcsp.parser.entries;
/**
* In this class, we find intern classes for managing variables and arrays of variables.
*
* @author Christophe Lecoutre
*/
public class XVariables {
public static final String OTHERS = "others";
/** The class used to represent variables. */
public static abstract class XVar extends VEntry implements IVar {
/** Builds a variable with the specified id, type and domain. */
public static final XVar build(String id, TypeVar type, IDom dom) {
switch (type) {
case integer:
return new XVarInteger(id, type, dom);
case symbolic:
return new XVarSymbolic(id, type, dom);
case stochastic:
return new XVarStochastic(id, type, dom);
case real:
return new XVarReal(id, type, dom);
case set:
return new XVarSet(id, type, dom);
default:
throw new RuntimeException("Unimplemented case ");
}
}
/** Builds a variable from an array with the specified id (combined with the specified indexes), type and domain. */
public static final XVar build(String idArray, TypeVar type, IDom dom, int[] indexes) {
return build(idArray + "[" + Utilities.join(indexes, "][") + "]", type, dom);
}
/** The domain of the variable. It is null if the variable is qualitative. */
public final IDom dom;
/** The degree of the variable. This is automatically computed after all constraints have been parsed. */
public int degree;
/** Builds a variable with the specified id, type and domain. */
protected XVar(String id, TypeVar type, IDom dom) {
super(id, type);
this.dom = dom;
}
// /** Builds a variable from an array with the specified id (combined with the specified indexes), type and domain. */
// protected VVar(String idArray, TypeVar type, DDom dom, int[] indexes) {
// this(idArray + "[" + XUtility.join(indexes, "][") + "]", type, dom);
// }
@Override
public String id() {
return id;
}
@Override
public String toString() {
return id; // + " :" + type + " of " + dom;
}
}
/** The following classes are introduced, only for being able to have types for variables in the parser interface */
public static final class XVarInteger extends XVar implements Var {
/**
* Returns the size of the Cartesian product for the domains of the specified variables. Importantly, if this value does not fit within a
* {@code long}, -1 is returned.
*/
public static long domainCartesianProductSize(XVarInteger[] scp) {
long[] domSizes = Stream.of(scp).mapToLong(x -> IntegerEntity.nValues((IntegerEntity[]) ((Dom) x.dom).values)).toArray();
if (LongStream.of(domSizes).anyMatch(l -> l == -1L))
return -1L;
long cnt = 1;
try {
for (long size : domSizes)
cnt = Math.multiplyExact(cnt, size);
} catch (ArithmeticException e) {
return -1L;
}
return cnt;
}
public TypePrimitive whichPrimitive() {
return TypePrimitive.whichPrimitiveFor(firstValue(), lastValue());
}
/** Builds an integer variable with the specified id, type and domain. */
protected XVarInteger(String id, TypeVar type, IDom dom) {
super(id, type, dom);
}
public long firstValue() {
return ((Dom) dom).firstValue();
}
public long lastValue() {
return ((Dom) dom).lastValue();
}
@Override
public Object allValues() {
return ((Dom) dom).allValues();
}
public boolean isZeroOne() {
return firstValue() == 0 && lastValue() == 1;
}
}
public static final class XVarSymbolic extends XVar implements VarSymbolic {
/** Builds a symbolic variable with the specified id, type and domain. */
protected XVarSymbolic(String id, TypeVar type, IDom dom) {
super(id, type, dom);
}
}
public static final class XVarStochastic extends XVar {
/** Builds a stochastic variable with the specified id, type and domain. */
protected XVarStochastic(String id, TypeVar type, IDom dom) {
super(id, type, dom);
}
}
public static final class XVarReal extends XVar {
/** Builds a real variable with the specified id, type and domain. */
protected XVarReal(String id, TypeVar type, IDom dom) {
super(id, type, dom);
}
}
public static final class XVarSet extends XVar {
/** Builds a set variable with the specified id, type and domain. */
protected XVarSet(String id, TypeVar type, IDom dom) {
super(id, type, dom);
}
}
/** The class used to represent arrays of variables. */
public static final class XArray extends VEntry {
/** The size of the array, as defined in XCSP3. */
public final int[] size;
/**
* The flat (one-dimensional) array composed of all variables contained in the (multi-dimensional) array. This way, we can easily deal with
* arrays of any dimensions.
*/
public final XVar[] vars;
/** Builds an array of variables with the specified id, type and size. */
public XArray(String id, TypeVar type, int[] size) {
super(id, type);
this.size = size;
this.vars = new XVar[Arrays.stream(size).reduce(1, (s, t) -> s * t)];
}
/** Builds a variable with the specified domain for each unoccupied cell of the flat array. */
private void buildVarsWith(IDom dom) {
int[] indexes = new int[size.length];
for (int i = 0; i < vars.length; i++) {
if (vars[i] == null)
vars[i] = XVar.build(id, type, dom, indexes);
for (int j = indexes.length - 1; j >= 0; j--)
if (++indexes[j] == size[j])
indexes[j] = 0;
else
break;
}
}
/**
* Builds an array of variables with the specified id, type and size. All variables are directly defined with the specified domain.
*/
public XArray(String id, TypeVar type, int[] sizes, IDom dom) {
this(id, type, sizes);
buildVarsWith(dom);
}
/** Transforms a flat index into a multi-dimensional index. */
protected int[] indexesFor(int flatIndex) {
int[] t = new int[size.length];
for (int i = t.length - 1; i > 0; i--) {
t[i] = flatIndex % size[i];
flatIndex = flatIndex / size[i];
}
t[0] = flatIndex;
return t;
}
/** Transforms a multi-dimensional index into a flat index. */
private int flatIndexFor(int... indexes) {
int sum = 0;
for (int i = indexes.length - 1, nb = 1; i >= 0; i--) {
sum += indexes[i] * nb;
nb *= size[i];
}
return sum;
}
/** Returns the variable at the position given by the multi-dimensional index. */
public XVar varAt(int... indexes) {
return vars[flatIndexFor(indexes)];
}
/**
* Returns the domain of the variable at the position given by the multi-dimensional index. However, if this variable does not exist or if its
* degree is 0, <code>null</code> is returned.
*/
public Dom domAt(int... indexes) {
XVar x = vars[flatIndexFor(indexes)];
return x == null || x.degree == 0 ? null : (Dom) x.dom;
}
/**
* Builds an array of IntegerEnity objects for representing the ranges of indexes that are computed with respect to the specified compact
* form.
*/
public IntegerEntity[] buildIndexRanges(String compactForm) {
IntegerEntity[] t = new IntegerEntity[size.length];
String suffix = compactForm.substring(compactForm.indexOf("["));
for (int i = 0; i < t.length; i++) {
int pos = suffix.indexOf("]");
String tok = suffix.substring(1, pos); | t[i] = tok.length() == 0 ? new IntegerInterval(0, size[i] - 1) : IntegerEntity.parse(tok); | 5 |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/classifier/feature/ExistingCleanPhraseFeature.java | [
"public class Phrase {\n // TODO: getters and setters for these\n /** phrase text array */\n public final List<Token> phrase;\n /** corresponding name type */\n public EntityClass phraseType;\n /** the start position of the phase in a sentence */\n public final int phrasePosition;\n /** the length of the phrase */\n public final int phraseLength;\n /** the start position of the phrase stub in a sentence */\n public final int phraseStubPosition;\n /** the length of the phrase stub */\n public final int phraseStubLength;\n /** score array, dimension equals to name type array */\n public Map<EntityClass, Double> score = new LinkedHashMap<>();\n /** attached word map */\n public Map<String, String> attachedWordMap;\n /** true if the phrase is a date; false if not */\n public boolean isDate;\n\n @JsonCreator\n public Phrase(@JsonProperty(\"phrase\") final List<Token> tokens,\n @JsonProperty(\"phrasePosition\") final int _phrasePos,\n @JsonProperty(\"phraseLength\") final int _phraseLen,\n @JsonProperty(\"phraseStubPosition\") final int _stubPos,\n @JsonProperty(\"phraseType\") final EntityClass type) {\n phrasePosition = _phrasePos;\n phraseLength = _phraseLen;\n phrase = ImmutableList.copyOf(tokens);\n phraseType = type;\n attachedWordMap = new HashMap<>();\n phraseStubPosition = _stubPos;\n phraseStubLength = phrase.size();\n }\n\n public String phraseString() {\n final StringBuilder sb = new StringBuilder();\n for (final Token aPhrase : phrase) sb.append(aPhrase.text).append(\" \");\n return sb.toString().trim();\n }\n\n /** Test if the phrase is a sub phrase of the input phrase. */\n public boolean isSubPhraseOf(final Phrase other) {\n if (phrase.isEmpty()) return false;\n\n // TODO: this should be refactored - the intent is not clear, implementation is sketchy\n boolean is = false;\n for (int i = 0; i < other.phrase.size() - phrase.size() + 1; i++) {\n boolean flag = true;\n for (int j = 0; j < phrase.size(); j++) {\n if (!phrase.get(j).text.equalsIgnoreCase(other.phrase.get(i + j).text)) {\n flag = false;\n break;\n }\n }\n if (flag) {\n is = true;\n break;\n }\n }\n return is;\n }\n\n /** This method will do the classification of a Phrase with a EntityClass. */\n public void classify() {\n EntityClass type = null;\n double s = 0;\n boolean ambiguous = false;\n for (final Map.Entry<EntityClass, Double> e : score.entrySet()) {\n if (type == null) {\n type = e.getKey();\n s = e.getValue();\n }\n else {\n if (Double.compare(e.getValue(), s) > 0) {\n type = e.getKey();\n s = e.getValue();\n ambiguous = false;\n }\n else if (Double.compare(s, e.getValue()) == 0) {\n ambiguous = true;\n }\n }\n }\n this.phraseType = ambiguous ? UNKNOWN : type;\n }\n\n @Override\n public String toString() {\n return \"Phrase{\" +\n \"phrase=\" + phrase +\n \", phraseType=\" + phraseType +\n \", phrasePosition=\" + phrasePosition +\n \", phraseLength=\" + phraseLength +\n \", phraseStubPosition=\" + phraseStubPosition +\n \", phraseStubLength=\" + phraseStubLength +\n \", score=\" + score.toString() +\n \", attachedWordMap=\" + attachedWordMap +\n \", isDate=\" + isDate +\n '}';\n }\n}",
"public final class IO {\n\n private static final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();\n private static final Splitter TABS = Splitter.on('\\t').trimResults().omitEmptyStrings();\n\n private IO() {}\n\n /** Return a Set containing trimmed lowercaseLines read from a file, skipping comments. */\n public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {\n return ImmutableSet.copyOf(new HashSet<String>() {{\n readResource(origin, resource, new NullReturnLineProcessor() {\n @Override\n public boolean processLine(@Nonnull final String line) {\n final String l = simplify(line);\n // add to the containing HashSet we are currently in the init block of\n if (!l.startsWith(\"#\") && !l.isEmpty()) add(toEngLowerCase(l));\n return true;\n }\n });\n }});\n }\n\n /** Return a Set containing lines with just the word characters of lines read from a file, skipping comments. */\n public static Set<String> cleanLowercaseLines(final Class<?> origin, final String resource) throws IOException {\n return ImmutableSet.copyOf(new HashSet<String>() {{\n readResource(origin, resource, new NullReturnLineProcessor() {\n @Override\n public boolean processLine(@Nonnull final String line) {\n final String l = simplify(line);\n // add to the containing HashSet we are currently in the init block of\n if (!l.startsWith(\"#\") && !l.isEmpty()) add(toEngLowerCase(clean(l)));\n return true;\n }\n });\n }});\n }\n\n /** Returns a Set containing only single words. */\n public static ImmutableSet<String> lowercaseWordSet(final Class<?> origin, final String resource,\n final boolean eliminatePrepAndConj) throws IOException {\n return ImmutableSet.copyOf(new HashSet<String>() {{\n readResource(origin, resource, new NullReturnLineProcessor() {\n @Override\n public boolean processLine(@Nonnull final String line) {\n final String l = simplify(line);\n if (!l.isEmpty() && !l.startsWith(\"#\")) {\n for (final String part : SPACES.split(l)) {\n if (eliminatePrepAndConj) {\n final String wordType = Dictionary.checkup(part);\n if (wordType != null && (wordType.startsWith(\"IN\") || wordType.startsWith(\"CC\"))) {\n continue;\n }\n }\n // add to the containing HashSet we are currently in the init block of\n add(toEngLowerCase(clean(part)));\n }\n }\n return true;\n }\n });\n }});\n }\n\n /** Return a set containing all non-comment non-empty words. */\n public static ImmutableSet<String> wordSet(final Class<?> origin, final String resource) throws IOException {\n return ImmutableSet.copyOf(new HashSet<String>() {{\n readResource(origin, resource, new NullReturnLineProcessor() {\n @Override\n public boolean processLine(@Nonnull final String line) {\n final String l = simplify(line);\n // add to the containing HashSet we are currently in the init block of\n if (!l.isEmpty() && !l.startsWith(\"#\")) {\n for (final String part : SPACES.split(l)) {\n add(clean(part));\n }\n }\n return true;\n }\n });\n }});\n }\n\n /** Return a map/dictionary of words from a file of key/values separated by a tab character. */\n public static ImmutableMap<String, String> dictionary(final Class<?> origin, final String resource)\n throws IOException {\n return ImmutableMap.copyOf(new HashMap<String, String>() {{\n readResource(origin, resource, new NullReturnLineProcessor() {\n @Override\n public boolean processLine(@Nonnull final String line) {\n final String l = simplify(line);\n if (!l.isEmpty() && !l.startsWith(\"#\")) {\n final List<String> parts = TABS.splitToList(l);\n // add the parts to the map we are in the init block of\n put(parts.get(0), parts.get(1));\n }\n return true;\n }\n });\n }});\n }\n\n private static <T> T readResource(final Class<?> origin, final String resource,\n final LineProcessor<T> processor) throws IOException {\n try { return readLines(getResource(origin, resource), UTF_8, processor); }\n catch (final IOException ioe) {\n throw new IOException(\"Error reading resource: '\" + resource + \"'\", ioe);\n }\n }\n\n // the way we are using the LineProcessor does not depend on the result that it returns\n private static abstract class NullReturnLineProcessor implements LineProcessor<Object> {\n @SuppressWarnings(\"ReturnOfNull\")\n @Override\n public Object getResult() { return null; }\n }\n}",
"public final class Strings {\n\n private static final Pattern CLEAN = Pattern.compile(\"[^\\\\p{L}\\\\p{Nd}]+\");\n\n private Strings() {}\n\n public static boolean equalss(final String word, final String... words) {\n if (word == null || words == null) return false;\n for (final String s : words) {\n if (word.equals(s)) return true;\n }\n return false;\n }\n\n public static boolean equalsIgnoreCase(final String word, final String... words) {\n if (word == null || words == null) return false;\n for (final String s : words) {\n if (word.equalsIgnoreCase(s)) return true;\n }\n return false;\n }\n\n public static boolean startsWith(final String word, final String... prefixes) {\n if (word == null || prefixes == null) return false;\n for (final String s : prefixes) {\n if (word.startsWith(s)) return true;\n }\n return false;\n }\n\n public static boolean endsWith(final String word, final String... suffixes) {\n if (word == null || suffixes == null) return false;\n for (final String s : suffixes) {\n if (word.endsWith(s)) return true;\n }\n return false;\n }\n\n public static boolean isSingleUppercaseChar(final String word) {\n return word.length() == 1 && isUpperCase(word.charAt(0));\n }\n\n public static char initChar(final String s) {\n return s.charAt(0);\n }\n\n public static char lastChar(final String s) {\n return s.charAt(s.length() -1);\n }\n\n @SuppressWarnings(\"ReturnOfNull\")\n public static String simplify(final String s) {\n if (s == null) return null;\n final String s1 = Normalizer.normalize(s, Normalizer.Form.NFC);\n return s1.trim();\n }\n\n public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }\n\n public static boolean isAllUppercase(final String s) { return s.equals(s.toUpperCase(Locale.ENGLISH)); }\n\n public static String clean(final String s) { return CLEAN.matcher(s).replaceAll(\"\"); }\n}",
"public static String clean(final String s) { return CLEAN.matcher(s).replaceAll(\"\"); }",
"public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }"
] | import java.util.List;
import java.util.Set;
import static org.t3as.ner.util.Strings.clean;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableSet;
import org.t3as.ner.Phrase;
import org.t3as.ner.util.IO;
import org.t3as.ner.util.Strings;
import javax.annotation.concurrent.Immutable;
import java.io.IOException;
import java.util.HashSet; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* 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 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 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-3.0.html>.
* #L%
*/
package org.t3as.ner.classifier.feature;
@Immutable
public class ExistingCleanPhraseFeature extends Feature {
private ImmutableCollection<String> phrases;
public ExistingCleanPhraseFeature(final List<String> resources, final int weight) throws IOException {
super(resources, weight);
}
@Override
public double score(final Phrase p) {
final int w = getWeight();
if (w == 0) return 0;
| final String phrase = Strings.simplify(p.phraseString()); | 2 |
wutongke/AndroidSkinAnimator | skin-app/src/main/java/com/ximsfei/dynamicskindemo/widget/CustomCircleImageView.java | [
"public class SkinCompatResources {\n private static volatile SkinCompatResources sInstance;\n private final Context mAppContext;\n private Resources mResources;\n private String mSkinPkgName;\n private boolean isDefaultSkin;\n\n private SkinCompatResources(Context context) {\n mAppContext = context.getApplicationContext();\n setSkinResource(mAppContext.getResources(), mAppContext.getPackageName());\n }\n\n public static void init(Context context) {\n if (sInstance == null) {\n synchronized (SkinCompatResources.class) {\n if (sInstance == null) {\n sInstance = new SkinCompatResources(context);\n }\n }\n }\n }\n\n public static SkinCompatResources getInstance() {\n return sInstance;\n }\n\n public void setSkinResource(Resources resources, String pkgName) {\n mResources = resources;\n mSkinPkgName = pkgName;\n isDefaultSkin = mAppContext.getPackageName().equals(pkgName);\n }\n\n public int getColor(int resId) {\n int originColor = ContextCompat.getColor(mAppContext, resId);\n if (isDefaultSkin) {\n return originColor;\n }\n\n String resName = mAppContext.getResources().getResourceEntryName(resId);\n\n int targetResId = mResources.getIdentifier(resName, \"color\", mSkinPkgName);\n\n return targetResId == 0 ? originColor : mResources.getColor(targetResId);\n }\n\n public Drawable getDrawable(int resId) {\n Drawable originDrawable = ContextCompat.getDrawable(mAppContext, resId);\n if (isDefaultSkin) {\n return originDrawable;\n }\n\n String resName = mAppContext.getResources().getResourceEntryName(resId);\n\n int targetResId = mResources.getIdentifier(resName, \"drawable\", mSkinPkgName);\n\n return targetResId == 0 ? originDrawable : mResources.getDrawable(targetResId);\n }\n\n public Drawable getMipmap(int resId) {\n Drawable originDrawable = ContextCompat.getDrawable(mAppContext, resId);\n if (isDefaultSkin) {\n return originDrawable;\n }\n\n String resName = mAppContext.getResources().getResourceEntryName(resId);\n\n int targetResId = mResources.getIdentifier(resName, \"mipmap\", mSkinPkgName);\n\n return targetResId == 0 ? originDrawable : mResources.getDrawable(targetResId);\n }\n\n public ColorStateList getColorStateList(int resId) {\n ColorStateList colorStateList = ContextCompat.getColorStateList(mAppContext, resId);\n if (isDefaultSkin) {\n return colorStateList;\n }\n\n String resName = mAppContext.getResources().getResourceEntryName(resId);\n\n int targetResId = mResources.getIdentifier(resName, \"color\", mSkinPkgName);\n\n return targetResId == 0 ? colorStateList : mResources.getColorStateList(targetResId);\n }\n}",
"public abstract class SkinCompatHelper {\n protected static final String TAG = SkinCompatHelper.class.getSimpleName();\n protected static final String SYSTEM_ID_PREFIX = \"1\";\n public static final int INVALID_ID = -1;\n\n final static public int checkResourceId(int resId) {\n String hexResId = Integer.toHexString(resId);\n SkinLog.d(TAG, \"hexResId = \" + hexResId);\n return hexResId.startsWith(SYSTEM_ID_PREFIX) ? INVALID_ID : resId;\n }\n\n abstract public void applySkin();\n}",
"public class SkinCompatImageHelper extends SkinCompatHelper {\n private static final String TAG = SkinCompatImageHelper.class.getSimpleName();\n private final ImageView mView;\n private int mSrcResId = INVALID_ID;\n\n public SkinCompatImageHelper(ImageView imageView) {\n mView = imageView;\n }\n\n public void loadFromAttributes(AttributeSet attrs, int defStyleAttr) {\n TintTypedArray a = null;\n try {\n a = TintTypedArray.obtainStyledAttributes(mView.getContext(), attrs,\n R.styleable.SkinCompatImageView, defStyleAttr, 0);\n\n mSrcResId = a.getResourceId(R.styleable.SkinCompatImageView_android_src, -1);\n } finally {\n if (a != null) {\n a.recycle();\n }\n }\n applySkin();\n }\n\n public void setImageResource(int resId) {\n mSrcResId = resId;\n applySkin();\n }\n\n public void applySkin() {\n mSrcResId = checkResourceId(mSrcResId);\n SkinLog.d(TAG, \"mSrcResId = \" + mSrcResId);\n if (mSrcResId == INVALID_ID) {\n return;\n }\n String typeName = mView.getResources().getResourceTypeName(mSrcResId);\n if (\"color\".equals(typeName)) {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n int color = SkinCompatResources.getInstance().getColor(mSrcResId);\n Drawable drawable = mView.getDrawable();\n if (drawable instanceof ColorDrawable) {\n ((ColorDrawable) drawable.mutate()).setColor(color);\n } else {\n mView.setImageDrawable(new ColorDrawable(color));\n }\n } else {\n ColorStateList colorStateList = SkinCompatResources.getInstance().getColorStateList(mSrcResId);\n Drawable drawable = mView.getDrawable();\n DrawableCompat.setTintList(drawable, colorStateList);\n mView.setImageDrawable(drawable);\n }\n } else if (\"drawable\".equals(typeName)) {\n Drawable drawable = SkinCompatResources.getInstance().getDrawable(mSrcResId);\n mView.setImageDrawable(drawable);\n } else if (\"mipmap\".equals(typeName)) {\n Drawable drawable = SkinCompatResources.getInstance().getMipmap(mSrcResId);\n mView.setImageDrawable(drawable);\n }\n }\n\n}",
"public interface SkinCompatSupportable {\n void applySkin();\n}",
"public static final int INVALID_ID = -1;"
] | import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import com.ximsfei.dynamicskindemo.R;
import skin.support.content.res.SkinCompatResources;
import skin.support.widget.SkinCompatHelper;
import skin.support.widget.SkinCompatImageHelper;
import skin.support.widget.SkinCompatSupportable;
import static skin.support.widget.SkinCompatHelper.INVALID_ID; | package com.ximsfei.dynamicskindemo.widget;
/**
* Created by ximsfei on 2017/1/17.
*/
public class CustomCircleImageView extends CircleImageView implements SkinCompatSupportable {
private final SkinCompatImageHelper mImageHelper;
private int mFillColorResId = INVALID_ID;
private int mBorderColorResId = INVALID_ID;
public CustomCircleImageView(Context context) {
this(context, null);
}
public CustomCircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomCircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mImageHelper = new SkinCompatImageHelper(this);
mImageHelper.loadFromAttributes(attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);
mBorderColorResId = a.getResourceId(R.styleable.CircleImageView_civ_border_color, INVALID_ID);
mFillColorResId = a.getResourceId(R.styleable.CircleImageView_civ_fill_color, INVALID_ID);
a.recycle();
applySkin();
}
@Override
public void setImageResource(@DrawableRes int resId) {
super.setImageResource(resId);
if (mImageHelper != null) {
mImageHelper.applySkin();
}
}
@Override
public void setBorderColorResource(@ColorRes int borderColorRes) {
super.setBorderColorResource(borderColorRes);
mBorderColorResId = borderColorRes;
applySkin();
}
@Override
public void setFillColorResource(@ColorRes int fillColorRes) {
super.setFillColorResource(fillColorRes);
mFillColorResId = fillColorRes;
applySkin();
}
@Override
public void applySkin() {
if (mImageHelper != null) {
mImageHelper.applySkin();
}
mBorderColorResId = SkinCompatHelper.checkResourceId(mBorderColorResId);
if (mBorderColorResId != INVALID_ID) { | int color = SkinCompatResources.getInstance().getColor(mBorderColorResId); | 0 |
sumeetchhetri/gatf | alldep-jar/src/main/java/com/gatf/selenium/SeleniumTest.java | [
"public class AcceptanceTestContext {\r\n\r\n\tprivate Logger logger = Logger.getLogger(AcceptanceTestContext.class.getSimpleName());\r\n\t\r\n\tpublic final static String\r\n\t PROP_SOAP_ACTION_11 = \"SOAPAction\",\r\n\t PROP_SOAP_ACTION_12 = \"action=\",\r\n\t PROP_CONTENT_TYPE = \"Content-Type\",\r\n\t PROP_CONTENT_LENGTH = \"Content-Length\",\r\n\t PROP_AUTH = \"Authorization\",\r\n\t PROP_PROXY_AUTH = \"Proxy-Authorization\",\r\n\t PROP_PROXY_CONN = \"Proxy-Connection\",\r\n\t PROP_KEEP_ALIVE = \"Keep-Alive\",\r\n\t PROP_BASIC_AUTH = \"Basic\",\r\n\t PROP_DELIMITER = \"; \";\r\n\t\r\n\tpublic final static String\r\n\t SOAP_1_1_NAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\",\r\n\t SOAP_1_2_NAMESPACE = \"http://www.w3.org/2003/05/soap-envelope\";\r\n\t\r\n\tpublic final static String\r\n\t MIMETYPE_TEXT_HTML = \"text/html\",\r\n\t MIMETYPE_TEXT_PLAIN = \"text/plain\",\r\n\t MIMETYPE_TEXT_XML = \"text/xml\",\r\n\t MIMETYPE_APPLICATION_XML = \"application/soap+xml\";\r\n\t\r\n\tpublic static final String GATF_SERVER_LOGS_API_FILE_NM = \"gatf-logging-api-int.xml\";\r\n\t\r\n\tprivate final Map<String, List<TestCase>> relatedTestCases = new HashMap<String, List<TestCase>>();\r\n\t\r\n\tprivate final Map<String, String> httpHeaders = new HashMap<String, String>();\r\n\r\n\tprivate ConcurrentHashMap<Integer, String> sessionIdentifiers = new ConcurrentHashMap<Integer, String>();\r\n\t\r\n\tprivate final Map<String, String> soapEndpoints = new HashMap<String, String>();\r\n\t\r\n\tprivate final Map<String, Document> soapMessages = new HashMap<String, Document>();\r\n\t\r\n\tprivate final Map<String, String> soapStrMessages = new HashMap<String, String>();\r\n\t\r\n\tprivate final Map<String, String> soapActions = new HashMap<String, String>();\r\n\t\r\n\tprivate final WorkflowContextHandler workflowContextHandler = new WorkflowContextHandler();\r\n\t\r\n\tprivate List<TestCase> serverLogsApiLst = new ArrayList<TestCase>();\r\n\t\r\n\tprivate GatfExecutorConfig gatfExecutorConfig;\r\n\t\r\n\tprivate ClassLoader projectClassLoader;\r\n\t\r\n\tprivate Map<String, Method> prePostTestCaseExecHooks = new HashMap<String, Method>();\r\n\t\r\n\tpublic static final UrlValidator URL_VALIDATOR = new UrlValidator(new String[]{\"http\",\"https\"}, UrlValidator.ALLOW_LOCAL_URLS);\r\n\t\r\n\tpublic static boolean isValidUrl(String url) {\r\n\t\tif(!URL_VALIDATOR.isValid(url)) {\r\n\t\t\tif(url.startsWith(\"host.docker.internal\")) {\r\n\t\t\t\turl = url.replace(\"host.docker.internal\", \"\");\r\n\t\t\t\tif(url.length()>0 && url.charAt(0)==':') {\r\n\t\t\t\t\turl = url.substring(1);\r\n\t\t\t\t}\r\n\t\t\t\tif(url.indexOf(\"/\")!=-1) {\r\n\t\t\t\t\turl = url.substring(0, url.indexOf(\"/\"));\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\tInteger.parseInt(url);\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic static void setCorsHeaders(Response response) {\r\n\t\tif(Boolean.FALSE.toString().equalsIgnoreCase(System.getenv(\"cors.enabled\")) || Boolean.FALSE.toString().equalsIgnoreCase(System.getProperty(\"cors.enabled\"))) {\r\n\t\t} else {\r\n\t\t\tresponse.setHeader(\"Access-Control-Allow-Origin\", \"*\");\r\n\t\t\tresponse.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, PUT\");\r\n\t\t\tresponse.setHeader(\"Access-Control-Allow-Headers\", \"*\");\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic ClassLoader getProjectClassLoader() {\r\n\t\treturn projectClassLoader;\r\n\t}\r\n\r\n\tprivate final Map<String, List<Map<String, String>>> providerTestDataMap = new HashMap<String, List<Map<String,String>>>();\r\n\tprivate final Map<String, String> fileProviderStateMap = new HashMap<String, String>();\r\n\t\r\n\tpublic List<Map<String, String>> getProviderTestDataMap(String providerName) {\r\n\t if(liveProviders.containsKey(providerName))\r\n {\r\n GatfTestDataProvider provider = liveProviders.get(providerName);\r\n return getProviderData(provider, null);\r\n }\r\n\t else \r\n\t {\r\n\t return providerTestDataMap.get(providerName);\r\n\t }\r\n\t}\r\n\t\r\n\tpublic String getFileProviderHash(String name) {\r\n\t if(!fileProviderStateMap.containsKey(name)) {\r\n\t return fileProviderStateMap.get(name);\r\n\t }\r\n\t return null;\r\n\t}\r\n\t\r\n\tpublic void newProvider(String name) {\r\n\t if(!providerTestDataMap.containsKey(name)) {\r\n\t providerTestDataMap.put(name, new ArrayList<Map<String,String>>());\r\n\t }\r\n\t}\r\n\t\r\n\tprivate final Map<String, TestDataSource> dataSourceMap = new HashMap<String, TestDataSource>();\r\n\t\r\n\tprivate final Map<String, TestDataSource> dataSourceMapForProfiling = new HashMap<String, TestDataSource>();\r\n\t\r\n\tprivate final Map<String, GatfTestDataSourceHook> dataSourceHooksMap = new HashMap<String, GatfTestDataSourceHook>();\r\n\r\n\tprivate final SingleTestCaseExecutor singleTestCaseExecutor = new SingleTestCaseExecutor();\r\n\t\r\n\tprivate final ScenarioTestCaseExecutor scenarioTestCaseExecutor = new ScenarioTestCaseExecutor();\r\n\t\r\n\tprivate final PerformanceTestCaseExecutor performanceTestCaseExecutor = new PerformanceTestCaseExecutor();\r\n\t\r\n\tprivate final Map<String, GatfTestDataProvider> liveProviders = new HashMap<String, GatfTestDataProvider>();\r\n\r\n\tpublic SingleTestCaseExecutor getSingleTestCaseExecutor() {\r\n\t\treturn singleTestCaseExecutor;\r\n\t}\r\n\r\n\tpublic ScenarioTestCaseExecutor getScenarioTestCaseExecutor() {\r\n\t\treturn scenarioTestCaseExecutor;\r\n\t}\r\n\r\n\tpublic PerformanceTestCaseExecutor getPerformanceTestCaseExecutor() {\r\n\t\treturn performanceTestCaseExecutor;\r\n\t}\r\n\r\n\tpublic AcceptanceTestContext(){}\r\n\t\r\n\tpublic AcceptanceTestContext(GatfExecutorConfig gatfExecutorConfig, ClassLoader projectClassLoader)\r\n\t{\r\n\t\tthis.gatfExecutorConfig = gatfExecutorConfig;\r\n\t\tthis.projectClassLoader = projectClassLoader;\r\n\t\tgetWorkflowContextHandler().init();\r\n\t}\r\n\t\r\n\tpublic AcceptanceTestContext(DistributedAcceptanceContext dContext, ClassLoader projectClassLoader)\r\n\t{\r\n this.projectClassLoader = projectClassLoader;\r\n\t\tthis.gatfExecutorConfig = dContext.getConfig();\r\n\t\tthis.httpHeaders.putAll(dContext.getHttpHeaders());\r\n\t\tthis.soapEndpoints.putAll(dContext.getSoapEndpoints());\r\n\t\tthis.soapActions.putAll(dContext.getSoapActions());\r\n\t\ttry {\r\n\t\t\tif(dContext.getSoapMessages()!=null) {\r\n\t\t\t\tDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n\t\t\t\tDocumentBuilder db = dbf.newDocumentBuilder();\r\n\t\t\t\tfor (Map.Entry<String, String> soapMsg : dContext.getSoapMessages().entrySet()) {\r\n\t\t\t\t\tDocument soapMessage = db.parse(new ByteArrayInputStream(soapMsg.getValue().getBytes()));\r\n\t\t\t\t\tthis.soapMessages.put(soapMsg.getKey(), soapMessage);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\t// TODO: handle exception\r\n\t\t}\r\n\t\tgetWorkflowContextHandler().init();\r\n\t}\r\n\t\r\n\tpublic GatfExecutorConfig getGatfExecutorConfig() {\r\n\t\treturn gatfExecutorConfig;\r\n\t}\r\n\r\n\tpublic void setGatfExecutorConfig(GatfExecutorConfig gatfExecutorConfig) {\r\n\t\tthis.gatfExecutorConfig = gatfExecutorConfig;\r\n\t}\r\n\r\n\tpublic ConcurrentHashMap<Integer, String> getSessionIdentifiers() {\r\n\t\treturn sessionIdentifiers;\r\n\t}\r\n\r\n\tpublic void setSessionIdentifiers(\r\n\t\t\tConcurrentHashMap<Integer, String> sessionIdentifiers) {\r\n\t\tthis.sessionIdentifiers = sessionIdentifiers;\r\n\t}\r\n\r\n\tpublic void setSessionIdentifier(String identifier, TestCase testCase) {\r\n\t\tInteger simulationNumber = testCase.getSimulationNumber();\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\tsimulationNumber = -1;\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\tsimulationNumber = -2;\r\n\t\t} else if(simulationNumber==null) {\r\n\t\t\tsimulationNumber = 0;\r\n\t\t}\r\n\t\tsessionIdentifiers.put(simulationNumber, identifier);\r\n\t}\r\n\t\r\n\tpublic String getSessionIdentifier(TestCase testCase) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn sessionIdentifiers.get(-1);\r\n\t\t}\r\n\t\tif(testCase.isExternalApi()) {\r\n\t\t\treturn sessionIdentifiers.get(-2);\r\n\t\t}\r\n\t\tif(testCase.getSimulationNumber()!=null)\r\n\t\t\treturn sessionIdentifiers.get(testCase.getSimulationNumber());\r\n\t\t\r\n\t\treturn sessionIdentifiers.get(0);\r\n\t}\r\n\t\r\n\tpublic Map<String, String> getHttpHeaders() {\r\n\t\treturn httpHeaders;\r\n\t}\r\n\r\n\tpublic Map<String, String> getSoapEndpoints() {\r\n\t\treturn soapEndpoints;\r\n\t}\r\n\r\n\tpublic Map<String, Document> getSoapMessages() {\r\n\t\treturn soapMessages;\r\n\t}\r\n\r\n\tpublic Map<String, String> getSoapActions() {\r\n\t\treturn soapActions;\r\n\t}\r\n\r\n\tpublic WorkflowContextHandler getWorkflowContextHandler() {\r\n\t\treturn workflowContextHandler;\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"rawtypes\")\r\n\tpublic Class addTestCaseHooks(Method method) {\r\n\t\tClass claz = null;\r\n\t\tif(method!=null && Modifier.isStatic(method.getModifiers())) {\r\n\t\t\t\r\n\t\t\tAnnotation preHook = method.getAnnotation(PreTestCaseExecutionHook.class);\r\n Annotation postHook = method.getAnnotation(PostTestCaseExecutionHook.class);\r\n\t\t\t\r\n\t\t\tif(preHook!=null)\r\n\t\t\t{\r\n\t\t\t\tPreTestCaseExecutionHook hook = (PreTestCaseExecutionHook)preHook;\r\n\t\t\t\t\r\n\t\t\t\tif(method.getParameterTypes().length!=1 || !method.getParameterTypes()[0].equals(TestCase.class))\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.severe(\"PreTestCaseExecutionHook annotated methods should \" +\r\n\t\t\t\t\t\t\t\"confirm to the method signature - `public static void {methodName} (\" +\r\n\t\t\t\t\t\t\t\"TestCase testCase)`\");\r\n\t\t\t\t\treturn claz;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(hook.value()!=null && hook.value().length>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (String testCaseName : hook.value()) {\r\n\t\t\t\t\t\tif(testCaseName!=null && !testCaseName.trim().isEmpty()) {\r\n\t\t\t\t\t\t\tprePostTestCaseExecHooks.put(\"pre\"+testCaseName, method);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tprePostTestCaseExecHooks.put(\"preAll\", method);\r\n\t\t\t\t}\r\n\t\t\t\tclaz = method.getDeclaringClass();\r\n\t\t\t}\r\n\t\t\tif(postHook!=null)\r\n\t\t\t{\r\n\t\t\t\tPostTestCaseExecutionHook hook = (PostTestCaseExecutionHook)postHook;\r\n\t\t\t\t\r\n\t\t\t\tif(method.getParameterTypes().length!=1 || !method.getParameterTypes()[0].equals(TestCaseReport.class))\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.severe(\"PostTestCaseExecutionHook annotated methods should \" +\r\n\t\t\t\t\t\t\t\"confirm to the method signature - `public static void {methodName} (\" +\r\n\t\t\t\t\t\t\t\"TestCaseReport testCaseReport)`\");\r\n\t\t\t\t\treturn claz;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(hook.value()!=null && hook.value().length>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (String testCaseName : hook.value()) {\r\n\t\t\t\t\t\tif(testCaseName!=null && !testCaseName.trim().isEmpty()) {\r\n\t\t\t\t\t\t\tprePostTestCaseExecHooks.put(\"post\"+testCaseName, method);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tprePostTestCaseExecHooks.put(\"postAll\", method);\r\n\t\t\t\t}\r\n\t\t\t\tclaz = method.getDeclaringClass();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn claz;\r\n\t}\r\n\t\r\n\tpublic List<Method> getPrePostHook(TestCase testCase, boolean isPreHook) {\r\n\t\tList<Method> methods = new ArrayList<Method>();\r\n\t\tString hookKey = (isPreHook?\"pre\":\"post\") + testCase.getName();\r\n\t\tMethod meth = prePostTestCaseExecHooks.get(hookKey);\r\n\t\tif(meth!=null)\r\n\t\t\tmethods.add(meth);\r\n\t\tmeth = prePostTestCaseExecHooks.get((isPreHook?\"preAll\":\"postAll\"));\r\n\t\tif(meth!=null)\r\n\t\t\tmethods.add(meth);\r\n\t\treturn methods;\r\n\t}\r\n\t\r\n\tpublic File getResourceFile(String filename) {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getTestCasesBasePath());\r\n\t File testPath = new File(basePath, gatfExecutorConfig.getTestCaseDir());\r\n\t File resource = new File(testPath, filename);\r\n if(!resource.exists()) {\r\n resource = new File(basePath, filename);\r\n }\r\n\t\treturn resource;\r\n\t}\r\n\t\r\n\tpublic File getNewOutResourceFile(String filename) {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath());\r\n\t\tFile resource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\tFile file = new File(resource, filename);\r\n\t\tif(!file.exists()) {\r\n\t\t\ttry {\r\n\t\t\t\tfile.createNewFile();\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn file;\r\n\t}\r\n\t\r\n\tpublic File getOutDir() {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath());\r\n\t\tFile resource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\treturn resource;\r\n\t}\r\n\t\r\n\tpublic String getOutDirPath() {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath());\r\n\t\tFile resource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\treturn resource.getAbsolutePath();\r\n\t}\r\n\t\r\n\tpublic Map<String, List<TestCase>> getRelatedTestCases() {\r\n\t\treturn relatedTestCases;\r\n\t}\r\n\r\n\tpublic static void removeFolder(File folder)\r\n\t{\r\n\t\tif(folder==null || !folder.exists())return;\r\n\t\ttry {\r\n\t\t\tFileUtils.deleteDirectory(folder);\r\n\t\t} catch (IOException e) {\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void validateAndInit(boolean flag) throws Exception\r\n\t{\r\n\t\tgatfExecutorConfig.validate();\r\n\t\t\r\n\t\tif(gatfExecutorConfig.getOutFilesBasePath()!=null)\r\n\t\t{\r\n\t\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath().trim());\r\n\t\t\tAssert.assertTrue(\"Invalid out files base path..\", basePath.exists());\r\n\t\t\tgatfExecutorConfig.setOutFilesBasePath(basePath.getAbsolutePath());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tFile basePath = new File(System.getProperty(\"user.dir\"));\r\n\t\t\tgatfExecutorConfig.setOutFilesBasePath(basePath.getAbsolutePath());\r\n\t\t}\r\n\t\t\r\n\t\tif(gatfExecutorConfig.getTestCasesBasePath()!=null)\r\n\t\t{\r\n\t\t\tFile basePath = new File(gatfExecutorConfig.getTestCasesBasePath());\r\n\t\t\tAssert.assertTrue(\"Invalid test cases base path..\", basePath.exists());\r\n\t\t\tgatfExecutorConfig.setTestCasesBasePath(basePath.getAbsolutePath());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tFile basePath = new File(System.getProperty(\"user.dir\"));\r\n\t\t\tgatfExecutorConfig.setTestCasesBasePath(basePath.getAbsolutePath());\r\n\t\t}\r\n\t\t\r\n\t\tAssert.assertEquals(\"Testcase directory not found...\", getResourceFile(gatfExecutorConfig.getTestCaseDir()).exists(), true);\r\n\t\t\r\n\t\tif(StringUtils.isNotBlank(gatfExecutorConfig.getBaseUrl()))\r\n\t\t{\r\n\t\t\tAssert.assertTrue(\"Base URL is not valid\", AcceptanceTestContext.isValidUrl(gatfExecutorConfig.getBaseUrl()));\r\n\t\t}\r\n\t\t\r\n\t\tif(gatfExecutorConfig.getOutFilesDir()!=null && !gatfExecutorConfig.getOutFilesDir().trim().isEmpty())\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tif(gatfExecutorConfig.getOutFilesBasePath()!=null)\r\n\t\t\t\t{\r\n\t\t\t\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath());\r\n\t\t\t\t\tFile resource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\t\t\t\tif(flag)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tremoveFolder(resource);\r\n\t\t\t\t\t\tFile nresource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\t\t\t\t\tnresource.mkdirs();\r\n\t\t\t\t\t\tAssert.assertTrue(\"Out files directory could not be created...\", nresource.exists());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tFile resource = new File(System.getProperty(\"user.dir\"));\r\n\t\t\t\t\tFile file = new File(resource, gatfExecutorConfig.getOutFilesDir());\r\n\t\t\t\t\tif(flag)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tremoveFolder(file);\r\n\t\t\t\t\t\tFile nresource = new File(resource, gatfExecutorConfig.getOutFilesDir());\r\n\t\t\t\t\t\tnresource.mkdir();\r\n\t\t\t\t\t\tAssert.assertTrue(\"Out files directory could not be created...\", nresource.exists());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tgatfExecutorConfig.setOutFilesDir(null);\r\n\t\t\t}\r\n\t\t\tAssert.assertNotNull(\"Testcase out file directory not found...\", gatfExecutorConfig.getOutFilesDir());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tFile resource = new File(System.getProperty(\"user.dir\"));\r\n\t\t\tif(flag)\r\n\t\t\t{\r\n\t\t\t\tremoveFolder(resource);\r\n\t\t\t\tFile nresource = new File(System.getProperty(\"user.dir\"), \"out\");\r\n\t\t\t\tnresource.mkdir();\r\n\t\t\t}\r\n\t\t\tgatfExecutorConfig.setOutFilesDir(\"out\");\r\n\t\t\tgatfExecutorConfig.setOutFilesBasePath(System.getProperty(\"user.dir\"));\r\n\t\t}\r\n\t\t\r\n\t\tif(flag)\r\n\t\t{\r\n\t\t\tinitSoapContextAndHttpHeaders();\r\n\t\t\t\r\n\t\t\tinitTestDataProviderAndGlobalVariables();\r\n\t\t}\r\n\t\t\r\n\t\tinitServerLogsApis();\r\n\t}\r\n\t\r\n\tpublic void initServerLogsApis() throws Exception {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getTestCasesBasePath());\r\n\t\tFile resource = new File(basePath, GATF_SERVER_LOGS_API_FILE_NM);\r\n\t\tif(resource.exists() && gatfExecutorConfig.isFetchFailureLogs()) {\r\n\t\t\tTestCaseFinder finder = new XMLTestCaseFinder();\r\n\t\t\tserverLogsApiLst.clear();\r\n\t\t\tserverLogsApiLst.addAll(finder.resolveTestCases(resource));\r\n\t\t\tfor (TestCase testCase : serverLogsApiLst) {\r\n\t\t\t\ttestCase.setSourcefileName(GATF_SERVER_LOGS_API_FILE_NM);\r\n\t\t\t\tif(testCase.getSimulationNumber()==null)\r\n\t\t\t\t{\r\n\t\t\t\t\ttestCase.setSimulationNumber(0);\r\n\t\t\t\t}\r\n\t\t\t\ttestCase.setExternalApi(true);\r\n\t\t\t\ttestCase.validate(getHttpHeaders(), null);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void initTestDataProviderAndGlobalVariables() throws Exception {\r\n\t\tGatfTestDataConfig gatfTestDataConfig = null;\r\n\t\tif(gatfExecutorConfig.getTestDataConfigFile()!=null) {\r\n\t\t\tFile file = getResourceFile(gatfExecutorConfig.getTestDataConfigFile());\r\n\t\t\tAssert.assertNotNull(\"Testdata configuration file not found...\", file);\r\n\t\t\tAssert.assertEquals(\"Testdata configuration file not found...\", file.exists(), true);\r\n\t\t\t\r\n\t\t\tif(gatfExecutorConfig.getTestDataConfigFile().trim().endsWith(\".xml\")) {\r\n\t\t\t\tXStream xstream = new XStream(new DomDriver(\"UTF-8\"));\r\n\t\t \r\n\t\t xstream.allowTypes(new Class[]{GatfTestDataConfig.class, GatfTestDataProvider.class});\r\n\t\t\t\txstream.processAnnotations(new Class[]{GatfTestDataConfig.class, GatfTestDataProvider.class});\r\n\t\t\t\txstream.alias(\"gatf-testdata-provider\", GatfTestDataProvider.class);\r\n\t\t\t\txstream.alias(\"args\", String[].class);\r\n\t\t\t\txstream.alias(\"arg\", String.class);\r\n\t\t\t\tgatfTestDataConfig = (GatfTestDataConfig)xstream.fromXML(file);\r\n\t\t\t} else {\r\n\t\t\t\tgatfTestDataConfig = WorkflowContextHandler.OM.readValue(file, GatfTestDataConfig.class);\r\n\t\t\t}\r\n\t\t\tgatfExecutorConfig.setGatfTestDataConfig(gatfTestDataConfig);\r\n\t\t} else {\r\n\t\t\tgatfTestDataConfig = gatfExecutorConfig.getGatfTestDataConfig();\r\n\t\t}\r\n\t\t\r\n\t\thandleTestDataSourcesAndHooks(gatfTestDataConfig);\r\n\t}\r\n\r\n\tpublic void handleTestDataSourcesAndHooks(GatfTestDataConfig gatfTestDataConfig) {\r\n\t\tif(gatfTestDataConfig!=null) {\r\n\t\t\tgetWorkflowContextHandler().addGlobalVariables(gatfTestDataConfig.getGlobalVariables());\r\n\t\t\t\r\n\t\t\tif(gatfTestDataConfig.getDataSourceList()!=null)\r\n\t\t\t{\r\n\t\t\t\thandleDataSources(gatfTestDataConfig.getDataSourceList(), false);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(gatfTestDataConfig.getDataSourceListForProfiling()!=null)\r\n\t\t\t{\r\n\t\t\t\thandleDataSources(gatfTestDataConfig.getDataSourceListForProfiling(), true);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(gatfTestDataConfig.getDataSourceHooks()!=null)\r\n\t\t\t{\r\n\t\t\t\thandleHooks(gatfTestDataConfig.getDataSourceHooks());\r\n\t\t\t}\r\n\t\t\t\t\r\n\t\t\tif(gatfTestDataConfig.getProviderTestDataList()!=null)\r\n\t\t\t{\r\n\t\t\t\thandleProviders(gatfTestDataConfig.getProviderTestDataList());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static Map<String, String> getHttpHeadersMap() throws Exception\r\n\t{\r\n\t\tMap<String, String> headers = new HashMap<String, String>();\r\n\t\tField[] declaredFields = HttpHeaders.class.getDeclaredFields();\r\n\t\tfor (Field field : declaredFields) {\r\n\t\t\tif (java.lang.reflect.Modifier.isStatic(field.getModifiers())\r\n\t\t\t\t\t&& field.getType().equals(String.class)) {\r\n\t\t\t\theaders.put(field.get(null).toString().toLowerCase(), field.get(null).toString());\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn headers;\r\n\t}\r\n\t\r\n\tprivate void initSoapContextAndHttpHeaders() throws Exception\r\n\t{\r\n\t\tField[] declaredFields = HttpHeaders.class.getDeclaredFields();\r\n\t\tfor (Field field : declaredFields) {\r\n\t\t\tif (java.lang.reflect.Modifier.isStatic(field.getModifiers())\r\n\t\t\t\t\t&& field.getType().equals(String.class)) {\r\n\t\t\t\thttpHeaders.put(field.get(null).toString().toLowerCase(), field.get(null).toString());\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tFile file = null;\r\n\t\tif(gatfExecutorConfig.getWsdlLocFile()!=null && !gatfExecutorConfig.getWsdlLocFile().trim().isEmpty())\r\n\t\t\tfile = getResourceFile(gatfExecutorConfig.getWsdlLocFile());\r\n\t\t\r\n\t\tif(file!=null)\r\n\t\t{\r\n\t\t\tScanner s = new Scanner(file);\r\n\t\t\ts.useDelimiter(\"\\n\");\r\n\t\t\tList<String> list = new ArrayList<String>();\r\n\t\t\twhile (s.hasNext()) {\r\n\t\t\t\tlist.add(s.next().replace(\"\\r\", \"\"));\r\n\t\t\t}\r\n\t\t\ts.close();\r\n\t\r\n\t\t\tfor (String wsdlLoc : list) {\r\n\t\t\t\tif(!wsdlLoc.trim().isEmpty())\r\n\t\t\t\t{\r\n\t\t\t\t\tString[] wsdlLocParts = wsdlLoc.split(\",\");\r\n\t\t\t\t\tlogger.info(\"Started Parsing WSDL location - \" + wsdlLocParts[1]);\r\n\t\t\t\t\tWsdl wsdl = Wsdl.parse(wsdlLocParts[1]);\r\n\t\t\t\t\tfor (QName bindingName : wsdl.getBindings()) {\r\n\t\t\t\t\t\tSoapBuilder builder = wsdl.getBuilder(bindingName);\r\n\t\t\t\t\t\tfor (SoapOperation operation : builder.getOperations()) {\r\n\t\t\t\t\t\t\tString request = builder.buildInputMessage(operation);\r\n\t\t\t\t\t\t\tDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n\t\t\t\t\t\t\tDocumentBuilder db = dbf.newDocumentBuilder();\r\n\t\t\t\t\t\t\tDocument soapMessage = db.parse(new ByteArrayInputStream(request.getBytes()));\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif(gatfExecutorConfig.isDistributedLoadTests()) {\r\n\t\t\t\t\t\t\t\tsoapStrMessages.put(wsdlLocParts[0]+operation.getOperationName(), request);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tsoapMessages.put(wsdlLocParts[0]+operation.getOperationName(), soapMessage);\r\n\t\t\t\t\t\t\tif(operation.getSoapAction()!=null) {\r\n\t\t\t\t\t\t\t\tsoapActions.put(wsdlLocParts[0]+operation.getOperationName(), operation.getSoapAction());\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tlogger.info(\"Adding message for SOAP operation - \" + operation.getOperationName());\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tsoapEndpoints.put(wsdlLocParts[0], builder.getServiceUrls().get(0));\r\n\t\t\t\t\t\tlogger.info(\"Adding SOAP Service endpoint - \" + builder.getServiceUrls().get(0));\r\n\t\t\t\t\t}\r\n\t\t\t\t\tlogger.info(\"Done Parsing WSDL location - \" + wsdlLocParts[1]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void shutdown() {\r\n\t\tfor (GatfTestDataSourceHook dataSourceHook : dataSourceHooksMap.values()) {\r\n\t\t\tTestDataSource dataSource = dataSourceMap.get(dataSourceHook.getDataSourceName());\r\n\t\t\t\r\n\t\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\t\r\n\t\t\tif(dataSourceHook.isExecuteOnShutdown() && dataSourceHook.getQueryStrs()!=null) {\r\n\t\t\t\tfor (String query : dataSourceHook.getQueryStrs()) {\r\n\t\t\t\t\tboolean flag = false;\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tflag = dataSource.execute(query);\r\n\t\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(!flag) {\r\n\t\t\t\t\t\tlogger.severe(\"Shutdown DataSourceHook execution for \" + dataSourceHook.getHookName()\r\n\t\t\t\t\t\t\t\t+ \" failed, queryString = \" + query);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor (GatfTestDataSourceHook dataSourceHook : dataSourceHooksMap.values()) {\r\n\t\t\tTestDataSource dataSource = dataSourceMap.get(dataSourceHook.getDataSourceName());\r\n\t\t\t\r\n\t\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\t\r\n\t\t\tdataSource.destroy();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void executeDataSourceHook(String hookName) {\r\n\t\tGatfTestDataSourceHook dataSourceHook = dataSourceHooksMap.get(hookName);\r\n\t\tAssert.assertNotNull(\"No DataSourceHook found\", dataSourceHook);\r\n\t\t\r\n\t\tTestDataSource dataSource = dataSourceMap.get(dataSourceHook.getDataSourceName());\r\n\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\r\n\t\tfor (String query : dataSourceHook.getQueryStrs()) {\r\n\t\t\tboolean flag = dataSource.execute(query);\r\n\t\t\tif(!flag) {\r\n\t\t\t\tAssert.assertNotNull(\"DataSourceHook execution for \" + dataSourceHook.getHookName()\r\n\t\t\t\t\t\t+ \" failed...\", null);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"rawtypes\")\r\n\tprivate void handleDataSources(List<GatfTestDataSource> dataSourceList, boolean forProfiling)\r\n\t{\r\n\t\tfor (GatfTestDataSource dataSource : dataSourceList) {\r\n\t\t\tAssert.assertNotNull(\"DataSource name is not defined\", dataSource.getDataSourceName());\r\n\t\t\tAssert.assertNotNull(\"DataSource class is not defined\", dataSource.getDataSourceClass());\r\n\t\t\tAssert.assertNotNull(\"DataSource args not defined\", dataSource.getArgs());\r\n\t\t\tAssert.assertTrue(\"DataSource args empty\", dataSource.getArgs().length>0);\r\n\t\t\tAssert.assertNull(\"Duplicate DataSource name found\", dataSourceMap.get(dataSource.getDataSourceName()));\r\n\t\t\t\r\n\t\t\tTestDataSource testDataSource = null;\r\n\t\t\tif(SQLDatabaseTestDataSource.class.getCanonicalName().equals(dataSource.getDataSourceClass())) {\r\n\t\t\t\ttestDataSource = new SQLDatabaseTestDataSource();\r\n\t\t\t} else if(MongoDBTestDataSource.class.getCanonicalName().equals(dataSource.getDataSourceClass())) {\r\n\t\t\t\ttestDataSource = new MongoDBTestDataSource();\r\n\t\t\t} else {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass claz = loadCustomClass(dataSource.getDataSourceClass());\r\n\t\t\t\t\tClass[] classes = claz.getInterfaces();\r\n\t\t\t\t\tboolean validProvider = false;\r\n\t\t\t\t\tif(classes!=null) {\r\n\t\t\t\t\t\tfor (Class class1 : classes) {\r\n\t\t\t\t\t\t\tif(class1.equals(TestDataSource.class)) {\r\n\t\t\t\t\t\t\t\tvalidProvider = true;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tAssert.assertTrue(\"DataSource class should extend the TestDataSource class\", validProvider);\r\n\t\t\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\t\t\tObject providerInstance = claz.getDeclaredConstructor().newInstance();\r\n\t\t\t\t\ttestDataSource = (TestDataSource)providerInstance;\r\n\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tthrow new AssertionError(e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ttestDataSource.setClassName(dataSource.getDataSourceClass());\r\n\t\t\ttestDataSource.setArgs(dataSource.getArgs());\r\n\t\t\ttestDataSource.setContext(this);\r\n\t\t\ttestDataSource.setDataSourceName(dataSource.getDataSourceName());\r\n\t\t\tif(dataSource.getPoolSize()>1)\r\n\t\t\t{\r\n\t\t\t\ttestDataSource.setPoolSize(dataSource.getPoolSize());\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(forProfiling)\r\n\t\t\t{\r\n\t\t\t\ttestDataSource.setPoolSize(1);\r\n\t\t\t\ttestDataSource.init();\r\n\t\t\t\tdataSourceMapForProfiling.put(dataSource.getDataSourceName(), testDataSource);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttestDataSource.init();\r\n\t\t\t\tdataSourceMap.put(dataSource.getDataSourceName(), testDataSource);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Map<String, TestDataSource> getDataSourceMapForProfiling()\r\n\t{\r\n\t\treturn dataSourceMapForProfiling;\r\n\t}\r\n\t\r\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\r\n\tprivate void handleHooks(List<GatfTestDataSourceHook> dataSourceHooks)\r\n\t{\r\n\t\tfor (GatfTestDataSourceHook dataSourceHook : dataSourceHooks) {\r\n\t\t\tAssert.assertNotNull(\"DataSourceHook name is not defined\", dataSourceHook.getHookName());\r\n\t\t\tAssert.assertNotNull(\"DataSourceHook query string is not defined\", dataSourceHook.getQueryStrs());\r\n\t\t\tAssert.assertNull(\"Duplicate DataSourceHook name found\", dataSourceHooksMap.get(dataSourceHook.getHookName()));\r\n\t\t\t\r\n\t\t\tTestDataSource dataSource = null;\r\n\t\t\tif(dataSourceHook.getDataSourceName()!=null && dataSourceHook.getHookClass()==null)\r\n\t\t\t{\r\n\t\t\t\tdataSource = dataSourceMap.get(dataSourceHook.getDataSourceName());\r\n\t\t\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\t}\r\n\t\t\telse if(dataSourceHook.getDataSourceName()!=null && dataSourceHook.getHookClass()!=null)\r\n\t\t\t{\r\n\t\t\t\tAssert.assertNotNull(\"Specify either hookClass or dataSourceName\", null);\r\n\t\t\t}\r\n\t\t\telse if(dataSourceHook.getDataSourceName()==null && dataSourceHook.getHookClass()==null)\r\n\t\t\t{\r\n\t\t\t\tAssert.assertNotNull(\"Specify any one of hookClass or dataSourceName\", null);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tdataSourceHooksMap.put(dataSourceHook.getHookName(), dataSourceHook);\r\n\t\t\t\r\n\t\t\tTestDataHook testDataHook = null;\r\n\t\t\tif(dataSourceHook.getHookClass()!=null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass claz = loadCustomClass(dataSourceHook.getHookClass());\r\n\t\t\t\t\tClass[] classes = claz.getInterfaces();\r\n\t\t\t\t\tboolean validProvider = false;\r\n\t\t\t\t\tif(classes!=null) {\r\n\t\t\t\t\t\tfor (Class class1 : classes) {\r\n\t\t\t\t\t\t\tif(class1.equals(TestDataProvider.class)) {\r\n\t\t\t\t\t\t\t\tvalidProvider = true;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tAssert.assertTrue(\"Hook class should implement the TestDataHook class\", validProvider);\r\n\t\t\t\t\tObject providerInstance = claz.getDeclaredConstructor().newInstance();\r\n\t\t\t\t\ttestDataHook = (TestDataHook)providerInstance;\r\n\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tthrow new AssertionError(e);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\ttestDataHook = dataSource;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(dataSourceHook.isExecuteOnStart()) {\r\n\t\t\t\tfor (String query : dataSourceHook.getQueryStrs()) {\r\n\t\t\t\t\tboolean flag = false;\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tflag = testDataHook.execute(query);\r\n\t\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(!flag) {\r\n\t\t\t\t\t\tlogger.severe(\"Startup DataSourceHook execution for \" + dataSourceHook.getHookName()\r\n\t\t\t\t\t\t\t\t+ \" failed, queryString = \" + query);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void handleProviders(List<GatfTestDataProvider> providerTestDataList)\r\n\t{\r\n\t\tfor (GatfTestDataProvider provider : providerTestDataList) {\r\n\t\t\tAssert.assertNotNull(\"Provider name is not defined\", provider.getProviderName());\r\n\t\t\t\r\n\t\t\tAssert.assertNotNull(\"Provider properties is not defined\", provider.getProviderProperties());\r\n\t\t\t\r\n\t\t\tAssert.assertNull(\"Duplicate Provider name found\", providerTestDataMap.get(provider.getProviderName()));\r\n\t\t\t\r\n\t\t\tTestDataSource dataSource = null;\r\n\t\t\tif(provider.getDataSourceName()!=null && provider.getProviderClass()==null)\r\n\t\t\t{\t\r\n\t\t\t\tAssert.assertNotNull(\"Provider DataSource name is not defined\", provider.getDataSourceName());\r\n\t\t\t\tdataSource = dataSourceMap.get(provider.getDataSourceName());\r\n\t\t\t\t\r\n\t\t\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\t\t\r\n\t\t\t\tif(dataSource instanceof MongoDBTestDataSource)\r\n\t\t\t\t{\r\n\t\t\t\t\tAssert.assertNotNull(\"Provider query string is not defined\", provider.getQueryStr());\r\n\t\t\t\t\tAssert.assertNotNull(\"Provider source properties not defined\", provider.getSourceProperties());\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(dataSource instanceof SQLDatabaseTestDataSource)\r\n\t\t\t\t{\r\n\t\t\t\t\tAssert.assertNotNull(\"Provider query string is not defined\", provider.getQueryStr());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if(provider.getDataSourceName()!=null && provider.getProviderClass()!=null)\r\n\t\t\t{\r\n\t\t\t\tAssert.assertNotNull(\"Specify either providerClass or dataSourceName\", null);\r\n\t\t\t}\r\n\t\t\telse if(provider.getDataSourceName()==null && provider.getProviderClass()==null)\r\n\t\t\t{\r\n\t\t\t\tAssert.assertNotNull(\"Specify any one of providerClass or dataSourceName\", null);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tif(provider.isEnabled()==null) {\r\n\t\t\t\tprovider.setEnabled(true);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(!provider.isEnabled()) {\r\n\t\t\t\tlogger.info(\"Provider \" + provider.getProviderName() + \" is Disabled...\");\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(provider.isLive()) {\r\n\t\t\t\tliveProviders.put(provider.getProviderName(), provider);\r\n\t\t\t\tlogger.info(\"Provider \" + provider.getProviderName() + \" is a Live one...\");\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tList<Map<String, String>> testData = getProviderData(provider, null);\r\n\t\t\tif(gatfExecutorConfig.isSeleniumExecutor() && gatfExecutorConfig.getConcurrentUserSimulationNum()>1) {\r\n\t\t\t for (int i = 0; i < gatfExecutorConfig.getConcurrentUserSimulationNum(); i++)\r\n {\r\n\t\t\t if(FileTestDataProvider.class.getCanonicalName().equals(provider.getProviderClass().trim())) {\r\n\t\t\t if(i==0) {\r\n\t\t\t providerTestDataMap.put(provider.getProviderName()+(i+1), testData);\r\n\t\t\t continue;\r\n\t\t\t }\r\n\t\t\t GatfTestDataProvider tp = new GatfTestDataProvider(provider);\r\n\t tp.setProviderName(provider.getProviderName()+(i+1));\r\n\t tp.getArgs()[0] = tp.getArgs()[0] + i;\r\n\t try {\r\n\t logger.info(\"Concurrent simulation scenario #\"+(i+1)+\" fetching provider with filePath \"+tp.getArgs()[0]);\r\n\t List<Map<String, String>> testDataT = getProviderData(tp, null);\r\n\t if(testDataT==null) {\r\n\t testDataT = testData;\r\n\t }\r\n\t providerTestDataMap.put(tp.getProviderName(), testDataT);\r\n\t } catch (Throwable e) {\r\n\t logger.severe(\"Cannot find data provider for the concurrent simulation scenario #\"+(i+1)+\" with name \" + tp.getProviderName());\r\n\t providerTestDataMap.put(tp.getProviderName(), testData);\r\n\t }\r\n\t\t\t } else {\r\n\t\t\t logger.severe(\"Concurrent simulation scenarios need file data providers\");\r\n\t\t\t }\r\n }\r\n\t\t\t} else {\r\n\t\t\t providerTestDataMap.put(provider.getProviderName(), testData);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic List<Map<String, String>> getLiveProviderData(String provName, TestCase testCase)\r\n\t{\r\n\t\tGatfTestDataProvider provider = liveProviders.get(provName);\r\n\t\treturn getProviderData(provider, testCase);\r\n\t}\r\n\t\r\n\tpublic List<Map<String, String>> getAnyProviderData(String provName, TestCase testCase)\r\n\t{\r\n\t\tif(liveProviders.containsKey(provName))\r\n\t\t{\r\n\t\t\tGatfTestDataProvider provider = liveProviders.get(provName);\r\n\t\t\treturn getProviderData(provider, testCase);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn providerTestDataMap.get(provName);\r\n\t\t}\r\n\t}\r\n\t\r\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\r\n\tprivate List<Map<String, String>> getProviderData(GatfTestDataProvider provider, TestCase testCase) {\r\n\t\t\r\n\t\tTestDataSource dataSource = dataSourceMap.get(provider.getDataSourceName());\r\n\t\t\r\n\t\tTestDataProvider testDataProvider = null;\r\n\t\tList<Map<String, String>> testData = null;\r\n\t\tif(provider.getProviderClass()!=null) {\r\n\t\t\tif(FileTestDataProvider.class.getCanonicalName().equals(provider.getProviderClass().trim())) {\r\n\t\t\t\ttestDataProvider = new FileTestDataProvider();\r\n\t\t\t} else if(InlineValueTestDataProvider.class.getCanonicalName().equals(provider.getProviderClass().trim())) {\r\n\t\t\t\ttestDataProvider = new InlineValueTestDataProvider();\r\n\t\t\t} else if(RandomValueTestDataProvider.class.getCanonicalName().equals(provider.getProviderClass().trim())) {\r\n\t\t\t\ttestDataProvider = new RandomValueTestDataProvider();\r\n\t\t\t} else {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass claz = loadCustomClass(provider.getProviderClass());\r\n\t\t\t\t\tClass[] classes = claz.getInterfaces();\r\n\t\t\t\t\tboolean validProvider = false;\r\n\t\t\t\t\tif(classes!=null) {\r\n\t\t\t\t\t\tfor (Class class1 : classes) {\r\n\t\t\t\t\t\t\tif(class1.equals(TestDataProvider.class)) {\r\n\t\t\t\t\t\t\t\tvalidProvider = true;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tAssert.assertTrue(\"Provider class should implement the TestDataProvider class\", validProvider);\r\n\t\t\t\t\tObject providerInstance = claz.getDeclaredConstructor().newInstance();\r\n\t\t\t\t\ttestDataProvider = (TestDataProvider)providerInstance;\r\n\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tthrow new AssertionError(e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\ttestDataProvider = dataSource;\r\n\t\t}\r\n\t\t\r\n\t\t//Live provider queries can have templatized parameter names\r\n\t\tif(provider.isLive() && provider.getQueryStr()!=null)\r\n\t\t{\r\n\t\t\tString oQs = provider.getQueryStr();\r\n\t\t\tprovider = new GatfTestDataProvider(provider);\r\n\t\t\tif(testCase!=null)\r\n\t\t\t{\r\n\t\t\t\tprovider.setQueryStr(getWorkflowContextHandler().evaluateTemplate(testCase, provider.getQueryStr(), this));\r\n\t\t\t\tif(provider.getQueryStr()==null || provider.getQueryStr().isEmpty()) {\r\n\t\t\t\t\tprovider.setQueryStr(oQs);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\ttestData = testDataProvider.provide(provider, this);\r\n\t\tif(testDataProvider instanceof FileTestDataProvider) {\r\n\t\t\tfileProviderStateMap.put(provider.getProviderName(), ((FileTestDataProvider)testDataProvider).getHash());\r\n\t\t}\r\n\t\treturn testData;\r\n\t}\r\n\r\n\tpublic DistributedAcceptanceContext getDistributedContext(String node, List<Object[]> selTestdata)\r\n\t{\r\n\t\tDistributedAcceptanceContext distributedTestContext = new DistributedAcceptanceContext();\r\n\t\tdistributedTestContext.setConfig(gatfExecutorConfig);\r\n\t\tdistributedTestContext.setHttpHeaders(httpHeaders);\r\n\t\tdistributedTestContext.setSoapActions(soapActions);\r\n\t\tdistributedTestContext.setSoapEndpoints(soapEndpoints);\r\n\t\tdistributedTestContext.setSoapMessages(soapStrMessages);\r\n\t\tdistributedTestContext.setNode(node);\r\n\t\tdistributedTestContext.setSelTestdata(selTestdata);\r\n\t\t\r\n\t\treturn distributedTestContext;\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"rawtypes\")\r\n\tprivate Class loadCustomClass(String className) throws ClassNotFoundException\r\n\t{\r\n\t\treturn getProjectClassLoader().loadClass(className);\r\n\t}\r\n\t\r\n\tpublic List<TestCase> getServerLogsApiLst() {\r\n\t\treturn serverLogsApiLst;\r\n\t}\r\n\t\r\n\tpublic TestCase getServerLogApi(boolean isAuth)\r\n\t{\r\n\t\tif(serverLogsApiLst.size()>0)\r\n\t\t{\r\n\t\t\tfor (TestCase tc : serverLogsApiLst) {\r\n\t\t\t\tif(isAuth && gatfExecutorConfig.isServerLogsApiAuthEnabled() && \"authapi\".equals(tc.getName()))\r\n\t\t\t\t{\r\n\t\t\t\t\ttc.setServerApiAuth(true);\r\n\t\t\t\t\ttc.setExternalApi(true);\r\n\t\t\t\t\treturn tc;\r\n\t\t\t\t}\r\n\t\t\t\telse if(!isAuth && \"targetapi\".equals(tc.getName()))\r\n\t\t\t\t{\r\n\t\t\t\t\ttc.setServerApiTarget(true);\r\n\t\t\t\t\ttc.setSecure(gatfExecutorConfig.isServerLogsApiAuthEnabled());\r\n\t\t\t\t\ttc.setExternalApi(true);\r\n\t\t\t\t\treturn tc;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n}\r",
"@XStreamAlias(\"gatf-execute-config\")\r\n@JsonAutoDetect(getterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY, isGetterVisibility=Visibility.NONE)\r\n@JsonInclude(value = Include.NON_NULL)\r\npublic class GatfExecutorConfig implements Serializable, GatfPluginConfig {\r\n\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\tprivate String baseUrl;\r\n\t\r\n\tprivate String testCasesBasePath;\r\n\t\r\n\tprivate String testCaseDir;\r\n\t\r\n\tprivate String outFilesBasePath;\r\n\t\r\n\tprivate String outFilesDir;\r\n\t\r\n\tprivate boolean authEnabled;\r\n\t\r\n\tprivate String authUrl;\r\n\t\r\n\tprivate String authExtractAuth;\r\n\t\r\n\tprivate String authParamsDetails;\r\n\t\r\n\tprivate String wsdlLocFile;\r\n\t\r\n\tprivate boolean soapAuthEnabled;\r\n\t\r\n\tprivate String soapAuthWsdlKey;\r\n\t\r\n\tprivate String soapAuthOperation;\r\n\t\r\n\tprivate String soapAuthExtractAuth;\r\n\t\r\n\tprivate Integer numConcurrentExecutions;\r\n\t\r\n\tprivate boolean httpCompressionEnabled;\r\n\t\r\n\tprivate Integer httpConnectionTimeout;\r\n\t\r\n\tprivate Integer httpRequestTimeout;\r\n\t\r\n\tprivate Integer concurrentUserSimulationNum;\r\n\t\r\n\tprivate String testDataConfigFile;\r\n\t\r\n\tprivate String authDataProvider;\r\n\t\r\n\tprivate boolean compareEnabled;\r\n\t\r\n\tprivate GatfTestDataConfig gatfTestDataConfig; \r\n\t\r\n\tprivate Boolean enabled;\r\n\t\r\n\tprivate String[] testCaseHooksPaths;\r\n\t\r\n\tprivate boolean loadTestingEnabled;\r\n\t\r\n\tprivate Long loadTestingTime = 0L;\r\n\t\r\n\tprivate boolean distributedLoadTests;\r\n\t\r\n\tprivate String[] distributedNodes;\r\n\t\r\n\t@XStreamOmitField\r\n\tprivate Integer compareBaseUrlsNum;\r\n\t\r\n\tprivate Long concurrentUserRampUpTime;\r\n\t\r\n\tprivate Integer loadTestingReportSamples;\r\n\t\r\n\tprivate boolean debugEnabled;\r\n\t\r\n\tprivate String[] ignoreFiles;\r\n\t\r\n\tprivate String[] orderedFiles;\r\n\t\r\n\tprivate boolean isOrderByFileName;\r\n\t\r\n\tprivate boolean isServerLogsApiAuthEnabled;\r\n\t\r\n\tprivate String serverLogsApiAuthExtractAuth;\r\n\t\r\n\tprivate boolean isFetchFailureLogs;\r\n\t\r\n\tprivate Integer repeatSuiteExecutionNum = 0;\r\n\t\r\n\tprivate boolean isGenerateExecutionLogs = false;\r\n\t\r\n\tprivate boolean isSeleniumExecutor = false;\r\n\t\r\n\tprivate boolean isSeleniumModuleTests = false;\r\n\t\r\n\tprivate String[] seleniumScripts;\r\n\t\r\n\tprivate SeleniumDriverConfig[] seleniumDriverConfigs;\r\n\t\r\n\tprivate String seleniumLoggerPreferences;\r\n\t\r\n private String javaHome;\r\n \r\n private String javaVersion;\r\n \r\n private String gatfJarPath;\r\n \r\n private boolean selDebugger;\r\n \r\n private String wrkPath;\r\n \r\n private String wrk2Path;\r\n \r\n private String vegetaPath;\r\n \r\n private String autocannonPath;\r\n\t\r\n\tpublic String getBaseUrl() {\r\n\t\treturn baseUrl;\r\n\t}\r\n\r\n\tpublic void setBaseUrl(String baseUrl) {\r\n\t\tthis.baseUrl = baseUrl;\r\n\t}\r\n\r\n\tpublic String getTestCasesBasePath() {\r\n\t\treturn testCasesBasePath;\r\n\t}\r\n\r\n\tpublic void setTestCasesBasePath(String testCasesBasePath) {\r\n\t\tthis.testCasesBasePath = testCasesBasePath;\r\n\t}\r\n\r\n\tpublic String getTestCaseDir() {\r\n\t\treturn testCaseDir;\r\n\t}\r\n\r\n\tpublic void setTestCaseDir(String testCaseDir) {\r\n\t\tthis.testCaseDir = testCaseDir;\r\n\t}\r\n\r\n\tpublic String getOutFilesBasePath() {\r\n\t\treturn outFilesBasePath;\r\n\t}\r\n\r\n\tpublic void setOutFilesBasePath(String outFilesBasePath) {\r\n\t\tthis.outFilesBasePath = outFilesBasePath;\r\n\t}\r\n\r\n\tpublic String getOutFilesDir() {\r\n\t\treturn outFilesDir;\r\n\t}\r\n\r\n\tpublic void setOutFilesDir(String outFilesDir) {\r\n\t\tthis.outFilesDir = outFilesDir;\r\n\t}\r\n\r\n\tpublic void setAuthEnabled(boolean authEnabled) {\r\n\t\tthis.authEnabled = authEnabled;\r\n\t}\r\n\r\n\tpublic String getAuthUrl() {\r\n\t\treturn authUrl;\r\n\t}\r\n\r\n\tpublic void setAuthUrl(String authUrl) {\r\n\t\tthis.authUrl = authUrl;\r\n\t}\r\n\r\n\tpublic String getAuthExtractAuth() {\r\n\t\treturn authExtractAuth;\r\n\t}\r\n\r\n\tpublic void setAuthExtractAuth(String authExtractAuth) {\r\n\t\tthis.authExtractAuth = authExtractAuth;\r\n\t}\r\n\r\n\tpublic String getWsdlLocFile() {\r\n\t\treturn wsdlLocFile;\r\n\t}\r\n\r\n\tpublic void setWsdlLocFile(String wsdlLocFile) {\r\n\t\tthis.wsdlLocFile = wsdlLocFile;\r\n\t}\r\n\r\n\tpublic void setSoapAuthEnabled(boolean soapAuthEnabled) {\r\n\t\tthis.soapAuthEnabled = soapAuthEnabled;\r\n\t}\r\n\r\n\tpublic String getSoapAuthWsdlKey() {\r\n\t\treturn soapAuthWsdlKey;\r\n\t}\r\n\r\n\tpublic void setSoapAuthWsdlKey(String soapAuthWsdlKey) {\r\n\t\tthis.soapAuthWsdlKey = soapAuthWsdlKey;\r\n\t}\r\n\r\n\tpublic String getSoapAuthOperation() {\r\n\t\treturn soapAuthOperation;\r\n\t}\r\n\r\n\tpublic void setSoapAuthOperation(String soapAuthOperation) {\r\n\t\tthis.soapAuthOperation = soapAuthOperation;\r\n\t}\r\n\r\n\tpublic String getSoapAuthExtractAuth() {\r\n\t\treturn soapAuthExtractAuth;\r\n\t}\r\n\r\n\tpublic void setSoapAuthExtractAuth(String soapAuthExtractAuth) {\r\n\t\tthis.soapAuthExtractAuth = soapAuthExtractAuth;\r\n\t}\r\n\r\n\tpublic Integer getNumConcurrentExecutions() {\r\n\t\treturn numConcurrentExecutions;\r\n\t}\r\n\r\n\tpublic void setNumConcurrentExecutions(Integer numConcurrentExecutions) {\r\n\t\tthis.numConcurrentExecutions = numConcurrentExecutions;\r\n\t}\r\n\r\n\tpublic String[] getAuthExtractAuthParams() {\r\n\t\tif(authExtractAuth!=null) {\r\n\t\t\treturn authExtractAuth.split(\",\");\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic String[] getServerApiAuthExtractAuthParams() {\r\n\t\tif(serverLogsApiAuthExtractAuth!=null) {\r\n\t\t\treturn serverLogsApiAuthExtractAuth.split(\",\");\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic String[] getAuthParamDetails() {\r\n\t\tif(authParamsDetails!=null) {\r\n\t\t\treturn authParamsDetails.split(\",\");\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic String[] getSoapAuthExtractAuthParams() {\r\n\t\tif(soapAuthExtractAuth!=null) {\r\n\t\t\treturn soapAuthExtractAuth.split(\",\");\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic Boolean isEnabled() {\r\n\t\treturn enabled;\r\n\t}\r\n\r\n\tpublic void setEnabled(Boolean enabled) {\r\n\t\tthis.enabled = enabled;\r\n\t}\r\n\r\n\tpublic boolean isAuthEnabled() {\r\n\t\treturn authEnabled && getAuthExtractAuthParams()!=null;\r\n\t}\r\n\t\r\n\tpublic boolean isSoapAuthEnabled() {\r\n\t\treturn soapAuthEnabled && getSoapAuthExtractAuthParams()!=null;\r\n\t}\r\n\t\r\n\tpublic boolean isSoapAuthTestCase(TestCase tcase) {\r\n\t\treturn getSoapAuthWsdlKey()!=null && getSoapAuthOperation()!=null &&\r\n\t\t\t\t(getSoapAuthWsdlKey() + \r\n\t\t\t\t\t\tgetSoapAuthOperation()).equals(tcase.getWsdlKey()+tcase.getOperationName());\r\n\t}\r\n\r\n\tpublic boolean isHttpCompressionEnabled() {\r\n\t\treturn httpCompressionEnabled;\r\n\t}\r\n\r\n\tpublic void setHttpCompressionEnabled(boolean httpCompressionEnabled) {\r\n\t\tthis.httpCompressionEnabled = httpCompressionEnabled;\r\n\t}\r\n\r\n\tpublic Integer getHttpConnectionTimeout() {\r\n\t\treturn httpConnectionTimeout;\r\n\t}\r\n\r\n\tpublic void setHttpConnectionTimeout(Integer httpConnectionTimeout) {\r\n\t\tthis.httpConnectionTimeout = httpConnectionTimeout;\r\n\t}\r\n\r\n\tpublic Integer getHttpRequestTimeout() {\r\n\t\treturn httpRequestTimeout;\r\n\t}\r\n\r\n\tpublic void setHttpRequestTimeout(Integer httpRequestTimeout) {\r\n\t\tthis.httpRequestTimeout = httpRequestTimeout;\r\n\t}\r\n\t\r\n\tpublic Integer getConcurrentUserSimulationNum() {\r\n\t\treturn concurrentUserSimulationNum;\r\n\t}\r\n\r\n\tpublic void setConcurrentUserSimulationNum(Integer concurrentUserSimulationNum) {\r\n\t\tthis.concurrentUserSimulationNum = concurrentUserSimulationNum;\r\n\t}\r\n\t\r\n\tpublic GatfTestDataConfig getGatfTestDataConfig() {\r\n\t\treturn gatfTestDataConfig;\r\n\t}\r\n\r\n\tpublic void setGatfTestDataConfig(GatfTestDataConfig gatfTestDataConfig) {\r\n\t\tthis.gatfTestDataConfig = gatfTestDataConfig;\r\n\t}\r\n\r\n\tpublic String getTestDataConfigFile() {\r\n\t\treturn testDataConfigFile;\r\n\t}\r\n\r\n\tpublic void setTestDataConfigFile(String testDataConfigFile) {\r\n\t\tthis.testDataConfigFile = testDataConfigFile;\r\n\t}\r\n\r\n\tpublic String getAuthDataProvider() {\r\n\t\treturn authDataProvider;\r\n\t}\r\n\r\n\tpublic void setAuthDataProvider(String authDataProvider) {\r\n\t\tthis.authDataProvider = authDataProvider;\r\n\t}\r\n\r\n\tpublic Integer getCompareBaseUrlsNum() {\r\n\t\treturn compareBaseUrlsNum;\r\n\t}\r\n\r\n\tpublic void setCompareBaseUrlsNum(Integer compareBaseUrlsNum) {\r\n\t\tthis.compareBaseUrlsNum = compareBaseUrlsNum;\r\n\t}\r\n\r\n\tpublic boolean isCompareEnabled() {\r\n\t\treturn compareEnabled;\r\n\t}\r\n\r\n\tpublic void setCompareEnabled(boolean compareEnabled) {\r\n\t\tthis.compareEnabled = compareEnabled;\r\n\t}\r\n\r\n\tpublic String getAuthParamsDetails() {\r\n\t\treturn authParamsDetails;\r\n\t}\r\n\r\n\tpublic void setAuthParamsDetails(String authParamsDetails) {\r\n\t\tthis.authParamsDetails = authParamsDetails;\r\n\t}\r\n\r\n\tpublic String[] getTestCaseHooksPaths() {\r\n\t\treturn testCaseHooksPaths;\r\n\t}\r\n\r\n\tpublic void setTestCaseHooksPaths(String[] testCaseHooksPaths) {\r\n\t\tthis.testCaseHooksPaths = testCaseHooksPaths;\r\n\t}\r\n\r\n\tpublic boolean isLoadTestingEnabled() {\r\n\t\treturn loadTestingEnabled;\r\n\t}\r\n\r\n\tpublic void setLoadTestingEnabled(boolean loadTestingEnabled) {\r\n\t\tthis.loadTestingEnabled = loadTestingEnabled;\r\n\t}\r\n\r\n\tpublic boolean isFetchFailureLogs() {\r\n\t\treturn isFetchFailureLogs;\r\n\t}\r\n\r\n\tpublic void setFetchFailureLogs(boolean isFetchFailureLogs) {\r\n\t\tthis.isFetchFailureLogs = isFetchFailureLogs;\r\n\t}\r\n\r\n\tpublic Long getLoadTestingTime() {\r\n\t\treturn loadTestingTime;\r\n\t}\r\n\r\n\tpublic void setLoadTestingTime(Long loadTestingTime) {\r\n\t\tthis.loadTestingTime = loadTestingTime;\r\n\t}\r\n\r\n\tpublic boolean isDistributedLoadTests() {\r\n\t\treturn distributedLoadTests;\r\n\t}\r\n\r\n\tpublic void setDistributedLoadTests(boolean distributedLoadTests) {\r\n\t\tthis.distributedLoadTests = distributedLoadTests;\r\n\t}\r\n\r\n\tpublic String[] getDistributedNodes() {\r\n\t\treturn distributedNodes;\r\n\t}\r\n\r\n\tpublic void setDistributedNodes(String[] distributedNodes) {\r\n\t\tthis.distributedNodes = distributedNodes;\r\n\t}\r\n\r\n\tpublic Long getConcurrentUserRampUpTime() {\r\n\t\treturn concurrentUserRampUpTime;\r\n\t}\r\n\r\n\tpublic void setConcurrentUserRampUpTime(Long concurrentUserRampUpTime) {\r\n\t\tthis.concurrentUserRampUpTime = concurrentUserRampUpTime;\r\n\t}\r\n\r\n\tpublic Integer getLoadTestingReportSamples() {\r\n\t\treturn loadTestingReportSamples;\r\n\t}\r\n\r\n\tpublic void setLoadTestingReportSamples(Integer loadTestingReportSamples) {\r\n\t\tthis.loadTestingReportSamples = loadTestingReportSamples;\r\n\t}\r\n\r\n\tpublic boolean isDebugEnabled() {\r\n\t\treturn debugEnabled;\r\n\t}\r\n\r\n\tpublic void setDebugEnabled(boolean debugEnabled) {\r\n\t\tthis.debugEnabled = debugEnabled;\r\n\t}\r\n\r\n\tpublic String[] getIgnoreFiles() {\r\n\t\treturn ignoreFiles;\r\n\t}\r\n\r\n\tpublic void setIgnoreFiles(String[] ignoreFiles) {\r\n\t\tthis.ignoreFiles = ignoreFiles;\r\n\t}\r\n\r\n\tpublic String[] getOrderedFiles() {\r\n\t\treturn orderedFiles;\r\n\t}\r\n\r\n\tpublic void setOrderedFiles(String[] orderedFiles) {\r\n\t\tthis.orderedFiles = orderedFiles;\r\n\t}\r\n\r\n\tpublic boolean isOrderByFileName() {\r\n\t\treturn isOrderByFileName;\r\n\t}\r\n\r\n\tpublic void setOrderByFileName(boolean isOrderByFileName) {\r\n\t\tthis.isOrderByFileName = isOrderByFileName;\r\n\t}\r\n\r\n\tpublic boolean isServerLogsApiAuthEnabled() {\r\n\t\treturn isServerLogsApiAuthEnabled;\r\n\t}\r\n\r\n\tpublic void setServerLogsApiAuthEnabled(boolean isServerLogsApiAuthEnabled) {\r\n\t\tthis.isServerLogsApiAuthEnabled = isServerLogsApiAuthEnabled;\r\n\t}\r\n\r\n\tpublic String getServerLogsApiAuthExtractAuth() {\r\n\t\treturn serverLogsApiAuthExtractAuth;\r\n\t}\r\n\r\n\tpublic void setServerLogsApiAuthExtractAuth(String serverLogsApiAuthExtractAuth) {\r\n\t\tthis.serverLogsApiAuthExtractAuth = serverLogsApiAuthExtractAuth;\r\n\t}\r\n\r\n\tpublic Integer getRepeatSuiteExecutionNum() {\r\n\t\treturn repeatSuiteExecutionNum;\r\n\t}\r\n\r\n\tpublic void setRepeatSuiteExecutionNum(Integer repeatSuiteExecutionNum) {\r\n\t\tthis.repeatSuiteExecutionNum = repeatSuiteExecutionNum;\r\n\t}\r\n\r\n\tpublic boolean isGenerateExecutionLogs() {\r\n\t\treturn isGenerateExecutionLogs;\r\n\t}\r\n\r\n\tpublic void setGenerateExecutionLogs(boolean isGenerateExecutionLogs) {\r\n\t\tthis.isGenerateExecutionLogs = isGenerateExecutionLogs;\r\n\t}\r\n\r\n\tpublic boolean isSeleniumExecutor() {\r\n\t\treturn isSeleniumExecutor;\r\n\t}\r\n\r\n\tpublic void setSeleniumExecutor(boolean isSeleniumExecutor) {\r\n\t\tthis.isSeleniumExecutor = isSeleniumExecutor;\r\n\t}\r\n\r\n\tpublic boolean isSeleniumModuleTests() {\r\n\t\treturn isSeleniumModuleTests;\r\n\t}\r\n\r\n\tpublic void setSeleniumModuleTests(boolean isSeleniumModuleTests) {\r\n\t\tthis.isSeleniumModuleTests = isSeleniumModuleTests;\r\n\t}\r\n\r\n\tpublic String[] getSeleniumScripts() {\r\n\t\treturn seleniumScripts;\r\n\t}\r\n\r\n\tpublic void setSeleniumScripts(String[] seleniumScripts) {\r\n\t\tthis.seleniumScripts = seleniumScripts;\r\n\t}\r\n\r\n\tpublic SeleniumDriverConfig[] getSeleniumDriverConfigs() {\r\n\t\treturn seleniumDriverConfigs;\r\n\t}\r\n\r\n\tpublic void setSeleniumDriverConfigs(SeleniumDriverConfig[] seleniumDriverConfigs) {\r\n\t\tthis.seleniumDriverConfigs = seleniumDriverConfigs;\r\n\t}\r\n\t\r\n\tpublic Map<String, SeleniumDriverConfig> getSelDriverConfigMap() {\r\n\t Map<String, SeleniumDriverConfig> mp = new HashMap<String, SeleniumDriverConfig>();\r\n\t for (SeleniumDriverConfig sc : seleniumDriverConfigs)\r\n {\r\n if(!mp.containsKey(sc.getDriverName()) && sc.getName().matches(\"chrome|firefox|ie|opera|edge|safari|appium-android|appium-ios|selendroid|ios-driver\"))\r\n {\r\n mp.put(sc.getName(), sc);\r\n }\r\n }\r\n\t return mp;\r\n\t}\r\n\t\r\n\tpublic String getSeleniumLoggerPreferences()\r\n {\r\n return seleniumLoggerPreferences;\r\n }\r\n\r\n public void setSeleniumLoggerPreferences(String seleniumLoggerPreferences)\r\n {\r\n this.seleniumLoggerPreferences = seleniumLoggerPreferences;\r\n }\r\n\r\n public boolean isValidSeleniumRequest() {\r\n\t\treturn isSeleniumExecutor && /*seleniumScripts!=null && seleniumScripts.length>0 && */\r\n\t\t seleniumDriverConfigs!=null && seleniumDriverConfigs.length>0 &&\r\n\t\t StringUtils.isNotEmpty(seleniumDriverConfigs[0].getName()) && StringUtils.isNotEmpty(seleniumDriverConfigs[0].getPath());\r\n\t}\r\n\r\n\tpublic String getJavaHome()\r\n {\r\n return javaHome;\r\n }\r\n\r\n public void setJavaHome(String javaHome)\r\n {\r\n this.javaHome = javaHome;\r\n }\r\n\r\n public String getJavaVersion() {\r\n return javaVersion;\r\n }\r\n\r\n public void setJavaVersion(String javaVersion) {\r\n this.javaVersion = javaVersion;\r\n }\r\n\r\n public String getGatfJarPath() {\r\n return gatfJarPath;\r\n }\r\n\r\n public void setGatfJarPath(String gatfJarPath) {\r\n this.gatfJarPath = gatfJarPath;\r\n }\r\n\r\n public boolean isSelDebugger() {\r\n\t\treturn selDebugger;\r\n\t}\r\n\r\n\tpublic void setSelDebugger(boolean selDebugger) {\r\n\t\tthis.selDebugger = selDebugger;\r\n\t}\r\n\r\n\tpublic String getWrkPath() {\r\n\t\treturn wrkPath;\r\n\t}\r\n\r\n\tpublic void setWrkPath(String wrkPath) {\r\n\t\tthis.wrkPath = wrkPath;\r\n\t}\r\n\r\n\tpublic String getWrk2Path() {\r\n\t\treturn wrk2Path;\r\n\t}\r\n\r\n\tpublic void setWrk2Path(String wrk2Path) {\r\n\t\tthis.wrk2Path = wrk2Path;\r\n\t}\r\n\r\n\tpublic String getVegetaPath() {\r\n\t\treturn vegetaPath;\r\n\t}\r\n\r\n\tpublic void setVegetaPath(String vegetaPath) {\r\n\t\tthis.vegetaPath = vegetaPath;\r\n\t}\r\n\r\n\tpublic String getAutocannonPath() {\r\n\t\treturn autocannonPath;\r\n\t}\r\n\r\n\tpublic void setAutocannonPath(String autocannonPath) {\r\n\t\tthis.autocannonPath = autocannonPath;\r\n\t}\r\n\r\n\tpublic void validate()\r\n\t{\r\n\t\tAssert.assertTrue(\"Testcase directory name is blank...\", \r\n\t\t\t\tgetTestCaseDir()!=null && !getTestCaseDir().trim().isEmpty());\r\n\t\t\r\n\t\tif(isAuthEnabled()) {\r\n\t\t\tAssert.assertTrue(\"Invalid auth extract params\", getAuthExtractAuthParams().length==4);\r\n\t\t\tAssert.assertTrue(\"Invalid auth extract token name\", !getAuthExtractAuthParams()[0].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth extract mode specified, should be one of (xml,json,header,plain,cookie)\", \r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"json\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"xml\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"header\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"plain\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"cookie\"));\r\n\t\t\tAssert.assertTrue(\"Invalid auth name specified\", !getAuthExtractAuthParams()[2].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth mode specified, should be one of (queryparam,header,cookie)\", \r\n\t\t\t\t\tgetAuthExtractAuthParams()[3].equalsIgnoreCase(\"queryparam\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[3].equalsIgnoreCase(\"cookie\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[3].equalsIgnoreCase(\"header\"));\r\n\t\t\tAssert.assertTrue(\"Invalid auth url\", getAuthUrl()!=null && !getAuthUrl().isEmpty());\r\n\t\t\t\r\n\t\t\tAssert.assertNotNull(\"Invalid auth param details\",getAuthParamsDetails());\r\n\t\t\tAssert.assertTrue(\"Invalid auth param details\", getAuthParamDetails().length==4);\r\n\t\t\tAssert.assertTrue(\"Invalid auth user param name\", !getAuthParamDetails()[0].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth user param name mode specified, should be one of (header,postparam,queryparam)\", \r\n\t\t\t\t\tgetAuthParamDetails()[1].equalsIgnoreCase(\"header\") ||\r\n\t\t\t\t\tgetAuthParamDetails()[1].equalsIgnoreCase(\"postparam\") ||\r\n\t\t\t\t\tgetAuthParamDetails()[1].equalsIgnoreCase(\"queryparam\"));\r\n\t\t\tAssert.assertTrue(\"Invalid auth password param name\", !getAuthParamDetails()[2].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth password param name mode specified, should be one of (header,queryparam,header)\", \r\n\t\t\t\t\tgetAuthParamDetails()[3].equalsIgnoreCase(\"queryparam\") ||\r\n\t\t\t\t\tgetAuthParamDetails()[3].equalsIgnoreCase(\"postparam\") ||\r\n\t\t\t\t\tgetAuthParamDetails()[3].equalsIgnoreCase(\"header\"));\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tif(isSoapAuthEnabled()) {\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap wsdl key\", getSoapAuthWsdlKey()!=null && !getSoapAuthWsdlKey().isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap wsdl operation\", getSoapAuthOperation()!=null && !getSoapAuthOperation().isEmpty());\r\n\t\t\t\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap extract params\", getSoapAuthExtractAuthParams().length==3);\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap extract token name\", !getSoapAuthExtractAuthParams()[0].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap name specified\", !getSoapAuthExtractAuthParams()[1].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap name\", !getSoapAuthExtractAuthParams()[2].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap name\", getSoapAuthExtractAuthParams()[2].equalsIgnoreCase(\"queryparam\"));\r\n\t\t}\r\n\t}\r\n}\r",
"public class WorkflowContextHandler {\r\n\t\r\n\tpublic static final ObjectMapper OM = new ObjectMapper();\r\n\r\n\tprivate final VelocityEngine engine = new VelocityEngine();\r\n\t\r\n\tpublic enum ResponseType {\r\n\t\tJSON,\r\n\t\tXML,\r\n\t\tSOAP,\r\n\t\tPLAIN,\r\n\t\tNONE\r\n\t}\r\n\t\r\n\tpublic VelocityEngine getEngine() {\r\n\t\treturn engine;\r\n\t}\r\n\r\n\tpublic void init() {\r\n\t\ttry {\r\n\t\t\tengine.init();\r\n\t\t} catch (Exception e) {\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate final Map<String, String> globalworkflowContext = new ConcurrentHashMap<String, String>();\r\n\t\r\n\tprivate final Map<Integer, Map<String, String>> suiteWorkflowContext = new ConcurrentHashMap<Integer, Map<String, String>>();\r\n\t\r\n\tprivate final Map<Integer, Map<String, List<Map<String, String>>>> suiteWorkflowScenarioContext = \r\n\t\t\tnew ConcurrentHashMap<Integer, Map<String, List<Map<String, String>>>>();\r\n\t\r\n\tprivate final Map<Integer, Map<String, String>> cookies = new ConcurrentHashMap<Integer, Map<String, String>>();\r\n\t\r\n\tpublic void initializeSuiteContext(int numberOfRuns) {\r\n\t\tsuiteWorkflowContext.clear();\r\n\t\tsuiteWorkflowScenarioContext.clear();\r\n\t\tcookies.clear();\r\n\t\t\r\n\t\tfor (int i = -2; i < numberOfRuns+1; i++) {\r\n\t\t\tsuiteWorkflowContext.put(i, new ConcurrentHashMap<String, String>());\r\n\t\t\tsuiteWorkflowScenarioContext.put(i, new ConcurrentHashMap<String, List<Map<String, String>>>());\r\n\t\t\tcookies.put(i, new ConcurrentHashMap<String, String>());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void initializeSuiteContextWithnum(int index) {\r\n\t\tsuiteWorkflowContext.put(index, new ConcurrentHashMap<String, String>());\r\n\t\tsuiteWorkflowScenarioContext.put(index, new ConcurrentHashMap<String, List<Map<String, String>>>());\r\n\t\tcookies.put(index, new ConcurrentHashMap<String, String>());\r\n\t}\r\n\t\r\n\tvoid addGlobalVariables(Map<String, String> variableMap) {\r\n\t\tif(variableMap!=null) {\r\n\t\t\tfor (String property : variableMap.keySet()) {\r\n\t\t\t\tString value = variableMap.get(property);\r\n\t\t\t\tif(value.equals(\"env.var\")) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvalue = System.getenv(property);\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if(value.equals(\"property.var\")) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvalue = System.getProperty(property);\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if(value.startsWith(\"env.\")) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvalue = System.getenv(value.substring(4));\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if(value.startsWith(\"property.\")) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvalue = System.getProperty(value.substring(9));\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif(value==null) {\r\n\t\t\t\t\tvalue = variableMap.get(property);\r\n\t\t\t\t}\r\n\t\t\t\tglobalworkflowContext.put(property, value);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Map<String, String> getSuiteWorkflowContext(TestCase testCase) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn suiteWorkflowContext.get(-1);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn suiteWorkflowContext.get(-2);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn suiteWorkflowContext.get(0);\r\n\t\t} else {\r\n\t\t\treturn suiteWorkflowContext.get(testCase.getSimulationNumber());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Map<String, List<Map<String, String>>> getSuiteWorkflowScnearioContext(TestCase testCase) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(-1);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(-2);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(0);\r\n\t\t} else {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(testCase.getSimulationNumber());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic List<Map<String, String>> getSuiteWorkflowScenarioContextValues(TestCase testCase, String varName) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(-1).get(varName);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(-2).get(varName);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(0).get(varName);\r\n\t\t} else {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(testCase.getSimulationNumber()).get(varName);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic String getCookie(TestCase testCase, String varName) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn cookies.get(-1).get(varName);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn cookies.get(-2).get(varName);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn cookies.get(0).get(varName);\r\n\t\t} else {\r\n\t\t\treturn cookies.get(testCase.getSimulationNumber()).get(varName);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Map<String, String> getCookies(TestCase testCase) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn cookies.get(-1);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn cookies.get(-2);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn cookies.get(0);\r\n\t\t} else {\r\n\t\t\treturn cookies.get(testCase.getSimulationNumber());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic List<Cookie> storeCookies(TestCase testCase, List<String> cookieLst) {\r\n\t\tint simNumber = testCase.getSimulationNumber()==null?0:testCase.getSimulationNumber();\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\tsimNumber = -1;\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\tsimNumber = -2;\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\tsimNumber = 0;\r\n\t\t}\r\n\t\tList<Cookie> cooklst = new ArrayList<Cookie>();\r\n\t\tif(cookieLst!=null && cookies.get(simNumber)!=null)\r\n\t\t{\r\n\t\t\tfor (String cookie : cookieLst) {\r\n\t\t\t\tCookie c = Cookie.parse(HttpUrl.parse(testCase.getBaseUrl()), cookie);\r\n\t\t\t\tcooklst.add(c);\r\n\t\t\t\tcookies.get(simNumber).put(c.name(), c.value());\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn cooklst;\r\n\t}\r\n\t\r\n\tpublic Map<String, String> getGlobalSuiteAndTestLevelParameters(TestCase testCase, Map<String, String> variableMap, int index) {\r\n\t Map<String, String> nmap = new HashMap<String, String>(globalworkflowContext);\r\n\t if(testCase!=null) {\r\n\t index = testCase.getSimulationNumber();\r\n\t if(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t index = -1;\r\n\t } else if(testCase.isExternalApi()) {\r\n\t index = -2;\r\n\t } else if(testCase.getSimulationNumber()==null) {\r\n\t index = 0;\r\n\t }\r\n\t nmap.putAll(suiteWorkflowContext.get(index));\r\n\t if(variableMap!=null && !variableMap.isEmpty()) {\r\n\t nmap.putAll(variableMap);\r\n\t }\r\n\t if(testCase.getCarriedOverVariables()!=null && !testCase.getCarriedOverVariables().isEmpty()) {\r\n\t nmap.putAll(testCase.getCarriedOverVariables());\r\n\t }\r\n\t } else {\r\n\t nmap.putAll(suiteWorkflowContext.get(index));\r\n\t if(variableMap!=null && !variableMap.isEmpty()) {\r\n nmap.putAll(variableMap);\r\n }\r\n\t }\r\n\t\treturn nmap;\r\n\t}\r\n\t\r\n\tpublic void addSuiteLevelParameter(int index, String name, String value) {\r\n\t if(suiteWorkflowContext.containsKey(index) && value!=null) {\r\n\t suiteWorkflowContext.get(index).put(name, value);\r\n\t }\r\n\t}\r\n\t\r\n\tpublic String evaluateTemplate(TestCase testCase, String template, AcceptanceTestContext acontext) {\r\n\t\tStringWriter writer = new StringWriter();\r\n\t\ttry {\r\n\t\t\tMap<String, String> nmap = getGlobalSuiteAndTestLevelParameters(testCase, null, -3);\r\n\t\t\tif(testCase!=null && !nmap.isEmpty()) {\r\n\t\t\t\tif(template!=null) {\r\n\t\t\t\t\tVelocityContext context = new VelocityContext(new HashMap<String, Object>(nmap));\r\n\t\t\t\t\tDataProviderAccessor dpa = new DataProviderAccessor(acontext, testCase);\r\n\t\t\t\t\tcontext.put(\"_DPA_\", dpa);\r\n\t\t\t\t\tengine.evaluate(context, writer, \"ERROR\", template);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn writer.toString();\r\n\t}\r\n\t\r\n\tpublic String templatize(Map<String, Object> variableMap, String template) throws Exception {\r\n\t VelocityContext context = new VelocityContext(variableMap);\r\n\t StringWriter writer = new StringWriter();\r\n engine.evaluate(context, writer, \"ERROR\", template);\r\n return writer.toString();\r\n\t}\r\n \r\n public String templatize(String template) throws Exception {\r\n VelocityContext context = new VelocityContext(Collections.<String, Object>unmodifiableMap(globalworkflowContext));\r\n StringWriter writer = new StringWriter();\r\n engine.evaluate(context, writer, \"ERROR\", template);\r\n return writer.toString();\r\n }\r\n\t\r\n\tpublic void handleContextVariables(TestCase testCase, Map<String, String> variableMap, AcceptanceTestContext acontext) \r\n\t\t\tthrows Exception {\r\n\t\t\r\n\t\tMap<String, String> nmap = getGlobalSuiteAndTestLevelParameters(testCase, variableMap, -3);\r\n\t\t\r\n\t\tVelocityContext context = new VelocityContext(new HashMap<String, Object>(nmap));\r\n\t\tDataProviderAccessor dpa = new DataProviderAccessor(acontext, testCase);\r\n\t\tcontext.put(\"_DPA_\", dpa);\r\n\t\t\r\n\t\t//initialize cookies and headers\r\n\t\tif(testCase != null) {\r\n\t\t\tMap<String, String> cookieMap = getCookies(testCase);\r\n\t\t\tif(cookieMap!=null) {\r\n\t\t\t\tfor (Map.Entry<String, String> entry : cookieMap.entrySet()) {\r\n\t\t\t\t\tif(testCase.getHeaders()==null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttestCase.setHeaders(new HashMap<String, String>());\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttestCase.getHeaders().put(\"Cookie\", entry.getKey() + \"=\" + entry.getValue());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(MapUtils.isNotEmpty(testCase.getHeaders())) {\r\n\t\t\t for (Map.Entry<String, String> entry : testCase.getHeaders().entrySet()) {\r\n\t\t\t StringWriter writer = new StringWriter();\r\n\t\t\t engine.evaluate(context, writer, \"ERROR\", entry.getValue());\r\n\t\t\t testCase.getHeaders().put(entry.getKey(), writer.toString());\r\n\t\t\t }\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif(testCase!=null && !nmap.isEmpty()) {\r\n\t\t\tif(testCase.getUrl()!=null) {\r\n\t\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\t\tengine.evaluate(context, writer, \"ERROR\", testCase.getUrl());\r\n\t\t\t\ttestCase.setAurl(writer.toString());\r\n\t\t\t}\r\n\t\t\tif(testCase.getContent()!=null) {\r\n\t\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\t\tengine.evaluate(context, writer, \"ERROR\", testCase.getContent());\r\n\t\t\t\ttestCase.setAcontent(writer.toString());\r\n\t\t\t}\r\n\t\t\tif(testCase.getExQueryPart()!=null) {\r\n\t\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\t\tengine.evaluate(context, writer, \"ERROR\", testCase.getExQueryPart());\r\n\t\t\t\ttestCase.setAexQueryPart(writer.toString());\r\n\t\t\t}\r\n\t\t\tif(testCase.getExpectedNodes()!=null && !testCase.getExpectedNodes().isEmpty()) {\r\n\t\t\t\tList<String> expectedNodes = new ArrayList<String>();\r\n\t\t\t\tfor (String nodecase : testCase.getExpectedNodes()) {\r\n\t\t\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\t\t\tengine.evaluate(context, writer, \"ERROR\", nodecase);\r\n\t\t\t\t\texpectedNodes.add(writer.toString());\r\n\t\t\t\t}\r\n\t\t\t\ttestCase.setAexpectedNodes(expectedNodes);\r\n\t\t\t}\r\n\t\t} else if(testCase!=null) {\r\n\t\t\ttestCase.setAurl(testCase.getUrl());\r\n\t\t\ttestCase.setAcontent(testCase.getContent());\r\n\t\t\ttestCase.setAexQueryPart(testCase.getExQueryPart());\r\n\t\t\ttestCase.setAexpectedNodes(testCase.getExpectedNodes());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic boolean velocityValidate(TestCase testCase, String template, Map<String, String> smap, \r\n\t\t\tAcceptanceTestContext acontext) {\r\n\t\tif(testCase!=null && template!=null) {\r\n\t\t\tMap<String, String> nmap = getGlobalSuiteAndTestLevelParameters(testCase, null, -3);\r\n\t\t\tif(smap!=null) {\r\n\t\t\t\tnmap.putAll(smap);\r\n\t\t\t}\r\n\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\tString condition = \"#if(\" + template + \")true#end\";\r\n\t\t\ttry {\r\n\t\t\t\tVelocityContext context = new VelocityContext(new HashMap<String, Object>(nmap));\r\n\t\t\t\tDataProviderAccessor dpa = new DataProviderAccessor(acontext, testCase);\r\n\t\t\t\tcontext.put(\"_DPA_\", dpa);\r\n\t\t\t\tengine.evaluate(context, writer, \"ERROR\", condition);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t\treturn \"true\".equals(writer.toString());\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic static List<Map<String, String>> getNodeCountMapList(String xmlValue, String nodeName)\r\n\t{\r\n\t\tint responseCount = -1;\r\n\t\ttry {\r\n\t\t\tresponseCount = Integer.valueOf(xmlValue);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new AssertionError(\"Invalid responseMappedCount variable defined, \" +\r\n\t\t\t\t\t\"derived value should be number - \"+nodeName);\r\n\t\t}\r\n\t\t\r\n\t\tList<Map<String, String>> xmlValues = new ArrayList<Map<String,String>>();\r\n\t\tfor (int i = 0; i < responseCount; i++) {\r\n\t\t\tMap<String, String> row = new HashMap<String, String>();\r\n\t\t\trow.put(\"index\", (i+1)+\"\");\r\n\t\t\txmlValues.add(row);\r\n\t\t}\r\n\t\t\r\n\t\treturn xmlValues;\r\n\t}\r\n\t\r\n\tpublic static List<Map<String, String>> getNodeValueMapList(String propNames, NodeList xmlNodeList)\r\n\t{\r\n\t\tList<Map<String, String>> nodeValues = new ArrayList<Map<String,String>>();\r\n\t\tif(propNames.endsWith(\"*\")) \r\n\t\t{\r\n\t\t\tfor (int i = 0; i < xmlNodeList.getLength(); i++) {\r\n\t\t\t\tMap<String, String> row = new HashMap<String, String>();\r\n\t\t\t\t\r\n\t\t\t\tNode node = xmlNodeList.item(i);\r\n\t\t\t\tif(node.getAttributes()!=null && node.getAttributes().getLength()>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int j = 0; j < node.getAttributes().getLength(); j++) {\r\n\t\t\t\t\t\tAttr attr = (Attr) node.getAttributes().item(j);\r\n\t\t\t\t\t\trow.put(attr.getName(), attr.getValue());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(node.getChildNodes()!=null && node.getChildNodes().getLength()>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int j = 0; j < node.getChildNodes().getLength(); j++) {\r\n\t\t\t\t\t\tString xmlValue = XMLResponseValidator.getXMLNodeValue(node.getChildNodes().item(j));\r\n\t\t\t\t\t\tif(xmlValue!=null)\r\n\t\t\t\t\t\t\trow.put(node.getChildNodes().item(j).getNodeName(), xmlValue);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tString xmlValue = XMLResponseValidator.getXMLNodeValue(node);\r\n\t\t\t\tif(xmlValue!=null)\r\n\t\t\t\t\trow.put(\"this\", xmlValue);\r\n\t\t\t\t\r\n\t\t\t\tif(row.size()>0)\r\n\t\t\t\t\tnodeValues.add(row);\r\n\t\t\t}\r\n\t\t} \r\n\t\telse\r\n\t\t{\r\n\t\t\tString[] props = propNames.split(\",\");\r\n\t\t\t\r\n\t\t\tfor (int i = 0; i < xmlNodeList.getLength(); i++) {\r\n\t\t\t\tMap<String, String> row = new HashMap<String, String>();\r\n\t\t\t\t\r\n\t\t\t\tNode node = xmlNodeList.item(i);\r\n\t\t\t\t\r\n\t\t\t\tboolean found = false;\r\n\t\t\t\t\r\n\t\t\t\tif(node.getAttributes()!=null && node.getAttributes().getLength()>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int j = 0; j < node.getAttributes().getLength(); j++) {\r\n\t\t\t\t\t\tAttr attr = (Attr) node.getAttributes().item(j);\r\n\t\t\t\t\t\tfor (String propName : props) {\r\n\t\t\t\t\t\t\tif(attr.getName().equals(propName)) {\r\n\t\t\t\t\t\t\t\tfound = true;\r\n\t\t\t\t\t\t\t\trow.put(propName, attr.getValue());\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(!found && node.getChildNodes()!=null && node.getChildNodes().getLength()>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int j = 0; j < node.getChildNodes().getLength(); j++) {\r\n\t\t\t\t\t\tfor (String propName : props) {\r\n\t\t\t\t\t\t\tif(node.getChildNodes().item(j).getNodeName().equals(propName)) {\r\n\t\t\t\t\t\t\t\tfound = true;\r\n\t\t\t\t\t\t\t\tString xmlValue = XMLResponseValidator.getXMLNodeValue(node.getChildNodes().item(j));\r\n\t\t\t\t\t\t\t\trow.put(propName, xmlValue);\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif(row.size()>0)\r\n\t\t\t\t\tnodeValues.add(row);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn nodeValues;\r\n\t}\r\n\t\r\n\tpublic static void copyResourcesToDirectory(String resPath, String directory) {\r\n\t\tif(new File(directory).exists()) {\r\n\t\t\ttry {\r\n\t\t\t\t/*if(persistHtmlFiles) {\r\n\t\t\t\t\tFile tmpfolder = new File(FileUtils.getTempDirectory(), \"out\");\r\n\t\t\t\t\tif(tmpfolder.exists()) {\r\n\t\t\t\t\t\tFileUtils.deleteDirectory(tmpfolder);\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttmpfolder.mkdir();\r\n\t\t\t\t\tFile[] existingFiles = new File(directory).listFiles(new FilenameFilter() {\r\n\t\t\t\t\t\tpublic boolean accept(File folder, String name) {\r\n\t\t\t\t\t\t\treturn name.endsWith(\".html\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t\tfor (File file : existingFiles) {\r\n\t\t\t\t\t\tFileUtils.moveFile(file, new File(tmpfolder, file.getName()));\r\n\t\t\t\t\t}\r\n\t\t\t\t}*/\r\n\t\t\t\tFileUtils.deleteDirectory(new File(directory));\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t}\r\n\t\t}\r\n\t\tOptional<JarFile> jarFile = ResourceCopy.jar(WorkflowContextHandler.class);\r\n\t\tif(jarFile.isPresent()) {\r\n\t\t\ttry {\r\n\t\t\t\tResourceCopy.copyResourceDirectory(jarFile.get(), resPath, new File(directory));\r\n\t\t\t} catch (IOException e1) {\r\n\t\t\t\te1.printStackTrace();\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tURL resourcesUrl = WorkflowContextHandler.class.getResource(\"/\" + resPath);\r\n\t if (resourcesUrl != null)\r\n\t {\r\n\t \ttry {\r\n\t \t\tFileUtils.copyDirectory(new File(resourcesUrl.getPath()), new File(directory));\r\n\t \t} catch (Exception e) {\r\n\t \t\tthrow new RuntimeException(e);\r\n\t \t}\r\n\t }\r\n\t\t}\r\n\t\t\r\n\t\t/*if(persistHtmlFiles) {\r\n\t\t\tFile tmpfolder = new File(FileUtils.getTempDirectory(), \"out\");\r\n\t\t\tFile[] existingFiles = tmpfolder.listFiles(new FilenameFilter() {\r\n\t\t\t\tpublic boolean accept(File folder, String name) {\r\n\t\t\t\t\treturn name.endsWith(\".html\");\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\tfor (File file : existingFiles) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tFileUtils.moveFile(file, new File(directory));\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttry {\r\n\t\t\t\tFileUtils.deleteDirectory(tmpfolder);\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t}\r\n\t\t}*/\r\n\t}\r\n}\r",
"public class RuntimeReportUtil {\r\n \r\n\tpublic static class LoadTestEntry implements Serializable\r\n\t{\r\n\t\tprivate static final long serialVersionUID = 1L;\r\n\t\t\r\n\t\tString node;\r\n\t\tString prefix;\r\n\t\tint runNo;\r\n\t\tString url;\r\n\t\tDate time;\r\n\t\tTestSuiteStats currStats;\r\n\t\tMap<String, Map<String, List<Object[]>>> currSelStats;\r\n\t\t\r\n\t\tpublic LoadTestEntry(String node, String prefix, int runNo, String url, TestSuiteStats currStats, Date time) {\r\n\t\t\tsuper();\r\n\t\t\tthis.node = node;\r\n\t\t\tthis.prefix = prefix;\r\n\t\t\tthis.runNo = runNo;\r\n\t\t\tthis.url = url;\r\n\t\t\tthis.currStats = currStats;\r\n\t\t\tthis.time = time;\r\n\t\t}\r\n \r\n public LoadTestEntry(String node, String prefix, int runNo, String url, Map<String, Map<String, List<Object[]>>> currSelStats) {\r\n super();\r\n this.node = node;\r\n this.prefix = prefix;\r\n this.runNo = runNo;\r\n this.url = url;\r\n this.currSelStats = currSelStats;\r\n }\r\n \r\n public LoadTestEntry() {\r\n }\r\n\t\t\r\n\t\tpublic String getNode() {\r\n\t\t\treturn node;\r\n\t\t}\r\n\t\tpublic String getPrefix() {\r\n\t\t\treturn prefix;\r\n\t\t}\r\n\t\tpublic int getRunNo() {\r\n\t\t\treturn runNo;\r\n\t\t}\r\n\t\tpublic String getUrl() {\r\n\t\t\treturn url;\r\n\t\t}\r\n\t\tpublic Date getTime() {\r\n\t\t\treturn time;\r\n\t\t}\r\n\t\tpublic TestSuiteStats getCurrStats() {\r\n\t\t\treturn currStats;\r\n\t\t}\r\n public Map<String, Map<String, List<Object[]>>> getCurrSelStats() {\r\n return currSelStats;\r\n }\r\n\t}\r\n\t\r\n\tprivate static volatile boolean registered = false;\r\n\t\r\n\tprivate static TestSuiteStats gloadStats = new TestSuiteStats();\r\n\t\r\n\tprivate static ConcurrentLinkedQueue<Object> Q = new ConcurrentLinkedQueue<Object>();\r\n\t\r\n\tprivate static ConcurrentLinkedQueue<Object> Qdl = new ConcurrentLinkedQueue<Object>();\r\n\t\r\n\tpublic static void registerConfigUI()\r\n\t{\r\n\t\tregistered = true;\r\n\t}\r\n\t\r\n\tpublic static void unRegisterConfigUI()\r\n\t{\r\n\t\tregistered = false;\r\n\t\tQ.clear();\r\n\t\tQdl.clear();\r\n\t\tsynchronized (gloadStats) {\r\n\t\t\tgloadStats = new TestSuiteStats();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void addLEntry(LoadTestEntry lentry)\r\n\t{\r\n\t\tQdl.add(lentry);\r\n\t}\r\n\t\r\n\tpublic static void addEntry(int runNo, boolean subtestPassed)\r\n {\r\n\t if(registered)\r\n {\r\n\t try {\r\n Q.add(\"local|\"+runNo+\"|\"+(subtestPassed?1:0));\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n\t else\r\n\t {\r\n\t try {\r\n\t Qdl.add(runNo+\"|\"+(subtestPassed?1:0));\r\n\t } catch (Exception e) {\r\n\t e.printStackTrace();\r\n\t }\r\n\t }\r\n }\r\n\t\r\n\tpublic static void addEntry(Object entry)\r\n\t{\r\n\t\tif(registered)\r\n\t\t{\r\n\t\t if(entry instanceof LoadTestEntry) {\r\n\t\t LoadTestEntry lentry = (LoadTestEntry)entry;\r\n\t\t List<Object> parts = new ArrayList<Object>();\r\n\t if(lentry.prefix==null)\r\n\t lentry.prefix = \"Run\";\r\n\t parts.add(lentry.prefix);//\r\n\t parts.add(lentry.runNo+\"\");\r\n\t parts.add(lentry.url);\r\n\t parts.add(lentry.node);\r\n\t parts.add(lentry.time);\r\n\t parts.add(lentry.currStats.toList());\r\n\t parts.add(lentry.currSelStats);\r\n\t if(lentry.currStats!=null) {\r\n\t synchronized (gloadStats) {\r\n\t gloadStats.updateStats(lentry.currStats, false);\r\n\t try {\r\n\t Q.add(parts);\r\n\t } catch (Exception e) {\r\n\t e.printStackTrace();\r\n\t }\r\n\t }\r\n\t }\r\n\t\t } else {\r\n\t\t try {\r\n Q.add(entry);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n\t\t }\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t if(entry instanceof LoadTestEntry) {\r\n LoadTestEntry lentry = (LoadTestEntry)entry;\r\n \t\t if(lentry.currStats!=null) {\r\n synchronized (gloadStats) {\r\n \t\t\t\tgloadStats.updateStats(lentry.currStats, false);\r\n \t\t\t\tSystem.out.println(gloadStats);\r\n \t\t\t}\r\n \t\t }\r\n\t\t }\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void addEntry(String node, String prefix, int runNo, String url, TestSuiteStats currStats, Date time)\r\n\t{\r\n\t\tif(registered)\r\n\t\t{\r\n\t\t\tList<Object> parts = new ArrayList<Object>();\r\n\t\t\tif(prefix==null)\r\n\t\t\t\tprefix = \"Run\";\r\n\t\t\tparts.add(prefix);\r\n\t\t\tparts.add(runNo+\"\");\r\n\t\t\tparts.add(url);\r\n\t\t\tparts.add(node);\r\n\t\t\tparts.add(time.getTime());\r\n\t\t\tparts.add(currStats.toList());\r\n\t\t\tparts.add(null);\r\n\t\t\tsynchronized (gloadStats) {\r\n\t\t\t\tgloadStats.updateStats(currStats, false);\r\n\t\t\t\ttry {\r\n\t\t\t\t\tQ.add(parts);\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsynchronized (gloadStats) {\r\n\t\t\t\tgloadStats.updateStats(currStats, false);\r\n\t\t\t\tSystem.out.println(gloadStats);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static boolean isDone() {\r\n\t return Q.isEmpty();\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n public static byte[] getEntry()\r\n\t{\r\n\t try {\r\n \t List<List<Object>> st = new ArrayList<List<Object>>();\r\n \t List<String> sst = new ArrayList<String>();\r\n \t Object parts = null;\r\n \t while((parts = Q.poll())!=null) {\r\n \t if(parts instanceof String) {\r\n \t sst.add((String)parts);\r\n \t } /*else if(parts instanceof Map) {\r\n \t st.add((Map<String, Object>)parts);\r\n \t }*/ else {\r\n \t \tst.add((List<Object>)parts);\r\n \t }\r\n \t if(st.size()>=1000 || sst.size()>=1000)break;\r\n \t }\r\n \t //synchronized (gloadStats) {\r\n \t //\tgstats = \",\\\"gstats\\\":\" + WorkflowContextHandler.OM.writeValueAsString(gloadStats);\r\n \t //}\r\n \t ByteArrayOutputStream baos = new ByteArrayOutputStream();\r\n \t baos.write(\"{\\\"error\\\":\\\"Execution already in progress..\\\",\\\"lstats\\\":\".getBytes(\"UTF-8\"));\r\n \t baos.write(WorkflowContextHandler.OM.writeValueAsBytes(st));\r\n \t baos.write(\",\\\"sstats\\\":\".getBytes(\"UTF-8\"));\r\n \t baos.write(WorkflowContextHandler.OM.writeValueAsBytes(sst));\r\n\t \tbaos.write(\",\\\"gstats\\\":\".getBytes(\"UTF-8\"));\r\n \t synchronized (gloadStats) {\r\n \t baos.write(WorkflowContextHandler.OM.writeValueAsBytes(gloadStats));\r\n \t }\r\n \t baos.write(\"}\".getBytes(\"UTF-8\"));\r\n //String arr = \"{\\\"error\\\":\\\"Execution already in progress..\\\",\\\"lstats\\\":\" + \r\n // WorkflowContextHandler.OM.writeValueAsString(st) + \",\\\"sstats\\\":\" + \r\n // WorkflowContextHandler.OM.writeValueAsString(sst) + gstats + \"}\";\r\n return baos.toByteArray();\r\n\t } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n\t return new byte[] {};\r\n\t}\r\n\t\r\n\tpublic static Object getDLEntry()\r\n\t{\r\n\t\treturn Qdl.poll();\r\n\t}\r\n}\r",
"@SuppressWarnings(\"serial\")\r\npublic static class GatfSelCodeParseError extends RuntimeException {\r\n public GatfSelCodeParseError(String message) {\r\n super(message);\r\n }\r\n public GatfSelCodeParseError(String message, Throwable e) {\r\n super(message, e);\r\n }\r\n}\r",
"public static class SeleniumResult implements Serializable {\n private static final long serialVersionUID = 1L;\n\n String browserName;\n\n SeleniumTestResult result;\n\n Map<String, SeleniumTestResult> __cresult__ = new LinkedHashMap<String, SeleniumTestResult>();\n\n public SeleniumTestResult getResult()\n {\n return result;\n }\n\n public Map<String,SeleniumTestResult> getSubTestResults()\n {\n return __cresult__;\n }\n\n public String getBrowserName()\n {\n return browserName;\n }\n}"
] | import java.awt.AWTException;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.TargetLocator;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.gatf.executor.core.AcceptanceTestContext;
import com.gatf.executor.core.GatfExecutorConfig;
import com.gatf.executor.core.WorkflowContextHandler;
import com.gatf.executor.report.RuntimeReportUtil;
import com.gatf.selenium.Command.GatfSelCodeParseError;
import com.gatf.selenium.SeleniumTestSession.SeleniumResult;
import com.google.common.io.Resources;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileDriver;
import io.appium.java_client.MultiTouchAction;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.ios.IOSDriver;
import io.selendroid.client.SelendroidDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
| return null;
} else {
Map<String, String> _mt = ___cxt___.getWorkflowContextHandler().getGlobalSuiteAndTestLevelParameters(null, null, index);
return _mt.get(key);
}
}
protected Object getProviderDataValueO(String key, boolean isVar) {
if(isVar) {
return ___get_var__(key);
}
if(getSession().providerTestDataMap.containsKey(TOP_LEVEL_PROV_NAME) && getSession().providerTestDataMap.get(TOP_LEVEL_PROV_NAME).get(0).containsKey(key)) {
return getSession().providerTestDataMap.get(TOP_LEVEL_PROV_NAME).get(0).get(key);
}
if(getSession().__provdetails__.size()>0) {
ArrayList<String> keys = new ArrayList<String>(getSession().__provdetails__.keySet());
for (int i=keys.size()-1;i>=0;i--)
{
String pn = keys.get(i);
Integer pp = getSession().__provdetails__.get(pn);
List<Map<String, String>> _t = getAllProviderData(pn);
if(_t!=null && _t.get(pp)!=null) {
Map<String, String> _mt = ___cxt___.getWorkflowContextHandler().getGlobalSuiteAndTestLevelParameters(null, _t.get(pp), index);
if(_mt.containsKey(key)) {
return _mt.get(key);
}
}
}
return null;
} else {
Map<String, String> _mt = ___cxt___.getWorkflowContextHandler().getGlobalSuiteAndTestLevelParameters(null, null, index);
return _mt.get(key);
}
}
protected void ___add_var__(String name, Object val) {
if(getSession().__vars__.containsKey(name)) {
throw new RuntimeException("Variable " + name + " redefined");
}
getSession().__vars__.put(name, val);
}
protected Object ___get_var__(String name) {
if(!getSession().__vars__.containsKey(name)) {
throw new RuntimeException("Variable " + name + " not defined");
}
return getSession().__vars__.get(name);
}
protected void addSubTest(String browserName, String stname) {
if(getSession().__result__.containsKey(browserName)) {
if(!getSession().__result__.get(getSession().browserName).__cresult__.containsKey(stname)) {
getSession().__result__.get(browserName).__cresult__.put(stname, null);
} else {
throw new RuntimeException("Duplicate subtest defined");
}
} else {
throw new RuntimeException("Invalid browser specified");
}
}
protected WebDriver get___d___()
{
if(getSession().___d___.size()==0)return null;
return getSession().___d___.get(getSession().__wpos__);
}
protected void set___d___(WebDriver ___d___)
{
___d___.manage().timeouts().pageLoadTimeout(100, TimeUnit.SECONDS);
getSession().___d___.add(___d___);
}
protected class PrettyPrintingMap<K, V> {
private Map<K, V> map;
public PrettyPrintingMap(Map<K, V> map) {
this.map = map;
}
public String toString() {
StringBuilder sb = new StringBuilder();
Iterator<Entry<K, V>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<K, V> entry = iter.next();
sb.append(entry.getKey());
sb.append('=').append('"');
sb.append(entry.getValue());
sb.append('"');
if (iter.hasNext()) {
sb.append(',').append(' ');
}
}
return sb.toString();
}
}
private String getPn(String name) {
String pn = name;
if(index>0) {
pn += index;
}
return pn;
}
protected void ___cxt___add_param__(String name, Object value)
{
___cxt___.getWorkflowContextHandler().addSuiteLevelParameter(index, name, value==null?null:value.toString());
}
protected void ___cxt___print_provider__(String name)
{
System.out.println(getAllProviderData(getPn(name)));
}
protected void ___cxt___print_provider__json(String name)
{
try
{
| System.out.println(WorkflowContextHandler.OM.writerWithDefaultPrettyPrinter().writeValueAsString(getAllProviderData(getPn(name))));
| 2 |
nichbar/Aequorea | app/src/main/java/nich/work/aequorea/ui/activitiy/TagActivity.java | [
"public class Constants {\n public static final String AUTHOR = \"author\";\n public static final String TAG = \"tag\";\n public static final String ARTICLE_ID = \"article_id\";\n public static final String AUTHOR_ID = \"author_id\";\n public static final String TAG_ID = \"tag_id\";\n public static final String SEARCH_KEY = \"search_key\";\n public static final String PHOTO = \"photo\";\n public static final String ARG_URL = \"arg_url\";\n \n // Article Type\n public static final String ARTICLE_TYPE_MAGAZINE = \"magazine_article\"; // 封面故事\n public static final String ARTICLE_TYPE_MAGAZINE_V2 = \"magazine\"; // 封面故事\n public static final String ARTICLE_TYPE_NORMAL = \"normal_article\"; // 一般文章\n public static final String ARTICLE_TYPE_NORMAL_V2 = \"normal\"; // 一般文章\n public static final String ARTICLE_TYPE_THEME = \"theme\"; // 专题\n public static final String ARTICLE_TYPE_TOP_ARTICLE = \"top_article\"; // 头条故事\n public static final String ARTICLE_TYPE_SUBJECT = \"subject\"; // 单行本\n\n\n public static final int TYPE_MAGAZINE = 1;\n public static final int TYPE_NORMAL = 2;\n public static final int TYPE_THEME = 3;\n public static final int TYPE_TOP_ARTICLE = 4;\n public static final int TYPE_SUBJECT = 5;\n \n // Theme\n public static final String THEME = \"theme\";\n public static final String THEME_LIGHT = \"theme_light\";\n public static final String THEME_DARK = \"theme_dark\";\n \n // Trigger\n public static final int AUTO_LOAD_TRIGGER = 30;\n \n // Key of SharePreference\n public static final String SP_LATEST_MAIN_PAGE = \"sp_latest_main_page\";\n public static final String SP_HD_SCREENSHOT = \"sp_hd_screenshot\";\n public static final String SP_ENABLE_SELECTION = \"sp_enable_selection\";\n public static final String SP_OFFLINE_CACHE = \"sp_offline_cache\";\n public static final String SP_DISABLE_RECOMMEND_ARTICLE = \"sp_disable_recommend_article\";\n \n // Cache dir\n public static final String ARTICLE_CACHE = \"article_cache\";\n public static final String ARTICLE_PIC_CACHE = \"article_pic_cache\";\n}",
"public class DisplayUtils {\n \n public static int getStatusBarHeight(Resources r) {\n int result = 0;\n int resourceId = r.getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n result = r.getDimensionPixelSize(resourceId);\n }\n return result;\n }\n \n public static void setStatusBarStyle(BaseActivity activity, boolean isLight) {\n boolean isMIUI = setMIUIStatusBarStyle(activity, isLight);\n\n if (!isMIUI) {\n Window window = activity.getWindow();\n View decor = window.getDecorView();\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isLight) {\n decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);\n } else {\n decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);\n }\n }\n }\n \n public static void setStatusInLowProfileMode(BaseActivity activity, boolean isLight) {\n View decor = activity.getWindow().getDecorView();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n if (isLight) {\n decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LOW_PROFILE);\n } else {\n decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE);\n }\n } else {\n decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE);\n }\n }\n\n private static boolean setMIUIStatusBarStyle(BaseActivity activity, boolean isLight) {\n boolean result = false;\n Window window = activity.getWindow();\n if (window != null) {\n Class clazz = window.getClass();\n try {\n int darkModeFlag = 0;\n Class layoutParams = Class.forName(\"android.view.MiuiWindowManager$LayoutParams\");\n Field field = layoutParams.getField(\"EXTRA_FLAG_STATUS_BAR_DARK_MODE\");\n darkModeFlag = field.getInt(layoutParams);\n Method extraFlagField = clazz.getMethod(\"setExtraFlags\", int.class, int.class);\n if (isLight) {\n extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体\n } else {\n extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体\n }\n result = true;\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n //开发版 7.7.13 及以后版本采用了系统API,旧方法无效但不会报错,所以两个方式都要加上\n if (isLight) {\n activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);\n } else {\n activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);\n }\n }\n } catch (Exception e) {\n // do nothing\n }\n }\n return result;\n }\n \n public static void cancelTranslucentNavigation(Activity a) {\n a.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);\n }\n\n public static int dp2px(Context context, int dp) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getApplicationContext().getResources().getDisplayMetrics());\n }\n \n public static int sp2px(Context context, int sp) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getApplicationContext().getResources().getDisplayMetrics());\n }\n \n // take a screen shot of given nestedScrollView\n public static Bitmap shotNestedScrollView(NestedScrollView nestedScrollView, int backgroundColor) {\n \n int recHeight = 0;\n View childView = nestedScrollView.getChildAt(0);\n View recommendationView = nestedScrollView.findViewById(R.id.container_recommendation);\n ViewGroup subRecommendationView = nestedScrollView.findViewById(R.id.container_recommendation_sub);\n \n if (subRecommendationView != null && subRecommendationView.getChildCount() > 0) {\n recHeight = recommendationView.getHeight();\n }\n \n childView.setBackgroundColor(backgroundColor);\n \n Bitmap bitmap = Bitmap.createBitmap(nestedScrollView.getWidth(), childView.getHeight() - recHeight, Bitmap.Config.RGB_565);\n \n Canvas canvas = new Canvas(bitmap);\n nestedScrollView.draw(canvas);\n \n childView.setBackgroundColor(Color.TRANSPARENT);\n \n return bitmap;\n }\n}",
"public class ThemeHelper {\n public static String getTheme() {\n String theme = SPUtils.getString(Constants.THEME);\n return \"\".equals(theme) ? Constants.THEME_LIGHT : theme;\n }\n \n public static void setTheme(String theme) {\n SPUtils.setString(Constants.THEME, theme);\n Aequorea.setCurrentTheme(theme);\n }\n \n public static int getThemeStyle(String theme) {\n switch (theme) {\n default:\n case Constants.THEME_LIGHT:\n return R.style.AppTheme_Light;\n case Constants.THEME_DARK:\n return R.style.AppTheme_Dark;\n }\n }\n \n public static int getArticleThemeStyle(String theme) {\n switch (theme) {\n default:\n case Constants.THEME_LIGHT:\n return R.style.AppTheme_Article_Light;\n case Constants.THEME_DARK:\n return R.style.AppTheme_Article_Dark;\n }\n }\n \n public static int getResourceId(Context context, int attr) {\n TypedValue typedValue = new TypedValue();\n context.getTheme().resolveAttribute(attr, typedValue, true);\n return typedValue.resourceId;\n }\n \n public static int getResourceColor(Context context, int attr){\n TypedValue typedValue = new TypedValue();\n context.getTheme().resolveAttribute(attr, typedValue, true);\n return ContextCompat.getColor(context, typedValue.resourceId);\n }\n}",
"public class SimpleArticleListModel extends BaseModel {\n private int mId;\n private String mKey;\n private String mTitle;\n \n public int getId() {\n return mId;\n }\n \n public void setId(int id) {\n this.mId = id;\n }\n \n public String getKey() {\n return mKey;\n }\n \n public void setKey(String key) {\n this.mKey = key;\n }\n \n public String getTitle() {\n return mTitle;\n }\n \n public void setTitle(String title) {\n this.mTitle = title;\n }\n}",
"public class Data {\n\n @SerializedName(\"data\")\n private List<Datum> mData;\n @SerializedName(\"meta\")\n private Meta mMeta;\n\n public List<Datum> getData() {\n return mData;\n }\n\n public void setData(List<Datum> data) {\n mData = data;\n }\n \n public Meta getMeta() {\n return mMeta;\n }\n \n public void setMeta(Meta meta) {\n mMeta = meta;\n }\n}",
"public class TagPresenter extends SimpleArticleListPresenter {\n @Override\n public void load() {\n if (!NetworkUtils.isNetworkAvailable()) {\n onError(new Throwable(getString(R.string.please_connect_to_the_internet)));\n return;\n }\n \n if (mPage > mTotalPage || mBaseView.getModel().isLoading()) {\n return;\n }\n mBaseView.getModel().setLoading(true);\n \n mComposite.add(mService.getTagsList(mBaseView.getModel().getId(), mPage, mPer)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Consumer<Data>() {\n @Override\n public void accept(Data author) throws Exception {\n onDataLoaded(author);\n }\n }, new Consumer<Throwable>() {\n @Override\n public void accept(Throwable throwable) throws Exception {\n onError(throwable);\n }\n }));\n }\n}",
"public class SimpleArticleListAdapter extends RecyclerView.Adapter<SimpleArticleListAdapter.ViewHolder> {\n private List<Datum> mArticleDataList;\n private Context mContext;\n private LayoutInflater mInflater;\n \n public SimpleArticleListAdapter(Context context, List<Datum> dataList) {\n mContext = context;\n mArticleDataList = dataList;\n mInflater = LayoutInflater.from(context);\n }\n \n @Override\n public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n return new ViewHolder(mInflater.inflate(R.layout.item_author, parent, false));\n }\n \n @Override\n public void onBindViewHolder(ViewHolder holder, int position) {\n Datum article = mArticleDataList.get(position);\n \n holder.bindData(article);\n holder.articleTitleTv.setText(article.getTitle());\n holder.articleSummaryTv.setText(article.getSummary());\n \n ImageHelper.setImage(mContext, article.getCoverUrl(), holder.coverIv, R.color.colorPrimary_light);\n }\n \n @Override\n public int getItemCount() {\n return mArticleDataList != null ? mArticleDataList.size() : 0;\n }\n \n public List<Datum> getArticleDataList() {\n return mArticleDataList;\n }\n \n public void setArticleDataList(List<Datum> mArticleDataList) {\n if (this.mArticleDataList == null) {\n this.mArticleDataList = mArticleDataList;\n } else {\n // filter repeat item\n for (Datum d : mArticleDataList) {\n if (!this.mArticleDataList.contains(d)) {\n this.mArticleDataList.add(d);\n }\n }\n }\n }\n \n public static class ViewHolder extends RecyclerView.ViewHolder {\n Datum article;\n \n @BindView(R.id.iv_article_cover)\n protected ImageView coverIv;\n @BindView(R.id.tv_article_title)\n protected TextView articleTitleTv;\n @BindView(R.id.tv_article_summary)\n protected TextView articleSummaryTv;\n \n @OnClick(R.id.container)\n protected void startArticleActivity() {\n IntentUtils.startArticleActivity(itemView.getContext(), article.getId());\n }\n \n public ViewHolder(View itemView) {\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n \n public void bindData(Datum data) {\n article = data;\n }\n }\n}"
] | import android.graphics.drawable.Drawable;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import butterknife.ButterKnife;
import nich.work.aequorea.R;
import nich.work.aequorea.common.Constants;
import nich.work.aequorea.common.utils.DisplayUtils;
import nich.work.aequorea.common.utils.ThemeHelper;
import nich.work.aequorea.model.SimpleArticleListModel;
import nich.work.aequorea.model.entity.Data;
import nich.work.aequorea.presenter.TagPresenter;
import nich.work.aequorea.ui.adapter.SimpleArticleListAdapter; | package nich.work.aequorea.ui.activitiy;
public class TagActivity extends SimpleArticleListActivity {
@Override
protected int getContentViewId() {
return R.layout.activity_tag;
}
@Override
protected void initModel() {
mModel = new SimpleArticleListModel();
mModel.setId((int) getIntent().getLongExtra(Constants.TAG_ID, 0));
mModel.setTitle(getIntent().getStringExtra(Constants.TAG));
}
@Override
protected void initView() {
ButterKnife.bind(this);
mToolbar.setNavigationIcon(R.drawable.icon_ab_back_material);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
mToolbar.setTitle(mModel.getTitle());
mCoordinatorLayout.setPadding(0, DisplayUtils.getStatusBarHeight(getResources()), 0, 0);
mAdapter = new SimpleArticleListAdapter(this, null);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addOnScrollListener(mScrollListener);
setStatusBarStyle();
}
@Override
protected void initPresenter() {
mPresenter = new TagPresenter();
mPresenter.attach(this);
mPresenter.load();
}
@Override
public void onDataLoaded(Data a) {
super.onDataLoaded(a);
}
@Override
public void onThemeSwitch() {
super.onThemeSwitch();
| int primaryColor = ThemeHelper.getResourceColor(this, R.attr.colorPrimary); | 2 |
beckchr/juel | modules/impl/src/main/java/de/odysseus/el/util/SimpleResolver.java | [
"public class ArrayELResolver extends ELResolver {\r\n\tprivate final boolean readOnly;\r\n\r\n\t/**\r\n\t * Creates a new read/write ArrayELResolver.\r\n\t */\r\n\tpublic ArrayELResolver() {\r\n\t\tthis(false);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a new ArrayELResolver whose read-only status is determined by the given parameter.\r\n\t * \r\n\t * @param readOnly\r\n\t * true if this resolver cannot modify arrays; false otherwise.\r\n\t */\r\n\tpublic ArrayELResolver(boolean readOnly) {\r\n\t\tthis.readOnly = readOnly;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a Java language array, returns the most general type that this resolver\r\n\t * accepts for the property argument. Otherwise, returns null. Assuming the base is an array,\r\n\t * this method will always return Integer.class. This is because arrays accept integers for\r\n\t * their index.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The array to analyze. Only bases that are a Java language array are handled by\r\n\t * this resolver.\r\n\t * @return null if base is not a Java language array; otherwise Integer.class.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getCommonPropertyType(ELContext context, Object base) {\r\n\t\treturn isResolvable(base) ? Integer.class : null;\r\n\t}\r\n\r\n\t/**\r\n\t * Always returns null, since there is no reason to iterate through set set of all integers. The\r\n\t * getCommonPropertyType(ELContext, Object)8 method returns sufficient information about what\r\n\t * properties this resolver accepts.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The array to analyze. Only bases that are a Java language array are handled by\r\n\t * this resolver.\r\n\t * @return null.\r\n\t */\r\n\t@Override\r\n\tpublic Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is an array, returns the most general acceptable type for a value in this\r\n\t * array. If the base is a array, the propertyResolved property of the ELContext object must be\r\n\t * set to true by this resolver, before returning. If this property is not true after this\r\n\t * method is called, the caller should ignore the return value. Assuming the base is an array,\r\n\t * this method will always return base.getClass().getComponentType(), which is the most general\r\n\t * type of component that can be stored at any given index in the array.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The array to analyze. Only bases that are a Java language array are handled by\r\n\t * this resolver.\r\n\t * @param property\r\n\t * The index of the element in the array to return the acceptable type for. Will be\r\n\t * coerced into an integer, but otherwise ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the most general\r\n\t * acceptable type; otherwise undefined.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the given index is out of bounds for this array.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getType(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tClass<?> result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\ttoIndex(base, property);\r\n\t\t\tresult = base.getClass().getComponentType();\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a Java language array, returns the value at the given index. The index\r\n\t * is specified by the property argument, and coerced into an integer. If the coercion could not\r\n\t * be performed, an IllegalArgumentException is thrown. If the index is out of bounds, null is\r\n\t * returned. If the base is a Java language array, the propertyResolved property of the\r\n\t * ELContext object must be set to true by this resolver, before returning. If this property is\r\n\t * not true after this method is called, the caller should ignore the return value.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The array to analyze. Only bases that are a Java language array are handled by\r\n\t * this resolver.\r\n\t * @param property\r\n\t * The index of the element in the array to return the acceptable type for. Will be\r\n\t * coerced into an integer, but otherwise ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the value at the\r\n\t * given index or null if the index was out of bounds. Otherwise, undefined.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the given index is out of bounds for this array.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Object getValue(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tObject result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tint index = toIndex(null, property);\r\n\t\t\tresult = index < 0 || index >= Array.getLength(base) ? null : Array.get(base, index);\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a Java language array, returns whether a call to\r\n\t * {@link #setValue(ELContext, Object, Object, Object)} will always fail. If the base is a Java\r\n\t * language array, the propertyResolved property of the ELContext object must be set to true by\r\n\t * this resolver, before returning. If this property is not true after this method is called,\r\n\t * the caller should ignore the return value. If this resolver was constructed in read-only\r\n\t * mode, this method will always return true. Otherwise, it returns false.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The array to analyze. Only bases that are a Java language array are handled by\r\n\t * this resolver.\r\n\t * @param property\r\n\t * The index of the element in the array to return the acceptable type for. Will be\r\n\t * coerced into an integer, but otherwise ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then true if calling\r\n\t * the setValue method will always fail or false if it is possible that such a call may\r\n\t * succeed; otherwise undefined.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the given index is out of bounds for this array.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic boolean isReadOnly(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\ttoIndex(base, property);\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn readOnly;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a Java language array, attempts to set the value at the given index\r\n\t * with the given value. The index is specified by the property argument, and coerced into an\r\n\t * integer. If the coercion could not be performed, an IllegalArgumentException is thrown. If\r\n\t * the index is out of bounds, a PropertyNotFoundException is thrown. If the base is a Java\r\n\t * language array, the propertyResolved property of the ELContext object must be set to true by\r\n\t * this resolver, before returning. If this property is not true after this method is called,\r\n\t * the caller can safely assume no value was set. If this resolver was constructed in read-only\r\n\t * mode, this method will always throw PropertyNotWritableException.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The array to analyze. Only bases that are a Java language array are handled by\r\n\t * this resolver.\r\n\t * @param property\r\n\t * The index of the element in the array to return the acceptable type for. Will be\r\n\t * coerced into an integer, but otherwise ignored by this resolver.\r\n\t * @param value\r\n\t * The value to be set at the given index.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the given index is out of bounds for this array.\r\n\t * @throws ClassCastException\r\n\t * if the class of the specified element prevents it from being added to this array.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws IllegalArgumentException\r\n\t * if the property could not be coerced into an integer, or if some aspect of the\r\n\t * specified element prevents it from being added to this array.\r\n\t * @throws PropertyNotWritableException\r\n\t * if this resolver was constructed in read-only mode.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic void setValue(ELContext context, Object base, Object property, Object value) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tif (readOnly) {\r\n\t\t\t\tthrow new PropertyNotWritableException(\"resolver is read-only\");\r\n\t\t\t}\r\n\t\t\tArray.set(base, toIndex(base, property), value);\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Test whether the given base should be resolved by this ELResolver.\r\n\t * \r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return base != null && base.getClass().isArray()\r\n\t */\r\n\tprivate final boolean isResolvable(Object base) {\r\n\t\treturn base != null && base.getClass().isArray();\r\n\t}\r\n\r\n\t/**\r\n\t * Convert the given property to an index in (array) base.\r\n\t * \r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return The index of property in base.\r\n\t * @throws IllegalArgumentException\r\n\t * if base property cannot be coerced to an integer or base is not an array.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the computed index is out of bounds for base.\r\n\t */\r\n\tprivate final int toIndex(Object base, Object property) {\r\n\t\tint index = 0;\r\n\t\tif (property instanceof Number) {\r\n\t\t\tindex = ((Number) property).intValue();\r\n\t\t} else if (property instanceof String) {\r\n\t\t\ttry {\r\n\t\t\t\tindex = Integer.valueOf((String) property);\r\n\t\t\t} catch (NumberFormatException e) {\r\n\t\t\t\tthrow new IllegalArgumentException(\"Cannot parse array index: \" + property);\r\n\t\t\t}\r\n\t\t} else if (property instanceof Character) {\r\n\t\t\tindex = ((Character) property).charValue();\r\n\t\t} else if (property instanceof Boolean) {\r\n\t\t\tindex = ((Boolean) property).booleanValue() ? 1 : 0;\r\n\t\t} else {\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot coerce property to array index: \" + property);\r\n\t\t}\r\n\t\tif (base != null && (index < 0 || index >= Array.getLength(base))) {\r\n\t\t\tthrow new PropertyNotFoundException(\"Array index out of bounds: \" + index);\r\n\t\t}\r\n\t\treturn index;\r\n\t}\r\n}\r",
"public class BeanELResolver extends ELResolver {\r\n\tprotected static final class BeanProperties {\r\n\t\tprivate final Map<String, BeanProperty> map = new HashMap<String, BeanProperty>();\r\n\r\n\t\tpublic BeanProperties(Class<?> baseClass) {\r\n\t\t\tPropertyDescriptor[] descriptors;\r\n\t\t\ttry {\r\n\t\t\t\tdescriptors = Introspector.getBeanInfo(baseClass).getPropertyDescriptors();\r\n\t\t\t} catch (IntrospectionException e) {\r\n\t\t\t\tthrow new ELException(e);\r\n\t\t\t}\r\n\t\t\tfor (PropertyDescriptor descriptor : descriptors) {\r\n\t\t\t\tmap.put(descriptor.getName(), new BeanProperty(descriptor));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic BeanProperty getBeanProperty(String property) {\r\n\t\t\treturn map.get(property);\r\n\t\t}\r\n\t}\r\n\r\n\tprotected static final class BeanProperty {\r\n\t\tprivate final PropertyDescriptor descriptor;\r\n\t\t\r\n\t\tprivate Method readMethod;\r\n\t\tprivate Method writedMethod;\r\n\r\n\t\tpublic BeanProperty(PropertyDescriptor descriptor) {\r\n\t\t\tthis.descriptor = descriptor;\r\n\t\t}\r\n\r\n\t\tpublic Class<?> getPropertyType() {\r\n\t\t\treturn descriptor.getPropertyType();\r\n\t\t}\r\n\r\n\t\tpublic Method getReadMethod() {\r\n\t\t\tif (readMethod == null) {\r\n\t\t\t\treadMethod = findAccessibleMethod(descriptor.getReadMethod());\r\n\t\t\t}\r\n\t\t\treturn readMethod;\r\n\t\t}\r\n\r\n\t\tpublic Method getWriteMethod() {\r\n\t\t\tif (writedMethod == null) {\r\n\t\t\t\twritedMethod = findAccessibleMethod(descriptor.getWriteMethod());\r\n\t\t\t}\r\n\t\t\treturn writedMethod;\r\n\t\t}\r\n\r\n\t\tpublic boolean isReadOnly() {\r\n\t\t\treturn getWriteMethod() == null;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static Method findPublicAccessibleMethod(Method method) {\r\n\t\tif (method == null || !Modifier.isPublic(method.getModifiers())) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (method.isAccessible() || Modifier.isPublic(method.getDeclaringClass().getModifiers())) {\r\n\t\t\treturn method;\r\n\t\t}\r\n\t\tfor (Class<?> cls : method.getDeclaringClass().getInterfaces()) {\r\n\t\t\tMethod mth = null;\r\n\t\t\ttry {\r\n\t\t\t\tmth = findPublicAccessibleMethod(cls.getMethod(method.getName(), method.getParameterTypes()));\r\n\t\t\t\tif (mth != null) {\r\n\t\t\t\t\treturn mth;\r\n\t\t\t\t}\r\n\t\t\t} catch (NoSuchMethodException ignore) {\r\n\t\t\t\t// do nothing\r\n\t\t\t}\r\n\t\t}\r\n\t\tClass<?> cls = method.getDeclaringClass().getSuperclass();\r\n\t\tif (cls != null) {\r\n\t\t\tMethod mth = null;\r\n\t\t\ttry {\r\n\t\t\t\tmth = findPublicAccessibleMethod(cls.getMethod(method.getName(), method.getParameterTypes()));\r\n\t\t\t\tif (mth != null) {\r\n\t\t\t\t\treturn mth;\r\n\t\t\t\t}\r\n\t\t\t} catch (NoSuchMethodException ignore) {\r\n\t\t\t\t// do nothing\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprivate static Method findAccessibleMethod(Method method) {\r\n\t\tMethod result = findPublicAccessibleMethod(method);\r\n\t\tif (result == null && method != null && Modifier.isPublic(method.getModifiers())) {\r\n\t\t\tresult = method;\r\n\t\t\ttry {\r\n\t\t\t\tmethod.setAccessible(true);\r\n\t\t\t} catch (SecurityException e) {\r\n\t\t\t\tresult = null; \r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate final boolean readOnly;\r\n\tprivate final ConcurrentHashMap<Class<?>, BeanProperties> cache;\r\n\t\r\n\tprivate ExpressionFactory defaultFactory;\r\n\r\n\t/**\r\n\t * Creates a new read/write BeanELResolver.\r\n\t */\r\n\tpublic BeanELResolver() {\r\n\t\tthis(false);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a new BeanELResolver whose read-only status is determined by the given parameter.\r\n\t */\r\n\tpublic BeanELResolver(boolean readOnly) {\r\n\t\tthis.readOnly = readOnly;\r\n\t\tthis.cache = new ConcurrentHashMap<Class<?>, BeanProperties>();\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is not null, returns the most general type that this resolver accepts for\r\n\t * the property argument. Otherwise, returns null. Assuming the base is not null, this method\r\n\t * will always return Object.class. This is because any object is accepted as a key and is\r\n\t * coerced into a string.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @return null if base is null; otherwise Object.class.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getCommonPropertyType(ELContext context, Object base) {\r\n\t\treturn isResolvable(base) ? Object.class : null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is not null, returns an Iterator containing the set of JavaBeans\r\n\t * properties available on the given object. Otherwise, returns null. The Iterator returned must\r\n\t * contain zero or more instances of java.beans.FeatureDescriptor. Each info object contains\r\n\t * information about a property in the bean, as obtained by calling the\r\n\t * BeanInfo.getPropertyDescriptors method. The FeatureDescriptor is initialized using the same\r\n\t * fields as are present in the PropertyDescriptor, with the additional required named\r\n\t * attributes \"type\" and \"resolvableAtDesignTime\" set as follows:\r\n\t * <ul>\r\n\t * <li>{@link ELResolver#TYPE} - The runtime type of the property, from\r\n\t * PropertyDescriptor.getPropertyType().</li>\r\n\t * <li>{@link ELResolver#RESOLVABLE_AT_DESIGN_TIME} - true.</li>\r\n\t * </ul>\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @return An Iterator containing zero or more FeatureDescriptor objects, each representing a\r\n\t * property on this bean, or null if the base object is null.\r\n\t */\r\n\t@Override\r\n\tpublic Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tfinal PropertyDescriptor[] properties;\r\n\t\t\ttry {\r\n\t\t\t\tproperties = Introspector.getBeanInfo(base.getClass()).getPropertyDescriptors();\r\n\t\t\t} catch (IntrospectionException e) {\r\n\t\t\t\treturn Collections.<FeatureDescriptor> emptyList().iterator();\r\n\t\t\t}\r\n\t\t\treturn new Iterator<FeatureDescriptor>() {\r\n\t\t\t\tint next = 0;\r\n\r\n\t\t\t\tpublic boolean hasNext() {\r\n\t\t\t\t\treturn properties != null && next < properties.length;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpublic FeatureDescriptor next() {\r\n\t\t\t\t\tPropertyDescriptor property = properties[next++];\r\n\t\t\t\t\tFeatureDescriptor feature = new FeatureDescriptor();\r\n\t\t\t\t\tfeature.setDisplayName(property.getDisplayName());\r\n\t\t\t\t\tfeature.setName(property.getName());\r\n\t\t\t\t\tfeature.setShortDescription(property.getShortDescription());\r\n\t\t\t\t\tfeature.setExpert(property.isExpert());\r\n\t\t\t\t\tfeature.setHidden(property.isHidden());\r\n\t\t\t\t\tfeature.setPreferred(property.isPreferred());\r\n\t\t\t\t\tfeature.setValue(TYPE, property.getPropertyType());\r\n\t\t\t\t\tfeature.setValue(RESOLVABLE_AT_DESIGN_TIME, true);\r\n\t\t\t\t\treturn feature;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpublic void remove() {\r\n\t\t\t\t\tthrow new UnsupportedOperationException(\"cannot remove\");\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is not null, returns the most general acceptable type that can be set on\r\n\t * this bean property. If the base is not null, the propertyResolved property of the ELContext\r\n\t * object must be set to true by this resolver, before returning. If this property is not true\r\n\t * after this method is called, the caller should ignore the return value. The provided property\r\n\t * will first be coerced to a String. If there is a BeanInfoProperty for this property and there\r\n\t * were no errors retrieving it, the propertyType of the propertyDescriptor is returned.\r\n\t * Otherwise, a PropertyNotFoundException is thrown.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the most general\r\n\t * acceptable type; otherwise undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the specified property does not exist or is not readable.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getType(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException();\r\n\t\t}\r\n\t\tClass<?> result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tresult = toBeanProperty(base, property).getPropertyType();\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is not null, returns the current value of the given property on this bean.\r\n\t * If the base is not null, the propertyResolved property of the ELContext object must be set to\r\n\t * true by this resolver, before returning. If this property is not true after this method is\r\n\t * called, the caller should ignore the return value. The provided property name will first be\r\n\t * coerced to a String. If the property is a readable property of the base object, as per the\r\n\t * JavaBeans specification, then return the result of the getter call. If the getter throws an\r\n\t * exception, it is propagated to the caller. If the property is not found or is not readable, a\r\n\t * PropertyNotFoundException is thrown.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the value of the\r\n\t * given property. Otherwise, undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the specified property does not exist or is not readable.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Object getValue(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException();\r\n\t\t}\r\n\t\tObject result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tMethod method = toBeanProperty(base, property).getReadMethod();\r\n\t\t\tif (method == null) {\r\n\t\t\t\tthrow new PropertyNotFoundException(\"Cannot read property \" + property);\r\n\t\t\t}\r\n\t\t\ttry {\r\n\t\t\t\tresult = method.invoke(base);\r\n\t\t\t} catch (InvocationTargetException e) {\r\n\t\t\t\tthrow new ELException(e.getCause());\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tthrow new ELException(e);\r\n\t\t\t}\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is not null, returns whether a call to\r\n\t * {@link #setValue(ELContext, Object, Object, Object)} will always fail. If the base is not\r\n\t * null, the propertyResolved property of the ELContext object must be set to true by this\r\n\t * resolver, before returning. If this property is not true after this method is called, the\r\n\t * caller can safely assume no value was set.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then true if calling\r\n\t * the setValue method will always fail or false if it is possible that such a call may\r\n\t * succeed; otherwise undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the specified property does not exist or is not readable.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic boolean isReadOnly(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException();\r\n\t\t}\r\n\t\tboolean result = readOnly;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tresult |= toBeanProperty(base, property).isReadOnly();\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is not null, attempts to set the value of the given property on this bean.\r\n\t * If the base is not null, the propertyResolved property of the ELContext object must be set to\r\n\t * true by this resolver, before returning. If this property is not true after this method is\r\n\t * called, the caller can safely assume no value was set. If this resolver was constructed in\r\n\t * read-only mode, this method will always throw PropertyNotWritableException. The provided\r\n\t * property name will first be coerced to a String. If property is a writable property of base\r\n\t * (as per the JavaBeans Specification), the setter method is called (passing value). If the\r\n\t * property exists but does not have a setter, then a PropertyNotFoundException is thrown. If\r\n\t * the property does not exist, a PropertyNotFoundException is thrown.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @param value\r\n\t * The value to be associated with the specified key.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the specified property does not exist or is not readable.\r\n\t * @throws PropertyNotWritableException\r\n\t * if this resolver was constructed in read-only mode, or if there is no setter for\r\n\t * the property\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic void setValue(ELContext context, Object base, Object property, Object value) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException();\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tif (readOnly) {\r\n\t\t\t\tthrow new PropertyNotWritableException(\"resolver is read-only\");\r\n\t\t\t}\r\n\t\t\tMethod method = toBeanProperty(base, property).getWriteMethod();\r\n\t\t\tif (method == null) {\r\n\t\t\t\tthrow new PropertyNotWritableException(\"Cannot write property: \" + property);\r\n\t\t\t}\r\n\t\t\ttry {\r\n\t\t\t\tmethod.invoke(base, value);\r\n\t\t\t} catch (InvocationTargetException e) {\r\n\t\t\t\tthrow new ELException(\"Cannot write property: \" + property, e.getCause());\r\n\t\t\t} catch (IllegalArgumentException e) {\r\n\t\t\t\tthrow new ELException(\"Cannot write property: \" + property, e);\r\n\t\t\t} catch (IllegalAccessException e) {\r\n\t\t\t\tthrow new PropertyNotWritableException(\"Cannot write property: \" + property, e);\r\n\t\t\t}\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is not <code>null</code>, invoke the method, with the given parameters on\r\n\t * this bean. The return value from the method is returned.\r\n\t * \r\n\t * <p>\r\n\t * If the base is not <code>null</code>, the <code>propertyResolved</code> property of the\r\n\t * <code>ELContext</code> object must be set to <code>true</code> by this resolver, before\r\n\t * returning. If this property is not <code>true</code> after this method is called, the caller\r\n\t * should ignore the return value.\r\n\t * </p>\r\n\t * \r\n\t * <p>\r\n\t * The provided method object will first be coerced to a <code>String</code>. The methods in the\r\n\t * bean is then examined and an attempt will be made to select one for invocation. If no\r\n\t * suitable can be found, a <code>MethodNotFoundException</code> is thrown.\r\n\t * \r\n\t * If the given paramTypes is not <code>null</code>, select the method with the given name and\r\n\t * parameter types.\r\n\t * \r\n\t * Else select the method with the given name that has the same number of parameters. If there\r\n\t * are more than one such method, the method selection process is undefined.\r\n\t * \r\n\t * Else select the method with the given name that takes a variable number of arguments.\r\n\t * \r\n\t * Note the resolution for overloaded methods will likely be clarified in a future version of\r\n\t * the spec.\r\n\t * \r\n\t * The provided parameters are coerced to the corresponding parameter types of the method, and\r\n\t * the method is then invoked.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bean on which to invoke the method\r\n\t * @param method\r\n\t * The simple name of the method to invoke. Will be coerced to a <code>String</code>.\r\n\t * If method is \"<init>\"or \"<clinit>\" a MethodNotFoundException is\r\n\t * thrown.\r\n\t * @param paramTypes\r\n\t * An array of Class objects identifying the method's formal parameter types, in\r\n\t * declared order. Use an empty array if the method has no parameters. Can be\r\n\t * <code>null</code>, in which case the method's formal parameter types are assumed\r\n\t * to be unknown.\r\n\t * @param params\r\n\t * The parameters to pass to the method, or <code>null</code> if no parameters.\r\n\t * @return The result of the method invocation (<code>null</code> if the method has a\r\n\t * <code>void</code> return type).\r\n\t * @throws MethodNotFoundException\r\n\t * if no suitable method can be found.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing (base, method) resolution. The thrown\r\n\t * exception must be included as the cause property of this exception, if available.\r\n\t * If the exception thrown is an <code>InvocationTargetException</code>, extract its\r\n\t * <code>cause</code> and pass it to the <code>ELException</code> constructor.\r\n\t * @since 2.2\r\n\t */\r\n\t@Override\r\n\tpublic Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException();\r\n\t\t}\r\n\t\tObject result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tif (params == null) {\r\n\t\t\t\tparams = new Object[0];\r\n\t\t\t}\r\n\t\t\tString name = method.toString();\r\n\t\t\tMethod target = findMethod(base, name, paramTypes, params.length);\r\n\t\t\tif (target == null) {\r\n\t\t\t\tthrow new MethodNotFoundException(\"Cannot find method \" + name + \" with \" + params.length + \" parameters in \" + base.getClass());\r\n\t\t\t}\r\n\t\t\ttry {\r\n\t\t\t\tresult = target.invoke(base, coerceParams(getExpressionFactory(context), target, params));\r\n\t\t\t} catch (InvocationTargetException e) {\r\n\t\t\t\tthrow new ELException(e.getCause());\r\n\t\t\t} catch (IllegalAccessException e) {\r\n\t\t\t\tthrow new ELException(e);\r\n\t\t\t}\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t};\r\n\r\n\tprivate Method findMethod(Object base, String name, Class<?>[] types, int paramCount) {\r\n\t\tif (types != null) {\r\n\t\t\ttry {\r\n\t\t\t\treturn findAccessibleMethod(base.getClass().getMethod(name, types));\r\n\t\t\t} catch (NoSuchMethodException e) {\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\tMethod varArgsMethod = null;\r\n\t\tfor (Method method : base.getClass().getMethods()) {\r\n\t\t\tif (method.getName().equals(name)) {\r\n\t\t\t\tint formalParamCount = method.getParameterTypes().length;\r\n\t\t\t\tif (method.isVarArgs() && paramCount >= formalParamCount - 1) {\r\n\t\t\t\t\tvarArgsMethod = method;\r\n\t\t\t\t} else if (paramCount == formalParamCount) {\r\n\t\t\t\t\treturn findAccessibleMethod(method);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn varArgsMethod == null ? null : findAccessibleMethod(varArgsMethod);\r\n\t}\r\n\r\n\t/**\r\n\t * Lookup an expression factory used to coerce method parameters in context under key\r\n\t * <code>\"javax.el.ExpressionFactory\"</code>.\r\n\t * If no expression factory can be found under that key, use a default instance created with\r\n\t * {@link ExpressionFactory#newInstance()}.\r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @return expression factory instance\r\n\t */\r\n\tprivate ExpressionFactory getExpressionFactory(ELContext context) {\r\n\t\tObject obj = context.getContext(ExpressionFactory.class);\r\n\t\tif (obj instanceof ExpressionFactory) {\r\n\t\t\treturn (ExpressionFactory)obj;\r\n\t\t}\r\n\t\tif (defaultFactory == null) {\r\n\t\t\tdefaultFactory = ExpressionFactory.newInstance();\r\n\t\t}\r\n\t\treturn defaultFactory;\r\n\t}\r\n\t\r\n\tprivate Object[] coerceParams(ExpressionFactory factory, Method method, Object[] params) {\r\n\t\tClass<?>[] types = method.getParameterTypes();\r\n\t\tObject[] args = new Object[types.length];\r\n\t\tif (method.isVarArgs()) {\r\n\t\t\tint varargIndex = types.length - 1;\r\n\t\t\tif (params.length < varargIndex) {\r\n\t\t\t\tthrow new ELException(\"Bad argument count\");\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < varargIndex; i++) {\r\n\t\t\t\tcoerceValue(args, i, factory, params[i], types[i]);\r\n\t\t\t}\r\n\t\t\tClass<?> varargType = types[varargIndex].getComponentType();\r\n\t\t\tint length = params.length - varargIndex;\r\n\t\t\tObject array = null;\r\n\t\t\tif (length == 1) {\r\n\t\t\t\tObject source = params[varargIndex];\r\n\t\t\t\tif (source != null && source.getClass().isArray()) {\r\n\t\t\t\t\tif (types[varargIndex].isInstance(source)) { // use source array as is\r\n\t\t\t\t\t\tarray = source;\r\n\t\t\t\t\t} else { // coerce array elements\r\n\t\t\t\t\t\tlength = Array.getLength(source);\r\n\t\t\t\t\t\tarray = Array.newInstance(varargType, length);\r\n\t\t\t\t\t\tfor (int i = 0; i < length; i++) {\r\n\t\t\t\t\t\t\tcoerceValue(array, i, factory, Array.get(source, i), varargType);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else { // single element array\r\n\t\t\t\t\tarray = Array.newInstance(varargType, 1);\r\n\t\t\t\t\tcoerceValue(array, 0, factory, source, varargType);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tarray = Array.newInstance(varargType, length);\r\n\t\t\t\tfor (int i = 0; i < length; i++) {\r\n\t\t\t\t\tcoerceValue(array, i, factory, params[varargIndex + i], varargType);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\targs[varargIndex] = array;\r\n\t\t} else {\r\n\t\t\tif (params.length != args.length) {\r\n\t\t\t\tthrow new ELException(\"Bad argument count\");\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < args.length; i++) {\r\n\t\t\t\tcoerceValue(args, i, factory, params[i], types[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn args;\r\n\t}\r\n\r\n\tprivate void coerceValue(Object array, int index, ExpressionFactory factory, Object value, Class<?> type) {\r\n\t\tif (value != null || type.isPrimitive()) {\r\n\t\t\tArray.set(array, index, factory.coerceToType(value, type));\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Test whether the given base should be resolved by this ELResolver.\r\n\t * \r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return base != null\r\n\t */\r\n\tprivate final boolean isResolvable(Object base) {\r\n\t\treturn base != null;\r\n\t}\r\n\r\n\t/**\r\n\t * Lookup BeanProperty for the given (base, property) pair.\r\n\t * \r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return The BeanProperty representing (base, property).\r\n\t * @throws PropertyNotFoundException\r\n\t * if no BeanProperty can be found.\r\n\t */\r\n\tprivate final BeanProperty toBeanProperty(Object base, Object property) {\r\n\t\tBeanProperties beanProperties = cache.get(base.getClass());\r\n\t\tif (beanProperties == null) {\r\n\t\t\tBeanProperties newBeanProperties = new BeanProperties(base.getClass());\r\n\t\t\tbeanProperties = cache.putIfAbsent(base.getClass(), newBeanProperties);\r\n\t\t\tif (beanProperties == null) { // put succeeded, use new value\r\n\t\t\t\tbeanProperties = newBeanProperties;\r\n\t\t\t}\r\n\t\t}\r\n\t\tBeanProperty beanProperty = property == null ? null : beanProperties.getBeanProperty(property.toString());\r\n\t\tif (beanProperty == null) {\r\n\t\t\tthrow new PropertyNotFoundException(\"Could not find property \" + property + \" in \" + base.getClass());\r\n\t\t}\r\n\t\treturn beanProperty;\r\n\t}\r\n\r\n\t/**\r\n\t * This method is not part of the API, though it can be used (reflectively) by clients of this\r\n\t * class to remove entries from the cache when the beans are being unloaded.\r\n\t * \r\n\t * Note: this method is present in the reference implementation, so we're adding it here to ease\r\n\t * migration.\r\n\t * \r\n\t * @param classloader\r\n\t * The classLoader used to load the beans.\r\n\t */\r\n\t@SuppressWarnings(\"unused\")\r\n\tprivate final void purgeBeanClasses(ClassLoader loader) {\r\n\t\tIterator<Class<?>> classes = cache.keySet().iterator();\r\n\t\twhile (classes.hasNext()) {\r\n\t\t\tif (loader == classes.next().getClassLoader()) {\r\n\t\t\t\tclasses.remove();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r",
"public class CompositeELResolver extends ELResolver {\r\n\tprivate final List<ELResolver> resolvers = new ArrayList<ELResolver>();\r\n\r\n\t/**\r\n\t * Adds the given resolver to the list of component resolvers. Resolvers are consulted in the\r\n\t * order in which they are added.\r\n\t * \r\n\t * @param elResolver\r\n\t * The component resolver to add.\r\n\t * @throws NullPointerException\r\n\t * If the provided resolver is null.\r\n\t */\r\n\tpublic void add(ELResolver elResolver) {\r\n\t\tif (elResolver == null) {\r\n\t\t\tthrow new NullPointerException(\"resolver must not be null\");\r\n\t\t}\r\n\t\tresolvers.add(elResolver);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the most general type that this resolver accepts for the property argument, given a\r\n\t * base object. One use for this method is to assist tools in auto-completion. The result is\r\n\t * obtained by querying all component resolvers. The Class returned is the most specific class\r\n\t * that is a common superclass of all the classes returned by each component resolver's\r\n\t * getCommonPropertyType method. If null is returned by a resolver, it is skipped.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The base object to return the most general property type for, or null to enumerate\r\n\t * the set of top-level variables that this resolver can evaluate.\r\n\t * @return null if this ELResolver does not know how to handle the given base object; otherwise\r\n\t * Object.class if any type of property is accepted; otherwise the most general property\r\n\t * type accepted for the given base.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getCommonPropertyType(ELContext context, Object base) {\r\n\t\tClass<?> result = null;\r\n\t\tfor (int i = 0, l = resolvers.size(); i < l; i++) {\r\n\t\t\tClass<?> type = resolvers.get(i).getCommonPropertyType(context, base);\r\n\t\t\tif (type != null) {\r\n\t\t\t\tif (result == null || type.isAssignableFrom(result)) {\r\n\t\t\t\t\tresult = type;\r\n\t\t\t\t} else if (!result.isAssignableFrom(type)) {\r\n\t\t\t\t\tresult = Object.class;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns information about the set of variables or properties that can be resolved for the\r\n\t * given base object. One use for this method is to assist tools in auto-completion. The results\r\n\t * are collected from all component resolvers. The propertyResolved property of the ELContext is\r\n\t * not relevant to this method. The results of all ELResolvers are concatenated. The Iterator\r\n\t * returned is an iterator over the collection of FeatureDescriptor objects returned by the\r\n\t * iterators returned by each component resolver's getFeatureDescriptors method. If null is\r\n\t * returned by a resolver, it is skipped.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The base object to return the most general property type for, or null to enumerate\r\n\t * the set of top-level variables that this resolver can evaluate.\r\n\t * @return An Iterator containing zero or more (possibly infinitely more) FeatureDescriptor\r\n\t * objects, or null if this resolver does not handle the given base object or that the\r\n\t * results are too complex to represent with this method\r\n\t */\r\n\t@Override\r\n\tpublic Iterator<FeatureDescriptor> getFeatureDescriptors(final ELContext context, final Object base) {\r\n\t\treturn new Iterator<FeatureDescriptor>() {\r\n\t\t\tIterator<FeatureDescriptor> empty = Collections.<FeatureDescriptor> emptyList().iterator();\r\n\t\t\tIterator<ELResolver> resolvers = CompositeELResolver.this.resolvers.iterator();\r\n\t\t\tIterator<FeatureDescriptor> features = empty;\r\n\r\n\t\t\tIterator<FeatureDescriptor> features() {\r\n\t\t\t\twhile (!features.hasNext() && resolvers.hasNext()) {\r\n\t\t\t\t\tfeatures = resolvers.next().getFeatureDescriptors(context, base);\r\n\t\t\t\t\tif (features == null) {\r\n\t\t\t\t\t\tfeatures = empty;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn features;\r\n\t\t\t}\r\n\r\n\t\t\tpublic boolean hasNext() {\r\n\t\t\t\treturn features().hasNext();\r\n\t\t\t}\r\n\r\n\t\t\tpublic FeatureDescriptor next() {\r\n\t\t\t\treturn features().next();\r\n\t\t\t}\r\n\r\n\t\t\tpublic void remove() {\r\n\t\t\t\tfeatures().remove();\r\n\t\t\t}\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * For a given base and property, attempts to identify the most general type that is acceptable\r\n\t * for an object to be passed as the value parameter in a future call to the\r\n\t * {@link #setValue(ELContext, Object, Object, Object)} method. The result is obtained by\r\n\t * querying all component resolvers. If this resolver handles the given (base, property) pair,\r\n\t * the propertyResolved property of the ELContext object must be set to true by the resolver,\r\n\t * before returning. If this property is not true after this method is called, the caller should\r\n\t * ignore the return value. First, propertyResolved is set to false on the provided ELContext.\r\n\t * Next, for each component resolver in this composite:\r\n\t * <ol>\r\n\t * <li>The getType() method is called, passing in the provided context, base and property.</li>\r\n\t * <li>If the ELContext's propertyResolved flag is false then iteration continues.</li>\r\n\t * <li>Otherwise, iteration stops and no more component resolvers are considered. The value\r\n\t * returned by getType() is returned by this method.</li>\r\n\t * </ol>\r\n\t * If none of the component resolvers were able to perform this operation, the value null is\r\n\t * returned and the propertyResolved flag remains set to false. Any exception thrown by\r\n\t * component resolvers during the iteration is propagated to the caller of this method.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The base object to return the most general property type for, or null to enumerate\r\n\t * the set of top-level variables that this resolver can evaluate.\r\n\t * @param property\r\n\t * The property or variable to return the acceptable type for.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the most general\r\n\t * acceptable type; otherwise undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the specified property does not exist or is not readable.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getType(ELContext context, Object base, Object property) {\r\n\t\tcontext.setPropertyResolved(false);\r\n\t\tfor (int i = 0, l = resolvers.size(); i < l; i++) {\r\n\t\t\tClass<?> type = resolvers.get(i).getType(context, base, property);\r\n\t\t\tif (context.isPropertyResolved()) {\r\n\t\t\t\treturn type;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * Attempts to resolve the given property object on the given base object by querying all\r\n\t * component resolvers. If this resolver handles the given (base, property) pair, the\r\n\t * propertyResolved property of the ELContext object must be set to true by the resolver, before\r\n\t * returning. If this property is not true after this method is called, the caller should ignore\r\n\t * the return value. First, propertyResolved is set to false on the provided ELContext. Next,\r\n\t * for each component resolver in this composite:\r\n\t * <ol>\r\n\t * <li>The getValue() method is called, passing in the provided context, base and property.</li>\r\n\t * <li>If the ELContext's propertyResolved flag is false then iteration continues.</li>\r\n\t * <li>Otherwise, iteration stops and no more component resolvers are considered. The value\r\n\t * returned by getValue() is returned by this method.</li>\r\n\t * </ol>\r\n\t * If none of the component resolvers were able to perform this operation, the value null is\r\n\t * returned and the propertyResolved flag remains set to false. Any exception thrown by\r\n\t * component resolvers during the iteration is propagated to the caller of this method.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The base object to return the most general property type for, or null to enumerate\r\n\t * the set of top-level variables that this resolver can evaluate.\r\n\t * @param property\r\n\t * The property or variable to return the acceptable type for.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the result of the\r\n\t * variable or property resolution; otherwise undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the specified property does not exist or is not readable.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Object getValue(ELContext context, Object base, Object property) {\r\n\t\tcontext.setPropertyResolved(false);\r\n\t\tfor (int i = 0, l = resolvers.size(); i < l; i++) {\r\n\t\t\tObject value = resolvers.get(i).getValue(context, base, property);\r\n\t\t\tif (context.isPropertyResolved()) {\r\n\t\t\t\treturn value;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * For a given base and property, attempts to determine whether a call to\r\n\t * {@link #setValue(ELContext, Object, Object, Object)} will always fail. The result is obtained\r\n\t * by querying all component resolvers. If this resolver handles the given (base, property)\r\n\t * pair, the propertyResolved property of the ELContext object must be set to true by the\r\n\t * resolver, before returning. If this property is not true after this method is called, the\r\n\t * caller should ignore the return value. First, propertyResolved is set to false on the\r\n\t * provided ELContext. Next, for each component resolver in this composite:\r\n\t * <ol>\r\n\t * <li>The isReadOnly() method is called, passing in the provided context, base and property.</li>\r\n\t * <li>If the ELContext's propertyResolved flag is false then iteration continues.</li>\r\n\t * <li>Otherwise, iteration stops and no more component resolvers are considered. The value\r\n\t * returned by isReadOnly() is returned by this method.</li>\r\n\t * </ol>\r\n\t * If none of the component resolvers were able to perform this operation, the value false is\r\n\t * returned and the propertyResolved flag remains set to false. Any exception thrown by\r\n\t * component resolvers during the iteration is propagated to the caller of this method.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The base object to return the most general property type for, or null to enumerate\r\n\t * the set of top-level variables that this resolver can evaluate.\r\n\t * @param property\r\n\t * The property or variable to return the acceptable type for.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then true if the\r\n\t * property is read-only or false if not; otherwise undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the specified property does not exist or is not readable.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic boolean isReadOnly(ELContext context, Object base, Object property) {\r\n\t\tcontext.setPropertyResolved(false);\r\n\t\tfor (int i = 0, l = resolvers.size(); i < l; i++) {\r\n\t\t\tboolean readOnly = resolvers.get(i).isReadOnly(context, base, property);\r\n\t\t\tif (context.isPropertyResolved()) {\r\n\t\t\t\treturn readOnly;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/**\r\n\t * Attempts to set the value of the given property object on the given base object. All\r\n\t * component resolvers are asked to attempt to set the value. If this resolver handles the given\r\n\t * (base, property) pair, the propertyResolved property of the ELContext object must be set to\r\n\t * true by the resolver, before returning. If this property is not true after this method is\r\n\t * called, the caller can safely assume no value has been set. First, propertyResolved is set to\r\n\t * false on the provided ELContext. Next, for each component resolver in this composite:\r\n\t * <ol>\r\n\t * <li>The setValue() method is called, passing in the provided context, base, property and\r\n\t * value.</li>\r\n\t * <li>If the ELContext's propertyResolved flag is false then iteration continues.</li>\r\n\t * <li>Otherwise, iteration stops and no more component resolvers are considered.</li>\r\n\t * </ol>\r\n\t * If none of the component resolvers were able to perform this operation, the propertyResolved\r\n\t * flag remains set to false. Any exception thrown by component resolvers during the iteration\r\n\t * is propagated to the caller of this method.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The base object to return the most general property type for, or null to enumerate\r\n\t * the set of top-level variables that this resolver can evaluate.\r\n\t * @param property\r\n\t * The property or variable to return the acceptable type for.\r\n\t * @param value\r\n\t * The value to set the property or variable to.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the specified property does not exist or is not readable.\r\n\t * @throws PropertyNotWritableException\r\n\t * if the given (base, property) pair is handled by this ELResolver but the\r\n\t * specified variable or property is not writable.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while attempting to set the property or variable. The\r\n\t * thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic void setValue(ELContext context, Object base, Object property, Object value) {\r\n\t\tcontext.setPropertyResolved(false);\r\n\t\tfor (int i = 0, l = resolvers.size(); i < l; i++) {\r\n\t\t\tresolvers.get(i).setValue(context, base, property, value);\r\n\t\t\tif (context.isPropertyResolved()) {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Attempts to resolve and invoke the given <code>method</code> on the given <code>base</code>\r\n\t * object by querying all component resolvers.\r\n\t * \r\n\t * <p>\r\n\t * If this resolver handles the given (base, method) pair, the <code>propertyResolved</code>\r\n\t * property of the <code>ELContext</code> object must be set to <code>true</code> by the\r\n\t * resolver, before returning. If this property is not <code>true</code> after this method is\r\n\t * called, the caller should ignore the return value.\r\n\t * </p>\r\n\t * \r\n\t * <p>\r\n\t * First, <code>propertyResolved</code> is set to <code>false</code> on the provided\r\n\t * <code>ELContext</code>.\r\n\t * </p>\r\n\t * \r\n\t * <p>\r\n\t * Next, for each component resolver in this composite:\r\n\t * <ol>\r\n\t * <li>The <code>invoke()</code> method is called, passing in the provided <code>context</code>,\r\n\t * <code>base</code>, <code>method</code>, <code>paramTypes</code>, and <code>params</code>.</li>\r\n\t * <li>If the <code>ELContext</code>'s <code>propertyResolved</code> flag is <code>false</code>\r\n\t * then iteration continues.</li>\r\n\t * <li>Otherwise, iteration stops and no more component resolvers are considered. The value\r\n\t * returned by <code>getValue()</code> is returned by this method.</li>\r\n\t * </ol>\r\n\t * </p>\r\n\t * \r\n\t * <p>\r\n\t * If none of the component resolvers were able to perform this operation, the value\r\n\t * <code>null</code> is returned and the <code>propertyResolved</code> flag remains set to\r\n\t * <code>false</code>\r\n\t * </p>\r\n\t * \r\n\t * <p>\r\n\t * Any exception thrown by component resolvers during the iteration is propagated to the caller\r\n\t * of this method.\r\n\t * </p>\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bean on which to invoke the method\r\n\t * @param method\r\n\t * The simple name of the method to invoke. Will be coerced to a <code>String</code>.\r\n\t * If method is \"<init>\"or \"<clinit>\" a NoSuchMethodException is raised.\r\n\t * @param paramTypes\r\n\t * An array of Class objects identifying the method's formal parameter types, in\r\n\t * declared order. Use an empty array if the method has no parameters. Can be\r\n\t * <code>null</code>, in which case the method's formal parameter types are assumed\r\n\t * to be unknown.\r\n\t * @param params\r\n\t * The parameters to pass to the method, or <code>null</code> if no parameters.\r\n\t * @return The result of the method invocation (<code>null</code> if the method has a\r\n\t * <code>void</code> return type).\r\n\t * @since 2.2\r\n\t */\r\n\t@Override\r\n\tpublic Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {\r\n\t\tcontext.setPropertyResolved(false);\r\n\t\tfor (int i = 0, l = resolvers.size(); i < l; i++) {\r\n\t\t\tObject result = resolvers.get(i).invoke(context, base, method, paramTypes, params);\r\n\t\t\tif (context.isPropertyResolved()) {\r\n\t\t\t\treturn result;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n}\r",
"public abstract class ELContext {\r\n\tprivate Map<Class<?>, Object> context;\r\n\tprivate Locale locale;\r\n\tprivate boolean resolved;\r\n\r\n\t/**\r\n\t * Returns the context object associated with the given key. The ELContext maintains a\r\n\t * collection of context objects relevant to the evaluation of an expression. These context\r\n\t * objects are used by ELResolvers. This method is used to retrieve the context with the given\r\n\t * key from the collection. By convention, the object returned will be of the type specified by\r\n\t * the key. However, this is not required and the key is used strictly as a unique identifier.\r\n\t * \r\n\t * @param key\r\n\t * The unique identifier that was used to associate the context object with this\r\n\t * ELContext.\r\n\t * @return The context object associated with the given key, or null if no such context was\r\n\t * found.\r\n\t * @throws NullPointerException\r\n\t * if key is null.\r\n\t */\r\n\tpublic Object getContext(Class<?> key) {\r\n\t\tif (key == null) {\r\n\t\t\tthrow new NullPointerException(\"key is null\");\r\n\t\t}\r\n\t\tif (context == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn context.get(key);\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieves the ELResolver associated with this context. The ELContext maintains a reference to\r\n\t * the ELResolver that will be consulted to resolve variables and properties during an\r\n\t * expression evaluation. This method retrieves the reference to the resolver. Once an ELContext\r\n\t * is constructed, the reference to the ELResolver associated with the context cannot be\r\n\t * changed.\r\n\t * \r\n\t * @return The resolver to be consulted for variable and property resolution during expression\r\n\t * evaluation.\r\n\t */\r\n\tpublic abstract ELResolver getELResolver();\r\n\r\n\t/**\r\n\t * Retrieves the FunctionMapper associated with this ELContext.\r\n\t * \r\n\t * @return The function mapper to be consulted for the resolution of EL functions.\r\n\t */\r\n\tpublic abstract FunctionMapper getFunctionMapper();\r\n\r\n\t/**\r\n\t * Get the Locale stored by a previous invocation to {@link #setLocale(Locale)}. If this method\r\n\t * returns non null, this Locale must be used for all localization needs in the implementation.\r\n\t * The Locale must not be cached to allow for applications that change Locale dynamically.\r\n\t * \r\n\t * @return The Locale in which this instance is operating. Used primarily for message\r\n\t * localization.\r\n\t */\r\n\tpublic Locale getLocale() {\r\n\t\treturn locale;\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieves the VariableMapper associated with this ELContext.\r\n\t * \r\n\t * @return The variable mapper to be consulted for the resolution of EL variables.\r\n\t */\r\n\tpublic abstract VariableMapper getVariableMapper();\r\n\r\n\t/**\r\n\t * Returns whether an {@link ELResolver} has successfully resolved a given (base, property)\r\n\t * pair. The {@link CompositeELResolver} checks this property to determine whether it should\r\n\t * consider or skip other component resolvers.\r\n\t * \r\n\t * @return The variable mapper to be consulted for the resolution of EL variables.\r\n\t * @see CompositeELResolver\r\n\t */\r\n\tpublic boolean isPropertyResolved() {\r\n\t\treturn resolved;\r\n\t}\r\n\r\n\t/**\r\n\t * Associates a context object with this ELContext. The ELContext maintains a collection of\r\n\t * context objects relevant to the evaluation of an expression. These context objects are used\r\n\t * by ELResolvers. This method is used to add a context object to that collection. By\r\n\t * convention, the contextObject will be of the type specified by the key. However, this is not\r\n\t * required and the key is used strictly as a unique identifier.\r\n\t * \r\n\t * @param key\r\n\t * The key used by an {@link ELResolver} to identify this context object.\r\n\t * @param contextObject\r\n\t * The context object to add to the collection.\r\n\t * @throws NullPointerException\r\n\t * if key is null or contextObject is null.\r\n\t */\r\n\tpublic void putContext(Class<?> key, Object contextObject) {\r\n\t\tif (key == null) {\r\n\t\t\tthrow new NullPointerException(\"key is null\");\r\n\t\t}\r\n\t\tif (context == null) {\r\n\t\t\tcontext = new HashMap<Class<?>, Object>();\r\n\t\t}\r\n\t\tcontext.put(key, contextObject);\r\n\t}\r\n\r\n\t/**\r\n\t * Set the Locale for this instance. This method may be called by the party creating the\r\n\t * instance, such as JavaServer Faces or JSP, to enable the EL implementation to provide\r\n\t * localized messages to the user. If no Locale is set, the implementation must use the locale\r\n\t * returned by Locale.getDefault( ).\r\n\t * \r\n\t * @param locale\r\n\t * The Locale in which this instance is operating. Used primarily for message\r\n\t * localization.\r\n\t */\r\n\tpublic void setLocale(Locale locale) {\r\n\t\tthis.locale = locale;\r\n\t}\r\n\r\n\t/**\r\n\t * Called to indicate that a ELResolver has successfully resolved a given (base, property) pair.\r\n\t * The {@link CompositeELResolver} checks this property to determine whether it should consider\r\n\t * or skip other component resolvers.\r\n\t * \r\n\t * @param resolved\r\n\t * true if the property has been resolved, or false if not.\r\n\t * @see CompositeELResolver\r\n\t */\r\n\tpublic void setPropertyResolved(boolean resolved) {\r\n\t\tthis.resolved = resolved;\r\n\t}\r\n}\r",
"public class ListELResolver extends ELResolver {\r\n\tprivate final boolean readOnly;\r\n\r\n\t/**\r\n\t * Creates a new read/write ListELResolver.\r\n\t */\r\n\tpublic ListELResolver() {\r\n\t\tthis(false);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a new ListELResolver whose read-only status is determined by the given parameter.\r\n\t * \r\n\t * @param readOnly\r\n\t * true if this resolver cannot modify lists; false otherwise.\r\n\t */\r\n\tpublic ListELResolver(boolean readOnly) {\r\n\t\tthis.readOnly = readOnly;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a list, returns the most general type that this resolver accepts for\r\n\t * the property argument. Otherwise, returns null. Assuming the base is a List, this method will\r\n\t * always return Integer.class. This is because Lists accept integers as their index.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The list to analyze. Only bases of type List are handled by this resolver.\r\n\t * @return null if base is not a List; otherwise Integer.class.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getCommonPropertyType(ELContext context, Object base) {\r\n\t\treturn isResolvable(base) ? Integer.class : null;\r\n\t}\r\n\r\n\t/**\r\n\t * Always returns null, since there is no reason to iterate through set set of all integers.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The list to analyze. Only bases of type List are handled by this resolver.\r\n\t * @return null.\r\n\t */\r\n\t@Override\r\n\tpublic Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a list, returns the most general acceptable type for a value in this\r\n\t * list. If the base is a List, the propertyResolved property of the ELContext object must be\r\n\t * set to true by this resolver, before returning. If this property is not true after this\r\n\t * method is called, the caller should ignore the return value. Assuming the base is a List,\r\n\t * this method will always return Object.class. This is because Lists accept any object as an\r\n\t * element.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The list to analyze. Only bases of type List are handled by this resolver.\r\n\t * @param property\r\n\t * The index of the element in the list to return the acceptable type for. Will be\r\n\t * coerced into an integer, but otherwise ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the most general\r\n\t * acceptable type; otherwise undefined.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the given index is out of bounds for this list.\r\n\t * @throws IllegalArgumentException\r\n\t * if the property could not be coerced into an integer.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getType(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tClass<?> result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\ttoIndex((List<?>) base, property);\r\n\t\t\tresult = Object.class;\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a list, returns the value at the given index. The index is specified by\r\n\t * the property argument, and coerced into an integer. If the coercion could not be performed,\r\n\t * an IllegalArgumentException is thrown. If the index is out of bounds, null is returned. If\r\n\t * the base is a List, the propertyResolved property of the ELContext object must be set to true\r\n\t * by this resolver, before returning. If this property is not true after this method is called,\r\n\t * the caller should ignore the return value.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The list to analyze. Only bases of type List are handled by this resolver.\r\n\t * @param property\r\n\t * The index of the element in the list to return the acceptable type for. Will be\r\n\t * coerced into an integer, but otherwise ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the value at the\r\n\t * given index or null if the index was out of bounds. Otherwise, undefined.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the given index is out of bounds for this list.\r\n\t * @throws IllegalArgumentException\r\n\t * if the property could not be coerced into an integer.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Object getValue(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tObject result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tint index = toIndex(null, property);\r\n\t\t\tList<?> list = (List<?>) base;\r\n\t\t\tresult = index < 0 || index >= list.size() ? null : list.get(index);\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a list, returns whether a call to\r\n\t * {@link #setValue(ELContext, Object, Object, Object)} will always fail. If the base is a List,\r\n\t * the propertyResolved property of the ELContext object must be set to true by this resolver,\r\n\t * before returning. If this property is not true after this method is called, the caller should\r\n\t * ignore the return value. If this resolver was constructed in read-only mode, this method will\r\n\t * always return true. If a List was created using java.util.Collections.unmodifiableList(List),\r\n\t * this method must return true. Unfortunately, there is no Collections API method to detect\r\n\t * this. However, an implementation can create a prototype unmodifiable List and query its\r\n\t * runtime type to see if it matches the runtime type of the base object as a workaround.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The list to analyze. Only bases of type List are handled by this resolver.\r\n\t * @param property\r\n\t * The index of the element in the list to return the acceptable type for. Will be\r\n\t * coerced into an integer, but otherwise ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then true if calling\r\n\t * the setValue method will always fail or false if it is possible that such a call may\r\n\t * succeed; otherwise undefined.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the given index is out of bounds for this list.\r\n\t * @throws IllegalArgumentException\r\n\t * if the property could not be coerced into an integer.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic boolean isReadOnly(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\ttoIndex((List<?>) base, property);\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn readOnly;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a list, attempts to set the value at the given index with the given\r\n\t * value. The index is specified by the property argument, and coerced into an integer. If the\r\n\t * coercion could not be performed, an IllegalArgumentException is thrown. If the index is out\r\n\t * of bounds, a PropertyNotFoundException is thrown. If the base is a List, the propertyResolved\r\n\t * property of the ELContext object must be set to true by this resolver, before returning. If\r\n\t * this property is not true after this method is called, the caller can safely assume no value\r\n\t * was set. If this resolver was constructed in read-only mode, this method will always throw\r\n\t * PropertyNotWritableException. If a List was created using\r\n\t * java.util.Collections.unmodifiableList(List), this method must throw\r\n\t * PropertyNotWritableException. Unfortunately, there is no Collections API method to detect\r\n\t * this. However, an implementation can create a prototype unmodifiable List and query its\r\n\t * runtime type to see if it matches the runtime type of the base object as a workaround.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The list to analyze. Only bases of type List are handled by this resolver.\r\n\t * @param property\r\n\t * The index of the element in the list to return the acceptable type for. Will be\r\n\t * coerced into an integer, but otherwise ignored by this resolver.\r\n\t * @param value\r\n\t * The value to be set at the given index.\r\n\t * @throws ClassCastException\r\n\t * if the class of the specified element prevents it from being added to this list.\r\n\t * @throws PropertyNotFoundException\r\n\t * if the given index is out of bounds for this list.\r\n\t * @throws PropertyNotWritableException\r\n\t * if this resolver was constructed in read-only mode, or if the set operation is\r\n\t * not supported by the underlying list.\r\n\t * @throws IllegalArgumentException\r\n\t * if the property could not be coerced into an integer.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic void setValue(ELContext context, Object base, Object property, Object value) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tif (readOnly) {\r\n\t\t\t\tthrow new PropertyNotWritableException(\"resolver is read-only\");\r\n\t\t\t}\r\n\t\t\tList list = (List) base;\r\n\t\t\tint index = toIndex(list, property);\r\n\t\t\ttry {\r\n\t\t\t\tlist.set(index, value);\r\n\t\t\t} catch (UnsupportedOperationException e) {\r\n\t\t\t\tthrow new PropertyNotWritableException(e);\r\n\t\t\t} catch (ArrayStoreException e) {\r\n\t\t\t\tthrow new IllegalArgumentException(e);\r\n\t\t\t}\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Test whether the given base should be resolved by this ELResolver.\r\n\t * \r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return base instanceof List\r\n\t */\r\n\tprivate static final boolean isResolvable(Object base) {\r\n\t\treturn base instanceof List<?>;\r\n\t}\r\n\r\n\t/**\r\n\t * Convert the given property to an index in (list) base.\r\n\t * \r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return The index of property in base.\r\n\t * @throws IllegalArgumentException\r\n\t * if base property cannot be coerced to an integer.\r\n\t * @throws PropertyNotFoundException\r\n\t * if base is not null and the computed index is out of bounds for base.\r\n\t */\r\n\tprivate static final int toIndex(List<?> base, Object property) {\r\n\t\tint index = 0;\r\n\t\tif (property instanceof Number) {\r\n\t\t\tindex = ((Number) property).intValue();\r\n\t\t} else if (property instanceof String) {\r\n\t\t\ttry {\r\n\t\t\t\tindex = Integer.valueOf((String) property);\r\n\t\t\t} catch (NumberFormatException e) {\r\n\t\t\t\tthrow new IllegalArgumentException(\"Cannot parse list index: \" + property);\r\n\t\t\t}\r\n\t\t} else if (property instanceof Character) {\r\n\t\t\tindex = ((Character) property).charValue();\r\n\t\t} else if (property instanceof Boolean) {\r\n\t\t\tindex = ((Boolean) property).booleanValue() ? 1 : 0;\r\n\t\t} else {\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot coerce property to list index: \" + property);\r\n\t\t}\r\n\t\tif (base != null && (index < 0 || index >= base.size())) {\r\n\t\t\tthrow new PropertyNotFoundException(\"List index out of bounds: \" + index);\r\n\t\t}\r\n\t\treturn index;\r\n\t}\r\n}\r",
"public class MapELResolver extends ELResolver {\r\n\tprivate final boolean readOnly;\r\n\r\n\t/**\r\n\t * Creates a new read/write MapELResolver.\r\n\t */\r\n\tpublic MapELResolver() {\r\n\t\tthis(false);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a new MapELResolver whose read-only status is determined by the given parameter.\r\n\t */\r\n\tpublic MapELResolver(boolean readOnly) {\r\n\t\tthis.readOnly = readOnly;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a map, returns the most general type that this resolver accepts for the\r\n\t * property argument. Otherwise, returns null. Assuming the base is a Map, this method will\r\n\t * always return Object.class. This is because Maps accept any object as a key.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The map to analyze. Only bases of type Map are handled by this resolver.\r\n\t * @return null if base is not a Map; otherwise Object.class.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getCommonPropertyType(ELContext context, Object base) {\r\n\t\treturn isResolvable(base) ? Object.class : null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a map, returns an Iterator containing the set of keys available in the\r\n\t * Map. Otherwise, returns null. The Iterator returned must contain zero or more instances of\r\n\t * java.beans.FeatureDescriptor. Each info object contains information about a key in the Map,\r\n\t * and is initialized as follows:\r\n\t * <ul>\r\n\t * <li>displayName - The return value of calling the toString method on this key, or \"null\" if\r\n\t * the key is null</li>\r\n\t * <li>name - Same as displayName property</li>\r\n\t * <li>shortDescription - Empty string</li>\r\n\t * <li>expert - false</li>\r\n\t * <li>hidden - false</li>\r\n\t * <li>preferred - true</li>\r\n\t * </ul>\r\n\t * In addition, the following named attributes must be set in the returned FeatureDescriptors:\r\n\t * <ul>\r\n\t * <li>{@link ELResolver#TYPE} - The return value of calling the getClass() method on this key,\r\n\t * or null if the key is null.</li>\r\n\t * <li>{@link ELResolver#RESOLVABLE_AT_DESIGN_TIME} - true</li>\r\n\t * </ul>\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The map to analyze. Only bases of type Map are handled by this resolver.\r\n\t * @return An Iterator containing zero or more (possibly infinitely more) FeatureDescriptor\r\n\t * objects, each representing a key in this map, or null if the base object is not a\r\n\t * map.\r\n\t */\r\n\t@Override\r\n\tpublic Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tMap<?, ?> map = (Map<?, ?>) base;\r\n\t\t\tfinal Iterator<?> keys = map.keySet().iterator();\r\n\t\t\treturn new Iterator<FeatureDescriptor>() {\r\n\t\t\t\tpublic boolean hasNext() {\r\n\t\t\t\t\treturn keys.hasNext();\r\n\t\t\t\t}\r\n\t\t\t\tpublic FeatureDescriptor next() {\r\n\t\t\t\t\tObject key = keys.next();\r\n\t\t\t\t\tFeatureDescriptor feature = new FeatureDescriptor();\r\n\t\t\t\t\tfeature.setDisplayName(key == null ? \"null\" : key.toString());\r\n\t\t\t\t\tfeature.setName(feature.getDisplayName());\r\n\t\t\t\t\tfeature.setShortDescription(\"\");\r\n\t\t\t\t\tfeature.setExpert(true);\r\n\t\t\t\t\tfeature.setHidden(false);\r\n\t\t\t\t\tfeature.setPreferred(true);\r\n\t\t\t\t\tfeature.setValue(TYPE, key == null ? null : key.getClass());\r\n\t\t\t\t\tfeature.setValue(RESOLVABLE_AT_DESIGN_TIME, true);\r\n\t\t\t\t\treturn feature;\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\tpublic void remove() {\r\n\t\t\t\t\tthrow new UnsupportedOperationException(\"cannot remove\");\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a map, returns the most general acceptable type for a value in this\r\n\t * map. If the base is a Map, the propertyResolved property of the ELContext object must be set\r\n\t * to true by this resolver, before returning. If this property is not true after this method is\r\n\t * called, the caller should ignore the return value. Assuming the base is a Map, this method\r\n\t * will always return Object.class. This is because Maps accept any object as the value for a\r\n\t * given key.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The map to analyze. Only bases of type Map are handled by this resolver.\r\n\t * @param property\r\n\t * The key to return the acceptable type for. Ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the most general\r\n\t * acceptable type; otherwise undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getType(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tClass<?> result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tresult = Object.class;\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a map, returns the value associated with the given key, as specified by\r\n\t * the property argument. If the key was not found, null is returned. If the base is a Map, the\r\n\t * propertyResolved property of the ELContext object must be set to true by this resolver,\r\n\t * before returning. If this property is not true after this method is called, the caller should\r\n\t * ignore the return value. Just as in java.util.Map.get(Object), just because null is returned\r\n\t * doesn't mean there is no mapping for the key; it's also possible that the Map explicitly maps\r\n\t * the key to null.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The map to analyze. Only bases of type Map are handled by this resolver.\r\n\t * @param property\r\n\t * The key to return the acceptable type for. Ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then the value\r\n\t * associated with the given key or null if the key was not found. Otherwise, undefined.\r\n\t * @throws ClassCastException\r\n\t * if the key is of an inappropriate type for this map (optionally thrown by the\r\n\t * underlying Map).\r\n\t * @throws NullPointerException\r\n\t * if context is null, or if the key is null and this map does not permit null keys\r\n\t * (the latter is optionally thrown by the underlying Map).\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Object getValue(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tObject result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tresult = ((Map<?, ?>) base).get(property);\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a map, returns whether a call to\r\n\t * {@link #setValue(ELContext, Object, Object, Object)} will always fail. If the base is a Map,\r\n\t * the propertyResolved property of the ELContext object must be set to true by this resolver,\r\n\t * before returning. If this property is not true after this method is called, the caller should\r\n\t * ignore the return value. If this resolver was constructed in read-only mode, this method will\r\n\t * always return true. If a Map was created using java.util.Collections.unmodifiableMap(Map),\r\n\t * this method must return true. Unfortunately, there is no Collections API method to detect\r\n\t * this. However, an implementation can create a prototype unmodifiable Map and query its\r\n\t * runtime type to see if it matches the runtime type of the base object as a workaround.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The map to analyze. Only bases of type Map are handled by this resolver.\r\n\t * @param property\r\n\t * The key to return the acceptable type for. Ignored by this resolver.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then true if calling\r\n\t * the setValue method will always fail or false if it is possible that such a call may\r\n\t * succeed; otherwise undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic boolean isReadOnly(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn readOnly;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a map, attempts to set the value associated with the given key, as\r\n\t * specified by the property argument. If the base is a Map, the propertyResolved property of\r\n\t * the ELContext object must be set to true by this resolver, before returning. If this property\r\n\t * is not true after this method is called, the caller can safely assume no value was set. If\r\n\t * this resolver was constructed in read-only mode, this method will always throw\r\n\t * PropertyNotWritableException. If a Map was created using\r\n\t * java.util.Collections.unmodifiableMap(Map), this method must throw\r\n\t * PropertyNotWritableException. Unfortunately, there is no Collections API method to detect\r\n\t * this. However, an implementation can create a prototype unmodifiable Map and query its\r\n\t * runtime type to see if it matches the runtime type of the base object as a workaround.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The map to analyze. Only bases of type Map are handled by this resolver.\r\n\t * @param property\r\n\t * The key to return the acceptable type for. Ignored by this resolver.\r\n\t * @param value\r\n\t * The value to be associated with the specified key.\r\n\t * @throws ClassCastException\r\n\t * if the class of the specified key or value prevents it from being stored in this\r\n\t * map.\r\n\t * @throws NullPointerException\r\n\t * if context is null, or if this map does not permit null keys or values, and the\r\n\t * specified key or value is null.\r\n\t * @throws IllegalArgumentException\r\n\t * if some aspect of this key or value prevents it from being stored in this map.\r\n\t * @throws PropertyNotWritableException\r\n\t * if this resolver was constructed in read-only mode, or if the put operation is\r\n\t * not supported by the underlying map.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic void setValue(ELContext context, Object base, Object property, Object value) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tif (readOnly) {\r\n\t\t\t\tthrow new PropertyNotWritableException(\"resolver is read-only\");\r\n\t\t\t}\r\n\t\t\t((Map) base).put(property, value);\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Test whether the given base should be resolved by this ELResolver.\r\n\t * \r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return base instanceof Map\r\n\t */\r\n\tprivate final boolean isResolvable(Object base) {\r\n\t\treturn base instanceof Map<?,?>;\r\n\t}\r\n}\r",
"public class ResourceBundleELResolver extends ELResolver {\r\n\t/**\r\n\t * If the base object is a ResourceBundle, returns the most general type that this resolver\r\n\t * accepts for the property argument. Otherwise, returns null. Assuming the base is a\r\n\t * ResourceBundle, this method will always return String.class.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bundle to analyze. Only bases of type ResourceBundle are handled by this\r\n\t * resolver.\r\n\t * @return null if base is not a ResourceBundle; otherwise String.class.\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getCommonPropertyType(ELContext context, Object base) {\r\n\t\treturn isResolvable(base) ? String.class : null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a ResourceBundle, returns an Iterator containing the set of keys\r\n\t * available in the ResourceBundle. Otherwise, returns null. The Iterator returned must contain\r\n\t * zero or more instances of java.beans.FeatureDescriptor. Each info object contains information\r\n\t * about a key in the ResourceBundle, and is initialized as follows:\r\n\t * <ul>\r\n\t * <li>displayName - The String key name</li>\r\n\t * <li>name - Same as displayName property</li>\r\n\t * <li>shortDescription - Empty string</li>\r\n\t * <li>expert - false</li>\r\n\t * <li>hidden - false</li>\r\n\t * <li>preferred - true</li>\r\n\t * </ul>\r\n\t * In addition, the following named attributes must be set in the returned FeatureDescriptors:\r\n\t * <ul>\r\n\t * <li>{@link ELResolver#TYPE} - String.class.</li>\r\n\t * <li>{@link ELResolver#RESOLVABLE_AT_DESIGN_TIME} - true</li>\r\n\t * </ul>\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bundle to analyze. Only bases of type ResourceBundle are handled by this\r\n\t * resolver.\r\n\t * @return An Iterator containing zero or more (possibly infinitely more) FeatureDescriptor\r\n\t * objects, each representing a key in this bundle, or null if the base object is not a\r\n\t * ResourceBundle.\r\n\t */\r\n\t@Override\r\n\tpublic Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tfinal Enumeration<String> keys = ((ResourceBundle) base).getKeys();\r\n\t\t\treturn new Iterator<FeatureDescriptor>() {\r\n\t\t\t\tpublic boolean hasNext() {\r\n\t\t\t\t\treturn keys.hasMoreElements();\r\n\t\t\t\t}\r\n\t\t\t\tpublic FeatureDescriptor next() {\r\n\t\t\t\t\tFeatureDescriptor feature = new FeatureDescriptor();\r\n\t\t\t\t\tfeature.setDisplayName(keys.nextElement());\r\n\t\t\t\t\tfeature.setName(feature.getDisplayName());\r\n\t\t\t\t\tfeature.setShortDescription(\"\");\r\n\t\t\t\t\tfeature.setExpert(true);\r\n\t\t\t\t\tfeature.setHidden(false);\r\n\t\t\t\t\tfeature.setPreferred(true);\r\n\t\t\t\t\tfeature.setValue(TYPE, String.class);\r\n\t\t\t\t\tfeature.setValue(RESOLVABLE_AT_DESIGN_TIME, true);\r\n\t\t\t\t\treturn feature;\r\n\t\t\t\t}\r\n\t\t\t\tpublic void remove() {\r\n\t\t\t\t\tthrow new UnsupportedOperationException(\"Cannot remove\");\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is an instance of ResourceBundle, return null, since the resolver is read\r\n\t * only. If the base is ResourceBundle, the propertyResolved property of the ELContext object\r\n\t * must be set to true by this resolver, before returning. If this property is not true after\r\n\t * this method is called, the caller should ignore the return value.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bundle to analyze. Only bases of type ResourceBundle are handled by this\r\n\t * resolver.\r\n\t * @param property\r\n\t * The name of the property to analyze.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then null; otherwise\r\n\t * undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null\r\n\t */\r\n\t@Override\r\n\tpublic Class<?> getType(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is an instance of ResourceBundle, the provided property will first be\r\n\t * coerced to a String. The Object returned by getObject on the base ResourceBundle will be\r\n\t * returned. If the base is ResourceBundle, the propertyResolved property of the ELContext\r\n\t * object must be set to true by this resolver, before returning. If this property is not true\r\n\t * after this method is called, the caller should ignore the return value.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bundle to analyze. Only bases of type ResourceBundle are handled by this\r\n\t * resolver.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return If the propertyResolved property of ELContext was set to true, then null if property\r\n\t * is null; otherwise the Object for the given key (property coerced to String) from the\r\n\t * ResourceBundle. If no object for the given key can be found, then the String \"???\" +\r\n\t * key + \"???\".\r\n\t * @throws NullPointerException\r\n\t * if context is null.\r\n\t * @throws ELException\r\n\t * if an exception was thrown while performing the property or variable resolution.\r\n\t * The thrown exception must be included as the cause property of this exception, if\r\n\t * available.\r\n\t */\r\n\t@Override\r\n\tpublic Object getValue(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tObject result = null;\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tif (property != null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tresult = ((ResourceBundle) base).getObject(property.toString());\r\n\t\t\t\t} catch (MissingResourceException e) {\r\n\t\t\t\t\tresult = \"???\" + property + \"???\";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is not null and an instanceof java.util.ResourceBundle, return true.\r\n\t * \r\n\t * @return If the propertyResolved property of ELContext was set to true, then true; otherwise\r\n\t * undefined.\r\n\t * @throws NullPointerException\r\n\t * if context is null.\r\n\t */\r\n\t@Override\r\n\tpublic boolean isReadOnly(ELContext context, Object base, Object property) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tcontext.setPropertyResolved(true);\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/**\r\n\t * If the base object is a ResourceBundle, throw a {@link PropertyNotWritableException}.\r\n\t * \r\n\t * @param context\r\n\t * The context of this evaluation.\r\n\t * @param base\r\n\t * The bundle to analyze. Only bases of type ResourceBundle are handled by this\r\n\t * resolver.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @param value\r\n\t * The value to be set.\r\n\t * @throws NullPointerException\r\n\t * if context is null.\r\n\t * @throws PropertyNotWritableException\r\n\t * Always thrown if base is an instance of ResourceBundle.\r\n\t */\r\n\t@Override\r\n\tpublic void setValue(ELContext context, Object base, Object property, Object value) {\r\n\t\tif (context == null) {\r\n\t\t\tthrow new NullPointerException(\"context is null\");\r\n\t\t}\r\n\t\tif (isResolvable(base)) {\r\n\t\t\tthrow new PropertyNotWritableException(\"resolver is read-only\");\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Test whether the given base should be resolved by this ELResolver.\r\n\t * \r\n\t * @param base\r\n\t * The bean to analyze.\r\n\t * @param property\r\n\t * The name of the property to analyze. Will be coerced to a String.\r\n\t * @return base instanceof ResourceBundle\r\n\t */\r\n\tprivate final boolean isResolvable(Object base) {\r\n\t\treturn base instanceof ResourceBundle;\r\n\t}\r\n}\r"
] | import java.beans.FeatureDescriptor;
import java.util.Iterator;
import javax.el.ArrayELResolver;
import javax.el.BeanELResolver;
import javax.el.CompositeELResolver;
import javax.el.ELContext;
import javax.el.ELResolver;
import javax.el.ListELResolver;
import javax.el.MapELResolver;
import javax.el.ResourceBundleELResolver;
| /*
* Copyright 2006-2009 Odysseus Software GmbH
*
* 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 de.odysseus.el.util;
/**
* Simple resolver implementation. This resolver handles root properties (top-level identifiers).
* Resolving "real" properties (<code>base != null</code>) is delegated to a resolver specified at
* construction time.
*
* @author Christoph Beck
*/
public class SimpleResolver extends ELResolver {
private static final ELResolver DEFAULT_RESOLVER_READ_ONLY = new CompositeELResolver() {
{
add(new ArrayELResolver(true));
add(new ListELResolver(true));
add(new MapELResolver(true));
| add(new ResourceBundleELResolver());
| 6 |
ardeleanasm/quantum_computing | quantumapp/src/main/java/com/ars/algorithms/grover/GroversAlgorithm.java | [
"public class MeasurementPerformer {\r\n\tprivate Qubit resultQubit = null;\r\n\tprivate int length;\r\n\tprivate static final double Q_TOLERANCE = 0.1e-5;\r\n\r\n\tpublic MeasurementPerformer() {\r\n\r\n\t}\r\n\r\n\tpublic MeasurementPerformer configure(Qubit resultQubit) {\r\n\t\tthis.resultQubit = resultQubit;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic Qubit measure() {\r\n\t\t// collapse state;\r\n\t\tint position = fakeMeasure();\r\n\t\tcollapseState(position);\r\n\t\treturn resultQubit;\r\n\t}\r\n\r\n\tprivate void collapseState(int position) {\r\n\t\tComplexNumber[] collapsedQubit = resultQubit.getQubit();\r\n\t\tfor (int i = 0; i < collapsedQubit.length; i++) {\r\n\t\t\tcollapsedQubit[i] = new ComplexNumber(0.0, 0.0);\r\n\t\t}\r\n\t\tcollapsedQubit[position] = new ComplexNumber(1.0, 0.0);\r\n\t\tresultQubit = new Qubit(collapsedQubit);\r\n\t}\r\n\r\n\tprivate int fakeMeasure() {\r\n\t\tlength = resultQubit.getQubit().length;\r\n\t\tdouble[] probabilities = new double[length];\r\n\t\tdouble value = 0.0;\r\n\t\tdouble total = 0.0;// total probability\r\n\t\tdouble choice;\r\n\t\tint position = 0;\r\n\t\tint idx = 0;\r\n\t\tint lastPositionWithNonZeroValue = 0;\r\n\t\t// fill probabilities array and calculate total probability\r\n\t\tfor (ComplexNumber c : resultQubit.getQubit()) {\r\n\t\t\tvalue = ComplexMath.multiply(c, ComplexMath.conjugate(c)).getReal();\r\n\t\t\ttotal += value;\r\n\t\t\tprobabilities[position++] = value;\r\n\t\t}\r\n\t\tassert (Math.abs(total - 1.0) < Q_TOLERANCE);\r\n\t\t// normalize probabilities array\r\n\t\tfor (position = 0; position < length; position++) {\r\n\t\t\tprobabilities[position] /= total;\r\n\t\t}\r\n\t\t// use random value to measure state\r\n\t\tchoice = new Random(System.currentTimeMillis()).nextDouble();\r\n\r\n\t\tfor (idx = 0, position = 0; idx < length; ++idx, ++position) {\r\n\t\t\tvalue = probabilities[idx];\r\n\t\t\tif (Double.compare(value, 0.0) != 0) {\r\n\t\t\t\tlastPositionWithNonZeroValue = idx;\r\n\t\t\t}\r\n\t\t\tif (Double.compare((choice - value), 0.0) == 0 || Double.compare((choice - value), 0.0) < 0) {\r\n\t\t\t\treturn position;// proper entry, just return it\r\n\t\t\t}\r\n\t\t\tchoice -= value;// update and continue\r\n\t\t}\r\n\t\tif (Math.abs(choice) < Q_TOLERANCE) {\r\n\t\t\treturn lastPositionWithNonZeroValue;\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n}\r",
"public abstract class QuantumAlgorithms {\r\n\tprotected IGate oracle;\r\n\tprotected Qubit resultQubit;\r\n\tprotected GatesAbstractFactory gateFactory = GateProducer.getGateFactory();\r\n\r\n\r\n\tpublic QuantumAlgorithms() {\r\n\r\n\t}\r\n\r\n\tpublic QuantumAlgorithms(IGate oracle) {\r\n\t\tthis.oracle = oracle;\r\n\t}\r\n\r\n\tpublic void setOracle(IGate oracle) {\r\n\t\tthis.oracle = oracle;\r\n\t}\r\n\r\n\tpublic abstract void init();\r\n\r\n\tpublic abstract void run();\r\n\r\n\tpublic abstract void measure();\r\n\r\n\r\n}\r",
"public enum EGateTypes {\r\n\t/**\r\n\t * Hadamard Gate\r\n\t */\r\n\tE_HadamardGate,\r\n\t/**\r\n\t * Pauli-X Gate\r\n\t */\r\n\tE_XGate,\r\n\t/**\r\n\t * Pauli-Y Gate\r\n\t */\r\n\tE_YGate,\r\n\t/**\r\n\t * Pauli-Z Gate\r\n\t */\r\n\tE_ZGate,\r\n\t/**\r\n\t * CNOT Gate\r\n\t */\r\n\tE_CNotGate,\r\n\t/**\r\n\t * Controlled Phase Shift\r\n\t */\r\n\tE_CPhaseShift,\r\n\t/**\r\n\t * Identity gate\r\n\t */\r\n\tE_IGate\r\n\t\r\n}\r",
"public interface IGate {\r\n\t\r\n\tpublic Qubit applyGate(Qubit inputQubit,int[] targetPosition,int[] conditions,int noOfEntangledQubits);\r\n\t\r\n\t\r\n\t\r\n}\r",
"public class RegisterOverflowException extends Exception {\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 4071226864956577717L;\n\n\tpublic RegisterOverflowException(){\n\t\tsuper(\"Register size exceeded!\");\n\t}\n}",
"public class QRegisterOperations {\n\tprivate static final QRegisterOperations INSTANCE = new QRegisterOperations();\n\n\tprivate QRegisterOperations() {\n\t}\n\n\tpublic static QRegisterOperations getInstance() {\n\t\treturn INSTANCE;\n\t}\n\n\tpublic List<Qubit> fillWith(List<Qubit> list,\n\t\t\tSupplier<Qubit> qubitSupplier, int size) {\n\t\tlist = Stream.generate(qubitSupplier).limit(size)\n\t\t\t\t.collect(Collectors.toList());\n\t\treturn list;\n\t}\n\n\tpublic QRegister fillWith(QRegister reg, Supplier<Qubit> qubitSupplier) {\n\t\treg.setQubits(Stream.generate(qubitSupplier).limit(reg.size())\n\t\t\t\t.collect(Collectors.toList()));\n\t\treturn reg;\n\t}\n\n\tpublic QRegister fillWithPattern(String pattern)\n\t\t\tthrows RegisterOverflowException {\n\t\tQRegister qreg = new QRegister(pattern.length()).initialize();\n\t\tfor (int i = 0; i < pattern.length(); i++) {\n\t\t\tif (pattern.charAt(i) == '1') {\n\t\t\t\tqreg.change(i, new QubitOne());\n\t\t\t} else {\n\t\t\t\tqreg.change(i, new QubitZero());\n\t\t\t}\n\t\t}\n\t\treturn qreg;\n\t}\n\n\t/**\n\t * Perform the tensor product between two or more qubits. Example, for three\n\t * qubits |0>, |0> and |1>, the result will be |001>.\n\t * \n\t * @param quantumRegister\n\t * @return qubit the tensor product of the two qubits.\n\t */\n\tpublic Qubit entangle(QRegister quantumRegister) {\n\t\tif (quantumRegister.size() < 2) {\n\t\t\treturn null;\n\t\t}\n\t\tQubit bufferQubit = quantumRegister.get(0);\n\t\tfor (int i = 1; i < quantumRegister.size(); i++) {\n\t\t\tbufferQubit = QuantumOperations.entangle(bufferQubit,\n\t\t\t\t\tquantumRegister.get(i));\n\n\t\t}\n\t\treturn bufferQubit;\n\t}\n\n}",
"public class QuantumOperations {\r\n\r\n\t/**\r\n\t * Performs the tensor product of two qubits. Example, if q1=|0> and q2=|1>\r\n\t * the method will return |01>.\r\n\t * \r\n\t * @param q1 first qubit\r\n\t * @param q2 second qubit\r\n\t * @return qubit the tensor product of the two qubits.\r\n\t */\r\n\tpublic static Qubit entangle(Qubit q1, Qubit q2) {\r\n\r\n\t\treturn performTensorProduct(q1, q2);\r\n\t}\r\n\r\n\t/**\r\n\t * Perform the tensor product between two or more qubits. Example, for three\r\n\t * qubits |0>, |0> and |1>, the result will be |001>.\r\n\t * \r\n\t * @param Variable number of qubits \r\n\t * @return qubit the tensor product of the two qubits.\r\n\t */\r\n\tpublic static Qubit entangle(Qubit...qubits){\r\n\t\tQubit bufferQubit=qubits[0];\r\n\t\tfor(int i=1;i<qubits.length;i++){\r\n\t\t\tbufferQubit = performTensorProduct(bufferQubit, qubits[i]);\r\n\t\t}\r\n\t\treturn bufferQubit;\r\n\t}\r\n\t\r\n\r\n\r\n\tprivate static Qubit performTensorProduct(Qubit q1, Qubit q2) {\r\n\t\tint len1 = q1.getQubit().length;\r\n\t\tint len2 = q2.getQubit().length;\r\n\t\tComplexNumber[] complexNumberList = new ComplexNumber[len1 * len2];\r\n\t\tint k = 0;\r\n\t\tfor (int i = 0; i < len1; i++) {\r\n\t\t\tfor (int j = 0; j < len2; j++) {\r\n\t\t\t\tcomplexNumberList[k++] = ComplexMath.multiply(q1.getQubit()[i], q2.getQubit()[j]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn new Qubit(complexNumberList);\r\n\t}\r\n\r\n\r\n\t\r\n\t\r\n\tprivate static ComplexNumber[][] calculateTranspose(ComplexNumber[] z) {\r\n\t\tComplexNumber[][] transpose = new ComplexNumber[1][z.length];\r\n\t\tfor (int i = 0; i < z.length; i++) {\r\n\t\t\ttranspose[0][i] = z[i];\r\n\t\t}\r\n\r\n\t\treturn transpose;\r\n\t}\r\n\r\n\t/**\r\n\t * Calculate the transpose of qubit; |q>-> <q|\r\n\t * \r\n\t * @param q qubit.\r\n\t * @return ComplexNumber[][]\r\n\t */\r\n\tpublic static ComplexNumber[][] transpose(Qubit q) {\r\n\t\treturn calculateTranspose(q.getQubit());\r\n\t}\r\n\r\n\t/**\r\n\t * Calculate the transpose of qubit; |q>-> <q|\r\n\t * \r\n\t * @param q qubit.\r\n\t * @return ComplexNumber[][]\r\n\t */\r\n\tpublic static ComplexNumber[][] transpose(ComplexNumber[] z) {\r\n\t\treturn calculateTranspose(z);\r\n\t}\r\n\r\n\tprivate static ComplexNumber[][] calculateOuterProduct(ComplexNumber[] z1, ComplexNumber[] z2) {\r\n\t\tComplexNumber[][] result = null;\r\n\t\tif (z1.length == z2.length) {\r\n\t\t\tComplexNumber[][] transposeSecondArray = calculateTranspose(z2);\r\n\t\t\tint numberOfRows = z1.length;\r\n\t\t\tint numberOfRowsSecondMatrix = 1;\r\n\t\t\tint numberOfCollsSecondMatrix = transposeSecondArray[0].length;\r\n\t\t\tresult = new ComplexNumber[numberOfRows][numberOfCollsSecondMatrix];\r\n\t\t\tComplexNumber sum = new ComplexNumber(0.0, 0.0);\r\n\t\t\t// fill matrix with 0;\r\n\t\t\tfor (int i = 0; i < numberOfRows; i++) {\r\n\t\t\t\tfor (int j = 0; j < numberOfCollsSecondMatrix; j++) {\r\n\t\t\t\t\tfor (int k = 0; k < numberOfRowsSecondMatrix; k++) {\r\n\t\t\t\t\t\tsum = ComplexMath.add(sum, ComplexMath.multiply(z1[i], transposeSecondArray[k][j]));\r\n\t\t\t\t\t}\r\n\t\t\t\t\tresult[i][j] = sum;\r\n\t\t\t\t\tsum = new ComplexNumber();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}else{\r\n\t\t\tthrow new IncorrectMatrixSizeException(\"Both state arrays must have the same size.\");\r\n\t\t}\r\n\t\r\n\t\treturn result;\r\n\t}\r\n\r\n\t\r\n\t\r\n\t/**\r\n\t * Performs the outer product of two qubits |q1><q2|\r\n\t * \r\n\t * @param q1 first qubit\r\n\t * @param q2 second qubit\r\n\t * @return ComplexNumber the outer product of the two qubits.\r\n\t */\r\n\tpublic static ComplexNumber[][] outerProduct(Qubit q1, Qubit q2) {\r\n\t\treturn calculateOuterProduct(q1.getQubit(), q2.getQubit());\r\n\t}\r\n\r\n\t/**\r\n\t * Performs the outer product of two qubits |q1><q2|\r\n\t * \r\n\t * @param z1 first qubit\r\n\t * @param z2 second qubit\r\n\t * @return ComplexNumber the outer product of the two qubits.\r\n\t */\r\n\tpublic static ComplexNumber[][] outerProduct(ComplexNumber[] z1, ComplexNumber[] z2) {\r\n\t\treturn calculateOuterProduct(z1, z2);\r\n\t}\r\n\r\n\tprivate static ComplexNumber calculateInnerProduct(ComplexNumber[] z1, ComplexNumber[] z2) {\r\n\t\tComplexNumber result = new ComplexNumber(0.0, 0.0);\r\n\t\tif (z1.length == z2.length) {\r\n\t\t\tComplexNumber[][] transposeFirstArray = calculateTranspose(z1);\r\n\t\t\tint numberOfRows = z2.length;\r\n\r\n\t\t\tfor (int i = 0; i < numberOfRows; i++) {\r\n\t\t\t\tresult = ComplexMath.add(result, ComplexMath.multiply(transposeFirstArray[0][i], z2[i]));\r\n\t\t\t}\r\n\t\t}else{\r\n\t\t\tthrow new IncorrectMatrixSizeException(\"Both state arrays must have the same size.\");\r\n\t\t}\r\n\t\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * Performs the inner product of two qubits <q1|q2>\r\n\t * \r\n\t * @param q1 first qubit\r\n\t * @param q2 second qubit\r\n\t * @return ComplexNumber the inner product of the two qubits.\r\n\t */\r\n\tpublic static ComplexNumber innerProduct(Qubit q1, Qubit q2) {\r\n\t\treturn calculateInnerProduct(q1.getQubit(), q2.getQubit());\r\n\t}\r\n\t\r\n\t/**\r\n\t * Performs the inner product of two qubits <q1|q2>\r\n\t * \r\n\t * @param z1 first qubit\r\n\t * @param z2 second qubit\r\n\t * @return ComplexNumber the inner product of the two qubits.\r\n\t */\r\n\tpublic static ComplexNumber innerProduct(ComplexNumber[] z1, ComplexNumber[] z2) {\r\n\t\treturn calculateInnerProduct(z1, z2);\r\n\t}\r\n\r\n}\r",
"public class QRegister implements Iterable<Qubit> {\n\tprivate List<Qubit>\tqubitRegister;\n\tprivate int\t\t\tregisterSize;\n\n\tpublic QRegister(int size) {\n\t\tthis.registerSize = size;\n\t\tqubitRegister = new ArrayList<>(size);\n\n\t}\n\n\tpublic QRegister initialize() {\n\t\tqubitRegister = QRegisterOperations.getInstance().fillWith(qubitRegister, QubitZero::new, registerSize);\n\t\treturn this;\n\t}\n\n\tpublic int size() {\n\t\treturn registerSize;\n\t}\n\n\tpublic void add(Qubit e) throws RegisterOverflowException {\n\t\tif (qubitRegister.size() >= registerSize) {\n\t\t\tthrow new RegisterOverflowException();\n\t\t}\n\t\tqubitRegister.add(e);\n\t}\n\n\tpublic QRegister change(int index, Qubit e) {\n\t\tqubitRegister.set(index, e);\n\t\treturn this;\n\t}\n\n\tpublic Qubit get(int index) {\n\t\treturn qubitRegister.get(index);\n\t}\n\n\t@Override\n\tpublic Iterator<Qubit> iterator() {\n\t\treturn qubitRegister.iterator();\n\t}\n\n\tpublic List<Qubit> getQubits() {\n\t\treturn qubitRegister;\n\t}\n\n\tpublic void setQubits(List<Qubit> qubits) {\n\t\tqubitRegister = qubits;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuffer buffer = new StringBuffer();\n\t\tfor (Qubit q : qubitRegister)\n\t\t\tbuffer.append(q);\n\t\treturn buffer.toString();\n\t}\n}"
] | import com.ars.algorithms.MeasurementPerformer;
import com.ars.algorithms.QuantumAlgorithms;
import com.ars.gates.EGateTypes;
import com.ars.gates.IGate;
import com.ars.quantum.exception.RegisterOverflowException;
import com.ars.quantum.utils.QRegisterOperations;
import com.ars.quantum.utils.QuantumOperations;
import com.ars.qubits.QRegister;
| package com.ars.algorithms.grover;
public class GroversAlgorithm extends QuantumAlgorithms {
private static final int NO_OF_INPUT = 3;
private IGate gateH;
private IGate gateX;
private IGate gateCNot;
private IGate gateCPhaseShift;
public GroversAlgorithm() {
}
@Override
public void init() {
gateH = gateFactory.getGate(EGateTypes.E_HadamardGate);
gateX = gateFactory.getGate(EGateTypes.E_XGate);
gateCNot = gateFactory.getGate(EGateTypes.E_CNotGate);
gateCPhaseShift = gateFactory.getGate(EGateTypes.E_CPhaseShift);
QRegister qRegister=new QRegister(NO_OF_INPUT+1);
| QRegisterOperations qRegOps=QRegisterOperations.getInstance();
| 5 |
nchambers/probschemas | src/main/java/nate/probschemas/KeywordDetector.java | [
"public class IDFMap {\n// private HashMap<String,Integer> _wordToDocAppearances;\n// private HashMap<String,Integer> _wordToFrequencies;\n// private HashMap<String,Float> _wordToIDF;\n private Map<String,WordCounts> _wordToCounts;\n private int _numDocs = 0;\n private int _totalCorpusCount = 0;\n\n private class WordCounts {\n public int docFrequency;\n public int tokenFrequency;\n public float idfScore;\n public float informationContent;\n public String toString() { return docFrequency + \" \" + tokenFrequency + \" \" + idfScore + \" \" + informationContent; }\n }\n \n public IDFMap() {\n this(20000);\n }\n\n public IDFMap(int capacity) {\n// _wordToDocAppearances = new HashMap<String, Integer>(capacity);\n// _wordToFrequencies = new HashMap<String, Integer>(capacity);\n// _wordToIDF = new HashMap<String, Float>(capacity);\n _wordToCounts = new HashMap<String, WordCounts>(capacity);\n }\n\n public IDFMap(String filename) {\n this(20000);\n fromFile(filename);\n }\n\n /**\n * Search for the file of IDF scores in the resource space and on disk.\n * @return Path to the file, or null if not found.\n */\n public static String findIDFPath() {\n // Search in the resource space (maven sets this up for you).\n URL url = (new IDFMap(1)).getClass().getClassLoader().getResource(\"tokens-lemmas-ap2006.idf.gz\");\n if( url != null )\n return url.getFile();\n\n // Search in hard-coded paths on your disk.\n \tString[] paths = { \"/home/nchamber/projects/muc/tokens-idfs-ap/tokens-lemmas.idf-20062\", \n \t \"/home/nchamber/scr/tokens-idfs-ap/tokens-lemmas.idf-2006\" };\n \tfor( String path : paths )\n \t\tif( Directory.fileExists(path) )\n \t\t\treturn path;\n \t \t\n return null;\n }\n \n /**\n * @param filename The name of a file to create for the IDF scores\n */ \n public void saveToFile(String filename) {\n Set<String> keys = _wordToCounts.keySet();\n System.out.println(\"key size \" + keys.size());\n TreeSet<String> treeset = new TreeSet<String>(keys);\n try {\n BufferedWriter out = new BufferedWriter(new FileWriter(filename));\n out.write(\"NUMDOCS \" + _numDocs + \"\\n\");\n for( String word : treeset ) {\n //\tout.write( word + \" : \" + wordToDocAppearances.get(word) + \" : \" +\n //\t\t wordToIDF.get(word) + \"\\n\");\n String outstr = String.format(\"%s\\t%d\\t%d\\t%.2f\", word, getFrequency(word), getDocCount(word), get(word));\n// out.write( word + \"\\t\" + \n// _wordToFrequencies.get(word) + \"\\t\" +\n// _wordToDocAppearances.get(word) + \"\\t\" +\n// _wordToIDF.get(word) + \"\\n\");\n out.write(outstr);\n float ic = getInformationContent(word); \n if( ic == 0 ) out.write(\"\\t0\");\n else out.write(String.format(\"\\t%.2f\", ic));\n out.write(\"\\n\");\n }\n out.close();\n } catch( Exception ex ) { ex.printStackTrace(); }\n }\n\n\n /**\n * @param filename The name of the IDF file\n * @desc Read in a list of words and their IDF counts\n */\n public void fromFile(String filename) {\n if( filename == null || filename.length() > 0 ) {\n System.out.println(\"...reading IDF file \" + filename);\n String line = null;\n\n BufferedReader in = null;\n try {\n // Zipped\n if( filename.endsWith(\".gz\") ) {\n InputStream istr = new GZIPInputStream(new FileInputStream(new File(filename)));\n in = new BufferedReader(new InputStreamReader(istr));\n }\n // Non-zipped\n else {\n in = new BufferedReader(new FileReader(filename));\n }\n } catch( Exception ex ) { \n System.out.println(\"(IDFMap.java) Error opening file: \" + filename);\n ex.printStackTrace();\n System.exit(-1);\n }\n\n try {\n line = in.readLine();\n // number of docs\n _numDocs = Integer.valueOf(line.substring(line.indexOf(' ')+1));\n System.out.println(\"...based on \" + _numDocs + \" docs\");\n // word list\n while( (line = in.readLine()) != null ) {\n String parts[] = line.split(\"\\t\");\n int freq = Integer.valueOf(parts[1]);\n _totalCorpusCount += freq;\n\n setFrequency(parts[0], freq);\n setDocCount(parts[0], Integer.valueOf(parts[2]));\n setIDFScore(parts[0], Float.valueOf(parts[3]));\n if( parts.length > 4 ) setInformationContent(parts[0], Float.valueOf(parts[4]));\n// System.out.println(\"idf\\t\" + parts[0] + \"\\t\" + getCounts(parts[0]));\n }\n in.close();\n } catch( Exception ex ) { \n System.out.println(\"Exception reading line: \" + line);\n ex.printStackTrace(); \n System.exit(1);\n }\n\n } else {\n System.out.println(\"WARNING: IDFMap fromFile() got an empty path\");\n System.exit(1);\n }\n }\n\n public void setFrequency(String token, int freq) {\n WordCounts counts = getCounts(token);\n counts.tokenFrequency = freq;\n// _wordToFrequencies.put(token, freq);\n }\n \n public void setDocCount(String token, int count) {\n WordCounts counts = getCounts(token);\n counts.docFrequency = count;\n// _wordToDocAppearances.put(token, count);\n }\n \n public void setIDFScore(String token, float score) {\n WordCounts counts = getCounts(token);\n counts.idfScore = score;\n// _wordToIDF.put(token, score);\n }\n \n public void setInformationContent(String token, float score) {\n WordCounts counts = getCounts(token);\n counts.informationContent = score;\n }\n \n private WordCounts getCounts(String token) {\n WordCounts counts = _wordToCounts.get(token);\n if( counts == null ) {\n counts = new WordCounts();\n _wordToCounts.put(token, counts);\n }\n return counts;\n }\n \n public void printIDF() {\n Set<String> keys = _wordToCounts.keySet();\n TreeSet<String> treeset = new TreeSet<String>(keys);\n // Object words[] = keys.toArray();\n // Arrays.sort(words);\n for( String word : treeset )\n System.out.println( word + \" \" + get(word) );\n }\n\n\n /**\n * @desc Calculate the IDF score for all verbs\n */\n public void calculateIDF() {\n System.out.println(\"Calculating IDF\");\n _totalCorpusCount = 0;\n double numDocs = (double)_numDocs;\n \n for( Map.Entry<String,WordCounts> entry : _wordToCounts.entrySet() ) {\n WordCounts counts = entry.getValue();\n double seenInDocs = (double)counts.docFrequency;\n float idf = (float)Math.log(numDocs / seenInDocs);\n counts.idfScore = idf;\n _totalCorpusCount += counts.tokenFrequency;\n }\n }\n \n /**\n * @return True if the given word is in our map, false otherwise.\n */\n public boolean contains(String word) {\n return _wordToCounts.containsKey(word);\n }\n \n /**\n * @param word A string word\n * @return The IDF of the word, or 0 if the word is unknown.\n */\n public float get(String word) {\n WordCounts counts = _wordToCounts.get(word); \n if( counts == null )\n return 0;\n else\n return counts.idfScore;\n }\n\n /**\n * @param word A string word\n * @return The number of documents in which the word appears\n */\n public int getDocCount(String word) {\n WordCounts counts = _wordToCounts.get(word); \n if( counts == null )\n return 0;\n else\n return counts.docFrequency;\n }\n\n /**\n * @param word A string word\n * @return The number of times the word appears (term frequency over corpus)\n */\n public int getFrequency(String word) {\n WordCounts counts = _wordToCounts.get(word); \n if( counts == null )\n return 0;\n else\n return counts.tokenFrequency;\n }\n\n public float getInformationContent(String word) {\n WordCounts counts = _wordToCounts.get(word); \n if( counts == null )\n return 0;\n else\n return counts.informationContent;\n }\n \n /**\n * @return The set of words\n */\n public Set<String> getWords() {\n return _wordToCounts.keySet();\n }\n \n /**\n * Make a new vector of just frequency counts. \n * @param cutoff Return all tokens that occur at least this many times.\n * @return A vector of frequency counts.\n */\n public Map<String,Integer> getFrequencyVector(int cutoff) {\n Map<String,Integer> freq = new HashMap<String,Integer>();\n for( Map.Entry<String,WordCounts> entry : _wordToCounts.entrySet() ) {\n if( entry.getValue().tokenFrequency >= cutoff )\n freq.put(entry.getKey(), entry.getValue().tokenFrequency);\n }\n return freq;\n }\n\n /**\n * @desc Increase the number of documents a single word appears in by one.\n * @param word A string word\n */\n public void increaseDocCount(String word) {\n WordCounts counts = _wordToCounts.get(word); \n if( counts == null ) {\n counts = new WordCounts();\n _wordToCounts.put(word, counts);\n counts.docFrequency = 1;\n }\n else counts.docFrequency++;\n }\n\n /**\n * @desc Increase the number of documents a single word appears in by one.\n * @param word A string word\n */\n public void increaseTermFrequency(String word) {\n WordCounts counts = _wordToCounts.get(word); \n if( counts == null ) {\n counts = new WordCounts();\n _wordToCounts.put(word, counts);\n counts.tokenFrequency = 1;\n }\n else counts.tokenFrequency++;\n }\n\n /**\n * @return The sum of all term frequency counts of all words.\n */\n public int totalCorpusCount() {\n return _totalCorpusCount;\n }\n\n /**\n * @desc Increase the total # of documents\n */\n public void increaseDocCount() {\n // System.out.println(\"Increasing total doc count \");\n _numDocs++;\n }\n\n public int numDocs() { return _numDocs; }\n \n public void clear() {\n \t_wordToCounts.clear();\n \t_wordToCounts = null;\n }\n}",
"public class ProcessedData {\n GigawordHandler _parseReader = null;\n GigaDocReader _eventReader = null;\n GigaDocReader _depsReader = null;\n GigaDocReader _nerReader = null;\n Vector<String> _parseStrings;\n\n String _pPath;\n String _dPath;\n String _cPath;\n String _nPath;\n \n public ProcessedData(String parsePath, String depsPath, String corefPath, String nerPath) {\n _pPath = parsePath;\n _dPath = depsPath;\n _cPath = corefPath;\n _nPath = nerPath;\n reset();\n }\n\n public void reset() { \n if( _pPath != null ) _parseReader = new GigawordProcessed(_pPath);\n if( _dPath != null ) _depsReader = new GigaDocReader(_dPath);\n if( _cPath != null ) _eventReader = new GigaDocReader(_cPath);\n if( _nPath != null ) _nerReader = new GigaDocReader(_nPath);\n System.out.println(\"ProcessedData reset() \" + _pPath + \" - \" + _dPath + \" - \" + _cPath + \" - \" + _nPath);\n }\n \n public String currentStory() {\n if( _parseReader == null ) {\n System.out.println(\"ERROR: null parses\");\n System.exit(-1);\n }\n return _parseReader.currentStory();\n }\n\n public int currentStoryNum() {\n if( _parseReader == null ) {\n System.out.println(\"ERROR: null parses\");\n System.exit(-1);\n }\n return _parseReader.currentStoryNum();\n }\n\n public int currentDoc() {\n if( _parseReader == null ) {\n System.out.println(\"ERROR: null parses\");\n System.exit(-1);\n }\n return _parseReader.currentDoc();\n }\n \n public void nextStory() {\n if( _parseReader == null ) {\n System.out.println(\"ERROR: null parses\");\n System.exit(-1);\n }\n\n _parseStrings = _parseReader.nextStory();\n if( _eventReader != null )\n _eventReader.nextStory(_parseReader.currentStory());\n if( _depsReader != null )\n _depsReader.nextStory(_parseReader.currentStory());\n if( _nerReader != null )\n _nerReader.nextStory(_parseReader.currentStory());\n }\n \n /**\n * Advance to a specific story.\n */\n public void nextStory(String storyname) {\n if( _parseReader == null ) {\n System.out.println(\"ERROR: null parses\");\n System.exit(-1);\n }\n\n _parseStrings = _parseReader.nextStory(storyname);\n if( _eventReader != null )\n _eventReader.nextStory(storyname);\n if( _depsReader != null )\n _depsReader.nextStory(storyname);\n if( _nerReader != null )\n _nerReader.nextStory(storyname);\n }\n\n public Vector<String> getParseStrings() {\n return _parseStrings;\n }\n \n public List<EntityMention> getEntities() {\n return _eventReader.getEntities();\n }\n \n public List<List<TypedDependency>> getDependencies() {\n return _depsReader.getDependencies();\n }\n \n public ProcessedDocument getDocument() {\n return new ProcessedDocument(_parseReader.currentStory(), getParseStrings(), getDependencies(), getEntities(), getNER());\n }\n \n public List<NERSpan> getNER() {\n if( _nerReader != null )\n return _nerReader.getNER();\n else return null;\n }\n \n public void close() {\n if( _eventReader != null )\n _eventReader.close();\n if( _depsReader != null )\n _depsReader.close();\n if( _nerReader != null )\n _nerReader.close();\n }\n}",
"public class Directory {\n\n public static String stripGZ(String filename) {\n if( filename.endsWith(\".gz\") )\n return filename.substring(0, filename.length()-3);\n else return filename;\n }\n \n /**\n * @return True if the given path is an existing file. False otherwise.\n */\n public static boolean fileExists(String filename) {\n try {\n File file = new File(filename);\n if( file.exists() ) return true;\n } catch(Exception ex) { ex.printStackTrace(); }\n return false;\n }\n \n public static boolean isDirectory(String path) {\n try {\n File file = new File(path);\n if( file.isDirectory() ) return true;\n } catch(Exception ex) { ex.printStackTrace(); }\n return false;\n }\n\n /**\n * Touches a file in a given directory.\n * @param filename The filename\n * @param dir The directory \n * @return true if it worked. false otherwise.\n */\n public static boolean touch(String dir, String filename) {\n return touch(dir + File.separator + filename);\n }\n \n /**\n * Touches a file at the given path.\n * @param filepath Path to the empty file to create.\n * @return true if it worked. false otherwise.\n */\n public static boolean touch(String filepath) {\n try {\n File file = new File(filepath);\n file.createNewFile();\n return true;\n } catch(Exception ex) { ex.printStackTrace(); }\n return false;\n }\n \n /**\n * @param fileName The file to remove.\n * @return True if the file was deleted or never existed in the first place. False otherwise.\n */\n public static boolean deleteFile(String fileName) {\n if( fileName == null ) return true;\n \n // A File object to represent the filename\n File f = new File(fileName);\n\n // Make sure the file or directory exists and isn't write protected\n if (f.exists()) {\n\n if (!f.canWrite())\n throw new IllegalArgumentException(\"Delete: write protected: \" + fileName);\n\n // If it is a directory, make sure it is empty\n if (f.isDirectory())\n throw new IllegalArgumentException(\"Delete: path is a directory: \" + fileName);\n\n // Attempt to delete it\n return f.delete();\n }\n return true;\n }\n \n /**\n * Read a directory and return all files.\n */\n public static List<String> getFiles(String dirPath) {\n return getFiles(new File(dirPath));\n }\n public static List<String> getFiles(File dir) {\n if( dir.isDirectory() ) {\n List<String> files = new LinkedList<String>();\n for( String file : dir.list() ) {\n if( !file.startsWith(\".\") )\n files.add(file);\n }\n return files;\n }\n\n return null;\n }\n\n /**\n * Read a directory and return all files in sorted order.\n */\n public static String[] getFilesSorted(String dirPath) {\n List<String> unsorted = getFiles(dirPath);\n\n if( unsorted == null )\n System.out.println(\"ERROR: Directory.getFilesSorted() path is not known: \" + dirPath);\n \n String[] sorted = new String[unsorted.size()];\n sorted = unsorted.toArray(sorted);\n Arrays.sort(sorted);\n\n return sorted;\n }\n\n /**\n * Finds the closest file in name in the given directory based on string\n * edit distance.\n * @param name The name that we want to find.\n * @param directory A directory.\n * @return A file in the directory.\n */\n public static String nearestFile(String name, String directory) {\n return nearestFile(name, directory, null);\n }\n\n public static String nearestFile(String name, String directory, String badSubstring) {\n name = name.toLowerCase();\n File dir = new File(directory);\n if( dir.isDirectory() ) {\n float best = Float.MAX_VALUE;\n String bestName = null;\n for( String file : getFiles(dir) ) {\n file = file.toLowerCase();\n // edit distance?\n float editscore = StringUtils.editDistance(name, file);\n// System.out.println(\"name=\" + name + \"\\tsimilar file \" + file + \" score = \" + editscore);\n if( editscore < best && (badSubstring == null || !file.contains(badSubstring)) ) {\n best = editscore;\n bestName = file;\n }\n // If tied with best, save this one if it ends with the desired name.\n else if( editscore == best && file.endsWith(name) && (badSubstring == null || !file.contains(badSubstring)) ) {\n best = editscore;\n bestName = file;\n }\n }\n return bestName;\n } else {\n System.out.println(\"(Directory) Not a directory: \" + dir);\n System.exit(-1);\n }\n return null;\n }\n\n public static String lastSubdirectory(String path) {\n if( path == null ) return null;\n int last = path.lastIndexOf(File.separator);\n if( last > -1 )\n path = path.substring(0, last);\n else return path;\n\n last = path.lastIndexOf(File.separator);\n if( last > -1 )\n path = path.substring(last+1);\n \n return path;\n }\n\n /**\n * Returns the path given but without the last file. Imitates unix 'dirname'\n * @param path The path to strip.\n * @return The dirname of the path\n */\n public static String dirname(String path) {\n if( path == null ) return null;\n int last = path.lastIndexOf(File.separator);\n if( last > -1 )\n return path.substring(0, last);\n\n // Might be on Windows, but given a UNIX path. Try again.\n else {\n \tlast = path.lastIndexOf(\"/\");\n if( last > -1 )\n return path.substring(0, last);\n else\n \treturn \".\";\n }\n }\n\n /**\n * Get just the file off the back of the full path.\n */\n public static String filename(String path) {\n if( path == null ) return null;\n int last = path.lastIndexOf(File.separator);\n if( last > -1 && last < path.length()-1 )\n return path.substring(last+1);\n \n // Might be on Windows, but given a UNIX path. Try again.\n else {\n \tlast = path.lastIndexOf(\"/\");\n if( last > -1 && last < path.length()-1 )\n return path.substring(last+1);\n else\n \treturn path;\n }\n }\n\n /**\n * Create a file and put the given string into it.\n * @param path Path to create the file.\n * @param str The string to write.\n */\n public static void stringToFile(String path, String str) {\n try {\n PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(path)));\n writer.write(str);\n writer.close();\n } catch( Exception ex ) { ex.printStackTrace(); }\n }\n \n public static void createDirectory(String path) {\n File dir = new File(path);\n if( !dir.exists() )\n dir.mkdir();\n }\n}",
"public class TreeOperator {\n\n TreeOperator() { }\n\n\n public static String argsOfPhrase(Tree tree, Tree parent) {\n String args = \"\";\n List<Tree> children = parent.getChildrenAsList();\n for( Tree child : children ) {\n if( child != tree ) {\n if( args.length() == 1 ) args = child.label().toString();\n else args += \":\" + child.label().toString();\n }\n }\n return args;\n }\n\n\n /**\n * @return A list of verb trees e.g. (VP (VBG running))\n public static Vector<Tree> verbTreesFromTree(Tree tree, Tree parent) {\n Vector<Tree> verbs = new Vector();\n // if tree is a leaf\n if( tree.isPreTerminal() && tree.label().toString().startsWith(\"VB\") ) {\n // add the verb subtree\n verbs.add(parent);\n }\n // else scale the tree \n else {\n List<Tree> children = tree.getChildrenAsList();\n for( Tree child : children ) {\n\tVector temp = verbTreesFromTree(child, tree);\n\tverbs.addAll(temp);\n }\n }\n\n return verbs;\n }\n */\n\n /**\n * @return A list of verb subtrees e.g. (VBG running)\n */\n public static Vector<Tree> verbTreesFromTree(Tree tree) {\n// System.out.println(\"verbTree: \" + tree);\n Vector<Tree> verbs = new Vector<Tree>();\n// System.out.println(\" tree label: \" + tree.label().value().toString());\n \n // if tree is a leaf\n if( tree.isPreTerminal() && tree.label().value().startsWith(\"VB\") ) {\n// System.out.println(\" if!!\");\n // add the verb subtree\n verbs.add(tree);\n }\n // else scale the tree \n else {\n// System.out.println(\" else!!\");\n List<Tree> children = tree.getChildrenAsList();\n for( Tree child : children ) {\n Vector<Tree> temp = verbTreesFromTree(child);\n verbs.addAll(temp);\n }\n }\n\n return verbs;\n }\n\n\n /**\n * @return A list of verbs in the tree\n */\n public static Vector<String> verbsFromTree(Tree tree, Tree parent) {\n Vector<String> verbs = new Vector<String>();\n // if tree is a leaf\n if( tree.isPreTerminal() && tree.label().toString().startsWith(\"VB\") ) {\n String verb = tree.firstChild().value();\n // get arguments\n // System.out.println(\"parent of \" + verb + \" is \" + parent);\n // verb += argsOfPhrase(tree, parent);\n // System.out.println(\"now: \" + verb);\n // add the verb\n verbs.add(verb);\n }\n // else scale the tree \n else {\n List<Tree> children = tree.getChildrenAsList();\n for( Tree child : children ) {\n Vector<String> temp = verbsFromTree(child, tree);\n verbs.addAll(temp);\n }\n }\n\n return verbs;\n }\n\n public static Vector<String> verbsFromTree(Tree tree) {\n return verbsFromTree(tree, null);\n }\n\n /**\n * @param index The index of the verb token in the sentence.\n * @param tree The entire parse tree.\n * @return The tense of the verb using hand-crafted rules.\n */\n public static String tenseOfVerb(int index, Tree tree) {\n if( index > 1000 ) index -= 1000;\n \n// Tree subtree = indexToSubtree(tree, index);\n List<Tree> leaves = leavesFromTree(tree);\n// System.out.println(\"leaves: \" + leaves);\n String leftmostVerbTag = null; \n String secondLeftmostVerbTag = null;\n int i = index-1; // word indexes start at 1, not 0\n \n \n // Move left until no more verbs.\n while( i > -1 && \n (leaves.get(i).label().value().startsWith(\"VB\") || leaves.get(i).label().value().startsWith(\"TO\") ||\n leaves.get(i).label().value().startsWith(\"RB\")) ) {\n if( leaves.get(i).label().value().startsWith(\"VB\") ) {\n secondLeftmostVerbTag = leftmostVerbTag; \n leftmostVerbTag = leaves.get(i).label().value();\n }\n// System.out.println(\"just checked \" + leaves.get(i)); \n i--;\n }\n \n if( leftmostVerbTag == null ) {\n System.out.println(\"ERROR: null lastVerb. Leaf i=\" + i + \" =\" + leaves.get(i) + \n \" from index=\" + index + \" tree=\" + tree);\n System.out.println(\" leaves = \" + leaves);\n System.out.println(\" indexToPOSTag = \" + indexToPOSTag(tree, index));\n System.out.println(\" countLeaves = \" + countLeaves(tree));\n System.exit(-1);\n }\n \n String tag = (i >= 0 ? leaves.get(i).label().value() : null);\n String token = (i >= 0 ? leaves.get(i).firstChild().value() : null);\n // System.out.println(\"tag=\" + tag + \" token=\" + token);\n if( tag != null && tag.equals(\"MD\") && (token.equals(\"will\") || token.equals(\"wo\")) ) {\n return \"FUTURE\";\n }\n else if( leftmostVerbTag != null && \n (leftmostVerbTag.equals(\"VBD\") || \n // \"He might have/VB left/VBN by midnight.\"\n (leftmostVerbTag.equals(\"VB\") && secondLeftmostVerbTag != null && secondLeftmostVerbTag.equals(\"VBN\"))) )\n return \"PAST\";\n else {\n // \"He should leave soon.\" (\"He should have left\" is covered by past tense \"VB VBN\" rule above.) \n if( token != null && (token.equals(\"should\") || token.equals(\"shall\") || token.equals(\"could\")) )\n return \"FUTURE\";\n \n if( tag != null && tag.equals(\"MD\") ) // some modal we don't know what to do with\n return null;\n \n else\n return \"PRESENT\";\n }\n }\n\n public static List<String> stringLeavesFromTree(Tree tree) {\n List<String> strs = new ArrayList<String>();\n List<Tree> leaves = leavesFromTree(tree);\n for( Tree leaf : leaves )\n strs.add(leaf.children()[0].nodeString());\n return strs;\n }\n \n public static List<String> posTagsFromTree(Tree tree) {\n List<String> strs = new ArrayList<String>();\n List<Tree> leaves = leavesFromTree(tree);\n for( Tree leaf : leaves )\n strs.add(leaf.label().value());\n return strs;\n }\n \n /**\n * @return A Vector of all the leaves ... we basically flatten the tree\n */\n public static List<Tree> leavesFromTree(Tree tree) {\n List<Tree> leaves = new ArrayList<Tree>();\n// System.out.println(\"myt=\" + tree);\n // if tree is a leaf\n// if( tree.isPreTerminal() || tree.firstChild().isLeaf() ) {\n if( tree.firstChild().isLeaf() ) {\n// System.out.println(\" * preterm\");\n // add the verb subtree\n leaves.add(tree);\n }\n // else scale the tree\n else {\n// System.out.println(\" * scaling\");\n List<Tree> children = tree.getChildrenAsList();\n for( Tree child : children ) {\n List<Tree> temp = leavesFromTree(child);\n leaves.addAll(temp);\n }\n }\n\n return leaves;\n }\n\n /**\n * @return The raw text of a parse tree's nodes\n */\n public static String toRaw(Tree full) {\n if( full == null ) return \"\";\n\n if( full.isPreTerminal() ) return full.firstChild().value();\n else {\n String str = \"\";\n for( Tree child : full.getChildrenAsList() ) {\n if( str.length() == 0 ) str = toRaw(child);\n else str += \" \" + toRaw(child);\n }\n return str;\n }\n }\n\n\n /**\n * @return The WORD INDEX (starting at 0) where the stop tree begins\n */\n public static int wordIndex(Tree full, Tree stop) {\n if( full == null || full == stop ) return 0;\n\n int sum = 0;\n// if( full.isPreTerminal() ) {\n if( full.firstChild().isLeaf() ) {\n return 1;\n }\n else {\n for( Tree child : full.getChildrenAsList() ) {\n if( child == stop ) {\n //\t System.out.println(\"Stopping at \" + child);\n return sum;\n }\n sum += wordIndex(child, stop);\n if( child.contains(stop) ) return sum;\n }\n }\n return sum;\n }\n\n /**\n * Retrieve the POS tag of the token at the given index in the given tree. Indices start at 1.\n * @param full The full parse tree.\n * @param goal The index of the desired token.\n * @return The token's POS tag in String form.\n */\n public static String indexToPOSTag(Tree full, int goal) {\n // Hack fix for old parser error with indices from conjunctions.\n if( goal > 1000 ) goal -= 1000;\n \n Tree subtree = indexToSubtree(full, goal);\n if( subtree == null )\n return null;\n else return subtree.label().value();\n }\n \n public static String indexToToken(Tree full, int goal) {\n // Hack fix for old parser error with indices from conjunctions.\n if( goal > 1000 ) goal -= 1000;\n \n Tree subtree = indexToSubtree(full, goal);\n if( subtree == null )\n return null;\n else return subtree.children()[0].nodeString();//.value().toString();\n }\n\n /**\n * Assumes the goal is a word index in the sentence, and the first word starts\n * at index 1.\n * @return Subtree rooted where the index begins. It's basically the\n * index's individual POS tree: (NNP June) or (CD 13)\n */\n public static Tree indexToSubtree(Tree full, int goal) {\n return indexToSubtreeHelp(full,0,goal);\n }\n public static Tree indexToSubtreeHelp(Tree full, int current, int goal) {\n// System.out.println(\"--\" + current + \"-\" + full + \"-preterm\" + full.isPreTerminal() + \"-goal\" + goal);\n if( full == null ) return null;\n\n if( (current+1) == goal && \n// (full.isPreTerminal() || full.label().value().equals(\"CD\")) )\n full.firstChild().isLeaf() )\n return full;\n else {\n for( Tree child : full.getChildrenAsList() ) {\n int length = countLeaves(child);\n //\tSystem.out.println(\"--Child length \" + length);\n if( goal <= current+length )\n return indexToSubtreeHelp(child, current, goal);\n else\n current += length;\n }\n }\n return null;\n }\n\n\n /**\n * @return The CHARACTER OFFSET where the stop tree begins\n */\n public static int inorderTraverse(Tree full, Tree stop) {\n if( full == null || full == stop ) return 0;\n\n int sum = 0;\n if( full.isPreTerminal() ) {\n String value = full.firstChild().value();\n // System.out.println(value + \" is \" + value.length());\n return value.length() + 1; // +1 for space character\n // return full.firstChild().value().length() + 1;\n }\n else {\n for( Tree child : full.getChildrenAsList() ) {\n if( child == stop ) {\n //\t System.out.println(\"Stopping at \" + child);\n return sum;\n }\n sum += inorderTraverse(child, stop);\n if( child.contains(stop) ) return sum;\n }\n }\n return sum;\n }\n\n public static String pathNodeToNode(Tree tree, Tree sub1, Tree sub2, boolean noPOS) {\n List<Tree> path = tree.pathNodeToNode(sub1, sub2);\n if( noPOS ) {\n if( path.size() < 2 ) { // probably comparing the same two subtrees\n System.out.println(\"ERROR: pathNodeToNode length too short: sub1=\" + sub1 + \" sub2=\" + sub2 + \" path=\" + path + \"\\ttree\" + tree);\n path = new ArrayList<Tree>();\n }\n else\n path = path.subList(1, path.size()-1);\n }\n \n int x = 0;\n String stringpath = \"\";\n for( Tree part : path ) {\n if( x == 0 )\n stringpath += part.label().value();\n else\n stringpath += \"-\" + part.label().value();\n x++;\n }\n return stringpath;\n }\n \n /**\n * @return The number of leaves (words) in this tree\n */\n // public static int treeWordLength(Tree tree) {\n // return countLeaves(tree)-1;\n // }\n public static int countLeaves(Tree tree) {\n int sum = 0;\n // System.out.println(\"top with tree \" + tree);\n // if( tree.isPreTerminal() ) {\n // Phone numbers are (CD (727) 894-1000) ... but they aren't in the\n // \"preterminal\" definition of the function, so we much explicitly check.\n// if( tree.isPreTerminal() || tree.label().value().equals(\"CD\") ) {\n if( tree.firstChild() != null && tree.firstChild().isLeaf() ) {\n // System.out.println(\"leaf: \" + tree);\n return 1;\n }\n else {\n // System.out.println(\"getchildren \" + tree.getChildrenAsList().size());\n for( Tree child : tree.getChildrenAsList() ) {\n sum += countLeaves(child);\n }\n }\n return sum;\n }\n \n /**\n * @return The char length of the string represented by this tree\n */\n public static int treeStringLength(Tree tree) {\n return getTreeLength(tree)-1;\n }\n\n public static int getTreeLength(Tree tree) {\n int sum = 0;\n if( tree.firstChild().isLeaf() )\n return 1;\n else\n for( Tree child : tree.getChildrenAsList() )\n sum += getTreeLength(child);\n return sum;\n }\n\n /**\n * Build the Tree object from its string form.\n */\n public static Tree stringToTree(String str, TreeFactory tf) {\n try {\n PennTreeReader ptr = new PennTreeReader(new BufferedReader(new StringReader(str)), tf);\n Tree parseTree = ptr.readTree();\n return parseTree;\n } catch( Exception ex ) { ex.printStackTrace(); }\n return null;\n }\n\n /**\n * Build Tree objects from a collection of parses in string form.\n */\n public static List<Tree> stringsToTrees(Collection<String> strings) {\n if( strings != null ) {\n List<Tree> trees = new ArrayList<Tree>();\n TreeFactory tf = new LabeledScoredTreeFactory();\n for( String str : strings )\n trees.add(stringToTree(str, tf));\n return trees;\n }\n else return null;\n }\n \n public static boolean flatNP(Tree tree, int start, int end) {\n Tree startTree = indexToSubtree(tree, start);\n Tree endTree = indexToSubtree(tree, end-1);\n\n Tree startParent = startTree.parent(tree);\n Tree endParent = endTree.parent(tree);\n \n// if( startParent == endParent ) System.out.println(\" same!!\");\n// else System.out.println(\" diff!!\");\n \n if( startParent == endParent )\n return true;\n else return false;\n }\n \n /**\n * Turn a string representation of a dependency into the JavaNLP object.\n * @param line String of dep: e.g. nsubj testified-17 dealer-16\n */\n public static TypedDependency stringToDependency(String line) {\n String parts[] = line.split(\"\\\\s+\");\n if( parts.length != 3 ) {\n System.out.println(\"ERROR: unknown dep format: \" + line);\n System.exit(-1);\n }\n return createDependency(parts[0], parts[1], parts[2]);\n }\n \n /**\n * Turn a string representation of a dependency into the JavaNLP object.\n * @param line String of dep: e.g. nsubj(testified-17, dealer-16)\n */\n public static TypedDependency stringParensToDependency(String line) {\n String parts[] = line.split(\"\\\\s+\");\n if( parts.length != 2 ) {\n System.out.println(\"ERROR: unknown dep format: \" + line);\n System.exit(-1);\n }\n int openParen = parts[0].indexOf('(');\n return createDependency(parts[0].substring(0,openParen), parts[0].substring(openParen+1,parts[0].length()-1), parts[1].substring(0, parts[1].length()-1));\n }\n \n\n /**\n * Find all dependencies with the event as governor, and particle as relation\n */\n public static String findParticle(Collection<TypedDependency> deps, WordEvent event) {\n for( TypedDependency dep : deps ) {\n if( dep.gov().index() == event.position() ) {\n if( dep.reln().toString().equals(\"prt\") ) {\n //\t System.out.println(\"Found particle: \" + dep.dep().value());\n return dep.dep().label().value();\n }\n }\n }\n return null;\n }\n\n /**\n * Return the participle of a verb's phrase structure tree.\n */\n public static String findParticleInTree(Tree verb) {\n if( verb != null ) {\n for( Tree child : verb.getChildrenAsList() ) {\n // (PRT (RB up))\n if( child.label().value().equals(\"PRT\") )\n return child.firstChild().firstChild().label().value();\n } \n }\n return null;\n }\n\n\n /**\n * Given string representations of the dependency's relation, governor and dependent, create\n * the JavaNLP object.\n * @param strReln e.g., nsubj\n * @param strGov e.g., testified-17\n * @param strDep e.g., dealer-16\n */\n public static TypedDependency createDependency(String strReln, String strGov, String strDep) {\n if( strReln == null || strGov == null || strDep == null ) {\n System.out.println(\"ERROR: unknown dep format: \" + strReln + \" \" + strGov + \" \" + strDep);\n System.exit(-1);\n }\n\n GrammaticalRelation rel = GrammaticalRelation.valueOf(strReln);\n\n try {\n // \"happy-12\"\n int hyphen = strGov.length()-2;\n while( hyphen > -1 && strGov.charAt(hyphen) != '-' ) hyphen--;\n if( hyphen < 0 ) return null;\n \n TreeGraphNode gov = new TreeGraphNode(new Word(strGov.substring(0,hyphen)));\n int end = strGov.length();\n // \"happy-12'\" -- can have many apostrophes, each indicates the nth copy of this relation\n int copies = 0;\n while( strGov.charAt(end-1) == '\\'' ) {\n copies++;\n end--;\n }\n if( copies > 0 ) gov.label().set(CopyAnnotation.class, copies);\n gov.label().setIndex(Integer.parseInt(strGov.substring(hyphen+1,end)));\n\n // \"sad-3\"\n hyphen = strDep.length()-2;\n while( hyphen > -1 && strDep.charAt(hyphen) != '-' ) hyphen--;\n if( hyphen < 0 ) return null;\n TreeGraphNode dep = new TreeGraphNode(new Word(strDep.substring(0,hyphen)));\n end = strDep.length();\n // \"sad-3'\" -- can have many apostrophes, each indicates the nth copy of this relation\n copies = 0;\n while( strDep.charAt(end-1) == '\\'' ) {\n copies++;\n end--;\n }\n if( copies > 0 ) dep.label().set(CopyAnnotation.class, copies);\n dep.label().setIndex(Integer.parseInt(strDep.substring(hyphen+1,end)));\n\n return new TypedDependency(rel,gov,dep);\n } catch( Exception ex ) {\n System.out.println(\"createDependency() error with input: \" + strReln + \" \" + strGov + \" \" + strDep);\n ex.printStackTrace();\n }\n return null;\n }\n \n /**\n * Calculate the shortest dependency path from token index start to end.\n * Indices start at 1, so the first word in the sentence is index 1.\n * @return A single string representing the shortest path.\n */\n public static String dependencyPath(int start, int end, List<TypedDependency> deps) {\n List<String> paths = paths(start, end, deps, null);\n // One path? Return now!\n if( paths.size() == 1 )\n return paths.get(0);\n\n // More than one path. Find the shortest!\n String shortest = null;\n int dist = Integer.MAX_VALUE;\n for( String path : paths ) { \n int count = path.split(\"->\").length;\n count += path.split(\"<-\").length;\n if( count < dist ) {\n dist = count;\n shortest = path;\n }\n }\n return shortest;\n }\n \n /**\n * Recursive helper function to the main dependency path. Builds all possible dependency paths between\n * two tokens.\n */\n private static List<String> paths(int start, int end, List<TypedDependency> deps, Set<Integer> visited) {\n// System.out.println(\"paths start=\" + start + \" end=\" + end);\n List<String> paths = new ArrayList<String>();\n \n if( start == end ) {\n paths.add(\"\");\n return paths;\n }\n\n if( visited == null ) visited = new HashSet<Integer>();\n visited.add(start);\n \n for( TypedDependency dep : deps ) {\n if( dep != null ) {\n// System.out.println(\"\\tdep=\" + dep);\n// System.out.println(\"\\tvisited=\" + visited);\n if( dep.gov().index() == start && !visited.contains(dep.dep().index()) ) {\n List<String> newpaths = paths(dep.dep().index(), end, deps, visited);\n for( String newpath : newpaths )\n paths.add(dep.reln() + \"->\" + newpath);\n }\n if( dep.dep().index() == start && !visited.contains(dep.gov().index()) ) {\n List<String> newpaths = paths(dep.gov().index(), end, deps, visited);\n for( String newpath : newpaths )\n paths.add(dep.reln() + \"<-\" + newpath);\n }\n }\n }\n\n return paths;\n }\n}",
"public class Ling {\n public enum Tense { present, past, future };\n Ling() { }\n\n// public static Tense getTenseOfVerb(Tree tree, int index) {\n// Tree subtree = TreeOperator.indexToSubtree(tree, index);\n// \n// Tree parent = subtree.parent(tree);\n// \n// return Tense.present;\n// }\n \n public static LexicalizedParser createParser(String grammarPath) {\n return LexicalizedParser.loadModel(grammarPath);\n }\n \n /**\n * @return true if the given string is a wh-word\n */\n public static boolean isWhWord(String token) {\n if( token.equals(\"who\") ||\n token.equals(\"what\") ||\n token.equals(\"where\") ||\n token.equals(\"when\") ||\n token.equals(\"why\") ||\n token.equals(\"which\") ||\n token.equals(\"how\") )\n return true;\n else return false;\n }\n \n /**\n * Returns true if the given string is a person reference\n */\n public static boolean isPersonRef(String token) {\n if( token.equals(\"man\") || \n token.equals(\"woman\") ||\n token.equals(\"men\") ||\n token.equals(\"women\") ||\n token.equals(\"person\") ||\n token.equals(\"people\") ||\n token.equals(\"boy\") ||\n token.equals(\"girl\")\n ) \n return true;\n else return false;\n }\n\n public static boolean isAbstractPerson(String token) {\n if( token.equals(\"nobody\") || \n token.equals(\"noone\") || \n token.equals(\"someone\") || \n token.equals(\"somebody\") || \n token.equals(\"anyone\") || \n token.equals(\"anybody\") \n )\n return true;\n else return false;\n }\n\n /**\n * Returns true if the given string is a person pronoun\n */\n public static boolean isPersonPronoun(String token) {\n if( token.equals(\"he\") || \n token.equals(\"him\") ||\n token.equals(\"his\") ||\n token.equals(\"himself\") ||\n token.equals(\"she\") ||\n token.equals(\"her\") ||\n token.equals(\"hers\") ||\n token.equals(\"herself\") ||\n token.equals(\"you\") ||\n token.equals(\"yours\") ||\n token.equals(\"yourself\") ||\n token.equals(\"we\") ||\n token.equals(\"us\") ||\n token.equals(\"our\") ||\n token.equals(\"ours\") ||\n token.equals(\"ourselves\") ||\n token.equals(\"i\") ||\n token.equals(\"me\") ||\n token.equals(\"my\") ||\n token.equals(\"mine\") ||\n token.equals(\"they\") ||\n token.equals(\"them\") ||\n token.equals(\"their\") ||\n token.equals(\"themselves\")\n )\n return true;\n else return false;\n }\n\n\n /**\n * Returns true if the given string is a potential non-person pronoun\n */\n public static boolean isInanimatePronoun(String token) {\n if( token.equals(\"it\") ||\n token.equals(\"itself\") ||\n token.equals(\"its\") ||\n token.equals(\"they\") ||\n token.equals(\"them\") ||\n token.equals(\"their\") ||\n token.equals(\"one\")\n ) \n return true;\n else return false;\n }\n \n public static boolean isObjectReference(String token) {\n if( token.equals(\"that\") ||\n token.equals(\"this\") ||\n token.equals(\"those\") ||\n token.equals(\"these\") ||\n token.equals(\"the\") \n )\n return true;\n else return false;\n }\n\n private static final Set<String> NUMERALS = new HashSet<String>() {{\n add(\"one\");\n add(\"two\");\n add(\"three\");\n add(\"four\");\n add(\"five\");\n add(\"six\");\n add(\"seven\");\n add(\"eight\");\n add(\"nine\");\n add(\"ten\");\n }};\n\n public static boolean isNumber(String token) {\n if( NUMERALS.contains(token) || token.matches(\"^[\\\\d\\\\s\\\\.-/\\\\\\\\]+$\") )\n return true;\n return false;\n }\n \n /**\n * @return True if the token's first letter is capitalized: A-Z. False otherwise.\n */\n public static boolean isCapitalized(String token) {\n if( token != null && token.length() > 0 ) {\n char first = token.charAt(0);\n if( first >= 'A' && first <= 'Z' )\n return true;\n }\n return false;\n }\n \n /**\n * Remove the determiner if there is one at the beginning of this\n * string, followed by a space. Trim the string including the space char.\n */\n public static String trimLeadingDeterminer(String str) {\n int space = str.indexOf(' ');\n if( space != -1 ) {\n char ch = str.charAt(0);\n if( ch == 't' || ch == 'T' || ch == 'A' || ch == 'a' ) {\n String lower = str.toLowerCase();\n if( lower.startsWith(\"the \") ||\n lower.startsWith(\"a \") ||\n lower.startsWith(\"an \") ||\n lower.startsWith(\"these \") ||\n lower.startsWith(\"those \")\n )\n return str.substring(space+1);\n }\n }\n return str;\n }\n\n\n public static Map<Integer,String> particlesInSentence(Collection<TypedDependency> deps) {\n // Find any particles - O(n)\n Map<Integer, String> particles = new HashMap<Integer, String>();\n for( TypedDependency dep : deps ) {\n if( dep.reln().toString().equals(\"prt\") ) {\n particles.put(dep.gov().index(), dep.dep().label().value());\n }\n }\n return particles;\n }\n\n /**\n * Finds all words that have object relations, and returns a map from the word indices\n * to a list of all object strings with their indices in the sentence.\n * @return A map from token index (governor) to its list of objects.\n */\n public static Map<Integer,List<WordPosition>> objectsInSentence(int sid, Collection<TypedDependency> sentDeps) {\n Map<Integer,List<WordPosition>> objects = new HashMap<Integer,List<WordPosition>>();\n for( TypedDependency dep : sentDeps ) {\n String reln = CountTokenPairs.normalizeRelation(dep.reln().toString(), false);\n if( reln.equals(WordEvent.DEP_OBJECT) ) {\n List<WordPosition> strs = objects.get(dep.gov().index());\n if( strs == null ) {\n strs = new ArrayList<WordPosition>();\n objects.put(dep.gov().index(), strs);\n }\n strs.add(new WordPosition(sid, dep.dep().index(), dep.dep().label().value().toString().toLowerCase()));\n }\n }\n return objects;\n }\n\n /**\n * Build a single string of the given List with spaces between the tokens.\n * @param words Any List of HasWord objects.\n * @return A single string (the sentence).\n */\n public static String appendTokens(List<HasWord> words) {\n if( words == null ) return null;\n\n int i = 0;\n StringBuffer buf = new StringBuffer();\n for( HasWord word : words ) {\n if( i > 0 ) buf.append(' ');\n buf.append(word.word());\n i++;\n }\n return buf.toString();\n }\n \n public static List<List<HasWord>> getSentencesFromText(String str, boolean invertible, String options) {\n List<List<HasWord>> sentences = new ArrayList<List<HasWord>>();\n StringReader reader = new StringReader(str);\n DocumentPreprocessor dp = new DocumentPreprocessor(reader);\n TokenizerFactory factory = null;\n\n if( invertible ) {\n factory = PTBTokenizer.factory(true, true);\n if( options != null && options.length() > 0 ) \n options = \"invertible=true, \" + options;\n else \n options = \"invertible=true\";\n } else {\n factory = PTBTokenizer.factory();\n }\n\n// System.out.println(\"Setting splitter options=\" + options);\n factory.setOptions(options);\n dp.setTokenizerFactory(factory);\n \n Iterator<List<HasWord>> iter = dp.iterator();\n while( iter.hasNext() ) {\n List<HasWord> sentence = iter.next();\n sentences.add(sentence);\n }\n return sentences;\n \n }\n \n /**\n * Splits a string that might contain multiple sentences into lists of sentences.\n */\n public static List<List<HasWord>> getSentencesFromTextNoNorm(String str) {\n return getSentencesFromText(str, false, \"ptb3Escaping=false\");\n }\n \n /**\n * Splits a string that might contain multiple sentences into lists of sentences.\n * This function does not change any characters (e.g., \" -> ''), and preserves whitespace\n * in the word objects.\n */\n public static List<List<HasWord>> getSentencesFromTextNormInvertible(String str) {\n return getSentencesFromText(str, true, \"\");\n }\n \n /**\n * Splits a string that might contain multiple sentences into lists of sentences.\n * This function does not change any characters (e.g., \" -> ''), and preserves whitespace\n * in the word objects.\n */\n public static List<List<HasWord>> getSentencesFromTextNoNormInvertible(String str) {\n return getSentencesFromText(str, true, \"ptb3Escaping=false\");\n }\n \n /**\n * Splits a string that might contain multiple sentences into lists of sentences.\n */\n public static List<List<HasWord>> getSentencesFromText(String str) {\n return getSentencesFromText(str, false, \"americanize=false\");\n }\n\n // NATE note: never actually double-checked that this new function works...\n public static List<Word> getWordsFromString(String str) {\n PTBTokenizerFactory<Word> factory = (PTBTokenizerFactory<Word>)PTBTokenizer.factory();\n // Stanford's tokenizer actually changes words to American...altering our original text. Stop it!!\n factory.setOptions(\"americanize=false\");\n Tokenizer<Word> tokenizer = factory.getTokenizer(new BufferedReader(new StringReader(str)));\n return tokenizer.tokenize();\n }\n\n // DocumentPreprocessor dp = new DocumentPreprocessor(new StringReader(str));\n // List<Word> words = dp.getWordsFromString(str);\n // }\n\n /**\n * Removes all leading and trailing punctuation.\n */\n public static String trimPunctuation(String token) {\n int start = 0, end = 0;\n for( start = 0; start < token.length(); start++ ) {\n char ch = token.charAt(start);\n if( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') )\n break;\n }\n\n if( start < token.length() )\n for( end = token.length()-1; end >= 0; end-- ) {\n char ch = token.charAt(end);\n if( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') )\n break;\n }\n\n if( start > end )\n return \"\";\n else if( start > 0 || end < token.length()-1 )\n return token.substring(start, end+1);\n else \n return token;\n }\n \n\n /**\n * @return True if the indexed word has a known definite determiner.\n * False otherwise, but this doesn't necessarily mean it's not definite.\n */\n public static boolean isDefinite(Vector<TypedDependency> deps, int index) {\n // System.out.println(\"isdef top with \" + index);\n for( TypedDependency dep : deps ) {\n int govIndex = dep.gov().index();\n if( govIndex == index ) {\n // System.out.println(\"isdef dep match: \" + dep);\n if( dep.reln().toString().equals(\"det\") ) {\n // System.out.println(\"isdef \" + dep + \" index=\" + index);\n String determiner = dep.dep().toString();\n // the, that, this, these, those, them\n if( determiner.startsWith(\"th\") )\n return true;\n }\n }\n }\n return false;\n }\n\n public static boolean isProper(List<NERSpan> ners, int index) {\n for( NERSpan ner : ners ) {\n if( ner.end()-1 == index )\n return true;\n }\n return false;\n }\n\n public static boolean isNominative(String govLemma, char normalPOS, WordNet wordnet) {\n if( normalPOS == 'n' ) {\n if( wordnet.isNominalization(govLemma) ) {\n // System.out.println(\"isNominalization \" + govLemma);\n return true;\n }\n if( wordnet.isNounEvent(govLemma) ) {\n // System.out.println(\"isNounEvent \" + govLemma);\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Determines if the given word index is the possessor in a possessive\n * relationship. This is either a \"poss\" reln, or a \"prep_of\" relation when\n * the index is a definite NP or an NER recognized (proper) noun.\n *\n * NOTE: For MUC, most important possessives are event nouns, so we could just\n * call isNominative and not this function.\n */\n public static boolean isPossessive(Tree tree, List<NERSpan> ners, \n Vector<TypedDependency> deps, int index) {\n Tree subtree = TreeOperator.indexToSubtree(tree, index);\n String posTag = subtree.label().value();\n\n if( posTag.startsWith(\"NN\") ) {\n\n for( TypedDependency dep : deps ) {\n int depIndex = dep.dep().index();\n if( depIndex == index ) {\n String reln = dep.reln().toString();\n\n if( reln.equals(\"poss\") ) return true;\n\n if( reln.equals(\"prep_of\") ) {\n if( isDefinite(deps, index) || isProper(ners, index) ) {\n // String gov = dep.gov().label().value().toString().toLowerCase();\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n\n public static void main(String[] args) {\n System.out.println(\"88.4 \" + Ling.isNumber(\"88.4\"));\n System.out.println(\"47 1/2 \" + Ling.isNumber(\"47 1/2\"));\n System.out.println(\"a47 1/2 \" + Ling.isNumber(\"a47 1/2\"));\n }\n}"
] | import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import edu.stanford.nlp.stats.ClassicCounter;
import edu.stanford.nlp.stats.Counter;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TypedDependency;
import nate.IDFMap;
import nate.ProcessedData;
import nate.util.Directory;
import nate.util.TreeOperator;
import nate.util.WordNet;
import nate.util.Ling; | package nate.probschemas;
/**
* Code that reads a document(s) and gives you the top most important event words.
* This should be used for IR to find similar documents based on these keywords.
*
* This code is used by --KeywordTokenizer-- to process all of Gigaword and provide a short list
* of keywords to be used by the Lucene index for search.
*
* getKeywords() is the main function.
* - this was used to convert Gigaword docs
* - use this to reduce current docs, and then call IRDocuments with those words
*
*/
public class KeywordDetector {
public WordNet wordnet = null;
public IDFMap idf;
public KeywordDetector() {
init();
}
public KeywordDetector(String[] args) {
init();
runit(args);
}
private void init() {
wordnet = new WordNet(WordNet.findWordnetPath());
idf = new IDFMap(IDFMap.findIDFPath());
}
public void runit(String[] args) {
load(args[args.length-1]);
}
/**
* Just a testing function.
*/
public void load(String dataDir) {
String parsesFile = dataDir + File.separator + Directory.nearestFile("parse", dataDir);
String depsFile = dataDir + File.separator + Directory.nearestFile("deps", dataDir);
String eventsFile = dataDir + File.separator + Directory.nearestFile("events", dataDir);
String nerFile = dataDir + File.separator + Directory.nearestFile("ner", dataDir);
// Read the data files from disk.
ProcessedData data = new ProcessedData(parsesFile, depsFile, eventsFile, nerFile);
data.nextStory();
// Count all of the verbs.
while( data.getParseStrings() != null ) {
List<Tree> trees = TreeOperator.stringsToTrees(data.getParseStrings());
Counter<String> verbs = getKeywordCounts(trees, data.getDependencies());
System.out.println("DOC " + data.currentStory());
for( String key : verbs.keySet() )
if( idf.get("v-" + key) > 1.5 )
System.out.println("\t" + key + "\t" + verbs.getCount(key) + "\t" + idf.get("v-" + key));
else
System.out.println("\t(skip) " + key + "\t" + verbs.getCount(key) + "\t" + idf.get("v-" + key));
verbs.clear();
data.nextStory();
}
}
public List<String> getKeywords(List<Tree> trees, List<List<TypedDependency>> deps) {
List<String> verbs = new ArrayList<String>();
int sid = 0;
if( trees.size() != deps.size() ) {
System.out.println("ERROR: " + trees.size() + " trees but " + deps.size() + " deps in KeywordDetector.getKeywords()");
return null;
}
for( Tree tree : trees ) {
// Look for particles. | Map<Integer,String> particles = Ling.particlesInSentence(deps.get(sid++)); | 4 |
TranquilMarmot/spaceout | src/com/bitwaffle/spaceguts/util/console/ConsoleCommands.java | [
"public class Audio {\n\t/** Used for deleting all sound sources on shutdown (see {@link SoundSource}'s constructor, each SoundSource gets added to this when it's created */\n\tprotected static ArrayList<SoundSource> soundSources = new ArrayList<SoundSource>();\n\t\n\t/** Factor to use for doppler effect */\n\tprivate static final float DOPPLER_FACTOR = 0.0f;\n\t\n\t/** Velocity to use for doppler effect*/\n\tprivate static final float DOPPLER_VELOCITY = 1.0f;\n\t\n\t/** Whether or not the game is muted */\n\tprivate static boolean muted = false;\n\t\n\t/** Current volume */\n\tprivate static float volume = 1.5f;\n\t\n\t/** Buffers for transferring data to OpenAL */\n\tprivate static FloatBuffer listenerPos, listenerVel, listenerOrient;\n\t\n\t/** For checking for errors */\n\tprivate static int err;\n\t\n\t\n\t/**\n\t * Initializes OpenAL\n\t */\n\tpublic static void init(){\n\t\ttry {\n\t\t\tAL.create();\n\t\t} catch (LWJGLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t// zero out error\n\t\tAL10.alGetError();\n\t\t\n\t\t// set doppler values\n\t\tAL10.alDopplerFactor(DOPPLER_FACTOR);\n\t\tAL10.alDopplerVelocity(DOPPLER_VELOCITY);\n\t\tAL11.alSpeedOfSound(700.0f);\n\t\t\n\t\t// initialize buffers\n\t\tlistenerPos = BufferUtils.createFloatBuffer(3);\n\t\tlistenerVel = BufferUtils.createFloatBuffer(3);\n\t\tlistenerOrient = BufferUtils.createFloatBuffer(6);\n\t}\n\t\n\t/**\n\t * Updates the listener's position, velocity and orientation to match the camera\n\t */\n\tpublic static void update(){\n\t\t// clear buffers\n\t\tlistenerPos.clear();\n\t\tlistenerVel.clear();\n\t\tlistenerOrient.clear();\n\t\t\n\t\t// if there's no camera, then we're playing 2D sounds\n\t\tif(Entities.camera == null){\n\t\t\tlistenerPos.put(0.0f);\n\t\t\tlistenerPos.put(0.0f);\n\t\t\tlistenerPos.put(0.0f);\n\t\t\t\n\t\t\tlistenerVel.put(0.0f);\n\t\t\tlistenerVel.put(0.0f);\n\t\t\tlistenerVel.put(0.0f);\n\t\t\t\n\t\t\tlistenerOrient.put(0.0f);\n\t\t\tlistenerOrient.put(0.0f);\n\t\t\tlistenerOrient.put(-1.0f);\n\t\t\tlistenerOrient.put(0.0f);\n\t\t\tlistenerOrient.put(1.0f);\n\t\t\tlistenerOrient.put(0.0f);\n\t\t} else{\n\t\t\t// position\n\t\t\tVector3f realPos = Entities.camera.getLocationWithOffset();\n\t\t\tlistenerPos.put(realPos.x);\n\t\t\tlistenerPos.put(realPos.y);\n\t\t\tlistenerPos.put(realPos.z);\n\t\t\tlistenerPos.rewind();\n\t\t\t\n\t\t\t// velocity\n\t\t\tjavax.vecmath.Vector3f linvec = new javax.vecmath.Vector3f();\n\t\t\t\n\t\t\t// if we're following anything, we want its velocity\n\t\t\tif(Entities.camera.buildMode || Entities.camera.freeMode)\n\t\t\t\tEntities.camera.rigidBody.getLinearVelocity(linvec);\n\t\t\telse\n\t\t\t\tEntities.camera.following.rigidBody.getLinearVelocity(linvec);\n\n\t\t\tlistenerVel.put(linvec.x);\n\t\t\tlistenerVel.put(linvec.y);\n\t\t\tlistenerVel.put(linvec.z);\n\t\t\t\n\t\t\t// orientation\n\t\t\tVector3f at = new Vector3f(0.0f, 0.0f, 1.0f);\n\t\t\tVector3f up = new Vector3f(0.0f, 1.0f, 0.0f);\n\t\t\tat = QuaternionHelper.rotateVectorByQuaternion(at, Entities.camera.rotation);\n\t\t\tup = QuaternionHelper.rotateVectorByQuaternion(up, Entities.camera.rotation);\n\t\t\tlistenerOrient.put(at.x);\n\t\t\tlistenerOrient.put(at.y);\n\t\t\tlistenerOrient.put(at.z);\n\t\t\tlistenerOrient.put(up.x);\n\t\t\tlistenerOrient.put(up.y);\n\t\t\tlistenerOrient.put(up.z);\n\t\t}\n\t\t\n\t\tlistenerPos.rewind();\n\t\tlistenerVel.rewind();\n\t\tlistenerOrient.rewind();\n\t\t\n\t\t// set AL's listener data\n\t\tAL10.alListener(AL10.AL_POSITION, listenerPos);\n\t\tAL10.alListener(AL10.AL_VELOCITY, listenerVel);\n\t\tAL10.alListener(AL10.AL_ORIENTATION, listenerOrient);\n\t\t\n\t\t// check for errors\n\t\terr = AL10.alGetError();\n\t\tif(err != AL10.AL_NO_ERROR){\n\t\t\tSystem.out.println(\"Error in OpenAL! number: \" + err + \" string: \" + AL10.alGetString(err));\n\t\t}\n\t\t\n\t\t// get rid of any straggling sound sources\n\t\tArrayList<SoundSource> toRemove = new ArrayList<SoundSource>();\n\t\tfor(SoundSource src : soundSources){\n\t\t\tif(src.removeFlag){\n\t\t\t\t// only remove something if it's not playing anything\n\t\t\t\tif(!src.isPlaying()){\n\t\t\t\t\tsrc.shutdown();\n\t\t\t\t\ttoRemove.add(src);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(SoundSource src : toRemove)\n\t\t\tsoundSources.remove(src);\n\t}\n\t\n\t/**\n\t * Changes the volume of everything\n\t * @param gain New volume level (0 = none, 0.5 = 50%, 1 = 100%, 2 = 200% etc.)\n\t */\n\tpublic static void setVolume(float gain){\n\t\tvolume = gain;\n\t\t\n\t\tfor(SoundSource src : soundSources)\n\t\t\tsrc.setGain(volume);\n\t}\n\t\n\t/**\n\t * @return Current volume level\n\t */\n\tpublic static float currentVolume(){\n\t\treturn volume;\n\t}\n\t\n\t/**\n\t * Pauses all sounds\n\t */\n\tpublic static void pause(){\n\t\tfor(SoundSource src : soundSources)\n\t\t\tsrc.pauseSound();\n\t}\n\t\n\t/**\n\t * Plays all sounds\n\t */\n\tpublic static void play(){\n\t\tfor(SoundSource src : soundSources)\n\t\t\tif(!src.isPlaying() && src.isLooping())\n\t\t\t\tsrc.playSound();\n\t}\n\t\n\t/**\n\t * Mutes/un-mutes audio\n\t */\n\tpublic static void mute(){\n\t\tmuted = !muted;\n\t\t\n\t\tfor(SoundSource src : soundSources)\n\t\t\tsrc.setGain(muted ? 0.0f : src.getDefaultGain());\n\t}\n\t\n\t/**\n\t * @return Whether or not audio is muted\n\t */\n\tpublic static boolean isMuted(){\n\t\treturn muted;\n\t}\n\t\n\t/**\n\t * Shuts down OpenAL\n\t */\n\tpublic static void shutdown(){\n\t\t// get rid of all sound sources\n\t\tfor(SoundSource src : soundSources)\n\t\t\tsrc.shutdown();\n\t\tAL.destroy();\n\t}\n\t\n\t/**\n\t * Plays a sound from {@link Sounds} once and then sets it to be removed from the list of sound sources.\n\t * This is useful for making noises in menus/item pickups/whatever that shouldn't be effected by the listener's\n\t * location or velocity.\n\t * @param sound Sound to play\n\t */\n\tpublic static void playSoundOnceAtListener(Sounds sound){\n\t\tVector3f location;\n\t\tjavax.vecmath.Vector3f velocity = new javax.vecmath.Vector3f();\n\t\t\n\t\t// if there's no camera, then the listener gets set to be at (0,0,0) - see update() method\n\t\tif(Entities.camera == null){\n\t\t\tlocation = new Vector3f(0.0f, 0.0f, 0.0f);\n\t\t\tvelocity = new javax.vecmath.Vector3f(0.0f, 0.0f, 0.0f);\n\t\t} else{\n\t\t\t// position\n\t\t\tlocation = Entities.camera.getLocationWithOffset();\n\n\t\t\t// if we're following anything, we want its velocity\n\t\t\tif(Entities.camera.buildMode || Entities.camera.freeMode)\n\t\t\t\tEntities.camera.rigidBody.getLinearVelocity(velocity);\n\t\t\telse\n\t\t\t\tEntities.camera.following.rigidBody.getLinearVelocity(velocity);\n\t\t}\n\t\t\n\t\t// create a sound source, play it, and set it up to be removed\n\t\tSoundSource tmp = new SoundSource(sound, false, location, new Vector3f(velocity.x, velocity.y, velocity.z));\n\t\ttmp.playSound();\n\t\ttmp.removeFlag = true;\n\t}\n}",
"public class DynamicEntity extends Entity {\n\t/** the rigid body for this entity */\n\tpublic RigidBody rigidBody;\n\n\t/** the model to use for this entity */\n\tpublic Model model;\n\n\t/**\n\t * if this is true, the next time the entity is updated it is removed from\n\t * the world\n\t */\n\tpublic boolean removeFlag = false;\n\n\t/**\n\t * Overloaded constructor\n\t */\n\tpublic DynamicEntity(Vector3f location, Quaternion rotation, Model model,\n\t\t\tfloat mass, float restitution) {\n\t\tthis(location, rotation, model, mass, restitution,\n\t\t\t\tCollisionTypes.NOTHING, CollisionTypes.NOTHING);\n\t}\n\n\tpublic DynamicEntity(Vector3f location, Quaternion rotation, Models model,\n\t\t\tfloat mass, float restitution) {\n\t\tthis(location, rotation, model.getModel(), mass, restitution,\n\t\t\t\tCollisionTypes.NOTHING, CollisionTypes.NOTHING);\n\t}\n\n\tpublic DynamicEntity(Vector3f location, Quaternion rotation, Models model,\n\t\t\tfloat mass, float restitution, short collisionGroup,\n\t\t\tshort collidesWith) {\n\t\tthis(location, rotation, model.getModel(), mass, restitution,\n\t\t\t\tcollisionGroup, collidesWith);\n\t}\n\n\t/**\n\t * Creates the entity and adds it to the dynamics world (but NOT to\n\t * Entities.dynamicEntities)\n\t * \n\t * @param location\n\t * Initial location of the entity\n\t * @param rotation\n\t * Initial rotation of the entity (<i>Be careful!</i> If the\n\t * quaternion isn't right, i.e. not normalized, funny things will\n\t * happen)\n\t * @param model\n\t * The {@link Model} for the entity\n\t * @param mass\n\t * The mass for the entity\n\t * @param restitution\n\t * The restitution (bounciness) of the entity\n\t * @param collisionGroup\n\t * which group from {@link CollisionTypes} this entity belongs to\n\t */\n\tpublic DynamicEntity(Vector3f location, Quaternion rotation, Model model,\n\t\t\tfloat mass, float restitution, short collisionGroup,\n\t\t\tshort collidesWith) {\n\t\t// see Entity for location and rotation\n\t\tthis.location = location;\n\t\tthis.rotation = rotation;\n\t\tthis.model = model;\n\n\t\t// the transform to use for putting the entity into the world\n\t\tTransform transform = new Transform();\n\t\ttransform.setRotation(new Quat4f(rotation.x, rotation.y, rotation.z,\n\t\t\t\trotation.w));\n\t\ttransform.origin.set(location.x, location.y, location.z);\n\t\tDefaultMotionState defaultState = new DefaultMotionState(transform);\n\n\t\t// location to use for the entity (need a javax.vecmath Vector3f instead\n\t\t// of the given org.lwjgl.util.vector Vector3f\n\t\tjavax.vecmath.Vector3f loca = new javax.vecmath.Vector3f(location.x,\n\t\t\t\tlocation.y, location.z);\n\n\t\t// the collision shape is made when the model is made\n\t\tCollisionShape shape = model.getCollisionShape();\n\n\t\t// no initial fall inertia (it isn't vital to set this)\n\t\tjavax.vecmath.Vector3f fallInertia = new javax.vecmath.Vector3f(0.0f,\n\t\t\t\t0.0f, 0.0f);\n\t\tshape.calculateLocalInertia(mass, fallInertia);\n\n\t\t// create the rigid body based on all the stuff we've grabbed\n\t\tRigidBodyConstructionInfo rigidBodyCI = new RigidBodyConstructionInfo(\n\t\t\t\tmass, defaultState, shape, loca);\n\t\trigidBodyCI.restitution = restitution;\n\t\trigidBody = new RigidBody(rigidBodyCI);\n\n\t\t// set the pointer so the entity can be updated (see\n\t\t// DynamicEntityCallback)\n\t\trigidBody.setUserPointer(this);\n\n\t\t// finally, add it to the world\n\t\tif (collisionGroup != CollisionTypes.NOTHING\n\t\t\t\t&& collidesWith != CollisionTypes.NOTHING)\n\t\t\tPhysics.dynamicsWorld.addRigidBody(rigidBody, collisionGroup,\n\t\t\t\t\tcollidesWith);\n\t\telse\n\t\t\tPhysics.dynamicsWorld.addRigidBody(rigidBody);\n\t}\n\t\n\tpublic DynamicEntity(Vector3f location, Quaternion rotation, CollisionShape shape,\n\t\t\tfloat mass, float restitution, short collisionGroup,\n\t\t\tshort collidesWith) {\n\t\t// see Entity for location and rotation\n\t\tthis.location = location;\n\t\tthis.rotation = rotation;\n\n\t\t// the transform to use for putting the entity into the world\n\t\tTransform transform = new Transform();\n\t\ttransform.setRotation(new Quat4f(rotation.x, rotation.y, rotation.z,\n\t\t\t\trotation.w));\n\t\ttransform.origin.set(location.x, location.y, location.z);\n\t\tDefaultMotionState defaultState = new DefaultMotionState(transform);\n\n\t\t// location to use for the entity (need a javax.vecmath Vector3f instead\n\t\t// of the given org.lwjgl.util.vector Vector3f\n\t\tjavax.vecmath.Vector3f loca = new javax.vecmath.Vector3f(location.x,\n\t\t\t\tlocation.y, location.z);\n\n\t\t// no initial fall inertia (it isn't vital to set this)\n\t\tjavax.vecmath.Vector3f fallInertia = new javax.vecmath.Vector3f(0.0f,\n\t\t\t\t0.0f, 0.0f);\n\t\tshape.calculateLocalInertia(mass, fallInertia);\n\n\t\t// create the rigid body based on all the stuff we've grabbed\n\t\tRigidBodyConstructionInfo rigidBodyCI = new RigidBodyConstructionInfo(\n\t\t\t\tmass, defaultState, shape, loca);\n\t\trigidBodyCI.restitution = restitution;\n\t\trigidBody = new RigidBody(rigidBodyCI);\n\n\t\t// set the pointer so the entity can be updated (see\n\t\t// DynamicEntityCallback)\n\t\trigidBody.setUserPointer(this);\n\n\t\t// finally, add it to the world\n\t\tif (collisionGroup != CollisionTypes.NOTHING\n\t\t\t\t&& collidesWith != CollisionTypes.NOTHING)\n\t\t\tPhysics.dynamicsWorld.addRigidBody(rigidBody, collisionGroup,\n\t\t\t\t\tcollidesWith);\n\t\telse\n\t\t\tPhysics.dynamicsWorld.addRigidBody(rigidBody);\n\t}\n\n\t@Override\n\t/**\n\t * Simple as possible drawing call. This assumes that it's called when the entity's location and rotation have already been applied to the modelview matrix.\n\t */\n\tpublic void draw() {\n\t\tmodel.getTexture().texture().bind();\n\t\tmodel.render();\n\t}\n\n\t/**\n\t * Draws the physics debug info for this entity. Should be called before\n\t * rotations are applied.\n\t */\n\tpublic void drawPhysicsDebug() {\n\t\tTransform worldTransform = new Transform();\n\t\trigidBody.getWorldTransform(worldTransform);\n\n\t\tCollisionShape shape = model.getCollisionShape();\n\n\t\tPhysics.dynamicsWorld.debugDrawObject(worldTransform, shape,\n\t\t\t\tnew javax.vecmath.Vector3f(0.0f, 0.0f, 0.0f));\n\t}\n\t\n\tpublic ClosestRayResultCallback rayTest(Vector3f direction){\n\t\t// rotate the direction we want to test so that it's realtive to the entity's rotation\n\t\tVector3f endRotated = QuaternionHelper.rotateVectorByQuaternion(direction, rotation);\n\t\tVector3f endAdd = new Vector3f();\n\t\t// add the rotated direction to the current location to get the end vector\n\t\tVector3f.add(location, endRotated, endAdd);\n\t\t\n\t\tjavax.vecmath.Vector3f start = new javax.vecmath.Vector3f(location.x, location.y, location.z);\n\t\tjavax.vecmath.Vector3f end = new javax.vecmath.Vector3f(endAdd.x, endAdd.y, endAdd.z);\n\t\t\n\t\tClosestRayResultCallback callback = new ClosestRayResultCallback(start, end);\n\t\tPhysics.dynamicsWorld.rayTest(start, end, callback);\n\t\t\n\t\treturn callback;\n\t}\n\n\t@Override\n\t/**\n\t * Removes the rigid body from the dynamics world it's in\n\t */\n\tpublic void cleanup() {\n\t\tremoveFlag = true;\n\t}\n\n\t@Override\n\t/**\n\t * Update the dynamic entity\n\t * NOTE: If you're making your own class that extends DynamicEntity,\n\t * you need to override this method!\n\t */\n\tpublic void update(float timeStep){};\n}",
"public class Entities {\n\t/** player instance */\n\tpublic static Player player;\n\t/** camera instance */\n\tpublic static Camera camera;\n\t/** the skybox */\n\tpublic static Skybox skybox;\n\n\t/** all the current passive entities */\n\tpublic static ArrayList<Entity> passiveEntities = new ArrayList<Entity>(10), passiveEntitiesToAdd = new ArrayList<Entity>(10), passiveEntitiesToRemove = new ArrayList<Entity>(10);\n\t/** all the dynamic entities */\n\tpublic static ArrayList<DynamicEntity> dynamicEntities = new ArrayList<DynamicEntity>(100);\n\t/** all the current lights */\n\tpublic static ArrayList<Light> lights = new ArrayList<Light>(8), lightsToAdd = new ArrayList<Light>(8), lightsToRemove = new ArrayList<Light>(8);\n\t\n\t/**\n\t * Updates everything that doesn't get updated by the {@link DynamicEntityCallback}\n\t * @param timeStep How much time has passed since the last tick (passed in from DynamicEntityCallback)\n\t */\n\tpublic static void updateAll(float timeStep){\n\t\t/*\n\t\t * Since passiveEntities and lights all get updated by iterating through their lists,\n\t\t * directly adding and removing from the list can cause a ConcurrentModificationException.\n\t\t * Everything in DynamicEntities is updated in the DynamicEntityCallback, and as such the list\n\t\t * in here is used solely for rendering. So adds and removes can be done directly on the\n\t\t * list.\n\t\t */\n\t\tif(!passiveEntitiesToRemove.isEmpty()){\n\t\t\tfor(Entity ent : passiveEntitiesToRemove)\n\t\t\t\tpassiveEntities.remove(ent);\n\t\t\tpassiveEntitiesToRemove.clear();\n\t\t}\n\t\t\n\t\tif(!passiveEntitiesToAdd.isEmpty()){\n\t\t\tfor(Entity ent : passiveEntitiesToAdd)\n\t\t\t\tpassiveEntities.add(ent);\n\t\t\tpassiveEntitiesToAdd.clear();\n\t\t}\n\t\t\n\t\tif(!lightsToRemove.isEmpty()){\n\t\t\tfor(Light l : lightsToRemove)\n\t\t\t\tlights.remove(l);\n\t\t\tlightsToRemove.clear();\n\t\t}\n\t\t\n\t\tif(!lightsToAdd.isEmpty()){\n\t\t\tfor(Light l : lightsToAdd)\n\t\t\t\tlights.add(l);\n\t\t\tlightsToAdd.clear();\n\t\t}\n\t\t\n\t\tcamera.update(timeStep);\n\t\tskybox.update(timeStep);\n\t\t\n\t\tfor(Entity ent : passiveEntities)\n\t\t\tent.update(timeStep);\n\t\t\n\t\tfor(Light l : lights)\n\t\t\tl.update(timeStep);\n\t}\n\t\n\t/**\n\t * Adds the given DynamicEntity to the rendering world\n\t * @param ent Entity to add\n\t */\n\tpublic static void addDynamicEntity(DynamicEntity ent){\n\t\tdynamicEntities.add(ent);\n\t}\n\t\n\t/**\n\t * Adds the given Entity to the rendering world\n\t * @param ent Entity to add\n\t */\n\tpublic static void addPassiveEntity(Entity ent){\n\t\tpassiveEntitiesToAdd.add(ent);\n\t}\n\t\n\t/**\n\t * Adds the given Light to the rendering world\n\t * @param light Light to add\n\t */\n\tpublic static void addLight(Light light){\n\t\tlightsToAdd.add(light);\n\t}\n\t\n\t/**\n\t * Removes the given DynamicEntity from the rendering world\n\t * @param ent Entity to remove\n\t */\n\tpublic static void removeDynamicEntity(DynamicEntity ent){\n\t\tdynamicEntities.remove(ent);\n\t}\n\t\n\t/**\n\t * Removes the given Entity from the rendering world\n\t * @param ent Entity to remove\n\t */\n\tpublic static void removePassiveEntity(Entity ent){\n\t\tpassiveEntitiesToRemove.add(ent);\n\t}\n\t\n\t/**\n\t * Removes the given Light from the rendering world\n\t * @param light Light to remove\n\t */\n\tpublic static void removeLight(Light l){\n\t\tlightsToRemove.add(l);\n\t}\n\n\t/**\n\t * @return Whether or not there are any entities at the moment\n\t */\n\tpublic static boolean entitiesExist() {\n\t\treturn !passiveEntities.isEmpty() || !dynamicEntities.isEmpty() || player != null;\n\t}\n\n\t/**\n\t * Gets the distance between two vectors\n\t * \n\t * @param first\n\t * The first vector\n\t * @param second\n\t * The second vector\n\t * @return The distance between the two vectors\n\t */\n\tpublic static float distance(Vector3f first, Vector3f second) {\n\t\tfloat xDist = first.x - second.x;\n\t\tfloat yDist = first.y - second.y;\n\t\tfloat zDist = first.z - second.z;\n\n\t\tfloat xSqr = xDist * xDist;\n\t\tfloat ySqr = yDist * yDist;\n\t\tfloat zSqr = zDist * zDist;\n\n\t\tdouble total = (double) (xSqr + ySqr + zSqr);\n\n\t\treturn (float) Math.sqrt(total);\n\t}\n\n\t/**\n\t * Delete all of the entities\n\t */\n\tpublic static void cleanup() {\n\t\tfor(Entity ent : passiveEntities){\n\t\t\tent.cleanup();\n\t\t}\n\t\t\n\t\tfor(DynamicEntity ent : dynamicEntities){\n\t\t\tent.cleanup();\n\t\t}\n\t\tplayer = null;\n\t\tcamera = null;\n\t\tpassiveEntities.clear();\n\t\tdynamicEntities.clear();\n\t\tlights.clear();\n\t}\n}",
"public abstract class Entity {\n\t/** the entity's current location */\n\tpublic Vector3f location;\n\n\t/** quaternion representing rotation */\n\tpublic Quaternion rotation;\n\n\t/** type, used for lots of things */\n\tpublic String type;\n\n\t/**\n\t * Entity constructor\n\t */\n\tpublic Entity() {\n\t\tlocation = new Vector3f(0.0f, 0.0f, 0.0f);\n\t\trotation = new Quaternion(1.0f, 0.0f, 0.0f, 1.0f);\n\t\ttype = \"entity\";\n\t}\n\n\t/**\n\t * Updates this entity\n\t */\n\tpublic abstract void update(float timeStep);\n\n\t/**\n\t * Draws this entity\n\t */\n\tpublic abstract void draw();\n\n\t/**\n\t * Have the entity provide any necessary cleanup\n\t */\n\tpublic abstract void cleanup();\n}",
"public abstract class Light extends Entity {\n\tpublic Vector3f intensity;\n\n\t/**\n\t * Create a new light\n\t * \n\t * @param location\n\t * Location of this light\n\t * @param light\n\t * Which OpenGL light to use (<code>GL11.GL_LIGHT[0-7]</code>)\n\t * @param ambient\n\t * Ambient light, should be 3 floats\n\t * @param diffuse\n\t * Diffuse light, should be 3 floats\n\t */\n\tpublic Light(Vector3f location, Vector3f intensity) {\n\t\tsuper();\n\t\tthis.location = location;\n\t\tthis.intensity = intensity;\n\t}\n\n\t@Override\n\tpublic void cleanup() {\n\t\t\n\t}\n}",
"public class QuaternionHelper {\n\tfinal static float PIOVER180 = ((float) Math.PI) / 180.0f;\n\n\t/**\n\t * Converts angles to a quaternion\n\t * @param pitch X axis rotation\n\t * @param yaw Y axis rotation\n\t * @param roll Z axis rotation\n\t * @return Quaternion representing angles\n\t */\n\tpublic static Quaternion getQuaternionFromAngles(float pitch, float yaw,\n\t\t\tfloat roll) {\n\t\tQuaternion quat;\n\n\t\tfloat p = pitch * PIOVER180 / 2.0f;\n\t\tfloat y = yaw * PIOVER180 / 2.0f;\n\t\tfloat r = roll * PIOVER180 / 2.0f;\n\n\t\tfloat sinp = (float) Math.sin(p);\n\t\tfloat siny = (float) Math.sin(y);\n\t\tfloat sinr = (float) Math.sin(r);\n\t\tfloat cosp = (float) Math.cos(p);\n\t\tfloat cosy = (float) Math.cos(y);\n\t\tfloat cosr = (float) Math.cos(r);\n\n\t\tfloat quatX = sinr * cosp * cosy - cosr * sinp * siny;\n\t\tfloat quatY = cosr * sinp * cosy + sinr * cosp * siny;\n\t\tfloat quatZ = cosr * cosp * siny - sinr * sinp * cosy;\n\t\tfloat quatW = cosr * cosp * cosy + sinr * sinp * siny;\n\n\t\tquat = new Quaternion(quatX, quatY, quatZ, quatW);\n\t\tQuaternion retQuat = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tQuaternion.normalise(quat, retQuat);\n\n\t\treturn retQuat;\n\t}\n\n\t/**\n\t * Not sure if this works\n\t * @param quat Quaternion to convert\n\t * @return float array with 4 elements- x, y, z, and angle\n\t */\n\tpublic static float[] convertToAxisAngle(Quaternion quat) {\n\t\tfloat scale = (float) Math\n\t\t\t\t.sqrt(((quat.x * quat.x) + (quat.y * quat.y) + (quat.z * quat.z)));\n\n\t\tfloat ax = quat.x / scale;\n\t\tfloat ay = quat.y / scale;\n\t\tfloat az = quat.z / scale;\n\n\t\tfloat angle = 2.0f * (float) Math.acos((double) quat.w);\n\n\t\treturn new float[] { ax, ay, az, angle };\n\t}\n\n\t/**\n\t * Converts a quaternion to a rotation matrix stored in a FloatBuffer\n\t * \n\t * @param quat\n\t * The quaternion to convert\n\t * @param dest\n\t * The float buffer to put the rotation matrix into. MUST have a\n\t * capacity of 16 and be direct\n\t */\n\tpublic static void toFloatBuffer(Quaternion quat, FloatBuffer dest) {\n\t\tif (!dest.isDirect()) {\n\t\t\tSystem.out\n\t\t\t\t\t.println(\"QuaternionHelper toFloatBuffer was passed an indirect FloatBuffer!\");\n\t\t} else if (dest.capacity() != 16) {\n\t\t\tSystem.out\n\t\t\t\t\t.println(\"QuaternionHelper toFloatBuffer was passed a buffer of the incorrect size!\");\n\t\t} else {\n\t\t\tdest.clear();\n\n\t\t\tfloat x = quat.x;\n\t\t\tfloat y = quat.y;\n\t\t\tfloat z = quat.z;\n\t\t\tfloat w = quat.w;\n\n\t\t\tfloat x2 = x * x;\n\t\t\tfloat y2 = y * y;\n\t\t\tfloat z2 = z * z;\n\t\t\tfloat xy = x * y;\n\t\t\tfloat xz = x * z;\n\t\t\tfloat yz = y * z;\n\t\t\tfloat wx = w * x;\n\t\t\tfloat wy = w * y;\n\t\t\tfloat wz = w * z;\n\n\t\t\tdest.put(1.0f - 2.0f * (y2 + z2));\n\t\t\tdest.put(2.0f * (xy - wz));\n\t\t\tdest.put(2.0f * (xz + wy));\n\t\t\tdest.put(0.0f);\n\t\t\tdest.put(2.0f * (xy + wz));\n\t\t\tdest.put(1.0f - 2.0f * (x2 + z2));\n\t\t\tdest.put(2.0f * (yz - wx));\n\t\t\tdest.put(0.0f);\n\t\t\tdest.put(2.0f * (xz - wy));\n\t\t\tdest.put(2.0f * (yz + wx));\n\t\t\tdest.put(1.0f - 2.0f * (x2 + y2));\n\t\t\tdest.put(0.0f);\n\t\t\tdest.put(0.0f);\n\t\t\tdest.put(0.0f);\n\t\t\tdest.put(0.0f);\n\t\t\tdest.put(1.0f);\n\n\t\t\tdest.rewind();\n\t\t}\n\t}\n\n\t/**\n\t * Rotates a vector by a quaternion\n\t * \n\t * @param vector\n\t * The vector to rotate\n\t * @param quat\n\t * The quaternion to rotate the vector by\n\t * @return Rotate vector\n\t */\n\tpublic static Vector3f rotateVectorByQuaternion(Vector3f vector,\n\t\t\tQuaternion quat) {\n\t\tQuaternion vecQuat = new Quaternion(vector.x, vector.y, vector.z, 0.0f);\n\n\t\tQuaternion quatNegate = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tquat.negate(quatNegate);\n\n\t\tQuaternion resQuat = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tQuaternion.mul(vecQuat, quatNegate, resQuat);\n\t\tQuaternion.mul(quat, resQuat, resQuat);\n\n\t\treturn new Vector3f(resQuat.x, resQuat.y, resQuat.z);\n\t}\n\t\n\t/**\n\t * Rotates a vector by a quaternion\n\t * \n\t * @param vector\n\t * The vector to rotate\n\t * @param quat\n\t * The quaternion to rotate the vector by\n\t * @return Rotate vector\n\t */\n\tpublic static Vector3f rotateVectorByQuaternion(javax.vecmath.Vector3f vector,\n\t\t\tQuaternion quat) {\n\t\tQuaternion vecQuat = new Quaternion(vector.x, vector.y, vector.z, 0.0f);\n\n\t\tQuaternion quatNegate = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tquat.negate(quatNegate);\n\n\t\tQuaternion resQuat = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tQuaternion.mul(vecQuat, quatNegate, resQuat);\n\t\tQuaternion.mul(quat, resQuat, resQuat);\n\n\t\treturn new Vector3f(resQuat.x, resQuat.y, resQuat.z);\n\t}\n\t\n\t/**\n\t * Rotates a vector by a quaternion\n\t * \n\t * @param vector\n\t * The vector to rotate\n\t * @param quat\n\t * The quaternion to rotate the vector by\n\t * @return Rotate vector\n\t */\n\tpublic static Vector3f rotateVectorByQuaternion(javax.vecmath.Vector3f vector,\n\t\t\tQuat4f quat) {\n\t\tQuaternion vecQuat = new Quaternion(vector.x, vector.y, vector.z, 0.0f);\n\n\t\tQuat4f quatNegate = new Quat4f(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tquat.negate(quatNegate);\n\n\t\tQuaternion resQuat = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tQuaternion.mul(vecQuat, new Quaternion(quatNegate.x, quatNegate.y, quatNegate.z, quatNegate.w), resQuat);\n\t\tQuaternion.mul(new Quaternion(quat.x, quat.y, quat.z, quat.w), resQuat, resQuat);\n\n\t\treturn new Vector3f(resQuat.x, resQuat.y, resQuat.z);\n\t}\n\n\t/**\n\t * Converts a quaternion to good ol' euler angles\n\t * \n\t * @param quat\n\t * The quaternion to convert\n\t * @return A vector containing the three euler angles\n\t */\n\tpublic static Vector3f getEulerAnglesFromQuaternion(Quaternion quat) {\n\t\tfloat xn = (2 * ((quat.x * quat.y) + (quat.z * quat.w)))\n\t\t\t\t/ (1 - (2 * ((quat.y * quat.y) + (quat.z * quat.z))));\n\t\tfloat x = (float) (Math.atan((double) xn));\n\n\t\tfloat yn = 2 * ((quat.x * quat.z) - (quat.w * quat.y));\n\t\tfloat y = (float) (Math.asin((double) yn));\n\n\t\tfloat zn = (2 * ((quat.x * quat.w) + (quat.y * quat.z)))\n\t\t\t\t/ (1 - (2 * ((quat.z * quat.z) + (quat.w * quat.w))));\n\t\tfloat z = (float) (Math.atan((double) zn));\n\n\t\tx = x * (180.0f / (float) Math.PI);\n\t\ty = y * (180.0f / (float) Math.PI);\n\t\tz = z * (180.0f / (float) Math.PI);\n\n\t\treturn new Vector3f(x, y, z);\n\t}\n\t\n\t/**\n\t * Rotate a quaternion by a vector\n\t * @param quat Quaternion to rotate\n\t * @param amount Amount to rotate quaternion by\n\t * @return Rotated quaternion\n\t */\n\tpublic static Quaternion rotate(Quaternion quat, Vector3f amount){\n\t\tQuaternion ret = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\n\t\tret = rotateX(quat, amount.x);\n\t\tret = rotateY(ret, amount.y);\n\t\tret = rotateZ(ret, amount.z);\n\t\t\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Rotate a quaternion along it's x axis a certain amount\n\t * \n\t * @param amount\n\t * Amount to rotate the quaternion\n\t * @return Rotated quaternion\n\t */\n\tpublic static Quaternion rotateX(Quaternion quat, float amount) {\n\t\tQuaternion ret = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tdouble radHalfAngle = Math.toRadians((double) amount) / 2.0;\n\t\tfloat sinVal = (float) Math.sin(radHalfAngle);\n\t\tfloat cosVal = (float) Math.cos(radHalfAngle);\n\t\tQuaternion rot = new Quaternion(sinVal, 0.0f, 0.0f, cosVal);\n\t\tQuaternion.mul(quat, rot, ret);\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Rotate a quaternion along it's y axis a certain amount\n\t * \n\t * @param amount\n\t * Amount to rotate the quaternion\n\t * @return Rotated quaternion\n\t */\n\tpublic static Quaternion rotateY(Quaternion quat, float amount) {\n\t\tQuaternion ret = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tdouble radHalfAngle = Math.toRadians((double) amount) / 2.0;\n\t\tfloat sinVal = (float) Math.sin(radHalfAngle);\n\t\tfloat cosVal = (float) Math.cos(radHalfAngle);\n\t\tQuaternion rot = new Quaternion(0.0f, sinVal, 0.0f, cosVal);\n\t\tQuaternion.mul(quat, rot, ret);\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Rotate a quaternion along it's z axis a certain amount\n\t * \n\t * @param amount\n\t * Amount to rotate the quaternion\n\t * @return Rotated quaternion\n\t */\n\tpublic static Quaternion rotateZ(Quaternion quat, float amount) {\n\t\tQuaternion ret = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tdouble radHalfAngle = Math.toRadians((double) amount) / 2.0;\n\t\tfloat sinVal = (float) Math.sin(radHalfAngle);\n\t\tfloat cosVal = (float) Math.cos(radHalfAngle);\n\t\tQuaternion rot = new Quaternion(0.0f, 0.0f, sinVal, cosVal);\n\t\tQuaternion.mul(quat, rot, ret);\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Moves the given vector a certain amount along the rotation of the given\n\t * quaternion\n\t * \n\t * @param quat\n\t * Rotation to use for movement\n\t * @param vec\n\t * Vector to add to\n\t * @param amount\n\t * Amount to add to the vector\n\t */\n\tpublic static Vector3f moveX(Quaternion quat, Vector3f vec, float amount) {\n\t\tVector3f ret = new Vector3f(0.0f, 0.0f, 0.0f);\n\t\tVector3f multi = rotateVectorByQuaternion(new Vector3f(amount, 0.0f,\n\t\t\t\t0.0f), quat);\n\t\tVector3f.add(vec, multi, ret);\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Moves the given vector a certain amount along the rotation of the given\n\t * quaternion\n\t * \n\t * @param quat\n\t * Rotation to use for movement\n\t * @param vec\n\t * Vector to add to\n\t * @param amount\n\t * Amount to add to the vector\n\t */\n\tpublic static Vector3f moveY(Quaternion quat, Vector3f vec, float amount) {\n\t\tVector3f ret = new Vector3f(0.0f, 0.0f, 0.0f);\n\t\tVector3f multi = rotateVectorByQuaternion(new Vector3f(0.0f, amount,\n\t\t\t\t0.0f), quat);\n\t\tVector3f.add(vec, multi, ret);\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Moves the given vector a certain amount along the rotation of the given\n\t * quaternion\n\t * \n\t * @param quat\n\t * Rotation to use for movement\n\t * @param vec\n\t * Vector to add to\n\t * @param amount\n\t * Amount to add to the vector\n\t */\n\tpublic static Vector3f moveZ(Quaternion quat, Vector3f vec, float amount) {\n\t\tVector3f ret = new Vector3f(0.0f, 0.0f, 0.0f);\n\t\tVector3f multi = rotateVectorByQuaternion(new Vector3f(0.0f, 0.0f,\n\t\t\t\tamount), quat);\n\t\tVector3f.add(vec, multi, ret);\n\t\treturn ret;\n\t}\n\t\n\t/**\n\t * Converts a quaternion to a rotation matrix\n\t * @param quat Quaternion to convert\n\t * @return Rotation matrix representing given quaternion\n\t */\n\tpublic static Matrix4f toMatrix(Quaternion quat){\n\t\tfloat x2 = quat.x * quat.x;\n\t\tfloat y2 = quat.y * quat.y;\n\t\tfloat z2 = quat.z * quat.z;\n\t\tfloat xy = quat.x * quat.y;\n\t\tfloat xz = quat.x * quat.z;\n\t\tfloat yz = quat.y * quat.z;\n\t\tfloat wx = quat.w * quat.x;\n\t\tfloat wy = quat.w * quat.y;\n\t\tfloat wz = quat.w * quat.z;\n\t\t\n\t\tMatrix4f ret = new Matrix4f();\n\n\n\t\tret.m00 = (1.0f - 2.0f * (y2 + z2));\n\t\tret.m10 = (2.0f * (xy - wz));\n\t\tret.m20 = (2.0f * (xz + wy));\n\t\tret.m30 = (0.0f);\n\t\t\n\t\tret.m01 = (2.0f * (xy + wz));\n\t\tret.m11 = (1.0f - 2.0f * (x2 + z2));\n\t\tret.m21 = (2.0f * (yz - wx));\n\t\tret.m31 = (0.0f);\n\t\t\n\t\tret.m02 = (2.0f * (xz - wy));\n\t\tret.m12 = (2.0f * (yz + wx));\n\t\tret.m22 = (1.0f - 2.0f * (x2 + y2));\n\t\tret.m32 = (0.0f);\n\t\t\n\t\tret.m03 = (0.0f);\n\t\tret.m13 = (0.0f);\n\t\tret.m23 = (0.0f);\n\t\tret.m33 = (1.0f);\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t/**\n\t * Finds the quaternion between two vectors. Assumes that the vectors are NOT unit length.\n\t * @param vec1 First vector\n\t * @param vec2 Second vector\n\t * @return Quaternion between vectors\n\t */\n\tpublic static Quaternion quaternionBetweenVectors(Vector3f vec1, Vector3f vec2){\n\t\tVector3f c = new Vector3f();\n\t\tVector3f.cross(vec1, vec2, c);\n\t\t\n\t\tdouble v1squr = (double)vec1.lengthSquared();\n\t\tdouble v2squr = (double)vec2.lengthSquared();\n\t\tdouble angle = Math.sqrt(v1squr * v2squr) + (double)Vector3f.dot(vec1, vec2);\n\t\t\n\t\tQuaternion q = new Quaternion(c.x, c.y, c.z, (float) angle);\n\t\tq.normalise(q);\n\t\treturn q;\n\t}\n\t\n\t/**\n\t * Converts an axis and an angle to a quaternion\n\t * @param axis Axis\n\t * @param angle Angle\n\t * @return Quaternion representing rotation\n\t */\n\tpublic static Quaternion quaternionFromAxisAngle(Vector3f axis, double angle){\n\t\tif(Math.abs(angle) < 1e-6)\n\t\t\treturn new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\n\t\tdouble halfAngle = angle * 0.5;\n\t\t\n\t\tfloat s = (float)Math.sin(halfAngle);\n\t\t\n\t\tfloat x = axis.x * s;\n\t\tfloat y = axis.y * s;\n\t\tfloat z = axis.z * s;\n\t\tfloat w = (float)Math.cos(halfAngle);\n\t\t\n\t\treturn new Quaternion(x, y, z, w);\n\t}\n}",
"public class Runner {\n\t/** what version of Spaceout is this? */\n\tpublic static final String VERSION = \"0.0.77.7\";\n\n\t/** prevents updates but still renders the scene */\n\tpublic static boolean paused = false;\n\n\t/** if this is true, it means it's time to shut down ASAP */\n\tpublic static boolean done = false;\n\n\t/** the keyboard and mouse handlers that need to be updated every frame */\n\tpublic static KeyboardManager keyboard = new KeyboardManager();\n\tpublic static MouseManager mouse = new MouseManager();\n\n\t/**\n\t * @param args Can be given a home directory to use to look for natives in instead of using the default System.getProperty(\"user.home\")\n\t */\n\tpublic static void main(String[] args) {\n\t\tif(args.length == 0)\n\t\t\tSystem.setProperty(\"org.lwjgl.librarypath\", System.getProperty(\"user.dir\") + \"/lib/natives\");\n\t\telse\n\t\t\tSystem.setProperty(\"org.lwjgl.librarypath\", args[0]);\n\t\t\n\t\t// Instantiate a runner, otherwise everything would have to be static\n\t\tRunner run = new Runner();\n\t\trun.run();\n\t}\n\n\t/**\n\t * Runs the game\n\t */\n\tpublic void run() {\n\t\t// initialize everything\n\t\tinit();\n\t\ttry {\n\t\t\t// keep going until the done flag is up or a window close is\n\t\t\t// requested\n\t\t\twhile (!done) {\n\t\t\t\t// update everything\n\t\t\t\tupdate();\n\t\t\t\t// render the scene\n\t\t\t\tGraphics.render();\n\t\t\t\t// update the display (this swaps the buffers)\n\t\t\t\tDisplay.update();\n\t\t\t\tDisplay.sync(DisplayHelper.targetFPS);\n\t\t\t}\n\t\t\tshutdown();\n\t\t} catch (Exception e) {\n\t\t\t// if an exception is caught, destroy the display and the frame\n\t\t\tshutdown();\n\t\t\t\n\t\t\t// TODO this should really bring up an error notification in the game rather than just dying\n\t\t\t// throw an alert window to let the user know what happened\n\t\t\tSys.alert(\"Oh great, what now...\", \"Spaceout has crashed!\\n\\n\" + e.getLocalizedMessage());\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Initialize OpenGL, variables, etc.\n\t */\n\tprivate void init() {\n\t\tDisplayHelper.createWindow();\n\t\t\n\t\tGraphics.initGL();\n\t\tAudio.init();\n\t\t\n\t\tDebug.init();\n\t\tDebug.printSysInfo();\n\t\t\n\t\tMainMenu mainMenu = new MainMenu();\n\t\tGUI.addGUIObject(mainMenu);\n\t\t\n\t\t//initialize resources\n\t\t// TODO loading screen!\n\t\tResourceLoader.addJob(Textures.MENU_BACKGROUND1);\n\t\tResourceLoader.addJob(Textures.MENU_BACKGROUND2);\n\t\tResourceLoader.addJob(Textures.SKYBOX);\n\t\tResourceLoader.addJob(Textures.WHITE);\n\t\tResourceLoader.addJob(Textures.TRANSPARENT_CHECKERS);\n\t\tResourceLoader.addJob(Textures.WING_X);\n\t\tResourceLoader.addJob(Textures.VENUS);\n\t\tResourceLoader.addJob(Textures.MARS);\n\t\tResourceLoader.addJob(Textures.MERCURY);\n\t\tResourceLoader.addJob(Textures.EARTH);\n\t\tResourceLoader.addJob(Textures.LASERBULLET);\n\t\tResourceLoader.addJob(Models.LASERBULLET);\n\t\tResourceLoader.addJob(Models.WESCOTT);\n\t\tResourceLoader.addJob(Models.SAUCER);\n\t\tResourceLoader.addJob(Models.SKYBOX);\n\t\tResourceLoader.addJob(Models.DIAMOND);\n\t\tResourceLoader.addJob(Models.ASTEROID);\n\t\tResourceLoader.addJob(Models.MISSILE);\n\t\tResourceLoader.addJob(Textures.MENU_PICKER_ACTIVE);\n\t\tResourceLoader.addJob(Textures.MENU_PICKER_MOUSEOVER);\n\t\tResourceLoader.addJob(Textures.MENU_PICKER_SELECTED);\n\t\tResourceLoader.addJob(Textures.MENU_PICKER_PRESSED);\n\t\tResourceLoader.addJob(Textures.MENU_BUTTON_ACTIVE);\n\t\tResourceLoader.addJob(Textures.MENU_BUTTON_INACTIVE);\n\t\tResourceLoader.addJob(Textures.MENU_BUTTON_MOUSEOVER);\n\t\tResourceLoader.addJob(Textures.MENU_BUTTON_PRESSED);\n\t\tResourceLoader.addJob(Textures.MENU_SPACEOUT_TEXT);\n\t\tResourceLoader.addJob(Textures.CROSSHAIR);\n\t\tResourceLoader.addJob(Textures.BUILDER_GRABBED);\n\t\tResourceLoader.addJob(Textures.BUILDER_OPEN);\n\t\tResourceLoader.addJob(Sounds.DIAMOND_PICKUP);\n\t\tResourceLoader.addJob(Sounds.PEW);\n\t\tResourceLoader.addJob(Sounds.SPLODE);\n\t\tResourceLoader.addJob(Sounds.THRUSTER);\n\t\tResourceLoader.addJob(Sounds.BACK);\n\t\tResourceLoader.addJob(Sounds.FRIENDLY_ALERT);\n\t\tResourceLoader.addJob(Sounds.HIT);\n\t\tResourceLoader.addJob(Sounds.SELECT);\n\t\tResourceLoader.processJobs();\n\t\t\n\t\tSystem.out.println(\"-------------------------------\");\n\t}\n\n\t/**\n\t * Updates everything\n\t */\n\tprivate void update() {\n\t\t// update the mouse and keyboard handlers\n\t\tmouse.update();\n\t\tkeyboard.update();\n\n\t\t// do pause logic\n\t\tpauseLogic();\n\t\t\n\t\t// check for window resizes\n\t\tDisplayHelper.resizeWindow();\n\t\t\n\t\t// update the GUI\n\t\tGUI.update();\n\t\n\t\tAudio.update();\n\t\t\n\t\t// update the physics engine\n\t\tif (!paused && Physics.dynamicsWorld != null)\n\t\t\tPhysics.update();\n\t\t\n\t\t// check for any resources that need to be loaded\n\t\tif(ResourceLoader.jobsExist())\n\t\t\tResourceLoader.processJobs();\n\t}\n\n\t/**\n\t * Checks whether or not the game's paused boolean needs to be flipped\n\t */\n\tprivate void pauseLogic() {\n\t\tif (KeyBindings.SYS_PAUSE.pressedOnce()){\n\t\t\tpaused = !paused;\n\t\t\t\n\t\t\tif(paused){\n\t\t\t\tAudio.pause();\n\t\t\t\t\n\t\t\t\tAudio.playSoundOnceAtListener(Sounds.SELECT);\n\t\t\t}else{\n\t\t\t\tAudio.play();\n\t\t\t\t\n\t\t\t\tAudio.playSoundOnceAtListener(Sounds.FRIENDLY_ALERT);\n\t\t\t}\n\t\t}\n\n\t\t// release the mouse if the game's paused or the console is on or the\n\t\t// menu is up\n\t\tif (!paused && !Console.consoleOn && !GUI.menuUp)\n\t\t\tMouse.setGrabbed(true);\n\t\telse\n\t\t\tMouse.setGrabbed(false);\n\t}\n\n\t/**\n\t * To be called when the game is quit\n\t */\n\tprivate void shutdown() {\n\t\tSystem.out.println(goodbye());\n\t\tAudio.shutdown();\n\t\tMouse.setGrabbed(false);\n\t\tDisplay.destroy();\n\t\tDisplayHelper.frame.dispose();\n\t}\n\t\n\t/**\n\t * This is a secret method that does secret things\n\t * @return None of your business\n\t */\n\tprivate String goodbye(){\n\t\tString[] shutdown = { \"Goodbye, world!...\", \"Goodbye, cruel world!...\", \"See ya!...\", \"Later!...\", \"Buh-bye!...\", \"Thank you, come again!...\",\n\t\t\t\t\"Until Next Time!...\", \"¡Adios, Amigo!...\", \"Game Over, Man! Game Over!!!...\", \"And So, I Bid You Adieu!...\", \"So Long, And Thanks For All The Fish!...\",\n\t\t\t\t\"¡Ciao!...\", \"Y'all Come Back Now, Ya Hear?...\", \"Catch You Later!...\", \"Mahalo And Aloha!...\", \"Sayonara!...\", \"Thanks For Playing!...\",\n\t\t\t\t\"Auf Wiedersehen!...\", \"Yo Homes, Smell Ya Later!... (Looked Up At My Kingdom, I Was Finally There, To Sit On My Throne As The Prince Of Bel-air)\",\n\t\t\t\t\"Shop Smart, Shop S-Mart!...\", \"Good Night, And Good Luck!...\", \"Remember, I'm Pulling For You. We're All In This Together!...\", \"Keep Your Stick On The Ice!...\",\n\t\t\t\t\"Omnia Extares!...\", \"C'est la vie!...\", \"See you on the flip side!...\", \"Toodle-oo!...\", \"Ta ta (For Now)!...\", \"¡Hasta La Vista, Baby!...\",\n\t\t\t\t\"Komapsumnida!...\", \"...!olleH\", \"Live Long And Prosper!...\", \"Cheerio!...\", \"Shalom!...\", \"Peace Out!...\", \"Arrivederci!...\"};\n\t\t\n\t\treturn shutdown[new Random().nextInt(shutdown.length)];\n\t}\n}"
] | import java.util.StringTokenizer;
import javax.vecmath.Quat4f;
import org.lwjgl.util.vector.Quaternion;
import org.lwjgl.util.vector.Vector3f;
import com.bitwaffle.spaceguts.audio.Audio;
import com.bitwaffle.spaceguts.entities.DynamicEntity;
import com.bitwaffle.spaceguts.entities.Entities;
import com.bitwaffle.spaceguts.entities.Entity;
import com.bitwaffle.spaceguts.entities.Light;
import com.bitwaffle.spaceguts.util.QuaternionHelper;
import com.bitwaffle.spaceout.Runner;
import com.bulletphysics.linearmath.DefaultMotionState;
import com.bulletphysics.linearmath.Transform; | package com.bitwaffle.spaceguts.util.console;
/**
* All the possible console commands. These are called by the console by their name,
* so name a command however you want it to be referenced to in-game.
* Each command constructor takes in a command class that implements the inner Command interface.
* Many commands can use the same command class.
* Commands can also take other commands in their constructors, which allows multiple commands to call the
* same Command class without needing to instantiate it.
* @author TranquilMarmot
*
*/
public enum ConsoleCommands {
help(new HelpCommand()),
list(new ListCommand()),
xyz(new PositionCommand()),
pos(xyz),
position(xyz),
clear(new ClearCommand()),
speed(new SpeedCommand()),
numentities(new NumberCommand()),
beer(new BeerCommand()),
camera(new CameraCommand()),
quit(new QuitCommand()),
q(quit),
exit(quit),
diamonds(new HowManyDiamonds()),
warp(new WarpCommand()),
mute(new MuteCommand()),
volume(new VolumeCommand()),
vol(volume);
protected Command function;
/**
* Create a console command with a new function
* @param function Function to use for this command
*/
private ConsoleCommands(Command function){
this.function = function;
}
/**
* Create a console command that uses a function that another command already uses
* @param command Command to get function from
*/
private ConsoleCommands(ConsoleCommands command){
function = command.function;
}
/**
* Issues a command
* @param toker StringTokenizer at the first arg for the command (calling toker.nextToken() will return the command's args[1]- the command itself is at args[0])
*/
public void issue(StringTokenizer toker){
function.issue(toker);
}
/**
* Prints out help for the command
*/
public void help(){
function.help();
}
}
/**
* Every command class should implement this and override the issue() function to carry out a command
* @author TranquilMarmot
*/
interface Command{
/**
* This should issue the command for the class implementing this interface
* @param toker This will contain the rest of the command, excluding the command itself, separated by spaces
*/
public void issue(StringTokenizer toker);
/**
* This should print out any help info about the command to the console
*/
public void help();
}
/**
*
*/
class HelpCommand implements Command{
@Override
public void issue(StringTokenizer toker){
if(toker.hasMoreElements()){
String commStr = toker.nextToken();
try{
ConsoleCommands command = ConsoleCommands.valueOf(commStr);
System.out.println("HELP for " + command + ":");
command.help();
} catch(IllegalArgumentException e){
System.out.println("Command not found! (" + commStr + ")");
}
} else{
System.out.println("AVAILABLE COMMANDS:");
System.out.println("(use /help COMMAND or /COMMAND help for more details)");
for(ConsoleCommands command : ConsoleCommands.values())
System.out.println(command.name());
}
}
@Override
public void help(){
System.out.println("Usage: /help command (leave command blank to get a list of commands)");
}
}
/**
* Clear the console
*/
class ClearCommand implements Command{
@Override
public void issue(StringTokenizer toker) {
Console.console.clear();
}
@Override
public void help(){
System.out.println("Clears the console");
}
}
/**
* Change the speed of the player
*/
class SpeedCommand implements Command{
@Override
public void issue(StringTokenizer toker) {
if(!toker.hasMoreTokens()){
this.help();
return;
}
String speedCommand = toker.nextToken().toLowerCase();
if(speedCommand.equals("top")){
if(toker.hasMoreTokens()){
Float speedChange = Float.parseFloat(toker.nextToken()); | System.out.printf("Changing player top speed from %f to %f\n", Entities.player.ship.getTopSpeed(), speedChange); | 2 |
dbuschman7/mongoFS | src/main/java/me/lightspeed7/mongofs/MongoFile.java | [
"public class MongoFileUrl {\n\n public static final String PROTOCOL = \"mongofile\";\n\n private URL url;\n\n // factories and helpers\n public static final MongoFileUrl construct(final ObjectId id, final String fileName, final String mediaType, final StorageFormat format)\n throws MalformedURLException {\n\n return construct(Parser.construct(id, fileName, mediaType, format));\n }\n\n public static final MongoFileUrl construct(final String spec) throws MalformedURLException {\n\n return construct(Parser.construct(spec));\n }\n\n /**\n * Construct a MogoFile object from the given URL, it will be tested from validity\n * \n * @param url\n * @return a MongoFile object for this URL\n */\n public static final MongoFileUrl construct(final URL url) {\n\n if (url == null) {\n throw new IllegalArgumentException(\"url cannot be null\");\n }\n\n if (!url.getProtocol().equals(PROTOCOL)) {\n throw new IllegalStateException(String.format(\"Only %s protocal is valid to be wrapped\", PROTOCOL));\n }\n return new MongoFileUrl(url);\n }\n\n /**\n * Is the given spec a valid MongoFile URL\n * \n * @param spec\n * @return true if the spec is a valid URL\n */\n public static final boolean isValidUrl(final String spec) {\n\n try {\n return (null != construct(spec));\n } catch (Throwable t) {\n return false;\n }\n\n }\n\n // CTOR- not visible, use construct methods above\n /* package */MongoFileUrl(final URL url) {\n\n this.url = url;\n }\n\n // toString\n @Override\n public String toString() {\n\n return this.url.toString();\n }\n\n // getters\n\n /**\n * Returns the 'attachment' protocol string\n * \n * @return the protocol\n */\n public String getProtocol() {\n\n return url.getProtocol();\n }\n\n /**\n * Returns the full URL object\n * \n * @return the URL object\n */\n public URL getUrl() {\n\n return this.url;\n }\n\n /**\n * Returns the lookup(Storage) Id from the URL\n * \n * @return the primary key to the mongoFS system\n */\n public ObjectId getMongoFileId() {\n\n return new ObjectId(url.getQuery());\n }\n\n /**\n * Returns the full path specified in the URL\n * \n * @return the full file path\n */\n public String getFilePath() {\n\n return url.getPath();\n }\n\n /**\n * Return just the last segment in the file path\n * \n * @return just the filename\n */\n public String getFileName() {\n\n return new File(url.getPath()).getName();\n }\n\n /**\n * Returns the extension on the filename\n * \n * @return the extension on the filename\n */\n public String getExtension() {\n\n // FindBugs, forced removal of null check\n return FileUtil.getExtension(new File(url.getPath())).toLowerCase();\n }\n\n /**\n * Returns the media type specified on the URL\n * \n * @return the media type for the file\n */\n public String getMediaType() {\n\n return url.getRef();\n }\n\n /**\n * Returns the storage format to the stored data, null if not compression\n * \n * @return the storage format\n */\n public StorageFormat getFormat() {\n\n return StorageFormat.find(url.getHost());\n }\n\n //\n // boolean helpers\n //\n\n /**\n * Is the data stored in the file compressed in the datastore\n * \n * @return true if compressed, false otherwise\n */\n public boolean isStoredCompressed() {\n\n StorageFormat fmt = StorageFormat.find(url.getHost());\n return fmt != null ? fmt.isCompressed() : false;\n }\n\n /**\n * Is the data encrypted within the chunks\n * \n * @return true if encrypted\n */\n public boolean isStoredEncrypted() {\n StorageFormat fmt = StorageFormat.find(url.getHost());\n return fmt != null ? fmt.isEncrypted() : false;\n }\n\n /**\n * Is the data compressible based on the media type of the file. This may differ from what is stored in the datasstore\n * \n * @return true if the data is already compressed based on its media-type\n */\n public boolean isDataCompressable() {\n\n return CompressionMediaTypes.isCompressable(getMediaType());\n }\n\n}",
"public final class Parser {\n\n private Parser() {\n // hidden\n }\n\n public static URL construct(final ObjectId id, final String fileName, final String mediaType, final StorageFormat format)\n throws MalformedURLException {\n\n String protocol = MongoFileUrl.PROTOCOL;\n\n boolean compressed = format.isCompressed() && CompressionMediaTypes.isCompressable(mediaType);\n if (compressed && format.isEncrypted()) {\n protocol += \":\" + StorageFormat.ENCRYPTED_GZIP.getCode();\n }\n else if (compressed) {\n protocol += \":\" + StorageFormat.GZIPPED.getCode();\n }\n else if (format.isEncrypted()) {\n protocol += \":\" + StorageFormat.ENCRYPTED.getCode();\n }\n\n return construct(String.format(\"%s:%s?%s#%s\", protocol, fileName, id.toString(), mediaType == null ? \"\" : mediaType.toString()));\n }\n\n public static URL construct(final String spec) throws MalformedURLException {\n\n return new URL(null, spec, new Handler());\n }\n\n}",
"public enum StorageFormat {\n\n GRIDFS(null, false, false), //\n GZIPPED(\"gz\", true, false), //\n ENCRYPTED(\"enc\", false, true), //\n ENCRYPTED_GZIP(\"encgz\", true, true) //\n //\n /* */;\n\n private final String code;\n private final boolean compressed;\n private final boolean encrypted;\n\n private StorageFormat(final String code, final boolean compressed, final boolean encrypted) {\n this.code = code;\n this.compressed = compressed;\n this.encrypted = encrypted;\n }\n\n public String getCode() {\n return code;\n }\n\n public boolean isCompressed() {\n return compressed;\n }\n\n public boolean isEncrypted() {\n return encrypted;\n }\n\n public static final StorageFormat find(final String str) {\n\n if (str == null) {\n return GRIDFS;\n }\n\n for (StorageFormat fmt : StorageFormat.values()) {\n if (fmt.name().equals(str)) {\n return fmt;\n }\n\n if (fmt.getCode() != null && fmt.getCode().equals(str)) {\n return fmt;\n }\n }\n return null;\n }\n\n public static final StorageFormat detect(final boolean compress, final boolean encrypt) {\n for (StorageFormat fmt : StorageFormat.values()) {\n if (fmt.isCompressed() == compress && fmt.isEncrypted() == encrypt) {\n return fmt;\n }\n }\n return GRIDFS;\n }\n}",
"public class BytesCopier {\n\n private final InputStream in;\n private final OutputStream out;\n\n private final int blocksize;\n private boolean closeStreamOnPersist;\n\n public BytesCopier(final InputStream in, final OutputStream out) {\n\n this(8192, in, out, false);\n }\n\n public BytesCopier(final InputStream in, final OutputStream out, final boolean closeStreamOnPersist) {\n\n this(8192, in, out, closeStreamOnPersist);\n }\n\n public BytesCopier(final int blocksize, final InputStream in, final OutputStream out) {\n\n this(blocksize, in, out, false);\n }\n\n public BytesCopier(final int blocksize, final InputStream in, final OutputStream out, final boolean closeStreamOnPersist) {\n\n this.closeStreamOnPersist = closeStreamOnPersist;\n this.blocksize = blocksize;\n this.in = in;\n this.out = out;\n }\n\n public BytesCopier closeOutput() {\n this.closeStreamOnPersist = true;\n return this;\n }\n\n public void transfer(final boolean flush) throws IOException {\n\n int nread;\n byte[] buf = new byte[blocksize];\n while ((nread = in.read(buf)) != -1) {\n out.write(buf, 0, nread);\n }\n if (flush) {\n out.flush();\n }\n if (closeStreamOnPersist) {\n in.close();\n }\n }\n\n public void transfer(final long bytesToRead, final boolean flush) throws IOException {\n\n long bytesLeft = bytesToRead;\n while (bytesLeft > 0) {\n long buffSize = bytesToRead < blocksize ? bytesToRead : blocksize;\n bytesLeft -= blocksize;\n\n byte[] buf = new byte[(int) buffSize];\n int nread = in.read(buf);\n\n // write any bytes\n if (nread != -1) {\n out.write(buf, 0, nread);\n }\n\n if (nread != buffSize) { // hit EOF\n if (flush) {\n out.flush();\n }\n if (closeStreamOnPersist) {\n in.close();\n }\n bytesLeft = 0;\n }\n }\n if (flush) {\n out.flush();\n }\n\n }\n\n}",
"public class Document {\n\n private DBObject surrogate;\n\n public Document(final String key, final Object id) {\n this();\n getSurrogate().put(key, unwrap(id));\n }\n\n public Document() {\n setSurrogate(new BasicDBObject());\n }\n\n public Document(final DBObject incoming) {\n this.setSurrogate(incoming);\n }\n\n public Document append(final String key, final Object value) {\n getSurrogate().put(key, unwrap(value));\n return this;\n }\n\n public Object put(final String key, final Object value) {\n return getSurrogate().put(key, unwrap(value));\n }\n\n public Object get(final String key) {\n return wrap(getSurrogate().get(key));\n }\n\n public String getString(final MongoFileConstants constant) {\n return this.getString(constant.name());\n }\n\n @SuppressWarnings(\"deprecation\")\n public boolean containsKey(final String key) {\n return getSurrogate().containsKey(key);\n }\n\n public Collection<? extends String> keySet() {\n\n return getSurrogate().keySet();\n }\n\n //\n // Private helpers\n // ///////////////////////////////\n private Object unwrap(final Object value) {\n\n if (value == null || !value.getClass().isAssignableFrom(Document.class)) {\n return value;\n }\n\n if (value.getClass().isAssignableFrom(Document.class) //\n && value.getClass().isAssignableFrom(Serializable.class)) {\n return value;\n }\n\n try {\n Field field = value.getClass().getDeclaredField(\"surrogate\");\n field.setAccessible(true);\n return field.get(value);\n\n } catch (Exception e) {\n throw new IllegalStateException(\"surrogate.surrogate not valid\", e);\n }\n }\n\n private Object wrap(final Object value) {\n\n if (value != null && value.getClass().isAssignableFrom(DBObject.class)) {\n return new Document((DBObject) value);\n }\n return value;\n }\n\n /**\n * Returns the value of a field as an <code>int</code>.\n * \n * @param key\n * the field to look for\n * @return the field value (or default)\n */\n public int getInt(final String key) {\n Object o = get(key);\n if (o == null) {\n throw new NullPointerException(\"no value for: \" + key);\n }\n return BSON.toInt(o);\n }\n\n /**\n * Returns the value of a field as an <code>int</code>.\n * \n * @param key\n * the field to look for\n * @param def\n * the default to return\n * @return the field value (or default)\n */\n public int getInt(final String key, final int def) {\n Object foo = get(key);\n if (foo == null) {\n return def;\n }\n return BSON.toInt(foo);\n }\n\n /**\n * Returns the value of a field as a <code>long</code>.\n * \n * @param key\n * the field to return\n * @return the field value\n */\n public long getLong(final String key) {\n Object foo = get(key);\n return ((Number) foo).longValue();\n }\n\n /**\n * Returns the value of a field as an <code>long</code>.\n * \n * @param key\n * the field to look for\n * @param def\n * the default to return\n * @return the field value (or default)\n */\n public long getLong(final String key, final long def) {\n Object foo = get(key);\n if (foo == null) {\n return def;\n }\n return ((Number) foo).longValue();\n }\n\n /**\n * Returns the value of a field as a <code>double</code>.\n * \n * @param key\n * the field to return\n * @return the field value\n */\n public double getDouble(final String key) {\n Object foo = get(key);\n return ((Number) foo).doubleValue();\n }\n\n /**\n * Returns the value of a field as an <code>double</code>.\n * \n * @param key\n * the field to look for\n * @param def\n * the default to return\n * @return the field value (or default)\n */\n public double getDouble(final String key, final double def) {\n Object foo = get(key);\n if (foo == null) {\n return def;\n }\n return ((Number) foo).doubleValue();\n }\n\n /**\n * Returns the value of a field as a string\n * \n * @param key\n * the field to look up\n * @return the value of the field, converted to a string\n */\n public String getString(final String key) {\n Object foo = get(key);\n if (foo == null) {\n return null;\n }\n return foo.toString();\n }\n\n /**\n * Returns the value of a field as a string\n * \n * @param key\n * the field to look up\n * @param def\n * the default to return\n * @return the value of the field, converted to a string\n */\n public String getString(final String key, final String def) {\n Object foo = get(key);\n if (foo == null) {\n return def;\n }\n\n return foo.toString();\n }\n\n /**\n * Returns the value of a field as a boolean.\n * \n * @param key\n * the field to look up\n * @return the value of the field, or false if field does not exist\n */\n public boolean getBoolean(final String key) {\n return getBoolean(key, false);\n }\n\n /**\n * Returns the value of a field as a boolean\n * \n * @param key\n * the field to look up\n * @param def\n * the default value in case the field is not found\n * @return the value of the field, converted to a string\n */\n public boolean getBoolean(final String key, final boolean def) {\n Object foo = get(key);\n if (foo == null) {\n return def;\n }\n if (foo instanceof Number) {\n return ((Number) foo).intValue() > 0;\n }\n if (foo instanceof Boolean) {\n return ((Boolean) foo).booleanValue();\n }\n throw new IllegalArgumentException(\"can't coerce to bool:\" + foo.getClass());\n }\n\n /**\n * Returns the object id or null if not set.\n * \n * @param field\n * The field to return\n * @return The field object value or null if not found (or if null :-^).\n */\n public ObjectId getObjectId(final String field) {\n return (ObjectId) get(field);\n }\n\n /**\n * Returns the object id or def if not set.\n * \n * @param field\n * The field to return\n * @param def\n * the default value in case the field is not found\n * @return The field object value or def if not set.\n */\n public ObjectId getObjectId(final String field, final ObjectId def) {\n final Object foo = get(field);\n return (foo != null) ? (ObjectId) foo : def;\n }\n\n /**\n * Returns the date or null if not set.\n * \n * @param field\n * The field to return\n * @return The field object value or null if not found.\n */\n public Date getDate(final String field) {\n return (Date) get(field);\n }\n\n /**\n * Returns the date or def if not set.\n * \n * @param field\n * The field to return\n * @param def\n * the default value in case the field is not found\n * @return The field object value or def if not set.\n */\n public Date getDate(final String field, final Date def) {\n final Object foo = get(field);\n return (foo != null) ? (Date) foo : def;\n }\n\n public Integer getInteger(final Object key) {\n return (Integer) get(key.toString());\n }\n\n public int getInteger(final Object key, final int defaultValue) {\n Object value = get(key.toString());\n return value == null ? defaultValue : (Integer) value;\n }\n\n public DBObject getSurrogate() {\n return surrogate;\n }\n\n public void setSurrogate(final DBObject surrogate) {\n this.surrogate = surrogate;\n }\n\n}",
"public class MongoException extends RuntimeException {\n\n private static final long serialVersionUID = -4415279469780082174L;\n\n /**\n * @param msg\n * the message\n */\n public MongoException(final String msg) {\n super(msg);\n this.code = -3;\n }\n\n /**\n * \n * @param code\n * the error code\n * @param msg\n * the message\n */\n public MongoException(final int code, final String msg) {\n super(msg);\n this.code = code;\n }\n\n /**\n * \n * @param msg\n * the message\n * @param t\n * the throwable cause\n */\n public MongoException(final String msg, final Throwable t) {\n super(msg, t);\n this.code = -4;\n }\n\n /**\n * \n * @param code\n * the error code\n * @param msg\n * the message\n * @param t\n * the throwable cause\n */\n public MongoException(final int code, final String msg, final Throwable t) {\n super(msg, t);\n this.code = code;\n }\n\n /**\n * Creates a MongoException from a BSON object representing an error\n * \n * @param o\n */\n public MongoException(final BSONObject o) {\n this(ServerError.getCode(o), ServerError.getMsg(o, \"UNKNOWN\"));\n }\n\n static MongoException parse(final BSONObject o) {\n String s = ServerError.getMsg(o, null);\n if (s == null) {\n return null;\n }\n return new MongoException(ServerError.getCode(o), s);\n }\n\n /**\n * Gets the exception code\n * \n * @return code\n */\n public int getCode() {\n return code;\n }\n\n private final int code;\n}"
] | import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;
import me.lightspeed7.mongofs.url.MongoFileUrl;
import me.lightspeed7.mongofs.url.Parser;
import me.lightspeed7.mongofs.url.StorageFormat;
import me.lightspeed7.mongofs.util.BytesCopier;
import org.bson.types.ObjectId;
import org.mongodb.Document;
import org.mongodb.MongoException;
import com.mongodb.BasicDBObject; | package me.lightspeed7.mongofs;
/**
* Object to hold the state of the file's metatdata. To persist this outside of MongoFS, use the getURL() and persist that.
*
* @author David Buschman
*
*/
public class MongoFile implements InputFile {
private final Document surrogate;
private final MongoFileStore store;
private StorageFormat format;
/**
* Construct a MongoFile object for reading data
*
* @param store
* @param o
*/
/* package */MongoFile(final MongoFileStore store, final Document surrogate) {
this.store = store;
this.surrogate = surrogate;
this.format = fetchFormat(surrogate);
}
private StorageFormat fetchFormat(final Document surrogate) {
String format = surrogate.getString(MongoFileConstants.format);
if (format == null) {
format = surrogate.getString(MongoFileConstants.compressionFormat);
}
if (format == null) {
return StorageFormat.GRIDFS;
}
return StorageFormat.find(format);
}
/**
* Construct a MongoFile object for writing data
*
* @param collection
* @param url
*/
/* package */MongoFile(final MongoFileStore store, final MongoFileUrl url, final long chunkSize) {
this.store = store;
this.format = url.getFormat();
surrogate = new Document();
surrogate.put(MongoFileConstants._id.toString(), url.getMongoFileId());
surrogate.put(MongoFileConstants.uploadDate.toString(), new Date());
surrogate.put(MongoFileConstants.chunkSize.toString(), chunkSize);
surrogate.put(MongoFileConstants.filename.toString(), url.getFilePath());
surrogate.put(MongoFileConstants.contentType.toString(), url.getMediaType());
if (url.getFormat() != null) {
surrogate.put(MongoFileConstants.format.toString(), url.getFormat().getCode());
}
}
//
// logic methods
// //////////////////
private String getBucketName() {
return store.getFilesCollection().getName().split("\\.")[0];
}
/**
* Saves the file entry meta data to the files collection
*
* @throws MongoException
*/
public void save() {
store.getFilesCollection().save(surrogate);
}
/**
* Verifies that the MD5 matches between the database and the local file. This should be called after transferring a file.
*
* @throws MongoException
*/
public void validate() {
MongoFileConstants md5key = MongoFileConstants.md5;
String md5 = getString(md5key);
if (md5 == null) {
throw new MongoException("no md5 stored");
}
Document cmd = new Document("filemd5", get(MongoFileConstants._id));
cmd.put("root", getBucketName());
Document res = store.getFilesCollection().getDatabase().executeCommand(cmd).getResponse();
if (res != null && res.containsKey(md5key.toString())) {
String m = res.get(md5key.toString()).toString();
if (m.equals(md5)) {
return;
}
throw new MongoException("md5 differ. mine [" + md5 + "] theirs [" + m + "]");
}
// no md5 from the server
throw new MongoException("no md5 returned from server: " + res);
}
public MongoFileUrl getURL() throws MalformedURLException {
// compression and encrypted read from stored format | URL url = Parser.construct(getId(), getFilename(), getContentType(), this.format); | 1 |
konachan700/JNekoImageDB | src/main/java/ui/dialogs/windows/MainWindow.java | [
"public interface UseServices {\n\tInitService initService = new InitService();\n\n\tdefault <T> T getService(Class<T> clazz) {\n\t\tif (initService.getServices() == null || !initService.getServices().containsKey(clazz)) {\n\t\t\tthrow new IllegalStateException(\"Class \\\"\" + clazz + \"\\\" not found in list of services\");\n\t\t}\n\t\treturn (T) initService.getServices().get(clazz);\n\t}\n\n\tdefault GlobalConfig getConfig() {\n\t\treturn initService.getGlobalConfig();\n\t}\n\n\tdefault void init(String password) {\n\t\tinitService.setPassword(password);\n\t\tinitService.init();\n\t}\n\n\tdefault void dispose() {\n\t\tinitService.dispose();\n\t}\n}",
"public class StyleParser {\n\tpublic static void parseStyles(Object object) {\n\t\tOptional.ofNullable(object)\n\t\t\t\t.map(Object::getClass)\n\t\t\t\t.map(Class::getDeclaredFields)\n\t\t\t\t.map(Arrays::asList)\n\t\t\t\t.map(list -> {\n\t\t\t\t\tfinal Class c = object.getClass().getSuperclass();\n\t\t\t\t\tif (c != null && c.isAnnotationPresent(HasStyledElements.class)) {\n\t\t\t\t\t\tfinal List<Field> fields = new ArrayList<>();\n\t\t\t\t\t\tfields.addAll(Arrays.asList(c.getDeclaredFields()));\n\t\t\t\t\t\tfields.addAll(list);\n\t\t\t\t\t\treturn fields;\n\t\t\t\t\t}\n\t\t\t\t\treturn list;\n\t\t\t\t})\n\t\t\t\t.orElse(new ArrayList<>())\n\t\t\t\t.stream()\n\t\t\t\t.filter(Objects::nonNull)\n\t\t\t\t.forEach(f -> {\n\t\t\t\t\tfinal Field field = (Field) f;\n\t\t\t\t\tif (!field.isAnnotationPresent(CssStyle.class)) return;\n\n\t\t\t\t\tfinal String[] styles = Optional.ofNullable((CssStyle) field.getAnnotation(CssStyle.class)).map(CssStyle::value).orElse(null);\n\t\t\t\t\tif (styles == null) return;\n\n\t\t\t\t\t//System.out.println(field.getName());\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfield.setAccessible(true);\n\t\t\t\t\t\tfinal Node node = (Node) field.get(object);\n\t\t\t\t\t\tif (node != null) node.getStyleClass().addAll(styles);\n\t\t\t\t\t\tfield.setAccessible(false);\n\t\t\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t});\n\t}\n}",
"public class ActivityHolder extends HBox {\n\tpublic static interface OnCountChangeListener {\n\t\tvoid activitiesCountChanged(int count);\n\t}\n\n\tprivate OnCountChangeListener onCountChangeListener = null;\n\n\tprivate final Stack<ActivityPage> prevActivities = new Stack<>();\n\tprivate ActivityPage currentActivity;\n\tprivate final Pane footerHolder, subheaderHolder, windowHeader;\n\tprivate final DefaultWindow defaultWindow;\n\n\tpublic ActivityHolder(DefaultWindow defaultWindow) {\n\t\tsuper();\n\t\tthis.defaultWindow = defaultWindow;\n\t\tthis.footerHolder = defaultWindow.getFooter();\n\t\tthis.subheaderHolder = defaultWindow.getSubheader();\n\t\tthis.windowHeader = defaultWindow.getHeader();\n\t}\n\n\tpublic void popup(String title, String text) {\n\t\tthis.defaultWindow.popup(title, text);\n\t}\n\n\tpublic void showFirst(ActivityPage activity) {\n\t\tprevActivities.clear();\n\t\tcurrentActivity = null;\n\t\tshow(activity);\n\t}\n\n\tpublic void show(ActivityPage activity) {\n\t\tif (currentActivity != null) {\n\t\t\tprevActivities.push(currentActivity);\n\t\t}\n\t\tcurrentActivity = activity;\n\t\tthis.getChildren().clear();\n\t\tthis.getChildren().add(activity);\n\t\tsetFooterAndHeader(activity);\n\t\tif (onCountChangeListener != null) {\n\t\t\tonCountChangeListener.activitiesCountChanged(prevActivities.size());\n\t\t}\n\t}\n\n\tpublic void close() {\n\t\tif (prevActivities.empty()) {\n\t\t\treturn;\n\t\t}\n\t\tfinal ActivityPage ap = currentActivity;\n\n\t\tcurrentActivity = prevActivities.pop();\n\t\tthis.getChildren().clear();\n\t\tthis.getChildren().add(currentActivity);\n\t\tsetFooterAndHeader(currentActivity);\n\t\tif (onCountChangeListener != null) {\n\t\t\tonCountChangeListener.activitiesCountChanged(prevActivities.size());\n\t\t}\n\n\t\tif (ap.getCloseAction() != null) {\n\t\t\tap.getCloseAction().OnClose();\n\t\t}\n\t}\n\n\tpublic void lockWindow(boolean lock) {\n\t\twindowHeader.getChildren().forEach(e -> e.setVisible(!lock));\n\t}\n\n\tprivate void setFooterAndHeader(ActivityPage activity) {\n\t\tif (footerHolder != null) {\n\t\t\tfooterHolder.getChildren().clear();\n\t\t\tfinal Node[] footerElements = activity.getFooterElements();\n\t\t\tif (footerElements != null) {\n\t\t\t\tfooterHolder.getChildren().addAll(footerElements);\n\t\t\t}\n\t\t}\n\n\t\tif (subheaderHolder != null) {\n\t\t\tsubheaderHolder.getChildren().clear();\n\t\t\tfinal Node[] subheaderElements = activity.getSubheaderElements();\n\t\t\tif (subheaderElements != null) {\n\t\t\t\tsubheaderHolder.getChildren().addAll(subheaderElements);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static VBox getSeparator() {\n\t\tfinal VBox v = new VBox();\n\t\tv.getStyleClass().addAll(\"null_pane\", \"fill_all\");\n\t\treturn v;\n\t}\n\n\tpublic OnCountChangeListener getOnCountChangeListener() {\n\t\treturn onCountChangeListener;\n\t}\n\n\tpublic void setOnCountChangeListener(OnCountChangeListener onCountChangeListener) {\n\t\tthis.onCountChangeListener = onCountChangeListener;\n\t}\n}",
"@HasStyledElements\npublic class MainActivity extends ActivityPage implements UseServices {\n\tprivate LocalDaoService localDaoService;\n\n\t@CssStyle({\"window_root_pane\"})\n\tprivate final ImportFromDiskActivity rootImportActivity = new ImportFromDiskActivity(this.getActivityHolder());\n\n\t@CssStyle({\"window_root_pane\"})\n\tprivate final TagsEditorActivity tagsEditorActivity = new TagsEditorActivity(this.getActivityHolder());\n\n\t@CssStyle({\"window_root_pane\"})\n\tprivate final ImageViewActivityLocalDb imageViewActivity = new ImageViewActivityLocalDb(this.getActivityHolder());\n\n\t@CssStyle({\"window_root_pane\"})\n\tprivate final HBox container = new HBox();\n\n\t@CssStyle({\"tree_container\", \"StringFieldElementTextArea\"})\n\tprivate final VBox containerTags = new VBox();\n\n\tprivate final ExtendedTagsList extendedTagsList = new ExtendedTagsList();\n\tprivate final Set<TagEntity> tagFilter = new HashSet<>();\n\n\t@CssStyle({\"window_root_pane\"})\n\tprivate final LocalDbImageDashboard localDbImageDashboard = new LocalDbImageDashboard() {\n\t\t@Override public void onPageChanged(int page) {\n\t\t\tpaginator.setCurrentPageIndex(page);\n\t\t}\n\n\t\t@Override public void onPageCountChanged(int pages) {\n\t\t\tpaginator.setPageCount(pages);\n\t\t\textendedTagsList.setDefaultTags(localDbImageDashboard.getRecomendedTags());\n\t\t}\n\n\t\t@Override public void onItemClick(MouseEvent e, ImageEntity image, int pageId, int id, int pageCount) {\n\t\t\timageViewActivity.showNext(tagFilter, image, pageId, id, localDbImageDashboard.getElementsPerPage(), pageCount);\n\t\t}\n\t};\n\n\t@CssStyle({\"tags_null_pane\"})\n\tprivate final TagsAddActivity addTagsActivity = new TagsAddActivity(getActivityHolder(), (r,t) -> {\n\t\tif (r == TagsAddActivity.Result.ADD_TAG && t != null && !t.isEmpty() && !localDbImageDashboard.getSelectedFiles().isEmpty()) {\n\t\t\tfinal List<TagEntity> list = localDaoService.tagGetOrCreate(t);\n\t\t\tlocalDbImageDashboard.getSelectedFiles().forEach(e -> localDaoService.imagesWrite(e.getImageHash(), list));\n\t\t\tlocalDbImageDashboard.selectNone();\n\t\t}\n\t});\n\n\tprivate final Paginator paginator = new Paginator() {\n\t\t@Override public void onPageChange(int currentPage, int pageCount) {\n\t\t\tlocalDbImageDashboard.pageChanged(currentPage);\n\t\t}\n\t};\n\n\t@CssStyle({\"panel_button_subheader_1\"})\n\tprivate final PanelButton importImages = new PanelButton(\"Import images\") {\n\t\t@Override\n\t\tpublic void onClick(ActionEvent e) {\n\t\t\trootImportActivity.showNext();\n\t\t}\n\t};\n\n\t@CssStyle({\"panel_button_subheader_1\"})\n\tprivate final PanelButton tagEditor = new PanelButton(\"Tag editor\") {\n\t\t@Override\n\t\tpublic void onClick(ActionEvent e) {\n\t\t\ttagsEditorActivity.showNext();\n\t\t}\n\t};\n\n\t@CssStyle({\"panel_button_footer_1\"})\n\tprivate final PanelButton addTagsToSelected = new PanelButton(\"Add tags for selected\") {\n\t\t@Override\n\t\tpublic void onClick(ActionEvent e) {\n\t\t\tif (localDbImageDashboard.getSelectedFiles().isEmpty()) {\n\t\t\t\tpopup(\"Error!\", \"Select at least a one file before setting tags!\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\taddTagsActivity.showNext();\n\t\t}\n\t};\n\n\t@CssStyle({\"panel_button_footer_1\"})\n\tprivate final PanelButton buttonSelectAll = new PanelButton(\"Select all\") {\n\t\t@Override\n\t\tpublic void onClick(ActionEvent e) {\n\t\t\tlocalDbImageDashboard.selectAll();\n\t\t}\n\t};\n\n\t@CssStyle({\"panel_button_footer_1\"})\n\tprivate final PanelButton buttonSelectNone = new PanelButton(\"Clear selection\") {\n\t\t@Override\n\t\tpublic void onClick(ActionEvent e) {\n\t\t\tlocalDbImageDashboard.selectNone();\n\t\t}\n\t};\n\n\tpublic MainActivity(ActivityHolder activityHolder) {\n\t\tsuper(activityHolder);\n\t\tStyleParser.parseStyles(this);\n\t\tthis.localDaoService = getService(LocalDaoService.class);\n\n\t\trootImportActivity.setCloseAction(() -> {\n\t\t\ttagFilter.clear();\n\t\t\trefresh();\n\t\t});\n\n\t\tlocalDbImageDashboard.generateView(getConfig().getLocalDbPreviewsCountInRow(), getConfig().getLocalDbPreviewsCountInCol());\n\n\t\textendedTagsList.setDisableNonExisted(true);\n\t\textendedTagsList.setSearchListener(list -> {\n\t\t\ttagFilter.clear();\n\t\t\ttagFilter.addAll(list);\n\t\t\trefresh();\n\t\t});\n\n\t\tcontainerTags.getChildren().addAll(extendedTagsList);\n\t\tcontainer.getChildren().addAll(containerTags, localDbImageDashboard);\n\t\tgetChildren().add(container);\n\t}\n\n\tpublic void refresh() {\n\t\tif (localDbImageDashboard.getElementsPerPage() == 0) return;\n\t\tlocalDbImageDashboard.refresh(0);\n\t\tlocalDbImageDashboard.setFilterByTags(tagFilter);\n\n\t\tpaginator.setCurrentPageIndex(0);\n\t}\n\n\t@Override\n\tpublic void showNext() {\n\t\tsuper.showNext();\n\t\trefresh();\n\t}\n\n\t@Override\n\tpublic void showFirst() {\n\t\tsuper.showFirst();\n\t\trefresh();\n\t}\n\n\t@Override public Node[] getSubheaderElements() {\n\t\treturn new Node[] { importImages, tagEditor };\n\t}\n\n\t@Override public Node[] getFooterElements() {\n\t\treturn new Node[] { addTagsToSelected, buttonSelectAll, buttonSelectNone, ActivityHolder.getSeparator(), paginator };\n\t}\n}",
"public class TagsEditorActivity extends ActivityPage implements UseServices {\n\t@CssStyle({\"tags_scroll_pane\"})\n\tprivate final ScrollPane scrollPane = new ScrollPane();\n\n\t@CssStyle({\"tags_null_pane\"})\n\tprivate final FlowPane flowPane = new FlowPane();\n\n\t@CssStyle({\"tag_text_field\"})\n\tprivate final TextField addTagTF = new TextField();\n\n\t@CssStyle({\"tag_text_field\"})\n\tprivate final TextField findTagTF = new TextField();\n\n\t@CssStyle({\"tag_add_container_a1\"})\n\tprivate final HBox addTagBox = new HBox();\n\n\t@CssStyle({\"tag_add_container_a2\"})\n\tprivate final HBox findTagBox = new HBox();\n\n\t@CssStyle({\"tag_add_container\"})\n\tprivate final HBox hBox = new HBox();\n\n\t@CssStyle({\"tag_total_count_label\"})\n\tprivate final Label totalCount = new Label(\"0\");\n\n\t@CssStyle({\"panel_button_subheader_1\"})\n\tprivate final PanelButton addTagBtn = new PanelButton(\"Add tag\", GoogleMaterialDesignIcons.ADD) {\n\t\t@Override public void onClick(ActionEvent e) {\n\t\t\tadd();\n\t\t}\n\t};\n\n\t@CssStyle({\"panel_button_subheader_1\"})\n\tprivate final PanelButton findTagBtn = new PanelButton(\"Find\", GoogleMaterialDesignIcons.FIND_IN_PAGE) {\n\t\t@Override public void onClick(ActionEvent e) {\n\t\t\tfinal String tag = findTagTF.getText().trim();\n\t\t\tfind(tag);\n\t\t}\n\t};\n\n\tprivate void onTagClick(MouseEvent me, String tag, TagElement te) {\n\t\tswitch (me.getButton()) {\n\t\tcase PRIMARY:\n\n\t\t\tbreak;\n\t\tcase SECONDARY:\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t}\n\t}\n\n\tprivate void add() {\n\t\tOptional.ofNullable(getService(LocalDaoService.class)).ifPresent(dao -> {\n\t\t\tfinal String tag = addTagTF.getText().trim();\n\t\t\tdao.tagSave(tag);\n\t\t\taddTagTF.setText(\"\");\n\t\t\tfind(null);\n\t\t});\n\t}\n\n\tprivate void find(String tag) {\n\t\tflowPane.getChildren().clear();\n\n\t\tOptional.ofNullable(getService(LocalDaoService.class))\n\t\t\t\t.map(e -> e.tagGetCount())\n\t\t\t\t.ifPresent(e -> totalCount.setText(\"Total tags count: \" + e));\n\n\t\tfinal List<TagEntity> tagEntities;\n\t\tif (tag != null && !tag.trim().isEmpty()) {\n\t\t\ttagEntities = Optional.ofNullable(getService(LocalDaoService.class).tagFindStartedWith(tag, 200)).orElse(new ArrayList<>(1));\n\t\t} else {\n\t\t\ttagEntities = Optional.ofNullable(getService(LocalDaoService.class).tagGetEntitiesList(0, 200)).orElse(new ArrayList<>(1));\n\t\t}\n\n\t\ttagEntities.stream()\n\t\t\t\t.map(t -> t.getTagText())\n\t\t\t\t.forEach(t -> {\n\t\t\t\t\tfinal TagElement te = new TagElement(t);\n\t\t\t\t\tte.setOnMouseClicked(event -> onTagClick(event, t, te));\n\t\t\t\t\tflowPane.getChildren().add(te);\n\t\t\t\t});\n\t}\n\n\tpublic TagsEditorActivity(ActivityHolder activityHolder) {\n\t\tsuper(activityHolder);\n\n\t\tStyleParser.parseStyles(this);\n\t\tflowPane.setVgap(4);\n\t\tflowPane.setHgap(6);\n\n\t\taddTagTF.setPromptText(\"Type tag for add...\");\n\t\tfindTagTF.setPromptText(\"Type for search...\");\n\n\t\tfindTagTF.setOnKeyReleased(e -> find(findTagTF.getText().trim()));\n\t\taddTagTF.setOnKeyPressed(e -> {\n\t\t\tif (e.getCode() == KeyCode.ENTER) add();\n\t\t});\n\n\t\tscrollPane.setContent(flowPane);\n\t\tscrollPane.setFitToWidth(true);\n\t\tscrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);\n\t\tscrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);\n\n\t\thBox.getChildren().addAll(addTagBox, findTagBox);\n\t\taddTagBox.getChildren().addAll(addTagTF, addTagBtn);\n\t\tfindTagBox.getChildren().addAll(findTagTF, findTagBtn);\n\n\t\tthis.getChildren().addAll(hBox, scrollPane);\n\t}\n\n\t@Override public void showFirst() {\n\t\tsuper.showFirst();\n\t\tfind(\"\");\n\t}\n\n\t@Override public void showNext() {\n\t\tsuper.showNext();\n\t\tfind(\"\");\n\t}\n\n\t@Override public Node[] getSubheaderElements() {\n\t\treturn new Node[] { };\n\t}\n\n\t@Override public Node[] getFooterElements() {\n\t\treturn new Node[] { totalCount };\n\t}\n}",
"@HasStyledElements\npublic class EditorActivity<T extends UIEntity> extends ActivityPage {\n\tpublic enum Result {\n\t\tSAVE, CANCEL\n\t}\n\n\tpublic interface ResultCallback<T extends UIEntity> {\n\t\tvoid onResult(Result result, T uiEntity);\n\t}\n\n\tprivate Result editorResult = Result.CANCEL;\n\tprivate final UIEntity uiEntity;\n\tprivate final ResultCallback resultCallback;\n\n\t@CssStyle({\"panel_button_subheader_1\"})\n\tprivate final PanelButton buttonSave = new PanelButton(\"Save\") {\n\t\t@Override\n\t\tpublic void onClick(ActionEvent e) {\n\t\t\teditorResult = Result.SAVE;\n\t\t\tresultCallback.onResult(editorResult, uiEntity);\n\t\t\tclose();\n\t\t}\n\t};\n\n\t@CssStyle({\"panel_button_subheader_1\"})\n\tprivate final PanelButton buttonCancel = new PanelButton(\"Cancel\") {\n\t\t@Override\n\t\tpublic void onClick(ActionEvent e) {\n\t\t\teditorResult = Result.CANCEL;\n\t\t\tresultCallback.onResult(editorResult, uiEntity);\n\t\t\tclose();\n\t\t}\n\t};\n\n\tpublic EditorActivity(ActivityHolder activityHolder, T uiEntity, ResultCallback<T> resultCallback) {\n\t\tsuper(activityHolder);\n\n\t\tthis.uiEntity = uiEntity;\n\t\tthis.resultCallback = resultCallback;\n\n\t\tStyleParser.parseStyles(this);\n\t\tgetStyleClass().addAll(\"editor_activity_pane\");\n\n\t\tfinal VBox vBox = UICreator.createUI(uiEntity);\n\t\tthis.getChildren().add(vBox);\n\t}\n\n\t@Override public Node[] getSubheaderElements() {\n\t\treturn new Node[] { ActivityHolder.getSeparator(), buttonCancel, buttonSave };\n\t}\n\n\t@Override public Node[] getFooterElements() {\n\t\treturn null;\n\t}\n\n\tpublic Result getResult() {\n\t\treturn editorResult;\n\t}\n}",
"@HasStyledElements\npublic class DefaultWindow extends Stage implements UseServices {\n\tprivate final Image logoImage = new Image(\"/style/images/logo_inv.png\");\n\tprivate final ImageView imgLogoNode = new ImageView(logoImage);\n\n\t@CssStyle({\"content_win_root_pane\"})\n\tfinal VBox windowContainer = new VBox();\n\n\t@CssStyle({\"popup_root_pane\"})\n\tfinal VBox notifyContainer = new VBox(8);\n\n\t@CssStyle({\"window_root_pane\"})\n\tfinal AnchorPane rootWindowPane = new AnchorPane(windowContainer, notifyContainer);\n\n\t@CssStyle({\"window_header\"})\n\tfinal HBox header = new HBox();\n\n\t@CssStyle({\"window_header_panel\"})\n\tfinal HBox headerPanel = new HBox();\n\n\t@CssStyle({\"window_subheader\"})\n\tfinal HBox subheader = new HBox(6);\n\n\t@CssStyle({\"window_footer\"})\n\tfinal HBox footerHolder = new HBox();\n\n\t@CssStyle({\"window_header_panel\"})\n\tfinal HBox footer = new HBox();\n\n\t@CssStyle({\"content_pane\"})\n\tprivate final ActivityHolder activityHolder = new ActivityHolder(this);\n\n\t@CssStyle({\"window_resizer\"})\n\tfinal HBox resizer = new HBox();\n\n\tprivate final Scene scene;\n\n\tprivate double xOffset = 0;\n\tprivate double yOffset = 0;\n\n\tprivate static final ArrayList<Timer> timers = new ArrayList<>();\n\tprivate final Timer timer = new Timer();\n\tprivate final TimerTask timerTask = new TimerTask() {\n\t\t@Override\n\t\tpublic void run() {\n\t\t\tfinal Long liveTime = getConfig().getPopupLifeTime();\n\t\t\tfinal Long time = System.currentTimeMillis();\n\t\t\tfinal Set<Node> nodes = new HashSet<>();\n\t\t\tPlatform.runLater(() -> {\n\t\t\t\tnotifyContainer.getChildren().forEach(node -> {\n\t\t\t\t\tif (node instanceof Popup) {\n\t\t\t\t\t\tif ((((Popup) node).getCreatedTime() + liveTime) < time) {\n\t\t\t\t\t\t\tnodes.add(node);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tnotifyContainer.getChildren().removeAll(nodes);\n\t\t\t});\n\t\t}\n\t};\n\n\tpublic DefaultWindow(String windowName, boolean hasHeader, boolean hasSubHeader, boolean hasFooter) {\n\t\tsuper();\n\t\ttimers.add(timer);\n\n\t\tsetResizable(false);\n\t\trootWindowPane.getStylesheets().add(getClass().getResource(\"/style/css/main.css\").toExternalForm());\n\t\tStyleParser.parseStyles(this);\n\n\t\tif (hasHeader) {\n\t\t\twindowContainer.getChildren().add(header);\n\t\t\theader.getChildren().addAll(imgLogoNode, headerPanel);\n\t\t\tif (hasSubHeader) windowContainer.getChildren().add(getSubheader());\n\t\t}\n\n\t\tAnchorPane.setLeftAnchor(windowContainer, 0D);\n\t\tAnchorPane.setTopAnchor(windowContainer, 0D);\n\t\tAnchorPane.setBottomAnchor(windowContainer, 0D);\n\t\tAnchorPane.setRightAnchor(windowContainer, 0D);\n\n\t\tAnchorPane.setRightAnchor(notifyContainer, 16D);\n\t\tAnchorPane.setBottomAnchor(notifyContainer, 16D);\n\n\t\tfinal Double w = 640D;\n\t\tfinal Double h = 480D;\n\n\t\tscene = new Scene(rootWindowPane, w, h);\n\t\tthis.setWidth(w);\n\t\tthis.setHeight(h);\n\t\twindowContainer.getChildren().add(getActivityHolder());\n\n\t\tif (hasFooter) {\n\t\t\twindowContainer.getChildren().add(footerHolder);\n\t\t\tfooterHolder.getChildren().addAll(footer);\n\t\t}\n\n\t\tthis.getIcons().add(new Image(\"/style/icons/icon32.png\"));\n\t\tthis.getIcons().add(new Image(\"/style/icons/icon64.png\"));\n\t\tthis.getIcons().add(new Image(\"/style/icons/icon128.png\"));\n\t\tthis.setMinWidth(w);\n\t\tthis.setMinHeight(h);\n\t\tthis.setTitle(windowName);\n\t\tthis.setScene(scene);\n\t\tthis.setOnCloseRequest(Event::consume);\n\t}\n\n\tpublic DefaultWindow(String windowId, String windowName, boolean hasHeader, boolean hasSubHeader, boolean hasFooter) {\n\t\tsuper();\n\t\ttimers.add(timer);\n\n\t\t//initStyle(StageStyle.UNDECORATED);\n\t\tsetResizable(false);\n\t\trootWindowPane.getStylesheets().add(getClass().getResource(\"/style/css/main.css\").toExternalForm());\n\t\tStyleParser.parseStyles(this);\n\n\t\tif (hasHeader) {\n\t\t\twindowContainer.getChildren().add(header);\n\t\t\theader.getChildren().addAll(imgLogoNode, headerPanel);\n\t\t\tif (hasSubHeader) windowContainer.getChildren().add(getSubheader());\n\n\t\t\theader.setOnMousePressed(e -> {\n\t\t\t\txOffset = getX() - e.getScreenX();\n\t\t\t\tyOffset = getY() - e.getScreenY();\n\t\t\t});\n\n\t\t\theader.setOnMouseDragged(e -> {\n\t\t\t\tsetX(e.getScreenX() + xOffset);\n\t\t\t\tsetY(e.getScreenY() + yOffset);\n\t\t\t});\n\t\t}\n\n\t\tAnchorPane.setLeftAnchor(windowContainer, 0D);\n\t\tAnchorPane.setTopAnchor(windowContainer, 0D);\n\t\tAnchorPane.setBottomAnchor(windowContainer, 0D);\n\t\tAnchorPane.setRightAnchor(windowContainer, 0D);\n\n\t\tAnchorPane.setRightAnchor(notifyContainer, 16D);\n\t\tAnchorPane.setBottomAnchor(notifyContainer, 16D);\n\n\t\tfinal Double w = getConfig().getWindowDimension(windowId).getWidth();\n\t\tfinal Double h = getConfig().getWindowDimension(windowId).getHeight();\n\t\tfinal int step = getConfig().getWindowResizeStep();\n\n\t\tscene = new Scene(rootWindowPane, w, h);\n\t\tthis.setWidth(w);\n\t\tthis.setHeight(h);\n\n\t\twindowContainer.getChildren().add(getActivityHolder());\n\t\tif (hasFooter) {\n\t\t\twindowContainer.getChildren().add(footerHolder);\n\t\t\tfooterHolder.getChildren().addAll(footer, resizer);\n\t\t\tresizer.setCursor(Cursor.NW_RESIZE);\n\t\t\tresizer.setOnMouseDragged(e -> {\n\t\t\t\tint w1 = ((int)(e.getSceneX() + step)) / step * step;\n\t\t\t\tint h1 = ((int)(e.getSceneY() + step)) / step * step;\n\t\t\t\tif (((int)getWidth()) != w1) setWidth(w1);\n\t\t\t\tif (((int)getHeight()) != h1) setHeight(h1);\n\t\t\t});\n\t\t}\n\n\t\tthis.getIcons().add(new Image(\"/style/icons/icon32.png\"));\n\t\tthis.getIcons().add(new Image(\"/style/icons/icon64.png\"));\n\t\tthis.getIcons().add(new Image(\"/style/icons/icon128.png\"));\n\t\tthis.setMinWidth(w);\n\t\tthis.setMinHeight(h);\n\t\tthis.setTitle(windowName);\n\t\tthis.setScene(scene);\n\t\tthis.setOnCloseRequest(Event::consume);\n\n\t\theightProperty().addListener((e, o, n) -> getConfig().getWindowDimension(windowId).setHeight(n.doubleValue()));\n\t\twidthProperty().addListener((e, o, n) -> getConfig().getWindowDimension(windowId).setWidth(n.doubleValue()));\n\n\t\ttimer.schedule(timerTask, 100, 1000);\n\t}\n\n\tpublic void popup(String title, String text) {\n\t\tfinal Popup popup = new Popup(title, text, (e, p) -> notifyContainer.getChildren().remove(p));\n\t\tnotifyContainer.getChildren().add(popup);\n\t}\n\n\tpublic void show(boolean modal) {\n\t\tif (modal) {\n\t\t\t//if (modal) this.initModality(Modality.APPLICATION_MODAL);\n\t\t\tthis.showAndWait();\n\t\t} else {\n\t\t\t//if (modal) this.initModality(Modality.NONE);\n\t\t\tthis.show();\n\t\t}\n\t}\n\n\tpublic HBox getHeader() {\n\t\treturn headerPanel;\n\t}\n\n\tpublic HBox getSubheader() {\n\t\treturn subheader;\n\t}\n\n\tpublic HBox getFooter() {\n\t\treturn footer;\n\t}\n\n\tpublic ActivityHolder getActivityHolder() {\n\t\treturn activityHolder;\n\t}\n\n\tpublic static void disposeStatic() {\n\t\ttimers.forEach(Timer::cancel);\n\t}\n}",
"@HasStyledElements\npublic abstract class PanelButton extends Button {\n public abstract void onClick(ActionEvent e);\n\n public PanelButton(String text) {\n super(text);\n super.setWrapText(false);\n super.getStyleClass().clear();\n //super.getStyleClass().addAll(\"panel_button\");\n super.setMinSize(Button.USE_PREF_SIZE, Button.USE_PREF_SIZE);\n setOnAction(e -> onClick(e));\n }\n\n public PanelButton(String text, IconCode iconCode) {\n super(text);\n final IconNode iconNode = new IconNode(iconCode);\n iconNode.getStyleClass().addAll(\"panel_button_icon\");\n iconNode.fillProperty().bind(this.textFillProperty());\n super.setGraphic(iconNode);\n super.setMinSize(Button.USE_PREF_SIZE, Button.USE_PREF_SIZE);\n setOnAction(e -> onClick(e));\n }\n}",
"@UICreatorDialog\npublic class GlobalConfigUiEntity implements UIEntity {\n\t@UICreatorEntityElement(caption = \"Folder, where you save an images\")\n\tString browserImageDirectory = \"./\";\n\n\t@UICreatorEntityElement(caption = \"Folder for quick save\")\n\tString fastSaveImageDirectory = \"./\";\n\n\t@UICreatorEntityElement(caption = \"Test number\")\n\tInteger number = 0;\n}"
] | import javafx.event.ActionEvent;
import javafx.scene.layout.VBox;
import proto.UseServices;
import ui.StyleParser;
import ui.annotation.style.CssStyle;
import ui.annotation.style.HasStyledElements;
import ui.dialogs.activities.engine.ActivityHolder;
import ui.dialogs.activities.MainActivity;
import ui.dialogs.activities.TagsEditorActivity;
import ui.dialogs.activities.engine.EditorActivity;
import ui.dialogs.windows.engine.DefaultWindow;
import ui.elements.PanelButton;
import ui.elements.entity.GlobalConfigUiEntity; | package ui.dialogs.windows;
@HasStyledElements
public class MainWindow extends DefaultWindow implements UseServices {
private final ActivityHolder activityHolder = this.getActivityHolder();
private final MainActivity mainActivity = new MainActivity(activityHolder);
private final GlobalConfigUiEntity uiEntity = new GlobalConfigUiEntity(); | private final EditorActivity editorActivity = new EditorActivity(activityHolder, uiEntity, (a,b) -> { | 5 |
thom-nic/openfire-jboss-clustering | src/main/java/com/enernoc/rnd/openfire/cluster/session/ClusteredClientSession.java | [
"public class ClientSessionTask extends RemoteSessionTask {\r\n private JID address;\r\n\r\n public ClientSessionTask() {\r\n super();\r\n }\r\n\r\n public ClientSessionTask(JID address, Operation operation) {\r\n super(operation);\r\n this.address = address;\r\n }\r\n\r\n protected Session getSession() {\r\n return XMPPServer.getInstance().getRoutingTable().getClientRoute(address);\r\n }\r\n\r\n public void run() {\r\n super.run();\r\n\r\n ClientSession session = (ClientSession) getSession();\r\n if (session instanceof ClusteredClientSession) {\r\n // The session is being hosted by other cluster node so log this unexpected case\r\n Cache<String, ClientRoute> usersCache = CacheFactory.createCache(RoutingTableImpl.C2S_CACHE_NAME);\r\n ClientRoute route = usersCache.get(address.toString());\r\n NodeID nodeID = route.getNodeID();\r\n\r\n Log.warn(\"Found remote session instead of local session. JID: \" + address + \" found in Node: \" +\r\n nodeID.toByteArray() + \" and local node is: \" + XMPPServer.getInstance().getNodeID().toByteArray());\r\n }\r\n if (operation == Operation.isInitialized) {\r\n if (session instanceof ClusteredClientSession) {\r\n // Something is wrong since the session shoud be local instead of remote\r\n // Assume some default value\r\n result = true;\r\n }\r\n else {\r\n result = session.isInitialized();\r\n }\r\n }\r\n else if (operation == Operation.incrementConflictCount) {\r\n if (session instanceof ClusteredClientSession) {\r\n // Something is wrong since the session shoud be local instead of remote\r\n // Assume some default value\r\n result = 2;\r\n }\r\n else {\r\n result = session.incrementConflictCount();\r\n }\r\n }\r\n }\r\n\r\n public void writeExternal(ObjectOutput out) throws IOException {\r\n super.writeExternal(out);\r\n ExternalizableUtil.getInstance().writeSafeUTF(out, address.toString());\r\n }\r\n\r\n public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {\r\n super.readExternal(in);\r\n address = new JID(ExternalizableUtil.getInstance().readSafeUTF(in));\r\n }\r\n\r\n public String toString() {\r\n return super.toString() + \" operation: \" + operation + \" address: \" + address;\r\n }\r\n}\r",
"public class DeliverRawTextTask implements ClusterTask {\r\n private SessionType sessionType;\r\n private JID address;\r\n private String streamID;\r\n private String text;\r\n\r\n public DeliverRawTextTask() {\r\n super();\r\n }\r\n\r\n public DeliverRawTextTask(ClusterSession clusterSession, JID address, String text) {\r\n if (clusterSession instanceof ClusterSession) {\r\n this.sessionType = SessionType.client;\r\n }\r\n //FIXME finish this\r\n /*\r\n else if (clusterSession instanceof RemoteOutgoingServerSession) {\r\n this.sessionType = SessionType.outgoingServer;\r\n }\r\n else if (clusterSession instanceof RemoteComponentSession) {\r\n this.sessionType = SessionType.component;\r\n }\r\n else if (clusterSession instanceof RemoteConnectionMultiplexerSession) {\r\n this.sessionType = SessionType.connectionManager;\r\n }\r\n */\r\n else {\r\n Log.error(\"Invalid RemoteSession was used for task: \" + clusterSession);\r\n }\r\n this.address = address;\r\n this.text = text;\r\n }\r\n\r\n public DeliverRawTextTask(String streamID, String text) {\r\n this.sessionType = SessionType.incomingServer;\r\n this.streamID = streamID;\r\n this.text = text;\r\n }\r\n\r\n public Object getResult() {\r\n return null;\r\n }\r\n\r\n public void run() {\r\n getSession().deliverRawText(text);\r\n }\r\n\r\n public void writeExternal(ObjectOutput out) throws IOException {\r\n ExternalizableUtil.getInstance().writeSafeUTF(out, text);\r\n ExternalizableUtil.getInstance().writeInt(out, sessionType.ordinal());\r\n ExternalizableUtil.getInstance().writeBoolean(out, address != null);\r\n if (address != null) {\r\n ExternalizableUtil.getInstance().writeSafeUTF(out, address.toString());\r\n }\r\n ExternalizableUtil.getInstance().writeBoolean(out, streamID != null);\r\n if (streamID != null) {\r\n ExternalizableUtil.getInstance().writeSafeUTF(out, streamID);\r\n }\r\n }\r\n\r\n public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {\r\n text = ExternalizableUtil.getInstance().readSafeUTF(in);\r\n sessionType = SessionType.values()[ExternalizableUtil.getInstance().readInt(in)];\r\n if (ExternalizableUtil.getInstance().readBoolean(in)) {\r\n address = new JID(ExternalizableUtil.getInstance().readSafeUTF(in));\r\n }\r\n if (ExternalizableUtil.getInstance().readBoolean(in)) {\r\n streamID = ExternalizableUtil.getInstance().readSafeUTF(in);\r\n }\r\n }\r\n\r\n Session getSession() {\r\n if (sessionType == SessionType.client) {\r\n return XMPPServer.getInstance().getRoutingTable().getClientRoute(address);\r\n }\r\n else if (sessionType == SessionType.component) {\r\n return SessionManager.getInstance().getComponentSession(address.getDomain());\r\n }\r\n else if (sessionType == SessionType.connectionManager) {\r\n return SessionManager.getInstance().getConnectionMultiplexerSession(address);\r\n }\r\n else if (sessionType == SessionType.outgoingServer) {\r\n return SessionManager.getInstance().getOutgoingServerSession(address.getDomain());\r\n }\r\n else if (sessionType == SessionType.incomingServer) {\r\n return SessionManager.getInstance().getIncomingServerSession(streamID);\r\n }\r\n Log.error(\"Found unknown session type: \" + sessionType);\r\n return null;\r\n }\r\n\r\n public String toString() {\r\n return super.toString() + \" sessionType: \" + sessionType + \" address: \" + address;\r\n }\r\n\r\n private enum SessionType {\r\n client,\r\n outgoingServer,\r\n incomingServer,\r\n component,\r\n connectionManager\r\n }\r\n}",
"public abstract class RemoteSessionTask implements ClusterTask {\n\tprotected Object result;\n protected Operation operation;\n\n public RemoteSessionTask() {\n }\n\n protected RemoteSessionTask(Operation operation) {\n this.operation = operation;\n }\n\n abstract Session getSession();\n\n public Object getResult() {\n return result;\n }\n\n public void run() {\n if (operation == Operation.getStreamID) {\n result = getSession().getStreamID().getID();\n }\n else if (operation == Operation.getServerName) {\n result = getSession().getServerName();\n }\n else if (operation == Operation.getCreationDate) {\n result = getSession().getCreationDate();\n }\n else if (operation == Operation.getLastActiveDate) {\n result = getSession().getLastActiveDate();\n }\n else if (operation == Operation.getNumClientPackets) {\n result = getSession().getNumClientPackets();\n }\n else if (operation == Operation.getNumServerPackets) {\n result = getSession().getNumServerPackets();\n }\n else if (operation == Operation.close) {\n // Run in another thread so we avoid blocking calls (in coherence) \n final Session session = getSession();\n if (session != null) {\n final Future<?> future = TaskEngine.getInstance().submit(new Runnable() {\n public void run() {\n session.close();\n }\n });\n // Wait until the close operation is done or timeout is met\n try {\n future.get(15, TimeUnit.SECONDS);\n }\n catch (Exception e) {\n // Ignore\n }\n }\n }\n else if (operation == Operation.isClosed) {\n result = getSession().isClosed();\n }\n else if (operation == Operation.isSecure) {\n result = getSession().isSecure();\n }\n else if (operation == Operation.getHostAddress) {\n try {\n result = getSession().getHostAddress();\n } catch (UnknownHostException e) {\n Log.error(\"Error getting address of session: \" + getSession(), e);\n }\n }\n else if (operation == Operation.getHostName) {\n try {\n result = getSession().getHostName();\n } catch (UnknownHostException e) {\n Log.error(\"Error getting address of session: \" + getSession(), e);\n }\n }\n else if (operation == Operation.validate) {\n result = getSession().validate();\n }\n }\n\n public void writeExternal(ObjectOutput out) throws IOException {\n ExternalizableUtil.getInstance().writeBoolean(out, operation != null);\n if (operation != null) {\n ExternalizableUtil.getInstance().writeInt(out, operation.ordinal());\n }\n }\n\n public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {\n if (ExternalizableUtil.getInstance().readBoolean(in)) {\n operation = Operation.values()[ExternalizableUtil.getInstance().readInt(in)];\n }\n }\n\n public enum Operation {\n /**\n * Basic session operations\n */\n getStreamID,\n getServerName,\n getCreationDate,\n getLastActiveDate,\n getNumClientPackets,\n getNumServerPackets,\n close,\n isClosed,\n isSecure,\n getHostAddress,\n getHostName,\n validate,\n \n /**\n * Operations of c2s sessions\n */\n isInitialized,\n incrementConflictCount,\n \n /**\n * Operations of outgoing server sessions\n */\n getAuthenticatedDomains,\n getHostnames,\n isUsingServerDialback,\n\n /**\n * Operations of external component sessions\n */\n getType,\n getCategory,\n getInitialSubdomain,\n getSubdomains,\n getName,\n getDescription,\n start,\n shutdown,\n\n /**\n * Operations of incoming server sessions\n */\n getLocalDomain,\n getAddress\n }\n}",
"public enum Operation {\n /**\n * Basic session operations\n */\n getStreamID,\n getServerName,\n getCreationDate,\n getLastActiveDate,\n getNumClientPackets,\n getNumServerPackets,\n close,\n isClosed,\n isSecure,\n getHostAddress,\n getHostName,\n validate,\n \n /**\n * Operations of c2s sessions\n */\n isInitialized,\n incrementConflictCount,\n \n /**\n * Operations of outgoing server sessions\n */\n getAuthenticatedDomains,\n getHostnames,\n isUsingServerDialback,\n\n /**\n * Operations of external component sessions\n */\n getType,\n getCategory,\n getInitialSubdomain,\n getSubdomains,\n getName,\n getDescription,\n start,\n shutdown,\n\n /**\n * Operations of incoming server sessions\n */\n getLocalDomain,\n getAddress\n}",
"public class ProcessPacketTask extends PacketTask<Packet> {\n\n\tpublic ProcessPacketTask() {}\n\tpublic ProcessPacketTask( Packet p ) {\n\t\tsuper( p );\n\t}\n\t\n\tpublic void run() {\n\t\tif(packet == null)\n\t\t\treturn;\n\t\t\t\n\t\t//Retry fetching the session a few times as it may not yet be replicated to this cache\n\t\tfor(int i = 0; i < 5; i++) {\n\t\t\tSession session = XMPPServer.getInstance().getSessionManager().getSession( packet.getTo() );\n\t\t\tif( session != null ) {\n\t\t\t\tsession.process( packet );\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(100);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}"
] | import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.privacy.PrivacyList;
import org.jivesoftware.openfire.privacy.PrivacyListManager;
import org.jivesoftware.openfire.session.ClientSession;
import org.jivesoftware.openfire.session.ClientSessionInfo;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.ClusterTask;
import org.jivesoftware.util.cache.ExternalizableUtil;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.Presence;
import com.enernoc.rnd.openfire.cluster.session.task.ClientSessionTask;
import com.enernoc.rnd.openfire.cluster.session.task.DeliverRawTextTask;
import com.enernoc.rnd.openfire.cluster.session.task.RemoteSessionTask;
import com.enernoc.rnd.openfire.cluster.session.task.RemoteSessionTask.Operation;
import com.enernoc.rnd.openfire.cluster.task.ProcessPacketTask; | /**
* 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.enernoc.rnd.openfire.cluster.session;
/**
* This class acts as a remote proxy to send requests to a remote client session.
* @author tnichols
*/
public class ClusteredClientSession extends ClusterSession implements ClientSession {
private long initialized = -1;
public ClusteredClientSession() {}
public ClusteredClientSession( JID jid, byte[] nodeID ) {
super( jid, nodeID );
}
@Override
void doCopy( Session s ) {
ClientSession cs = (ClientSession)s;
this.initialized = cs.isInitialized() ? 1 : 0;
}
@Override
void doReadExternal( ExternalizableUtil ext, ObjectInput in ) throws IOException, ClassNotFoundException {
this.initialized = ext.readLong(in);
}
@Override
void doWriteExternal( ExternalizableUtil ext, ObjectOutput out ) throws IOException {
ext.writeLong(out, this.initialized );
}
public boolean canFloodOfflineMessages() {
// Code copied from LocalClientSession to avoid remote calls
if(isOfflineFloodStopped()) {
return false;
}
String username = getAddress().getNode();
for (ClientSession session : SessionManager.getInstance().getSessions(username)) {
if (session.isOfflineFloodStopped()) {
return false;
}
}
return true;
}
public PrivacyList getActiveList() {
Cache<String, ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache();
ClientSessionInfo sessionInfo = cache.get(getAddress().toString());
if (sessionInfo != null && sessionInfo.getActiveList() != null) {
return PrivacyListManager.getInstance().getPrivacyList(address.getNode(), sessionInfo.getActiveList());
}
return null;
}
public PrivacyList getDefaultList() {
Cache<String, ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache();
ClientSessionInfo sessionInfo = cache.get(getAddress().toString());
if (sessionInfo != null && sessionInfo.getDefaultList() != null) {
return PrivacyListManager.getInstance().getPrivacyList(address.getNode(), sessionInfo.getDefaultList());
}
return null;
}
public Presence getPresence() {
Cache<String,ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache();
ClientSessionInfo sessionInfo = cache.get(getAddress().toString());
if (sessionInfo != null) {
return sessionInfo.getPresence();
}
return null;
}
public String getUsername() throws UserNotFoundException {
return address.getNode();
}
public boolean isAnonymousUser() {
return SessionManager.getInstance().isAnonymousRoute(getAddress());
}
public boolean isInitialized() {
if (initialized == -1) {
Presence presence = getPresence();
if (presence != null && presence.isAvailable()) {
// Optimization to avoid making a remote call
initialized = 1;
}
else { | ClusterTask task = getRemoteSessionTask(RemoteSessionTask.Operation.isInitialized); | 3 |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/view/WheelView.java | [
"public interface OnTickListener {\n public void onNextTick();\n public void onPreviousTick();\n public SelectionDetail getCurrentSelection();\n}",
"public class Theme {\n\n static private Theme defaultTheme;\n\n class Icons {\n @SerializedName(\"next\")\n public String icNext;\n @SerializedName(\"prev\")\n public String icPrev;\n @SerializedName(\"play\")\n public String icPlay;\n @SerializedName(\"menu\")\n public String icMenu;\n }\n\n private Icons icons;\n @SerializedName(\"wheel_outer\")\n private float outer;\n @SerializedName(\"wheel_inner\")\n private float inner;\n @SerializedName(\"button_size\")\n private float buttonSize;\n @SerializedName(\"wheel_color\")\n private String wheelColor;\n @SerializedName(\"button_color\")\n private String buttonColor;\n @SerializedName(\"background_color\")\n private String backgroundColor;\n @SerializedName(\"card_color\")\n private String cardColor;\n @SerializedName(\"item_color\")\n private String itemColor;\n @SerializedName(\"text_color\")\n private String textColor;\n private String name;\n\n @SerializedName(\"wheel_shape\")\n private String wheelShape;\n\n private int shape;\n @SerializedName(\"polygon_sides\")\n public int sides;\n\n public Theme(String icNext,\n String icPrev,\n String icPlay,\n String icMenu,\n float outer,\n float inner,\n float buttonSize,\n String wheelColor,\n String buttonColor,\n String backgroundColor,\n String cardColor,\n String itemColor,\n String textColor,\n int shape,\n int sides) {\n this.icons = new Icons();\n this.icons.icNext = icNext;\n this.icons.icPrev = icPrev;\n this.icons.icPlay = icPlay;\n this.icons.icMenu = icMenu;\n\n this.outer = outer;\n this.inner = inner;\n this.buttonSize = buttonSize;\n this.wheelColor = wheelColor;\n this.buttonColor = buttonColor;\n this.backgroundColor = backgroundColor;\n this.cardColor = cardColor;\n this.itemColor = itemColor;\n this.textColor = textColor;\n this.shape = shape;\n this.sides = sides;\n }\n\n public Theme setName(String name) {\n this.name = name;\n return this;\n }\n\n public String getName() {\n return name;\n }\n\n public String getNextIcon() {\n return themeFolder() + icons.icNext;\n }\n\n public String getPrevIcon() {\n return themeFolder() + icons.icPrev;\n }\n\n public String getPlayIcon() {\n return themeFolder() + icons.icPlay;\n }\n\n public String getMenuIcon() {\n return themeFolder() + icons.icMenu;\n }\n\n public int getWheelColor() {\n return Color.parseColor(wheelColor);\n }\n\n public int getButtonColor() {\n return Color.parseColor(buttonColor);\n }\n\n public int getBackgroundColor() {\n return Color.parseColor(backgroundColor);\n }\n\n public int getCardColor() {\n return Color.parseColor(cardColor);\n }\n\n public int getItemColor() {\n return Color.parseColor(itemColor);\n }\n\n public int getTextColor() {\n return Color.parseColor(textColor);\n }\n\n public int getShape() {\n if (wheelShape == null) {\n return AppConstants.ThemeShapeOval;\n }\n switch (wheelShape) {\n case \"rect\":\n shape = AppConstants.ThemeShapeRect;\n break;\n case \"oval\":\n shape = AppConstants.ThemeShapeOval;\n break;\n case \"polygon\":\n shape = AppConstants.ThemeShapePolygon;\n break;\n\n default:\n shape = AppConstants.ThemeShapeOval;\n break;\n }\n return shape;\n }\n\n public float getOuter() {\n return outer;\n }\n\n public float getInner() {\n return 1.0f - inner;\n }\n\n public float getButtonSize() {\n return buttonSize;\n }\n\n private String themeFolder() {\n return Environment.getExternalStorageDirectory() + AppConstants.themeFolder + name + \"/\";\n }\n\n public static @NonNull Theme defaultTheme() {\n if (defaultTheme == null) {\n defaultTheme = new Theme(null, null, null, null, 1.0f, 0.3f, 20, \"#FFFFFF\", \"#000000FF\", \"#578EBB\", \"#FFFFFF\", \"#578EBB\", \"#000000\", AppConstants.ThemeShapeOval, 8);\n defaultTheme.setName(\"Default\");\n }\n return defaultTheme;\n }\n}",
"public class ThemeManager {\n\n private static ThemeManager instance;\n private volatile Theme currentTheme = null;\n private Context context;\n private Gson gson;\n\n private ThemeManager(Context ctx) {\n context = ctx;\n gson = new Gson();\n copyThemesIfNeeded();\n }\n\n public static ThemeManager getInstance(Context context) {\n if (instance == null)\n instance = new ThemeManager(context);\n\n return instance;\n }\n\n private void copyThemesIfNeeded() {\n String themeDirInExt = Environment.getExternalStorageDirectory().getAbsolutePath();\n themeDirInExt += AppConstants.themeFolder;\n File themeDir = new File(themeDirInExt);\n if (themeDir.exists()) {\n return;\n }\n themeDir.mkdirs();\n\n AssetManager am = context.getAssets();\n InputStream inputStream = null;\n OutputStream outputStream = null;\n boolean copied = false;\n try {\n inputStream = am.open(\"themes.zip\");\n String fileName = themeDirInExt + \"builtin.zip\";\n outputStream = new FileOutputStream(fileName);\n\n byte[] buffer = new byte[1024];\n int read;\n while ((read = inputStream.read(buffer)) != -1) {\n outputStream.write(buffer, 0, read);\n }\n inputStream.close();\n outputStream.flush();\n outputStream.close();\n copied = true;\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n if (copied) {\n unzip();\n }\n\n }\n\n\n private void unzip() { //Oh, naughty~\n String folder = Environment.getExternalStorageDirectory().getAbsolutePath() + AppConstants.themeFolder;\n String zipFile = folder + \"builtin.zip\";\n try {\n FileInputStream fin = new FileInputStream(zipFile);\n ZipInputStream zin = new ZipInputStream(fin);\n ZipEntry ze = null;\n while ((ze = zin.getNextEntry()) != null) {\n if(ze.isDirectory()) {\n File f = new File(folder + ze.getName());\n if(!f.isDirectory()) {\n f.mkdirs();\n }\n } else {\n FileOutputStream fout = new FileOutputStream(folder + ze.getName());\n BufferedOutputStream bufout = new BufferedOutputStream(fout);\n byte[] buffer = new byte[1024];\n int read = 0;\n while ((read = zin.read(buffer)) != -1) {\n bufout.write(buffer, 0, read);\n }\n bufout.close();\n zin.closeEntry();\n fout.close();\n }\n\n }\n zin.close();\n new File(zipFile).delete();\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n\n public @NonNull Theme loadThemeNamed(@NonNull String name) {\n if (name != null && \"Default\".equalsIgnoreCase(name)) {\n return Theme.defaultTheme();\n }\n if (!validateByName(name)) {\n UserDefaults.getStaticInstance(context).setTheme(\"Default\");\n return Theme.defaultTheme();\n }\n Theme ret = null;\n File folder = new File(Environment.getExternalStorageDirectory() + AppConstants.themeFolder + name);\n if (!folder.exists()) {\n currentTheme = Theme.defaultTheme();\n return currentTheme;\n }\n File config = new File(Environment.getExternalStorageDirectory() + AppConstants.themeFolder + name + \"/config.json\");\n if (!config.exists()) {\n currentTheme = Theme.defaultTheme();\n return currentTheme;\n }\n JsonParser parser = new JsonParser();\n JsonReader reader = null;\n JsonObject json;\n try {\n reader = new JsonReader(new FileReader(config));\n json = parser.parse(reader).getAsJsonObject();\n ret = gson.fromJson(json, Theme.class);\n ret.setName(name);\n reader.close();\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n if (ret == null) {\n ret = Theme.defaultTheme();\n } else {\n UserDefaults.getStaticInstance(context).setTheme(name);\n }\n currentTheme = ret;\n return ret;\n }\n\n public @NonNull Theme loadCurrentTheme() {\n String name = UserDefaults.getStaticInstance(context).getTheme();\n Theme ret;\n ret = loadThemeNamed(name);\n if (ret == null) {\n ret = Theme.defaultTheme();\n }\n currentTheme = ret;\n return ret;\n }\n\n public @NonNull Theme getCurrentTheme() {\n if (currentTheme == null) {\n currentTheme = loadCurrentTheme();\n }\n return currentTheme;\n }\n\n public boolean validateByName(String name) {\n boolean ret = true;\n File theme = new File(Environment.getExternalStorageDirectory() + AppConstants.themeFolder + '/' + name);\n if (!theme.isDirectory()) {\n return false;\n }\n String[] files = theme.list(new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return \"config.json\".equalsIgnoreCase(name);\n }\n });\n if (files.length == 0) {\n return false;\n }\n return ret;\n }\n\n public @NonNull ArrayList<String> getAllThemes() {\n ArrayList<String> ret = new ArrayList<>();\n ret.add(Theme.defaultTheme().getName());\n File folder = new File(Environment.getExternalStorageDirectory() + AppConstants.themeFolder);\n String[] themes = folder.list();\n if (themes == null) {\n ret.add(\"Default\");\n return ret;\n }\n for (String t : themes) {\n if (validateByName(t)) {\n ret.add(t);\n }\n }\n return ret;\n }\n\n}",
"public class AppConstants {\n\n public static final int RepeatAll = 0x233;\n public static final int RepeatOne = 0x234;\n public static final int RepeatNone = 0x235;\n\n //Theme\n public static final int ThemeShapeOval = 0;\n public static final int ThemeShapeRect = 1;\n public static final int ThemeShapePolygon = 2;\n\n\n public static final String pref_tag = \"mpod_app_settings\";\n public static final String kShuffle = \"mpod_app_settings.key.shuffle\";\n public static final String kRepeat = \"mpod_app_settings.key.repeat\";\n\n public static final String broadcastSongChange = \"sun.bob.bender.songchanged\";\n public static final String broadcastPermission = \"sun.bob.bender.allow_broadcast\";\n\n private static final String playlistfile = \"/data/data/bob.sun.bender/playlistobject\";\n private static final String packageFolder = \"/data/data/bob.sun.bender/\";\n\n public static final String themeFolder = \"/data/Prodigal/Themes/\";\n\n public static String getPlayistfile() {\n return Environment.getExternalStorageDirectory().getPath() + playlistfile;\n }\n\n public static String getExtFolder() {\n return Environment.getExternalStorageDirectory().getPath() + packageFolder;\n }\n\n}",
"public class VibrateUtil {\n private static VibrateUtil staticInstance;\n private Context context;\n private Vibrator vibrator;\n private VibrateUtil(Context context){\n this.context = context;\n vibrator = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);\n }\n public static VibrateUtil getStaticInstance(Context context){\n if(staticInstance == null)\n staticInstance = new VibrateUtil(context);\n return staticInstance;\n }\n\n public void TickVibrate(){\n vibrator.vibrate(20);\n }\n\n}"
] | import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Region;
import android.graphics.Shader;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import bob.sun.bender.BuildConfig;
import bob.sun.bender.R;
import bob.sun.bender.controller.OnButtonListener;
import bob.sun.bender.controller.OnTickListener;
import bob.sun.bender.theme.Theme;
import bob.sun.bender.theme.ThemeManager;
import bob.sun.bender.utils.AppConstants;
import bob.sun.bender.utils.VibrateUtil; | package bob.sun.bender.view;
/**
* Created by bob.sun on 2015/4/23.
*/
public class WheelView extends View {
private Point center;
private Path viewBound;
private int radiusOut,radiusIn;
private Paint paintOut, paintIn, ripplePaint;
private OnTickListener onTickListener;
private float startDeg = Float.NaN;
private OnButtonListener onButtonListener;
private float buttonWidth, buttonHeight; | private Theme theme; | 1 |
dkhmelenko/Varis-Android | app/src/main/java/com/khmelenko/lab/varis/repositories/RepositoriesPresenter.java | [
"public final class Constants {\n\n // denied constructor\n private Constants() {\n }\n\n /**\n * URL for open source projects\n */\n public static final String OPEN_SOURCE_TRAVIS_URL = \"https://api.travis-ci.org\";\n\n /**\n * URL for private projects\n */\n public static final String PRIVATE_TRAVIS_URL = \"https://api.travis-ci.com\";\n\n /**\n * URL for Github access\n */\n public static final String GITHUB_URL = \"https://api.github.com\";\n\n}",
"public abstract class MvpPresenter<T extends MvpView> {\n\n private T mView;\n\n /**\n * Notifies on attach presenter to view\n */\n public abstract void onAttach();\n\n /**\n * Notifies on detach presenter from view\n */\n public abstract void onDetach();\n\n /**\n * Attaches presenter\n */\n public void attach(@NonNull T view) {\n setView(view);\n onAttach();\n }\n\n /**\n * Detaches presenter\n */\n public void detach() {\n onDetach();\n mView = null;\n }\n\n /**\n * Sets the view for the presenter\n *\n * @param view View\n */\n protected void setView(@NonNull T view) {\n mView = view;\n }\n\n /**\n * Gets the view\n *\n * @return View\n */\n public T getView() {\n return mView;\n }\n}",
"public final class User {\n\n @SerializedName(\"id\")\n private long mId;\n\n @SerializedName(\"name\")\n private String mName;\n\n @SerializedName(\"login\")\n private String mLogin;\n\n @SerializedName(\"email\")\n private String mEmail;\n\n @SerializedName(\"gravatar_id\")\n private String mGravatarId;\n\n @SerializedName(\"is_syncing\")\n private boolean mSyncing;\n\n @SerializedName(\"synced_at\")\n private String mSyncedAt;\n\n @SerializedName(\"correct_scopes\")\n private boolean mCorrectScopes;\n\n @SerializedName(\"created_at\")\n private String mCreatedAt;\n\n public long getId() {\n return mId;\n }\n\n public void setId(long id) {\n mId = id;\n }\n\n public String getName() {\n return mName;\n }\n\n public void setName(String name) {\n mName = name;\n }\n\n public String getLogin() {\n return mLogin;\n }\n\n public void setLogin(String login) {\n mLogin = login;\n }\n\n public String getEmail() {\n return mEmail;\n }\n\n public void setEmail(String email) {\n mEmail = email;\n }\n\n public String getGravatarId() {\n return mGravatarId;\n }\n\n public void setGravatarId(String gravatarId) {\n mGravatarId = gravatarId;\n }\n\n public boolean isSyncing() {\n return mSyncing;\n }\n\n public void setSyncing(boolean syncing) {\n mSyncing = syncing;\n }\n\n public String getSyncedAt() {\n return mSyncedAt;\n }\n\n public void setSyncedAt(String syncedAt) {\n mSyncedAt = syncedAt;\n }\n\n public boolean isCorrectScopes() {\n return mCorrectScopes;\n }\n\n public void setCorrectScopes(boolean correctScopes) {\n mCorrectScopes = correctScopes;\n }\n\n public String getCreatedAt() {\n return mCreatedAt;\n }\n\n public void setCreatedAt(String createdAt) {\n mCreatedAt = createdAt;\n }\n}",
"public class TravisRestClient {\n\n private final Retrofit mRetrofit;\n\n private final OkHttpClient mOkHttpClient;\n\n private final AppSettings mAppSettings;\n\n private TravisApiService mApiService;\n\n public TravisRestClient(Retrofit retrofit, OkHttpClient okHttpClient, AppSettings appSettings) {\n mRetrofit = retrofit;\n mOkHttpClient = okHttpClient;\n mAppSettings = appSettings;\n final String travisUrl = appSettings.getServerUrl();\n updateTravisEndpoint(travisUrl);\n }\n\n /**\n * Updates Travis endpoint\n *\n * @param newEndpoint New endpoint\n */\n public void updateTravisEndpoint(String newEndpoint) {\n Retrofit retrofit = mRetrofit.newBuilder()\n .baseUrl(newEndpoint)\n .client(getHttpClient())\n .build();\n\n mApiService = retrofit.create(TravisApiService.class);\n }\n\n private OkHttpClient getHttpClient() {\n final String userAgent = String.format(\"TravisClient/%1$s\", PackageUtils.getAppVersion());\n\n return mOkHttpClient.newBuilder()\n .addInterceptor(new Interceptor() {\n @Override\n public Response intercept(Chain chain) throws IOException {\n Request original = chain.request();\n\n Request.Builder request = original.newBuilder()\n .header(\"User-Agent\", userAgent)\n .header(\"Accept\", \"application/vnd.travis-ci.2+json\");\n\n String accessToken = mAppSettings.getAccessToken();\n if (!TextUtils.isEmpty(accessToken)) {\n String headerValue = String.format(\"token %1$s\", accessToken);\n request.addHeader(\"Authorization\", headerValue);\n }\n\n return chain.proceed(request.build());\n }\n })\n .build();\n }\n\n /**\n * Gets travis API service\n *\n * @return Travis API service\n */\n public TravisApiService getApiService() {\n return mApiService;\n }\n\n}",
"public class AppSettings {\n\n private static final String ACCESS_TOKEN_KEY = \"TravisAccessToken\";\n private static final String SERVER_TYPE_KEY = \"ServerTypeKey\";\n private static final String SERVER_URL_KEY = \"ServerUrlKey\";\n\n private SharedPreferences mSharedPreferences;\n\n public AppSettings(Context context) {\n mSharedPreferences = getPreferences(context);\n }\n\n /**\n * Gets shared preferences\n *\n * @return Shared preferences\n */\n private SharedPreferences getPreferences(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context);\n }\n\n /**\n * Gets access token\n *\n * @return Access token\n */\n public String getAccessToken() {\n return mSharedPreferences.getString(ACCESS_TOKEN_KEY, \"\");\n }\n\n /**\n * Puts access token to settings\n *\n * @param accessToken Access token\n */\n public void putAccessToken(String accessToken) {\n SharedPreferences.Editor editor = mSharedPreferences.edit();\n editor.putString(ACCESS_TOKEN_KEY, accessToken);\n editor.apply();\n }\n\n /**\n * Gets server type from Settings\n *\n * @return Server type\n */\n public int getServerType() {\n return mSharedPreferences.getInt(SERVER_TYPE_KEY, 1);\n }\n\n /**\n * Puts server type to the settings\n *\n * @param serverType Server type\n */\n public void putServerType(int serverType) {\n SharedPreferences.Editor editor = mSharedPreferences.edit();\n editor.putInt(SERVER_TYPE_KEY, serverType);\n editor.apply();\n }\n\n /**\n * Gets server url from Settings\n *\n * @return Server type\n */\n public String getServerUrl() {\n return mSharedPreferences.getString(SERVER_URL_KEY, \"\");\n }\n\n /**\n * Puts server url to the settings\n *\n * @param serverUrl Server type\n */\n public void putServerUrl(String serverUrl) {\n SharedPreferences.Editor editor = mSharedPreferences.edit();\n editor.putString(SERVER_URL_KEY, serverUrl);\n editor.apply();\n }\n\n}",
"public class CacheStorage {\n\n private static final String USER_FILE = \"UserData\";\n private static final String REPOS_FILE = \"ReposFile\";\n\n private CacheStorage() {\n\n }\n\n public static CacheStorage newInstance() {\n return new CacheStorage();\n }\n\n /**\n * Saves user to the cache\n *\n * @param user User\n */\n public void saveUser(User user) {\n Gson gson = new Gson();\n String dataToStore = gson.toJson(user);\n FileUtils.writeInternalFile(USER_FILE, dataToStore);\n }\n\n /**\n * Restores user from the cache\n *\n * @return User\n */\n public User restoreUser() {\n String fileData = FileUtils.readInternalFile(USER_FILE);\n Gson gson = new Gson();\n User user = gson.fromJson(fileData, User.class);\n return user;\n }\n\n /**\n * Deletes the user from the cache\n */\n public void deleteUser() {\n FileUtils.deleteInternalFile(USER_FILE);\n }\n\n /**\n * Caches repositories data\n *\n * @param repos Repositories to cache\n */\n public void saveRepos(List<Repo> repos) {\n StringBuilder builder = new StringBuilder();\n for (Repo repo : repos) {\n builder.append(repo.getSlug());\n builder.append(\",\");\n }\n FileUtils.writeInternalFile(REPOS_FILE, builder.toString());\n }\n\n /**\n * Restores the list of repositories\n *\n * @return Collection of repositories slugs\n */\n public String[] restoreRepos() {\n String fileData = FileUtils.readInternalFile(REPOS_FILE);\n return fileData.split(\",\");\n }\n\n /**\n * Deletes cached repositories\n */\n public void deleteRepos() {\n FileUtils.deleteInternalFile(REPOS_FILE);\n }\n}",
"public final class StringUtils {\n\n // denied constructor\n private StringUtils() {\n\n }\n\n /**\n * Gets random string\n *\n * @return Random string\n */\n public static String getRandomString() {\n final int length = 10;\n return getRandomString(length);\n }\n\n /**\n * Gets random string\n *\n * @param length String length\n * @return Random string\n */\n public static String getRandomString(int length) {\n char[] chars = \"ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\".toCharArray();\n StringBuilder builder = new StringBuilder();\n Random random = new Random();\n for (int i = 0; i < length; i++) {\n char c = chars[random.nextInt(chars.length)];\n builder.append(c);\n }\n return builder.toString();\n }\n\n /**\n * Checks whether the string is null or not\n *\n * @param string String for checking\n * @return True if string is empty. False otherwise\n */\n public static boolean isEmpty(String string) {\n return string == null || string.isEmpty();\n }\n}"
] | import com.khmelenko.lab.varis.common.Constants;
import com.khmelenko.lab.varis.mvp.MvpPresenter;
import com.khmelenko.lab.varis.network.response.Repo;
import com.khmelenko.lab.varis.network.response.User;
import com.khmelenko.lab.varis.network.retrofit.travis.TravisRestClient;
import com.khmelenko.lab.varis.storage.AppSettings;
import com.khmelenko.lab.varis.storage.CacheStorage;
import com.khmelenko.lab.varis.util.StringUtils;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiConsumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers; | package com.khmelenko.lab.varis.repositories;
/**
* Repositories presenter
*
* @author Dmytro Khmelenko ([email protected])
*/
public class RepositoriesPresenter extends MvpPresenter<RepositoriesView> {
private final TravisRestClient mTravisRestClient; | private final CacheStorage mCache; | 5 |
mziccard/secureit | src/main/java/me/ziccard/secureit/async/upload/BluetoothPeriodicPositionUploaderTask.java | [
"public class SecureItPreferences {\n\t\n\tprivate SharedPreferences appSharedPrefs;\n private Editor prefsEditor;\n \n public static final String LOW = \"Low\";\n public static final String MEDIUM = \"Medium\";\n public static final String HIGH = \"High\";\n \n public static final String FRONT = \"Front\";\n public static final String BACK = \"Back\";\n\t\n\tprivate static final String APP_SHARED_PREFS=\"me.ziccard.secureit\";\n\tprivate static final String ACCELEROMETER_ACTIVE=\"accelerometer_active\";\n\tprivate static final String ACCELEROMETER_SENSITIVITY=\"accelerometer_sensibility\";\n\tprivate static final String CAMERA_ACTIVE=\"camera_active\";\n\tprivate static final String CAMERA=\"camera\";\n\tprivate static final String CAMERA_SENSITIVITY=\"camera_sensitivity\";\n\tprivate static final String FLASH_ACTIVE=\"flash_active\";\n\tprivate static final String MICROPHONE_ACTIVE=\"microphone_active\";\n\tprivate static final String MICROPHONE_SENSITIVITY=\"microphone_sensitivity\";\n\tprivate static final String SMS_ACTIVE=\"sms_active\";\n\tprivate static final String SMS_NUMBER=\"sms_number\";\n\tprivate static final String REMOTE_ACTIVE=\"remote_active\";\n\tprivate static final String REMOTE_EMAIL=\"remote_email\";\n\tprivate static final String UNLOCK_CODE=\"unlock_code\";\n\t\n\tprivate static final String ACCESS_TOKEN=\"access_token\";\n\tprivate static final String DELEGATED_ACCESS_TOKEN=\"deferred_access_token\";\n\t\n\tprivate static final String PHONE_ID=\"phone_id\";\n\t\n\tprivate static final String DIR_PATH = \"/secureit\";\n\t\n\tprivate static final String IMAGE_PATH = DIR_PATH+\"/secureit\";\n\tprivate static final int MAX_IMAGES = 10;\n\t\n\tprivate static final String AUDIO_PATH = DIR_PATH+\"/SecureIt_Audio\";\n\tprivate static final long AUDIO_LENGTH = 10000;\n\t\n\t\n public SecureItPreferences(Context context) {\n this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);\n this.prefsEditor = appSharedPrefs.edit();\n }\n \n public void activateAccelerometer(boolean active) {\n \tprefsEditor.putBoolean(ACCELEROMETER_ACTIVE, active);\n \tprefsEditor.commit();\n }\n \n public boolean getAccelerometerActivation() {\n \treturn appSharedPrefs.getBoolean(ACCELEROMETER_ACTIVE, true);\n }\n \n public void setAccelerometerSensitivity(String sensitivity) {\n \tprefsEditor.putString(ACCELEROMETER_SENSITIVITY, sensitivity);\n \tprefsEditor.commit();\n }\n \n public String getAccelerometerSensitivity() {\n \treturn appSharedPrefs.getString(ACCELEROMETER_SENSITIVITY, \"\");\n }\n \n public void activateCamera(boolean active) {\n \tprefsEditor.putBoolean(CAMERA_ACTIVE, active);\n \tprefsEditor.commit();\n }\n \n public boolean getCameraActivation() {\n \treturn appSharedPrefs.getBoolean(CAMERA_ACTIVE, true);\n }\n \n public void setCamera(String camera) {\n \tprefsEditor.putString(CAMERA, camera);\n \tprefsEditor.commit();\n }\n \n public String getCamera() {\n \treturn appSharedPrefs.getString(CAMERA, BACK);\n }\n \n public void setCameraSensitivity(String sensitivity) {\n \tprefsEditor.putString(CAMERA_SENSITIVITY, sensitivity);\n \tprefsEditor.commit();\n }\n \n public String getCameraSensitivity() {\n \treturn appSharedPrefs.getString(CAMERA_SENSITIVITY, \"\");\n }\n \n public void activateFlash(boolean active) {\n \tprefsEditor.putBoolean(FLASH_ACTIVE, active);\n \tprefsEditor.commit();\n }\n \n public boolean getFlashActivation() {\n \treturn appSharedPrefs.getBoolean(FLASH_ACTIVE, true);\n }\n \n public void activateMicrophone(boolean active) {\n \tprefsEditor.putBoolean(MICROPHONE_ACTIVE, active);\n \tprefsEditor.commit();\n }\n \n public boolean getMicrophoneActivation() {\n \treturn appSharedPrefs.getBoolean(MICROPHONE_ACTIVE, true);\n }\n \n public void setMicrophoneSensitivity(String sensitivity) {\n \tprefsEditor.putString(MICROPHONE_SENSITIVITY, sensitivity);\n \tprefsEditor.commit();\n }\n \n public String getMicrophoneSensitivity() {\n \treturn appSharedPrefs.getString(MICROPHONE_SENSITIVITY, \"\");\n }\n \n public void activateSms(boolean active) {\n \tprefsEditor.putBoolean(SMS_ACTIVE, active);\n \tprefsEditor.commit();\n }\n \n public boolean getSmsActivation() {\n \treturn appSharedPrefs.getBoolean(SMS_ACTIVE, true);\n }\n \n public void setSmsNumber(String number) {\n \tprefsEditor.putString(SMS_NUMBER, number);\n \tprefsEditor.commit();\n }\n \n public String getSmsNumber() {\n \treturn appSharedPrefs.getString(SMS_NUMBER, \"\");\n }\n \n public void activateRemote(boolean active) {\n \tprefsEditor.putBoolean(REMOTE_ACTIVE, active);\n \tprefsEditor.commit();\n }\n \n public boolean getRemoteActivation() {\n \treturn appSharedPrefs.getBoolean(REMOTE_ACTIVE, true);\n }\n \n public void setRemoteEmail(String email) {\n \tprefsEditor.putString(REMOTE_EMAIL, email);\n \tprefsEditor.commit();\n }\n \n public void setUnlockCode(String unlockCode) {\n \tprefsEditor.putString(UNLOCK_CODE, unlockCode);\n \tprefsEditor.commit();\n }\n \n public String getUnlockCode() {\n \treturn appSharedPrefs.getString(UNLOCK_CODE, \"\");\n }\n \n public String getRemoteEmail() {\n \treturn appSharedPrefs.getString(REMOTE_EMAIL, \"\");\n }\n \n public void setAccessToken(String accessToken) {\n \tprefsEditor.putString(ACCESS_TOKEN, accessToken);\n \tprefsEditor.commit();\n }\n \n public String getAccessToken() {\n \treturn appSharedPrefs.getString(ACCESS_TOKEN, \"\");\n }\n \n public void unsetAccessToken() {\n \tprefsEditor.remove(ACCESS_TOKEN);\n }\n \n public void setDelegatedAccessToken(String deferredAccessToken) {\n \tprefsEditor.putString(DELEGATED_ACCESS_TOKEN, deferredAccessToken);\n \tprefsEditor.commit();\n }\n \n public String getDelegatedAccessToken() {\n \treturn appSharedPrefs.getString(DELEGATED_ACCESS_TOKEN, \"\");\n }\n \n public void unsetDelegatedAccessToken() {\n \tprefsEditor.remove(DELEGATED_ACCESS_TOKEN);\n }\n \n public String getImagePath() {\n \treturn IMAGE_PATH;\n }\n \n public int getMaxImages() {\n \treturn MAX_IMAGES;\n }\n \n public void setPhoneId(String phoneId) {\n \tprefsEditor.putString(PHONE_ID, phoneId);\n \tprefsEditor.commit();\n }\n \n public void unsetPhoneId() {\n \tprefsEditor.remove(PHONE_ID);\n }\n \n public String getPhoneId() {\n \treturn appSharedPrefs.getString(PHONE_ID, \"\");\n }\n \n public String getDirPath() {\n \treturn DIR_PATH;\n }\n \n public String getAudioPath() {\n \treturn AUDIO_PATH;\n }\n \n public long getAudioLenght() {\n \treturn AUDIO_LENGTH;\n }\n \n public String getSMSText() {\n \treturn \"WARNING: SecureIt has detected an intrusion.\\n\"+\n \t\t\t\"PhoneId: \"+getPhoneId();\n }\n}",
"public class ObjectBluetoothSocket {\n\t\n\t/**\n\t * Original byte oriented socket\n\t */\n\tprivate BluetoothSocket socket;\n\t\n\t/**\n\t * Object output stream associated with socket\n\t */\n\tprivate ObjectOutputStream outputStream;\n\t\n\t/**\n\t * Object input stream associated with socket\n\t */\n\tprivate ObjectInputStream inputStream;\n\t\n\tpublic ObjectBluetoothSocket(BluetoothSocket socket) throws IOException {\n\t\tthis.socket = socket;\n\t\tthis.outputStream = new ObjectOutputStream(this.socket.getOutputStream());\n\t\tthis.inputStream = new ObjectInputStream(this.socket.getInputStream());\n\t}\n\t\n\tpublic ObjectInputStream getInputStream() {\n\t\treturn inputStream;\n\t}\n\t\n\tpublic ObjectOutputStream getOutputStream() {\n\t\treturn outputStream;\n\t}\n\t\n\tpublic void close() throws IOException {\n\t\toutputStream.close();\n\t\tinputStream.close();\n\t\tsocket.close();\n\t}\n\t\n\tpublic void connect() throws IOException {\n\t\tsocket.connect();\n\t}\n\t\n\n}",
"public class Remote {\n\t\n\tpublic static final String HOST = \"http://10.192.6.90:9000/\";\n\t\n\tpublic static final String ACCESS_TOKEN = \"users/accesstoken\";\n\t\n\tpublic static final String PHONES = \"api/phones\";\n\t\n\tpublic static final String UPLOAD_IMAGES = \"/image\";\n\t\t\t\n\tpublic static final String UPLOAD_AUDIO = \"/audio\";\n\t\n\tpublic static final String UPLOAD_POSITION = \"/position\";\n\t\n\tpublic static final String DELEGATED_UPLOAD_POSITION = \"/position/delegated\";\n\t\n\tpublic static final String BLUETOOTH_NAME = \"me.ziccard.secureit\";\n\t\n\tpublic static final UUID BLUETOOTH_UUID =\n\t\t UUID.fromString(\"00001101-0000-1000-8000-00805F9B34FB\");\n}",
"public interface BluetoothMessage extends Serializable {\n\t\n\tpublic MessageType getType();\n\t\n}",
"public class KeyRequest extends BluetoothMessageData implements BluetoothMessage {\n\t\n\tprivate double lat;\n\tprivate double lng;\n\t\n\tpublic KeyRequest(double lat, double lng, Date timestamp) {\n\t\tthis.lat = lat; \n\t\tthis.lng = lng;\n\t\tthis.timestamp = timestamp;\n\t}\n\t\n\tpublic double getLat() {\n\t\treturn lat;\n\t}\n\n\tpublic double getLng() {\n\t\treturn lng;\n\t}\n\t\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = -5241265795662117718L;\n\n\tpublic MessageType getType() {\n\t\treturn MessageType.KEY_REQUEST;\n\t}\n\n}",
"public class MessageBuilder {\n\t\n\t/**\n\t * Phone Id\n\t */\n\tprivate String phoneId;\n\t\n\t/**\n\t * Latitude value\n\t */\n\tprivate double lat;\n\t\n\t/**\n\t * Longitude value\t\n\t */\n\tprivate double lng;\n\t\n\t/**\n\t * Timestamp\n\t */\n\tprivate Date timestamp;\n\t\n\t/**\n\t * Password used to encrypt KeyResponse\n\t */\n\tprivate String password;\t\n\t\n\tpublic void setPhoneId(String phoneId) {\n\t\tthis.phoneId = phoneId;\n\t}\n\n\tpublic void setLat(double lat) {\n\t\tthis.lat = lat;\n\t}\n\n\tpublic void setLng(double lng) {\n\t\tthis.lng = lng;\n\t}\n\n\tpublic void setTimestamp(Date timestamp) {\n\t\tthis.timestamp = timestamp;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t/**\n\t * Constructor\n\t * @param type\n\t * @return\n\t */\t\n\tpublic BluetoothMessage buildMessage(MessageType type) {\n\t\tswitch (type) {\n\t\tcase HELLO:\n\t\t\treturn new HelloMessage(phoneId, new Date());\n\t\tcase KEY_REQUEST:\n\t\t\treturn new KeyRequest(lat, lng, new Date());\t\t\n\t\tcase KEY_RESPONSE:\n\t\t\tString accessKey = \"{\\\"lat\\\": \\\"\" + lat + \"\\\",\" +\n\t\t\t\t\t\t\t\t\"\\\"long\\\": \\\"\" + lng + \"\\\",\" +\t\n\t\t\t\t\t\t\t\t\"\\\"timestamp\\\": \\\"\" + timestamp + \"\\\"}\";\n\n\t\t\tSecretKeySpec key = new SecretKeySpec(password.getBytes(), \"AES\");\n\t\t AlgorithmParameterSpec paramSpec = new IvParameterSpec(password.substring(0, 16).getBytes());\n\t\t Cipher cipher;\n\t\t\ttry {\n\t\t\t\tcipher = Cipher.getInstance(\"AES/CBC/PKCS5Padding\");\t \n\t\t\t cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);\t\t\t \t\n\t\t\t byte[] ecrypted = cipher.doFinal(accessKey.getBytes());\n\t\t\t accessKey = Base64.encodeToString(ecrypted, Base64.DEFAULT);\n\t\t\t} catch (Exception e) {\n\t\t\t\n\t\t\t\te.printStackTrace();\n\t\t\t} \n\t\t\treturn new KeyResponse(accessKey, new Date());\n\t\tdefault:\n\t\t\treturn new HelloMessage(phoneId, new Date());\n\t\t}\n\t}\n}",
"public enum MessageType {\n\t\n\tHELLO,\n\tKEY_REQUEST,\n\tKEY_RESPONSE\n\n}"
] | import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import me.ziccard.secureit.SecureItPreferences;
import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket;
import me.ziccard.secureit.config.Remote;
import me.ziccard.secureit.messages.BluetoothMessage;
import me.ziccard.secureit.messages.KeyRequest;
import me.ziccard.secureit.messages.MessageBuilder;
import me.ziccard.secureit.messages.MessageType;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast; | /*
* Copyright (c) 2013-2015 Marco Ziccardi, Luca Bonato
* Licensed under the MIT license.
*/
package me.ziccard.secureit.async.upload;
public class BluetoothPeriodicPositionUploaderTask extends AsyncTask<Void, Void, Void> {
private Context context;
/**
* Boolean true iff last thread iterations position has been sent
*/
private boolean dataSent = false;
private SecureItPreferences prefs;
/**
* Adapter for bluetooth services
*/
private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
/**
* Creates a BroadcastReceiver for ACTION_FOUND and ACTION_DISCOVERY_FINISHED
*/
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
private ArrayList<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
Log.i("BluetoothPeriodicPositionUploaderTask", "Discovered "+device.getName());
CharSequence text = "Discovered "+device.getName();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
// When ending the discovery
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
for (BluetoothDevice device : devices){
Log.i("DISCOVERY", "FINISHED");
try {
BluetoothSocket tmp = null;
tmp = device.createInsecureRfcommSocketToServiceRecord(Remote.BLUETOOTH_UUID);
if (tmp != null) {
Log.i("BluetoothPeriodicPositionUploaderTask", "Trying to connect to " + device.getName());
adapter.cancelDiscovery();
tmp.connect();
Log.i("BluetoothPeriodicPositionUploaderTask", "Connected to " + device.getName());
ObjectBluetoothSocket socket = new ObjectBluetoothSocket(tmp);
MessageBuilder builder = new MessageBuilder();
builder.setPhoneId(phoneId);
builder.setTimestamp(new Date());
//Sending hello message | BluetoothMessage message = builder.buildMessage(MessageType.HELLO); | 6 |
Fedict/dcattools | scrapers/src/main/java/be/fedict/dcat/scrapers/wiv/HtmlWIV.java | [
"public class Cache {\n private static final Logger logger = LoggerFactory.getLogger(Cache.class);\n \n private DB db = null;\n private static final String CACHE = \"cache\";\n private static final String URLS = \"urls\";\n private static final String PAGES = \"pages\";\n\n /**\n * Store list of URLs.\n * \n * @param urls \n */\n public void storeURLList(List<URL> urls) {\n ConcurrentMap<String, List<URL>> map = db.hashMap(Cache.CACHE);\n map.put(Cache.URLS, urls);\n db.commit();\n }\n \n /**\n * Get the list of URLs in the cache.\n * \n * @return \n */\n public List<URL> retrieveURLList() {\n ConcurrentMap<String, List<URL>> map = db.hashMap(Cache.CACHE);\n return map.getOrDefault(Cache.URLS, new ArrayList<>());\n }\n \n /**\n * Store a web page\n * \n * @param id\n * @param page\n * @param lang \n */\n public void storePage(URL id, String lang, Page page) {\n logger.debug(\"Storing page {} with lang {} to cache\", id, lang);\n ConcurrentMap<URL, Map<String, Page>> map = db.hashMap(Cache.PAGES);\n Map<String, Page> p = map.getOrDefault(id, new HashMap<>());\n p.put(lang, page);\n map.put(id, p);\n db.commit();\n }\n \n /**\n * Retrieve a page from the cache.\n * \n * @param id\n * @return page object\n */\n public Map<String, Page> retrievePage(URL id) {\n logger.debug(\"Retrieving page {} from cache\", id);\n ConcurrentMap<URL, Map<String, Page>> map = db.hashMap(Cache.PAGES);\n return map.getOrDefault(id, Collections.emptyMap());\n }\n\t\n\t/**\n * Get the list of pages in the cache.\n * \n * @return \n */\n public Set<URL> retrievePageList() {\n\t\tConcurrentMap<URL, Map<String, Page>> map = db.hashMap(Cache.PAGES);\n return (map == null) ? Collections.emptySet() : map.keySet();\n }\n \n /**\n * Store a map to the cache.\n * \n * @param id\n * @param map \n */\n public void storeMap(URL id, Map<String,String> map) {\n ConcurrentMap<URL, Map<String,String>> m = db.hashMap(Cache.PAGES);\n m.put(id, map);\n db.commit();\n }\n \n /**\n * Retrieve a map from the cache.\n * \n * @param id\n * @return \n */\n public Map<String,String> retrieveMap(URL id) {\n ConcurrentMap<URL, Map<String,String>> map = db.hashMap(Cache.PAGES);\n return map.getOrDefault(id, Collections.emptyMap());\n }\n \n /**\n * Close cache\n */\n public void shutdown() {\n logger.info(\"Closing cache file\");\n db.close();\n }\n \n\t/**\n\t * Constructor\n\t * \n\t * @param f \n\t */\n public Cache(File f) {\n logger.info(\"Opening cache file {}\", f.getAbsolutePath());\n db = DBMaker.fileDB(f).make();\n }\n}",
"public class Page implements Serializable {\n private static final long serialVersionUID = 14846132166L;\n \n private URL url;\n private String content;\n\n /**\n * Get the URL of this page.\n * \n * @return the url\n */\n public URL getUrl() {\n return url;\n }\n\n /**\n * Set the URL of this page.\n * \n * @param url the url to set\n */\n public void setUrl(URL url) {\n this.url = url;\n }\n\n /**\n * Get the content/body of this page.\n * \n * @return the content\n */\n public String getContent() {\n return content;\n }\n\n /**\n * Set the content/body of this page.\n * \n * @param content the content to set\n */\n public void setContent(String content) {\n this.content = content;\n }\n \n /**\n * Constructor\n * \n * @param url\n * @param content \n */\n public Page(URL url, String content) {\n this.url = url;\n this.content = content;\n }\n \n /**\n * Empty constructor.\n */\n public Page() {\n this.url = null;\n this.content = \"\";\n }\n}",
"public class Storage {\n private final static Logger logger = LoggerFactory.getLogger(Storage.class);\n \n\tpublic final static String DATAGOVBE = \"http://data.gov.be\";\n\n private Repository repo = null;\n private ValueFactory fac = null;\n private RepositoryConnection conn = null;\n \n /**\n * Get triple store.\n * \n * @return \n */\n public Repository getRepository() {\n return repo;\n }\n\n /**\n * Delete the triple store file.\n */\n public void deleteRepository() {\n if (repo != null) {\n logger.info(\"Removing RDF backend file\");\n \n if(!repo.getDataDir().delete()) {\n logger.warn(\"Could not remove RDF backend file\");\n }\n repo = null;\n }\n }\n \n /**\n * Get value factory.\n * \n * @return \n */\n public ValueFactory getValueFactory() {\n return fac;\n }\n\n\t/**\n\t * Get parser configuration\n\t * \n\t * @return \n\t */\n\tprivate ParserConfig getParserConfig() {\n\t\tParserConfig cfg = new ParserConfig();\n\t\tcfg.set(BasicParserSettings.VERIFY_URI_SYNTAX, false);\n\t\tcfg.set(BasicParserSettings.SKOLEMIZE_ORIGIN, DATAGOVBE);\n\t\tcfg.set(XMLParserSettings.FAIL_ON_SAX_NON_FATAL_ERRORS, false);\n\t\treturn cfg;\n\t}\n\n /**\n * Create IRI using value factory.\n * \n * @param str string\n * @return trimmed IRI \n */\n public IRI getURI(String str) {\n\t\treturn fac.createIRI(str.trim());\n }\n \n /**\n * Check if a triple exists.\n * \n * @param subj\n * @param pred\n * @return\n * @throws RepositoryException \n */\n public boolean has(IRI subj, IRI pred) throws RepositoryException {\n return conn.hasStatement(subj, pred, null, false);\n }\n\n /**\n * Get multiple values from map structure.\n * \n * @param map\n * @param prop\n * @param lang\n * @return \n */\n public static List<String> getMany(Map<Resource, ListMultimap<String, String>> map, \n IRI prop, String lang) {\n List<String> res = new ArrayList<>();\n \n ListMultimap<String, String> multi = map.get(prop);\n if (multi != null && !multi.isEmpty()) {\n List<String> list = multi.get(lang);\n if (list != null && !list.isEmpty()) {\n res = list;\n }\n }\n return res;\n }\n \n /**\n * Get one value from map structure.\n * \n * @param map\n * @param prop\n * @param lang\n * @return \n */\n public static String getOne(Map<Resource, ListMultimap<String, String>> map, \n IRI prop, String lang) {\n String res = \"\";\n \n ListMultimap<String, String> multi = map.get(prop);\n if (multi != null && !multi.isEmpty()) {\n List<String> list = multi.get(lang);\n if (list != null && !list.isEmpty()) {\n res = list.get(0);\n }\n }\n return res;\n }\n\n /**\n * Add to the repository\n * \n * @param in\n * @param format\n * @throws RepositoryException \n * @throws RDFParseException \n * @throws IOException \n */\n public void add(InputStream in, RDFFormat format) \n throws RepositoryException, RDFParseException, IOException {\n conn.add(in, DATAGOVBE, format, (Resource) null);\n }\n \n /**\n * Add an IRI property to the repository.\n * \n * @param subj\n * @param pred\n * @param obj\n * @throws RepositoryException \n */\n public void add(Resource subj, IRI pred, IRI obj) throws RepositoryException {\n conn.add(subj, pred, obj);\n }\n\n /**\n * Add a value to the repository.\n * \n * @param subj\n * @param pred\n * @param obj\n * @throws RepositoryException \n */\n public void add(Resource subj, IRI pred, Value obj) throws RepositoryException {\n conn.add(subj, pred, obj);\n }\n \n\t\n /**\n * Add an URL property to the repository.\n * \n * @param subj\n * @param pred\n * @param url\n * @throws RepositoryException \n */\n public void add(IRI subj, IRI pred, URL url) throws RepositoryException {\n String s = url.toString().replace(\" \", \"%20\");\n conn.add(subj, pred, fac.createIRI(s));\n }\n \n /**\n * Add a date property to the repository.\n * \n * @param subj\n * @param pred\n * @param date\n * @throws RepositoryException \n */\n public void add(IRI subj, IRI pred, Date date) throws RepositoryException {\n conn.add(subj, pred, fac.createLiteral(date));\n }\n \n /**\n * Add a string property to the repository.\n * \n * @param subj\n * @param pred\n * @param value\n * @throws RepositoryException \n */\n public void add(IRI subj, IRI pred, String value) throws RepositoryException {\n\t\tif ((value != null) && !value.isEmpty()) {\n\t\t\tconn.add(subj, pred, fac.createLiteral(value));\n\t\t} else {\n\t\t\tlogger.warn(\"Skipping empty or null value for {} {}\", subj, pred);\n\t\t}\n }\n \n /**\n * Add a language string property to the repository.\n * \n * @param subj\n * @param pred\n * @param value\n * @param lang\n * @throws RepositoryException \n */\n public void add(Resource subj, IRI pred, String value, String lang) \n throws RepositoryException {\n\t\tif ((value != null) && !value.isEmpty()) {\n\t\t\tconn.add(subj, pred, fac.createLiteral(value, lang));\n\t\t} else {\n\t\t\tlogger.warn(\"Skipping empty or null value for {} {}\", subj, pred);\n\t\t}\n }\n\n /**\n * Add a typed property to the repository.\n * \n * @param subj\n * @param pred\n * @param value\n * @param dtype\n * @throws RepositoryException \n */\n public void add(Resource subj, IRI pred, String value, IRI dtype) \n throws RepositoryException {\n\t\tif ((value != null) && !value.isEmpty()) {\n\t\t\tconn.add(subj, pred, fac.createLiteral(value, dtype));\n\t\t} else {\n\t\t\tlogger.warn(\"Skipping empty or null value for {} {}\", subj, pred);\n\t\t}\n }\n\n /**\n * Escape spaces in object URIs to avoid SPARQL issues\n * \n * @param pred \n * @throws RepositoryException \n */\n public void escapeURI(IRI pred) throws RepositoryException {\n int i = 0;\n try (RepositoryResult<Statement> stmts = \n conn.getStatements(null, pred, null, false)) {\n while(stmts.hasNext()) {\n Statement stmt = stmts.next();\n Value val = stmt.getObject();\n // Check if object is Literal or URI\n\t\t\t\tif (val instanceof Resource) {\n String uri = val.stringValue();\n\t\t\t\t\tif (uri.contains(\" \") || uri.contains(\"\\\\\") || uri.contains(\"[\") || uri.contains(\"]\")) {\n // Check if URI contains a space or brackets\n\t\t\t\t\t\tif (uri.startsWith(\"[\") && uri.endsWith(\"]\")) {\n\t\t\t\t\t\t\turi = uri.substring(1, uri.length() - 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tString esc = uri.replace(\" \", \"%20\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"\\\\\\\\\", \"%5c\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"\\\\\", \"%5c\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"[\", \"%5b\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"]\", \"%5d\");\n\t\t\t\t\t\tlogger.debug(\"Changing {} into {}\", uri, esc);\n\t\t\t\t\t\tIRI obj = fac.createIRI(esc);\n\t\t\t\t\t\tconn.add(stmt.getSubject(), stmt.getPredicate(), obj);\n\t\t\t\t\t\tconn.remove(stmt);\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n }\n }\n }\n logger.info(\"Replaced characters in {} URIs\", i);\n }\n \n /**\n * Execute SPARQL Update query\n * \n * @param sparql\n * @throws RepositoryException\n */\n public void queryUpdate(String sparql) throws RepositoryException {\n try {\n Update upd = conn.prepareUpdate(QueryLanguage.SPARQL, sparql);\n upd.execute();\n } catch (MalformedQueryException | UpdateExecutionException ex) {\n throw new RepositoryException(ex);\n }\n }\n \n /**\n * Get the list of all URIs of a certain class.\n * \n * @param rdfClass\n * @return list of subjects\n * @throws RepositoryException \n */\n public List<IRI> query(IRI rdfClass) throws RepositoryException {\n ArrayList<IRI> lst = new ArrayList<>();\n int i = 0;\n \n try (RepositoryResult<Statement> stmts = \n conn.getStatements(null, RDF.TYPE, rdfClass, false)) {\n \n if (! stmts.hasNext()) {\n logger.warn(\"No results for class {}\", rdfClass.stringValue());\n }\n\n while(stmts.hasNext()) {\n Statement stmt = stmts.next();\n lst.add((IRI) stmt.getSubject());\n i++;\n }\n }\n logger.debug(\"Retrieved {} statements for {}\", i, rdfClass.stringValue());\n return lst;\n }\n \n /**\n * Get a DCAT Dataset or a Distribution.\n * \n * @param uri\n * @return \n * @throws org.eclipse.rdf4j.repository.RepositoryException \n */\n public Map<Resource, ListMultimap<String, String>> queryProperties(Resource uri) \n throws RepositoryException {\n Map<Resource, ListMultimap<String, String>> map = new HashMap<>();\n \n try (RepositoryResult<Statement> stmts = conn.getStatements(uri, null, null, true)) {\n if (! stmts.hasNext()) {\n logger.warn(\"No properties for {}\", uri.stringValue());\n }\n \n while(stmts.hasNext()) {\n Statement stmt = stmts.next();\n IRI pred = stmt.getPredicate();\n Value val = stmt.getObject();\n \n String lang = \"\";\n if (val instanceof Literal) {\n String l = ((Literal) val).getLanguage().orElse(null);\n if (l != null) {\n lang = l;\n }\n }\n /* Handle multiple values for different languages */\n ListMultimap<String, String> multi = map.get(pred);\n if (multi == null) {\n multi = ArrayListMultimap.create();\n map.put(pred, multi);\n }\n multi.put(lang, val.stringValue());\n }\n }\n \n return map;\n }\n\n /**\n * Initialize RDF repository\n * \n * @throws RepositoryException \n */\n public void startup() throws RepositoryException {\n logger.info(\"Opening RDF repository\");\n conn = repo.getConnection();\n fac = repo.getValueFactory();\n\n\t\tconn.setParserConfig(getParserConfig());\n }\n \n /**\n * Stop the RDF repository\n * \n * @throws RepositoryException \n */\n public void shutdown() throws RepositoryException {\n logger.info(\"Closing RDF repository\");\n conn.commit();\n conn.close();\n repo.shutDown();\n }\n \n /**\n * Read contents of N-Triples input into a RDF repository\n * \n * @param in\n * @throws RepositoryException \n * @throws java.io.IOException \n * @throws org.eclipse.rdf4j.rio.RDFParseException \n */\n public void read(Reader in) throws RepositoryException, IOException, RDFParseException {\n this.read(in, RDFFormat.NTRIPLES);\n }\n \n /**\n * Read contents of input into a RDF repository\n * \n * @param in\n * @param format RDF input format\n * @throws RepositoryException \n * @throws IOException \n * @throws RDFParseException \n */\n public void read(Reader in, RDFFormat format) throws RepositoryException,\n IOException, RDFParseException {\n logger.info(\"Reading triples from input stream\");\n\t\tconn.setParserConfig(getParserConfig());\n conn.add(in, DATAGOVBE, format);\n }\n \n /**\n * Write contents of RDF repository to N-Triples output\n * \n * @param out\n * @throws RepositoryException \n */\n public void write(Writer out) throws RepositoryException {\n this.write(out, RDFFormat.NTRIPLES);\n } \n \n /**\n * Write contents of RDF repository to N-Triples output\n * \n * @param out\n * @param format RDF output format\n * @throws RepositoryException \n */\n public void write(Writer out, RDFFormat format) throws RepositoryException {\n RDFWriter writer = Rio.createWriter(RDFFormat.NTRIPLES, out);\n try {\n conn.export(writer);\n } catch (RDFHandlerException ex) {\n logger.warn(\"Error writing RDF\");\n }\n }\n \n /**\n * RDF store\n * \n */\n public Storage() {\n logger.info(\"Opening RDF store\");\n \n MemoryStore mem = new MemoryStore();\n mem.setPersist(false);\n repo = new SailRepository(mem);\n }\n}",
"public abstract class Html extends BaseScraper {\n\t\t/**\n\t * Return an absolute URL\n\t *\n\t * @param rel relative URL\n\t * @return\n\t * @throws MalformedURLException\n\t */\n\tprotected URL makeAbsURL(String rel) throws MalformedURLException {\n\t\t// Check if URL is already absolute\n\t\tif (rel.startsWith(\"http:\") || rel.startsWith(\"https:\")) {\n\t\t\treturn new URL(rel);\n\t\t}\n\t\treturn new URL(getBase().getProtocol(), getBase().getHost(), rel);\n\t}\n\n\n\t/**\n\t * Generate DCAT Dataset\n\t *\n\t * @param store RDF store\n\t * @param id dataset id\n\t * @param page\n\t * @throws MalformedURLException\n\t * @throws RepositoryException\n\t */\n\tprotected abstract void generateDataset(Storage store, String id, Map<String, Page> page)\n\t\t\tthrows MalformedURLException, RepositoryException;\n\n\t/**\n\t * Generate DCAT.\n\t *\n\t * @param cache\n\t * @param store\n\t * @throws RepositoryException\n\t * @throws MalformedURLException\n\t */\n\t@Override\n\tpublic void generateDcat(Cache cache, Storage store) throws RepositoryException, MalformedURLException {\n\t\tlogger.info(\"Generate DCAT\");\n\n\t\t/* Get the list of all datasets */\n\t\tList<URL> urls = cache.retrieveURLList();\n\t\tfor (URL u : urls) {\n\t\t\tMap<String, Page> page = cache.retrievePage(u);\n\t\t\tString id = makeHashId(u.toString());\n\t\t\tgenerateDataset(store, id, page);\n\t\t}\n\t\tgenerateCatalog(store);\n\t}\n\t\n\t/**\n\t * Get the list of all the downloads (DCAT Dataset).\n\t *\n\t * @return List of URLs\n\t * @throws IOException\n\t */\n\tprotected abstract List<URL> scrapeDatasetList() throws IOException;\n\t\n\t/**\n\t * Scrape a dataset\n\t * \n\t * @param u url\n\t * @throws IOException \n\t */\n\tprotected void scrapeDataset(URL u) throws IOException {\n\t\tCache cache = getCache();\n\t\tString html = makeRequest(u);\n\t\tcache.storePage(u, \"\", new Page(u, html));\n\t}\n\t\n\t/**\n\t * Scrape the site.\n\t *\n\t * @throws IOException\n\t */\n\t@Override\n\tpublic void scrape() throws IOException {\n\t\tlogger.info(\"Start scraping\");\n\t\tCache cache = getCache();\n\n\t\tList<URL> urls = cache.retrieveURLList();\n\t\tif (urls.isEmpty()) {\n\t\t\turls = scrapeDatasetList();\n\t\t\tcache.storeURLList(urls);\n\t\t}\n\n\t\tlogger.info(\"Found {} datasets on page\", String.valueOf(urls.size()));\n\t\tlogger.info(\"Start scraping (waiting between requests)\");\n\n\t\tint i = 0;\n\t\tfor (URL u : urls) {\n\t\t\tMap<String, Page> page = cache.retrievePage(u);\n\t\t\tif (page.isEmpty()) {\n\t\t\t\tsleep();\n\t\t\t\tif (++i % 100 == 0) {\n\t\t\t\t\tlogger.info(\"Download {}...\", Integer.toString(i));\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tscrapeDataset(u);\n\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\tlogger.error(\"Failed to scrape {}\", u);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlogger.info(\"Done scraping\");\n\t}\n\n\t/**\n\t * Constructor\n\t *\n\t * @param prop\n\t * @throws IOException\n\t */\n\tprotected Html(Properties prop) throws IOException {\n\t\tsuper(prop);\n\t}\n}",
"public class MDR_LANG {\r\n public static final String NAMESPACE = \r\n \"http://publications.europa.eu/resource/authority/language/\";\r\n \r\n public final static String PREFIX = \"mdrlang\";\r\n \r\n public final static IRI DE;\r\n public final static IRI EN;\r\n public final static IRI FR;\r\n public final static IRI NL;\r\n \r\n public final static Map<String,IRI> MAP = new HashMap<>();\r\n \r\n static {\r\n\tValueFactory factory = SimpleValueFactory.getInstance();\r\n \r\n DE = factory.createIRI(MDR_LANG.NAMESPACE, \"DEU\");\r\n EN = factory.createIRI(MDR_LANG.NAMESPACE, \"ENG\");\r\n FR = factory.createIRI(MDR_LANG.NAMESPACE, \"FRA\");\r\n NL = factory.createIRI(MDR_LANG.NAMESPACE, \"NLD\");\r\n \r\n MAP.put(\"de\", DE);\r\n MAP.put(\"en\", EN);\r\n MAP.put(\"fr\", FR);\r\n MAP.put(\"nl\", NL);\r\n }\r\n}\r"
] | import be.fedict.dcat.scrapers.Cache;
import be.fedict.dcat.scrapers.Page;
import be.fedict.dcat.helpers.Storage;
import be.fedict.dcat.scrapers.Html;
import be.fedict.dcat.vocab.MDR_LANG;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.text.html.HTML.Attribute;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.vocabulary.DCAT;
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.repository.RepositoryException; | /*
* Copyright (c) 2020, FPS BOSA DG DT
* 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.
*
* 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 HOLDER 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 be.fedict.dcat.scrapers.wiv;
/**
* Scraper WIV-ISP Covid data
*
* @see https://epistat.wiv-isp.be/covid/
* @author Bart Hanssens
*/
public class HtmlWIV extends Html {
private final static String H_TITLE = "h2";
private final static String SECTION_P = "section#Covid p";
private final static String DIST_ROW = "table.table tbody tr";
private final static String HREFS = "a";
@Override
protected List<URL> scrapeDatasetList() throws IOException {
List<URL> urls = new ArrayList<>();
urls.add(getBase());
return urls;
}
/**
* Generate DCAT distribution.
*
* @param store RDF store
* @param dataset URI
* @param access access URL of the dataset
* @param row row element
* @param lang language code
* @throws MalformedURLException
* @throws RepositoryException
*/
private void generateDist(Storage store, IRI dataset, URL access,
Elements rows, String lang) throws MalformedURLException, RepositoryException {
for (Element row: rows) {
Elements cols = row.select("td");
String title = cols.get(0).ownText().trim();
Element link = cols.get(1).selectFirst(HREFS);
String href = link.attr(Attribute.HREF.toString());
URL download = makeAbsURL(href);
String ftype = link.text().trim();
URL u = makeDistURL(makeHashId(title) + "/" + ftype);
IRI dist = store.getURI(u.toString());
logger.debug("Generating distribution {}", dist.toString());
store.add(dataset, DCAT.HAS_DISTRIBUTION, dist);
store.add(dist, RDF.TYPE, DCAT.DISTRIBUTION);
store.add(dist, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang));
store.add(dist, DCTERMS.TITLE, title, lang);
store.add(dist, DCAT.ACCESS_URL, access);
store.add(dist, DCAT.DOWNLOAD_URL, download);
store.add(dist, DCAT.MEDIA_TYPE, ftype.toLowerCase());
}
}
/**
* Generate DCAT Dataset
*
* @param store RDF store
* @param id dataset id
* @param page
* @throws MalformedURLException
* @throws RepositoryException
*/
@Override
protected void generateDataset(Storage store, String id, Map<String, Page> page)
throws MalformedURLException, RepositoryException {
String lang = getDefaultLang();
Page p = page.getOrDefault("", new Page());
String html = p.getContent();
URL u = p.getUrl();
Element content = Jsoup.parse(html).body();
IRI dataset = store.getURI(makeDatasetURL(makeHashId(id)).toString());
logger.debug("Generating dataset {}", dataset.toString());
Element h2 = content.select(H_TITLE).first();
if (h2 == null) {
logger.warn("Empty title, skipping");
return;
}
String title = h2.text().trim();
Element div = content.select(SECTION_P).first();
String desc = (div != null) ? div.text() : title;
store.add(dataset, RDF.TYPE, DCAT.DATASET);
store.add(dataset, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang));
store.add(dataset, DCTERMS.TITLE, title, lang);
store.add(dataset, DCTERMS.DESCRIPTION, desc, lang);
store.add(dataset, DCTERMS.IDENTIFIER, makeHashId(id));
store.add(dataset, DCAT.LANDING_PAGE, u);
Elements dist = content.select(DIST_ROW);
generateDist(store, dataset, u, dist, lang);
}
/**
* Generate DCAT.
*
* @param cache
* @param store
* @throws RepositoryException
* @throws MalformedURLException
*/
@Override | public void generateDcat(Cache cache, Storage store) | 0 |
D-3/BS808 | app/src/main/java/com/deew/bs808/MainActivity.java | [
"public class ClientConstants {\n\n public static final String PREF_FILE_NAME = \"client_preferences\";\n\n // Preference keys\n public static final String PREF_KEY_HOST = \"host\";\n public static final String PREF_KEY_PORT = \"port\";\n public static final String PREF_KEY_AUTH_CODE = \"auth_code\";\n\n // Preference defaults\n// public static final String PREF_DEFAULT_HOST = \"10.1.5.21\";\n// public static final int PREF_DEFAULT_PORT = 29930;\n\n public static final String PREF_DEFAULT_HOST = \"119.88.237.11\";\n public static final int PREF_DEFAULT_PORT = 11001;\n\n\n}",
"public interface ClientStateCallback {\n /**\n * callback when client connect to server\n */\n void connectSuccess();\n\n /**\n * callback when client connect to server\n */\n void connectFail();\n\n /**\n * callback when connection between client and server closed\n */\n void connectionClosed();\n\n /**\n * callback when client registered on server\n */\n void registerComplete(RegisterReply reply);\n\n /**\n * callback when client authenticated on server\n */\n void authComplete(ServerGenericReply reply);\n}",
"public class JT808Client implements ConnectionStateCallback{\n\n private static final String TAG = LogUtils.makeTag(JT808Client.class);\n\n private String mHost;\n private int mPort;\n\n private Connection mConnection;\n private ConnectionConfiguration mConnectionConfiguration;\n private ClientStateCallback mStateCallback;\n\n private boolean isAuthenticate = false;\n\n public JT808Client(){\n mConnection = new Connection();\n }\n\n /**\n * Connect to server\n *\n * @param host\n * @param port\n * @param stateCallback\n */\n public void connect(String host, int port, ClientStateCallback stateCallback){\n Log.d(TAG, \"connect: \" + host +\":\" + port );\n //TODO check params whether right or throw IllegalArgumentException\n mHost = host;\n mPort = port;\n\n mStateCallback = stateCallback;\n\n mConnectionConfiguration = new ConnectionConfiguration(mHost, mPort);\n if(mConnection == null){\n mConnection = new Connection();\n mConnection.setStateCallback(this);\n }\n mConnection.setConfig(mConnectionConfiguration);\n mConnection.connect();\n }\n\n public boolean isConnected(){\n return mConnection == null ? false : mConnection.isConnected();\n }\n\n public boolean isClosed(){\n return mConnection == null ? true : mConnection.isClosed();\n }\n\n /**\n * close connection and reset other members\n */\n public void close(){\n mConnection.close();\n mConnection = null;\n mConnectionConfiguration = null;\n mStateCallback = null;\n\n isAuthenticate = false;\n }\n\n /**\n * Send a message to the server.\n *\n * Be careful with that you must wait until the connection connected (using ConnectionStateCallback)\n * before calling this method to send a message\n *\n * @param message\n */\n public void sendMessage(Message message) throws IllegalAccessException{\n if(isAuthenticate){\n mConnection.sendMessage(message);\n }else{\n throw new IllegalAccessException(\"Can not send any message before authenticated\");\n }\n }\n\n @Override\n public void onSuccess() {\n if(mStateCallback != null){\n mStateCallback.connectSuccess();\n }\n }\n\n @Override\n public void onFail() {\n if(mStateCallback != null){\n mStateCallback.connectFail();\n }\n }\n\n public void registerClient(RegisterRequest registerRequest){\n Log.d(TAG, \"registerClient \" + registerRequest);\n mConnection.addRcvListener(mRegisterMsgListener, new MessageIdFilter(RegisterReply.ID));\n mConnection.sendMessage(registerRequest);\n }\n\n public void authenticate(String authCode){\n Log.d(TAG, \"authenticate \" + authCode);\n AuthenticateRequest request = new AuthenticateRequest.Builder(authCode).build();\n mConnection.addRcvListener(mAuthMsgListener, new MessageIdFilter(ServerGenericReply.ID));\n mConnection.sendMessage(request);\n }\n\n /** A message listener to process register reply. */\n private MessageListener mRegisterMsgListener = new MessageListener(){\n\n @Override\n public void processMessage(Message msg) {\n Log.d(TAG, \"processMessage: msg=\" + msg);\n// if (RegisterReply.ID == msg.getId()) {\n RegisterReply reply = new RegisterReply.Builder(msg).build();\n mConnection.removeRcvListener(mRegisterMsgListener);\n if(mStateCallback != null){\n mStateCallback.registerComplete(reply);\n }\n// }\n }\n\n };\n\n\n /** A message listener to process auth reply. */\n private MessageListener mAuthMsgListener = new MessageListener(){\n\n @Override\n public void processMessage(Message msg) {\n Log.d(TAG, \"processMessage: msg=\" + msg);\n// if(ServerGenericReply.ID == msg.getId()){\n ServerGenericReply reply = new ServerGenericReply.Builder(msg).build();\n mConnection.removeRcvListener(mAuthMsgListener);\n if(reply.getResult() == ServerGenericReply.RESULT_OK){\n isAuthenticate = true;\n }\n if(mStateCallback != null){\n mStateCallback.authComplete(reply);\n }\n// }\n }\n\n };\n\n\n\n}",
"public class AuthenticateRequest extends Message {\n\n private static final String TAG = LogUtils.makeTag(AuthenticateRequest.class);\n\n public static final short ID = 0x0102;\n\n private final String mAuthCode;\n\n private AuthenticateRequest(Builder builder) {\n super(ID, builder.cipher, builder.phone, builder.body);\n\n mAuthCode = builder.authCode;\n }\n\n @Override\n public String toString() {\n return new StringBuilder(\"{ id=0102\")\n .append(\", auth=\").append(mAuthCode)\n .append(\" }\").toString();\n }\n\n public static class Builder extends MessageBuilder {\n\n // Required parameters\n private final String authCode;\n\n public Builder(String auth) {\n if (auth == null) {\n throw new NullPointerException(\"Authentication code is null.\");\n }\n\n this.authCode = auth;\n }\n\n @Override\n public AuthenticateRequest build() {\n try {\n this.body = this.authCode.getBytes(\"GBK\");\n } catch (UnsupportedEncodingException uee) {\n Log.e(TAG, \"build: Encode message body failed.\", uee);\n }\n\n return new AuthenticateRequest(this);\n }\n\n }\n\n}",
"public class LocationMessage extends Message {\n\n private static final String TAG = LogUtils.makeTag(LocationMessage.class);\n\n public static final short ID = 0x0200;\n\n private int alarm;\n private int state;\n private double longitude;\n private double latitude;\n private int altitude;\n private short speed;\n private short direction;\n private long timestamp;\n\n private boolean emergency = false;\n private boolean overspeed = false;\n private boolean fatigued = false;\n private boolean danger = false;\n private boolean GNSS_model_broken = false;\n private boolean GNSS_antenna_loss = false;\n private boolean GNSS_antenna_short = false;\n private boolean low_power = false;\n private boolean power_off = false;\n\n// private final byte[] alarmBytes;\n// private final byte[] stateBytes;\n// private final byte[] longitudeBytes;\n// private final byte[] latitudeBytes;\n// private final byte[] altitudeBytes;\n// private final byte[] speedBytes;\n// private final byte[] directionBytes;\n// private final byte[] timestampBytes;\n\n private static final int MASK_EMERGENCY_ALARM = 0x00000001;\n private static final int MASK_OVERSPEED_ALARM = 0x00000002;\n private static final int MASK_FATIGUED_ALARM = 0x00000004;\n private static final int MASK_DANGER_ALARM = 0x00000008;\n private static final int MASK_GNSS_MODEL_BROKEN_ALARM = 0x00000010;\n private static final int MASK_GNSS_ANTENNA_LOSS_ALARM = 0x00000020;\n private static final int MASK_GNSS_ANTENNA_SHORT_ALARM = 0x00000040;\n private static final int MASK_LOW_POWER_ALARM = 0x00000080;\n private static final int MASK_POWER_OFF_ALARM = 0x00000100;\n //\n //\n\n private LocationMessage(Builder builder) {\n super(ID, builder.cipher, builder.phone, builder.body);\n// this.alarmBytes = builder.alarmBytes;\n// this.stateBytes = builder.stateBytes;\n// this.longitudeBytes = builder.longitudeBytes;\n// this.latitudeBytes = builder.latitudeBytes;\n// this.altitudeBytes = builder.altitudeBytes;\n// this.speedBytes = builder.speedBytes;\n// this.directionBytes = builder.directionBytes;\n// this.timestampBytes = builder.timestampBytes;\n\n this.alarm = builder.alarm;\n this.state = builder.state;\n this.longitude = builder.longitude;\n this.latitude = builder.latitude;\n this.altitude = builder.altitude;\n this.speed = builder.speed;\n this.direction = builder.direction;\n this.timestamp = builder.timestamp;\n this.emergency = builder.emergency;\n this.overspeed = builder.overspeed;\n this.fatigued = builder.fatigued;\n this.danger = builder.danger;\n this.GNSS_model_broken = builder.GNSS_model_broken;\n this.GNSS_antenna_loss = builder.GNSS_antenna_loss;\n this.GNSS_antenna_short = builder.GNSS_antenna_short;\n this.low_power = builder.low_power;\n this.power_off = builder.power_off;\n }\n\n public static class Builder extends MessageBuilder {\n\n private int alarm = 0;\n private int state = 0;\n private double longitude = 0;\n private double latitude = 0;\n private int altitude = 0;\n private short speed = 0;\n private short direction = 0;\n private long timestamp = 0;\n\n private boolean emergency = false;\n private boolean overspeed = false;\n private boolean fatigued = false;\n private boolean danger = false;\n private boolean GNSS_model_broken = false;\n private boolean GNSS_antenna_loss = false;\n private boolean GNSS_antenna_short = false;\n private boolean low_power = false;\n private boolean power_off = false;\n\n// private byte[] alarmBytes;\n// private byte[] stateBytes;\n// private byte[] longitudeBytes;\n// private byte[] latitudeBytes;\n// private byte[] altitudeBytes;\n// private byte[] speedBytes;\n// private byte[] directionBytes;\n// private byte[] timestampBytes = new byte[6];\n\n public void setEmergency(boolean isEmergency) {\n this.emergency = isEmergency;\n if(emergency) alarm = alarm | MASK_EMERGENCY_ALARM;\n }\n\n public void setOverspeed(boolean isOverspeed) {\n this.overspeed = isOverspeed;\n if(overspeed) alarm = alarm | MASK_OVERSPEED_ALARM;\n }\n\n public void setFatigued(boolean isFatigued) {\n this.fatigued = isFatigued;\n if(fatigued) alarm = alarm | MASK_FATIGUED_ALARM;\n }\n\n public void setDanger(boolean isDanger) {\n this.danger = isDanger;\n if(danger) alarm = alarm | MASK_DANGER_ALARM;\n }\n\n public void setGNSSModelBroken(boolean isGNSSModelBroken) {\n this.GNSS_model_broken = isGNSSModelBroken;\n if(GNSS_model_broken) alarm = alarm | MASK_GNSS_MODEL_BROKEN_ALARM;\n }\n\n public void setGNSSAntennaLoss(boolean isGNSSAntennaLoss) {\n this.GNSS_antenna_loss = isGNSSAntennaLoss;\n if(GNSS_antenna_loss) alarm = alarm | MASK_GNSS_ANTENNA_LOSS_ALARM;\n }\n\n public void setGNSSAntennaShort(boolean isGNSSAntennaShort) {\n this.GNSS_antenna_short = isGNSSAntennaShort;\n if(GNSS_antenna_short) alarm = alarm | MASK_GNSS_ANTENNA_SHORT_ALARM;\n }\n\n public void setLowPower(boolean isLowPower) {\n this.low_power = isLowPower;\n if(low_power) alarm = alarm | MASK_LOW_POWER_ALARM;\n }\n\n public void setPowerOff(boolean isPowerOff) {\n this.power_off = isPowerOff;\n if(power_off) alarm = alarm | MASK_POWER_OFF_ALARM;\n }\n\n public Builder setSpeed(short speed) {\n this.speed = speed;\n return this;\n }\n\n public Builder setDirection(short direction) {\n this.direction = direction;\n return this;\n }\n\n public Builder setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n return this;\n }\n\n public Builder setLongitude(double longitude) {\n this.longitude = longitude;\n return this;\n }\n\n public Builder setLatitude(double latitude) {\n this.latitude = latitude;\n return this;\n }\n\n public Builder setAltitude(int altitude) {\n this.altitude = altitude;\n return this;\n }\n\n @Override\n public LocationMessage build() {\n// this.alarmBytes = IntegerUtils.asBytes(alarm);\n// this.stateBytes = IntegerUtils.asBytes(state);\n// this.longitudeBytes = IntegerUtils.asBytes(longitude);\n// this.latitudeBytes = IntegerUtils.asBytes(latitude);\n// this.altitudeBytes = IntegerUtils.asBytes(altitude);\n// this.stateBytes = IntegerUtils.asBytes(speed);\n// this.directionBytes = IntegerUtils.asBytes(direction);\n// this.timestampBytes = IntegerUtils.toBcd(timestamp);\n\n\n this.body = ArrayUtils.concatenate(\n IntegerUtils.asBytes(alarm),\n IntegerUtils.asBytes(state),\n IntegerUtils.asBytes((int)(longitude*1E6)),\n IntegerUtils.asBytes((int)(latitude*1E6)),\n IntegerUtils.asBytes(altitude),\n IntegerUtils.asBytes(speed),\n IntegerUtils.asBytes(direction),\n IntegerUtils.toBcd(timestamp));\n\n return new LocationMessage(this);\n }\n }\n}",
"public class RegisterReply extends Message {\n\n private static final String TAG = LogUtils.makeTag(RegisterReply.class);\n\n public static final short ID = (short) 0x8100;\n\n public static final byte RESULT_OK = 0;\n public static final byte RESULT_VEH_REGISTERED = 1;\n public static final byte RESULT_VEH_NOT_FOUND = 2;\n public static final byte RESULT_CLT_REGISTERED = 3;\n public static final byte RESULT_CLT_NOT_FOUND = 4;\n\n private final short mReqSn;\n private final byte mResult;\n private final String mAuthCode;\n\n private RegisterReply(Builder builder) {\n super(ID, builder.cipher, builder.phone, builder.body);\n\n mReqSn = builder.reqSn;\n mResult = builder.result;\n mAuthCode = builder.authCode;\n }\n\n public short getReqSn() {\n return mReqSn;\n }\n\n public byte getResult() {\n return mResult;\n }\n\n public String getAuthCode() {\n return mAuthCode;\n }\n\n @Override\n public String toString() {\n return new StringBuilder(\"{ id=8100\")\n .append(\", reqSn=\").append(mReqSn)\n .append(\", result=\").append(mResult)\n .append(\", auth=\").append(mAuthCode)\n .append(\" }\").toString();\n }\n\n public static class Builder extends MessageBuilder {\n\n // Required parameters\n private final short reqSn;\n private final byte result;\n\n // Optional parameters - initialized to default values\n private String authCode = null;\n\n public Builder(Message msg) {\n if (msg == null) {\n throw new NullPointerException(\"Message is null.\");\n }\n if (ID != msg.getId()) {\n throw new IllegalArgumentException(\"Wrong message ID.\");\n }\n if (msg.getBody().length < 3) {\n throw new IllegalArgumentException(\"Message body incomplete.\");\n }\n\n this.cipher = msg.getCipher();\n this.phone = msg.getPhone();\n this.body = msg.getBody();\n\n this.reqSn = IntegerUtils.parseShort(Arrays.copyOf(this.body, 2));\n\n switch (this.body[2]) {\n case RESULT_OK:\n if (this.body.length < 4) {\n throw new IllegalArgumentException(\"Authentication code missing.\");\n }\n try {\n this.authCode = new String(Arrays.copyOfRange(this.body, 3, this.body.length), \"ascii\");\n } catch (UnsupportedEncodingException uee) {\n Log.e(TAG, \"Builder: Encode authentication code failed.\", uee);\n }\n case RESULT_VEH_REGISTERED:\n case RESULT_VEH_NOT_FOUND:\n case RESULT_CLT_REGISTERED:\n case RESULT_CLT_NOT_FOUND:\n this.result = this.body[2];\n break;\n default:\n throw new IllegalArgumentException(\"Unknown result.\");\n }\n }\n\n @Override\n public RegisterReply build() {\n return new RegisterReply(this);\n }\n\n }\n\n}",
"public class RegisterRequest extends Message {\n\n private static final String TAG = LogUtils.makeTag(RegisterRequest.class);\n\n public static final short ID = 0x0100;\n\n private static final byte[] EMPTY_MFRS_ID = new byte[5];\n private static final byte[] EMPTY_CLT_MODEL = new byte[20];\n private static final byte[] EMPTY_CLT_ID = new byte[7];\n private static final String EMPTY_PLATE_TEXT = \"\";\n\n private final short mProvId; //WORD\n private final short mCityId; //WORD\n private final byte[] mMfrsId; //BYTE[5]\n private final byte[] mCltModel; //BYTE[20]\n private final byte[] mCltId; //BYTE[7]\n private final byte mPlateColor; //BYTE\n private final String mPlateText; //STRING\n\n private RegisterRequest(Builder builder) {\n super(ID, builder.cipher, builder.phone, builder.body);\n\n mProvId = builder.provId;\n mCityId = builder.cityId;\n mMfrsId = builder.mfrsId;\n mCltModel = builder.cltModel;\n mCltId = builder.cltId;\n mPlateColor = builder.plateColor;\n mPlateText = builder.plateText;\n }\n\n @Override\n public String toString() {\n return new StringBuilder(\"{ id=0100\")\n .append(\", prov=\").append(mProvId)\n .append(\", city=\").append(mCityId)\n .append(\", mfrs=\").append(Arrays.toString(mMfrsId))\n .append(\", model=\").append(Arrays.toString(mCltModel))\n .append(\", cltId=\").append(Arrays.toString(mCltId))\n .append(\", pClr=\").append(mPlateColor)\n .append(\", pTxt=\").append(mPlateText)\n .append(\" }\").toString();\n }\n\n public static class Builder extends MessageBuilder {\n\n // Optional parameters - initialized to default values\n private short provId = 0;\n private short cityId = 0;\n private byte[] mfrsId = EMPTY_MFRS_ID;\n private byte[] cltModel = EMPTY_CLT_MODEL;\n private byte[] cltId = EMPTY_CLT_ID;\n private byte plateColor = Jtt415Constants.PLATE_COLOR_TEST;\n private String plateText = EMPTY_PLATE_TEXT;\n\n public Builder provId(short id) {\n this.provId = id;\n return this;\n }\n\n public Builder cityId(short id) {\n this.cityId = id;\n return this;\n }\n\n public Builder mfrsId(byte[] id) {\n if (id != null && id.length == 5) {\n this.mfrsId = id;\n } else {\n Log.w(TAG, \"mfrsId: Illegal manufacturer ID, use default.\");\n }\n\n return this;\n }\n\n public Builder cltModel(byte[] model) {\n if (model != null && model.length == 20) {\n this.cltModel = model;\n } else {\n Log.w(TAG, \"cltModel: Illegal client model, use default.\");\n }\n\n return this;\n }\n\n public Builder cltId(byte[] id) {\n if (id != null && id.length == 7) {\n this.cltId = id;\n } else {\n Log.w(TAG, \"cltId: Illegal client ID, use default.\");\n }\n\n return this;\n }\n\n public Builder plateColor(byte color) {\n switch (color) {\n case Jtt415Constants.PLATE_COLOR_NONE:\n case Jtt415Constants.PLATE_COLOR_BLUE:\n case Jtt415Constants.PLATE_COLOR_YELLOW:\n case Jtt415Constants.PLATE_COLOR_BLACK:\n case Jtt415Constants.PLATE_COLOR_WHITE:\n case Jtt415Constants.PLATE_COLOR_TEST:\n this.plateColor = color;\n break;\n default:\n Log.w(TAG, \"plateColor: Unknown plate color, use default.\");\n }\n\n return this;\n }\n\n public Builder plateText(String text) {\n if (text != null) {\n this.plateText = text;\n } else {\n Log.w(TAG, \"plateText: Plate text is null, use default.\");\n }\n\n return this;\n }\n\n @Override\n public RegisterRequest build() {\n try {\n this.body = ArrayUtils.concatenate(IntegerUtils.asBytes(this.provId),\n IntegerUtils.asBytes(this.cityId),\n this.mfrsId,\n this.cltModel,\n this.cltId,\n IntegerUtils.asBytes(this.plateColor),\n this.plateText.getBytes(\"GBK\"));\n } catch (UnsupportedEncodingException uee) {\n Log.e(TAG, \"build: Encode message body failed.\", uee);\n }\n\n return new RegisterRequest(this);\n }\n\n }\n\n}",
"public class ServerGenericReply extends Message {\n\n private static final String TAG = LogUtils.makeTag(ServerGenericReply.class);\n\n public static final short ID = (short) 0x8001;\n\n public static final byte RESULT_OK = 0;\n public static final byte RESULT_FAIL = 1;\n public static final byte RESULT_BAD_REQUEST = 2;\n public static final byte RESULT_UNSUPPORTED = 3;\n public static final byte RESULT_CONFIRM = 4;\n\n private final short mReqSn;\n private final short mReqId;\n private final byte mResult;\n\n private ServerGenericReply(Builder builder) {\n super(ID, builder.cipher, builder.phone, builder.body);\n\n mReqSn = builder.reqSn;\n mReqId = builder.reqId;\n mResult = builder.result;\n }\n\n public short getReqSn() {\n return mReqSn;\n }\n\n public short getReqId() {\n return mReqId;\n }\n\n public byte getResult() {\n return mResult;\n }\n\n @Override\n public String toString() {\n return new StringBuilder(\"{ id=8001\")\n .append(\", reqSn=\").append(mReqSn)\n .append(\", reqId=\").append(mReqId)\n .append(\", result=\").append(mResult)\n .append(\" }\").toString();\n }\n\n public static class Builder extends MessageBuilder {\n\n // Required parameters\n private final short reqSn;\n private final short reqId;\n private final byte result;\n\n public Builder(Message msg) {\n if (msg == null) {\n throw new NullPointerException(\"Message is null.\");\n }\n if (ID != msg.getId()) {\n throw new IllegalArgumentException(\"Wrong message ID.\");\n }\n\n this.cipher = msg.getCipher();\n this.phone = msg.getPhone();\n this.body = msg.getBody();\n if (this.body.length != 5) {\n throw new IllegalArgumentException(\"Message body incorrect.\");\n }\n\n this.reqSn = IntegerUtils.parseShort(Arrays.copyOfRange(this.body, 0, 2));\n this.reqId = IntegerUtils.parseShort(Arrays.copyOfRange(this.body, 2, 4));\n\n switch (this.body[4]) {\n case RESULT_OK:\n case RESULT_FAIL:\n case RESULT_BAD_REQUEST:\n case RESULT_UNSUPPORTED:\n case RESULT_CONFIRM:\n this.result = this.body[4];\n break;\n default:\n throw new IllegalArgumentException(\"Unknown result.\");\n }\n }\n\n @Override\n public ServerGenericReply build() {\n return new ServerGenericReply(this);\n }\n\n }\n\n}",
"public class LogUtils {\n\n @SuppressWarnings(\"unchecked\")\n public static String makeTag(Class cls) {\n return \"JT808_\" + cls.getSimpleName();\n }\n\n}"
] | import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.deew.jt808.ClientConstants;
import com.deew.jt808.ClientStateCallback;
import com.deew.jt808.JT808Client;
import com.deew.jt808.msg.AuthenticateRequest;
import com.deew.jt808.msg.LocationMessage;
import com.deew.jt808.msg.RegisterReply;
import com.deew.jt808.msg.RegisterRequest;
import com.deew.jt808.msg.ServerGenericReply;
import com.deew.jt808.util.LogUtils;
import java.util.Timer;
import java.util.TimerTask; | package com.deew.bs808;
public class MainActivity extends AppCompatActivity implements ClientStateCallback, View.OnClickListener{
private static final String TAG = LogUtils.makeTag(MainActivity.class);
private SharedPreferences mPrefs;
private String mHost;
private int mPort;
private String mAuthCode;
private JT808Client mJT808Client;
private RegisterRequest.Builder mRegisterReqBuilder;
private AuthenticateRequest.Builder mAuthReqBuilder;
private LocationMessage.Builder mLocationMessageBuilder;
private Timer mTimer;
private Button mBtnRegister;
private Button mBtnAuth;
private Button mBtnLocation;
private Button mBtnClose;
private Button mBtnConnect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnRegister = (Button) findViewById(R.id.btn_regsiter);
mBtnRegister.setOnClickListener(this);
mBtnAuth = (Button) findViewById(R.id.btn_auth);
mBtnAuth.setOnClickListener(this);
mBtnLocation = (Button) findViewById(R.id.btn_location);
mBtnLocation.setOnClickListener(this);
mBtnClose = (Button) findViewById(R.id.btn_close);
mBtnClose.setOnClickListener(this);
mBtnConnect = (Button) findViewById(R.id.btn_connect);
mBtnConnect.setOnClickListener(this);
mPrefs = getSharedPreferences(ClientConstants.PREF_FILE_NAME, MODE_PRIVATE);
mHost = mPrefs.getString(ClientConstants.PREF_KEY_HOST, ClientConstants.PREF_DEFAULT_HOST);
mPort = mPrefs.getInt(ClientConstants.PREF_KEY_PORT, ClientConstants.PREF_DEFAULT_PORT);
mAuthCode = mPrefs.getString(ClientConstants.PREF_KEY_AUTH_CODE, null);
mRegisterReqBuilder = new RegisterRequest.Builder();
mLocationMessageBuilder = new LocationMessage.Builder();
mJT808Client = new JT808Client();
}
@Override
protected void onDestroy() {
super.onDestroy();
mJT808Client.close();
mJT808Client = null;
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_regsiter:
if(mJT808Client != null && mJT808Client.isConnected()){
registerClient();
}
break;
case R.id.btn_auth:
if(mJT808Client != null && mJT808Client.isConnected()){
authenticate(mAuthCode);
}
break;
case R.id.btn_location:
if(mJT808Client != null && mJT808Client.isConnected()){
sendLocation();
}
break;
case R.id.btn_close:
if (mJT808Client != null && mJT808Client.isConnected()){
mJT808Client.close();
}
break;
case R.id.btn_connect:
if (mJT808Client != null){
connectToServer(mHost, mPort);
}
break;
}
}
private void connectToServer(String host, int port){
mJT808Client.connect(host, port, this);
}
private void registerClient(){
RegisterRequest request = new RegisterRequest.Builder().build();
mJT808Client.registerClient(request);
}
private void authenticate(String authCode){
if(authCode == null){
Toast.makeText(this, "鉴权码为空", Toast.LENGTH_SHORT).show();
return;
}
mJT808Client.authenticate(mAuthCode);
}
@Override
public void connectSuccess() {
Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show();
if(mAuthCode == null){
registerClient();
}else{
authenticate(mAuthCode);
}
}
@Override
public void connectFail() {
Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show();
}
@Override
public void connectionClosed() {
Toast.makeText(this, "已关闭连接", Toast.LENGTH_SHORT).show();
}
@Override | public void registerComplete(RegisterReply reply) { | 5 |
Catalysts/cat-boot | cat-boot-report-pdf/src/main/java/cc/catalysts/boot/report/pdf/PdfReportBuilder.java | [
"public class PdfPageLayout {\n\n private float width;\n private float height;\n private float marginLeft;\n private float marginRight;\n private float marginTop;\n private float marginBottom;\n private float lineDistance;\n private float header;\n private float footer;\n private PositionOfStaticElements footerPosition;\n private PositionOfStaticElements headerPosition;\n\n public static PdfPageLayout getPortraitA4Page() {\n return new PdfPageLayout(595.27563F, 841.8898F, 28.346457F, 10, 100, 20, 1);\n }\n\n public static PdfPageLayout getPortraitA4PageWithSmallTopMargin() {\n return new PdfPageLayout(595.27563F, 841.8898F, 28.346457F, 10, 20, 20, 1);\n }\n\n public static PdfPageLayout getPortraitA4PageWithDoubleMargins() {\n return new PdfPageLayout(595.27563F, 841.8898F, 56.6929F, 56.6929F, 100, 20, 1);\n }\n\n public static PdfPageLayout getLandscapeA4Page() {\n return new PdfPageLayout(841.8898F, 595.27563F, 28.346457F, 10, 100, 20, 1);\n }\n\n public static PdfPageLayout getLandscapeA4PageWithSmallTopMargin() {\n return new PdfPageLayout(841.8898F, 595.27563F, 28.346457F, 10, 20, 20, 1);\n }\n\n public PdfPageLayout(float width, float height, float marginLeft, float marginRight, float marginTop, float marginBottom, float lineDistance) {\n this.width = width;\n this.height = height;\n this.marginLeft = marginLeft;\n this.marginRight = marginRight;\n this.marginTop = marginTop;\n this.marginBottom = marginBottom;\n this.lineDistance = lineDistance;\n }\n\n public float getWidth() {\n return width;\n }\n\n public float getHeight() {\n return height;\n }\n\n public float getMarginLeft() {\n return marginLeft;\n }\n\n public float getMarginRight() {\n return marginRight;\n }\n\n public float getMarginTop() {\n return marginTop;\n }\n\n public float getMarginBottom() {\n return marginBottom;\n }\n\n public float getLineDistance() {\n return lineDistance;\n }\n\n public void setMarginLeft(float marginLeft) {\n this.marginLeft = marginLeft;\n }\n\n public void setMarginRight(float marginRight) {\n this.marginRight = marginRight;\n }\n\n public void setMarginTop(float marginTop) {\n this.marginTop = marginTop;\n }\n\n public void setMarginBottom(float marginBottom) {\n this.marginBottom = marginBottom;\n }\n\n public void setLineDistance(float lineDistance) {\n this.lineDistance = lineDistance;\n }\n\n public PositionOfStaticElements getFooterPosition() {\n return footerPosition;\n }\n\n public void setFooterPosition(PositionOfStaticElements footerPosition) {\n this.footerPosition = footerPosition;\n }\n\n public PositionOfStaticElements getHeaderPosition() {\n return headerPosition;\n }\n\n public void setHeaderPosition(PositionOfStaticElements headerPosition) {\n this.headerPosition = headerPosition;\n }\n\n public void setFooter(float footerSize) {\n this.footer = footerSize;\n }\n\n public void setHeader(float headerSize) {\n this.header = headerSize;\n }\n\n public float getUsableWidth() {\n return width - marginLeft - marginRight;\n }\n\n public float getUsableHeight(int pageNo) {\n return getStartY(pageNo) - getLastY(pageNo);\n }\n\n public PDRectangle getPageSize() {\n return new PDRectangle(width, height);\n }\n\n public float getStartY() {\n return height - marginTop - header;\n }\n\n public float getStartY(int pageNo) {\n return pageNo == 0 && headerPosition == PositionOfStaticElements.ON_ALL_PAGES_BUT_FIRST ? height - marginTop : getStartY();\n }\n\n public float getStartX() {\n return marginLeft;\n }\n\n public float getLastY() {\n return marginBottom + footer;\n }\n\n public float getLastY(int pageNo) {\n return pageNo == 0 && footerPosition == PositionOfStaticElements.ON_ALL_PAGES_BUT_FIRST ? marginBottom : getLastY();\n }\n\n public float getLastX() {\n return width - marginRight;\n }\n}",
"public class PdfTextStyle {\n\n\n private float fontSize;\n private PdfFont font;\n private PDColor color;\n private String style;\n\n public PdfTextStyle(float fontSize, PdfFont defaultFont, PDColor color, String style) {\n this.fontSize = fontSize;\n this.font = defaultFont;\n this.color = color;\n this.style = style;\n }\n\n /**\n * This constructor is used by spring when creating a font from properties.\n *\n * @param config e.g. 10,Times-Roman,#000000\n */\n public PdfTextStyle(String config) {\n Assert.hasText(config);\n String[] split = config.split(\",\");\n Assert.isTrue(split.length == 3, \"config must look like: 10,Times-Roman,#000000\");\n fontSize = Float.parseFloat(split[0]);\n font = PdfFont.getFont(split[1]);\n Color tempColor = new Color(Integer.valueOf(split[2].substring(1), 16));\n float[] components = {tempColor.getRed(), tempColor.getGreen(), tempColor.getBlue()};\n color = new PDColor(components, PDDeviceRGB.INSTANCE);\n }\n\n public float getFontSize() {\n return fontSize;\n }\n\n public PdfFont getFont() {\n return font;\n }\n\n public PDColor getColor() {\n return color;\n }\n\n public PDFont getCurrentFontStyle() {\n return font.getStyle(style);\n }\n\n public String getStyle() {\n return style;\n }\n\n public void setStyle(String style) {\n this.style = style;\n }\n}",
"public interface ReportElement {\n\n /**\n * @param document PdfBox document\n * @param stream PdfBox stream\n * @param pageNumber current page number (0 based)\n * @param startX starting x\n * @param startY starting y\n * @param allowedWidth maximal width of segment\n * @return the Y position of the next line\n * @throws java.io.IOException in case something happens during printing\n */\n float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException;\n\n /**\n * Height of this segment\n *\n * @param allowedWidth allowed with of the segment\n * @return height of the segment\n */\n float getHeight(float allowedWidth);\n\n /**\n * In case the element may be split over pages, this method should return true\n *\n * @return may the element be split over multiple pages\n */\n boolean isSplitable();\n\n /**\n * in case isSplitable is true, this method will be called.\n *\n * @param allowedWidth the maximum allowed width for this element\n * @return the height of the first nonSplitable segment\n */\n float getFirstSegmentHeight(float allowedWidth);\n\n /**\n * If the element my be split this method should return two elements. The first unsplitable elements, and the rest.\n * The second arrays element may be null\n *\n * @param allowedWidth allowed with of the segment\n * @return Arrays with <b>two</b> report elements\n */\n ReportElement[] split(float allowedWidth);\n\n /**\n * Will split the report element, so the height of the first segment will the maximum value less or equal to the allowed height value.\n *\n * @param allowedWidth width of report element\n * @param allowedHeight max height of first segment.\n * @return two report elements\n */\n ReportElement[] split(float allowedWidth, float allowedHeight);\n\n /**\n * For splittable elements returns the current height of the element that needs to be split.\n *\n * @param allowedWidth width of report element\n * @param allowedHeight max height of first segment.\n */\n float getHeightOfElementToSplit(float allowedWidth, float allowedHeight);\n\n /**\n * Returns all the images that should have been printed by this element\n *\n * @return collection, can't be null, migth be empty\n */\n Collection<ReportImage.ImagePrintIntent> getImageIntents();\n\n}",
"public class PdfFontContext implements AutoCloseable {\n\n private static ThreadLocal<PdfFontContext> pdfFontContexts = new ThreadLocal<>();\n\n /**\n * Fonts currently loaded.\n */\n private Map<String, PdfFont> type0Fonts = new HashMap<>();\n\n /**\n * Fallback fonts to use when a target font doesn't support a given glyph.\n */\n private List<PDFont> fallbackFonts = new ArrayList();\n\n private PdfFontEncodingExceptionHandler fontEncodingExceptionHandler = null;\n\n public static PdfFontContext create() {\n final PdfFontContext oldContext = current();\n if (oldContext != null) {\n oldContext.close();\n }\n\n PdfFontContext context = new PdfFontContext();\n pdfFontContexts.set(context);\n return context;\n }\n\n /**\n * Gets the currently set stylesheet from the context or null if none set\n */\n public static PdfFontContext current() {\n return pdfFontContexts.get();\n }\n\n public static PdfFontContext currentOrCreate() {\n final PdfFontContext current = current();\n if (current == null) {\n return create();\n }\n return current;\n }\n\n private PdfFontContext() {\n }\n\n public PdfFont getFont(String fontName) {\n return type0Fonts.get(fontName);\n }\n\n public Collection<String> getAllFontNames() {\n return type0Fonts.keySet();\n }\n\n /**\n * Finds a font (PDFont not PdfFont wrapper) by name or returns null if not found.\n */\n public PDFont getInternalFont(String name) {\n return type0Fonts.values()\n .stream()\n .map(it -> it.getStyleByFontName(name))\n .filter(Objects::nonNull)\n .findFirst()\n .orElseGet(() -> PdfFont.getInternalFont(name));\n }\n\n public PdfFont registerFont(PDType0Font font) {\n String fontBaseName = font.getName();\n String fontStyle = \"regular\";\n\n if (font.getDescendantFont() instanceof PDCIDFontType2) {\n PDCIDFontType2 tmpFont = (PDCIDFontType2) font.getDescendantFont();\n NamingTable ttfNamingTable = (NamingTable) tmpFont.getTrueTypeFont().getTableMap().get(\"name\");\n\n fontBaseName = ttfNamingTable.getFontFamily();\n fontStyle = ttfNamingTable.getFontSubFamily().toLowerCase();\n }\n\n PdfFont f;\n if (type0Fonts.containsKey(fontBaseName)) {\n f = type0Fonts.get(fontBaseName);\n f.addStyle(fontStyle, font);\n } else {\n f = new PdfFont(fontBaseName);\n f.addStyle(fontStyle, font);\n type0Fonts.put(fontBaseName, f);\n }\n\n return f;\n }\n\n /**\n * Set global fallback fonts.\n */\n public void setFallbackFonts(List<PDFont> fallbacks) {\n if (fallbacks.stream().anyMatch(it -> it == null)) {\n throw new IllegalArgumentException(\"Must not pass null fonts.\");\n }\n this.fallbackFonts.clear();\n this.fallbackFonts.addAll(fallbacks);\n }\n\n public List<PDFont> getPossibleFonts(PDFont font) {\n List<PDFont> fonts = new ArrayList();\n fonts.add(font);\n fonts.addAll(fallbackFonts);\n return fonts;\n }\n\n /**\n * Register a custom font encoding exception handler which gives the program a chance to either\n * replace the problematic codepoints or simply log/throw custom exceptions.\n */\n public void registerFontEncodingExceptionHandler(PdfFontEncodingExceptionHandler handler) {\n this.fontEncodingExceptionHandler = handler;\n }\n\n public String handleFontEncodingException(String text, String codePointString, int start, int end) {\n if (this.fontEncodingExceptionHandler != null) {\n return this.fontEncodingExceptionHandler.handleFontEncodingException(text, codePointString, start, end);\n }\n throw new PdfBoxHelperException(\"Cannot encode '\" + codePointString + \"' in '\" + text + \"'.\");\n }\n\n\n @Override\n public void close() {\n type0Fonts.clear();\n\n pdfFontContexts.remove();\n }\n\n}",
"public enum PositionOfStaticElements {\n ON_ALL_PAGES, ON_ALL_PAGES_BUT_FIRST, ON_ALL_PAGES_BUT_LAST\n}"
] | import cc.catalysts.boot.report.pdf.config.PdfPageLayout;
import cc.catalysts.boot.report.pdf.config.PdfTextStyle;
import cc.catalysts.boot.report.pdf.elements.ReportElement;
import cc.catalysts.boot.report.pdf.utils.PdfFontContext;
import cc.catalysts.boot.report.pdf.utils.PositionOfStaticElements;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.core.io.Resource;
import java.io.IOException; | package cc.catalysts.boot.report.pdf;
/**
* @author Klaus Lehner
*/
public interface PdfReportBuilder {
PdfReportBuilder addElement(ReportElement element);
PdfReportBuilder addHeading(String heading);
PdfReportBuilder addImage(Resource resource, float width, float height) throws IOException;
PdfReportBuilder addImageWithMaxSize(Resource resource, float width, float height) throws IOException;
PdfReportBuilder addLink(String text, String link);
PdfReportBuilder addPadding(float padding);
PdfReportBuilder addText(String text);
PdfReportBuilder addText(String text, PdfTextStyle textConfig);
PdfReportBuilder beginNewSection(String title, boolean startNewPage);
| PdfReport buildReport(String fileName, PdfPageLayout pageConfig, Resource templateResource) throws IOException; | 0 |
MinecraftForge/Srg2Source | src/test/java/net/minecraftforge/srg2source/test/SimpleTestBase.java | [
"public class RangeApplierBuilder {\n private PrintStream logStd = System.out;\n private PrintStream logErr = System.err;\n private List<InputSupplier> inputs = new ArrayList<>();\n private OutputSupplier output = null;\n private Consumer<RangeApplier> range = null;\n private List<Consumer<RangeApplier>> srgs = new ArrayList<>();\n private List<Consumer<RangeApplier>> excs = new ArrayList<>();\n private boolean keepImports = false;\n private boolean guessLambdas = false;\n private boolean guessLocals = false;\n private boolean sortImports = false;\n\n public RangeApplierBuilder logger(PrintStream value) {\n this.logStd = value;\n return this;\n }\n\n public RangeApplierBuilder errorLogger(PrintStream value) {\n this.logErr = value;\n return this;\n }\n\n public RangeApplierBuilder output(Path value) {\n try {\n if (Files.isDirectory(value))\n this.output = FolderSupplier.create(value, null);\n else\n this.output = new ZipOutputSupplier(value);\n } catch (IOException e) {\n throw new IllegalArgumentException(\"Invalid output: \" + value, e);\n }\n return this;\n }\n\n public RangeApplierBuilder srg(Path value) {\n this.srgs.add(a -> a.readSrg(value));\n return this;\n }\n\n\n public RangeApplierBuilder exc(Path value) {\n this.excs.add(a -> a.readExc(value));\n return this;\n }\n\n public RangeApplierBuilder input(Path value) {\n return input(value, StandardCharsets.UTF_8);\n }\n\n public RangeApplierBuilder guessLambdas() {\n return guessLambdas(true);\n }\n\n public RangeApplierBuilder guessLambdas(boolean value) {\n this.guessLambdas = value;\n return this;\n }\n\n public RangeApplierBuilder guessLocals() {\n return guessLocals(true);\n }\n\n public RangeApplierBuilder guessLocals(boolean value) {\n this.guessLocals = value;\n return this;\n }\n\n public RangeApplierBuilder sortImports() {\n return sortImports(true);\n }\n\n public RangeApplierBuilder sortImports(boolean value) {\n this.sortImports = value;\n return this;\n }\n\n @SuppressWarnings(\"resource\")\n public RangeApplierBuilder input(Path value, Charset encoding) {\n if (value == null || !Files.exists(value))\n throw new IllegalArgumentException(\"Invalid input value: \" + value);\n\n String filename = value.getFileName().toString().toLowerCase(Locale.ENGLISH);\n try {\n if (Files.isDirectory(value))\n inputs.add(FolderSupplier.create(value, encoding));\n else if (filename.endsWith(\".jar\") || filename.endsWith(\".zip\")) {\n inputs.add(ZipInputSupplier.create(value, encoding));\n } else\n throw new IllegalArgumentException(\"Invalid input value: \" + value);\n } catch (IOException e) {\n throw new IllegalArgumentException(\"Invalid input: \" + value, e);\n }\n\n return this;\n }\n\n public RangeApplierBuilder input(InputSupplier value) {\n this.inputs.add(value);\n return this;\n }\n\n public RangeApplierBuilder range(File value) {\n this.range = a -> a.readRangeMap(value);\n return this;\n }\n\n public RangeApplierBuilder range(Path value) {\n this.range = a -> a.readRangeMap(value);\n return this;\n }\n\n public RangeApplierBuilder trimImports() {\n this.keepImports = false;\n return this;\n }\n\n public RangeApplierBuilder keepImports() {\n this.keepImports = true;\n return this;\n }\n\n public RangeApplier build() {\n if (output == null)\n throw new IllegalStateException(\"Builder State Exception: Missing Output\");\n if (range == null)\n throw new IllegalArgumentException(\"Builder State Exception: Missing Range Map\");\n\n RangeApplier ret = new RangeApplier();\n ret.setLogger(logStd);\n ret.setErrorLogger(logErr);\n\n if (this.inputs.size() == 1)\n ret.setInput(this.inputs.get(0));\n else\n ret.setInput(new ChainedInputSupplier(this.inputs));\n\n ret.setOutput(output);\n range.accept(ret);\n\n ret.setGuessLambdas(guessLambdas);\n ret.setGuessLocals(guessLocals);\n ret.setSortImports(sortImports);\n\n srgs.forEach(e -> e.accept(ret));\n excs.forEach(e -> e.accept(ret));\n\n ret.keepImports(keepImports);\n\n return ret;\n }\n}",
"public class RangeExtractorBuilder {\n private SourceVersion sourceVersion = SourceVersion.JAVA_1_8;\n private PrintStream logStd = System.out;\n private PrintStream logErr = System.err;\n private PrintWriter output = null;\n private boolean batch = true;\n private List<File> libraries = new ArrayList<>();\n private List<InputSupplier> inputs = new ArrayList<>();\n private File cache = null;\n private boolean enableMixins = false;\n private boolean fatalMixins = false;\n private boolean logWarnings = false;\n private boolean enablePreview = false;\n\n public RangeExtractorBuilder sourceCompatibility(SourceVersion value) {\n this.sourceVersion = value;\n return this;\n }\n\n public RangeExtractorBuilder logger(File value) {\n try {\n return logger(new PrintStream(value));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public RangeExtractorBuilder logger(Path value) {\n try {\n return logger(new PrintStream(Files.newOutputStream(value)));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public RangeExtractorBuilder logger(PrintStream value) {\n this.logStd = value;\n return this;\n }\n\n public RangeExtractorBuilder errorLogger(PrintStream value) {\n this.logErr = value;\n return this;\n }\n\n public RangeExtractorBuilder output(File value) {\n return output(value, StandardCharsets.UTF_8);\n }\n\n public RangeExtractorBuilder output(File value, Charset encoding) {\n try {\n if (!value.exists()) {\n File parent = value.getCanonicalFile().getParentFile();\n if (!parent.exists())\n parent.mkdirs();\n value.createNewFile();\n }\n\n return output(new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(value), encoding))));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public RangeExtractorBuilder output(Path value) {\n return output(value, StandardCharsets.UTF_8);\n }\n\n public RangeExtractorBuilder output(Path value, Charset encoding) {\n try {\n if (!Files.exists(value)) {\n Path parent = value.toAbsolutePath().getParent();\n if (!Files.exists(parent))\n Files.createDirectories(parent);\n Files.createFile(value);\n }\n return output(new PrintWriter(Files.newBufferedWriter(value, encoding)));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public RangeExtractorBuilder output(PrintWriter value) {\n if (output != null)\n output.close();\n output = value;\n return this;\n }\n\n public RangeExtractorBuilder batch() {\n return this.batch(true);\n }\n\n public RangeExtractorBuilder batch(boolean value) {\n this.batch = true;\n return this;\n }\n\n public RangeExtractorBuilder library(File value) {\n this.libraries.add(value);\n return this;\n }\n\n\n public RangeExtractorBuilder input(Path value) {\n return input(value, StandardCharsets.UTF_8);\n }\n\n @SuppressWarnings(\"resource\")\n public RangeExtractorBuilder input(Path value, @Nullable Charset encoding) {\n if (value == null || !Files.exists(value))\n throw new IllegalArgumentException(\"Invalid input value: \" + value);\n\n String filename = value.getFileName().toString().toLowerCase(Locale.ENGLISH);\n try {\n if (Files.isDirectory(value))\n inputs.add(FolderSupplier.create(value, encoding));\n else if (filename.endsWith(\".jar\") || filename.endsWith(\".zip\")) {\n try {\n inputs.add(ZipInputSupplier.create(value, encoding));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n } else\n throw new IllegalArgumentException(\"Invalid input value: \" + value);\n } catch (IOException e) {\n throw new IllegalArgumentException(\"Invalid input: \" + value, e);\n }\n\n return this;\n }\n\n public RangeExtractorBuilder input(InputSupplier value) {\n this.inputs.add(value);\n return this;\n }\n\n public RangeExtractorBuilder cache(File value) {\n this.cache = value;\n return this;\n }\n\n public RangeExtractorBuilder enableMixins() {\n this.enableMixins = true;\n return this;\n }\n\n public RangeExtractorBuilder fatalMixins() {\n this.fatalMixins = true;\n return this;\n }\n\n public RangeExtractorBuilder logWarnings() {\n this.logWarnings = true;\n return this;\n }\n\n public RangeExtractorBuilder enablePreview() {\n this.enablePreview = true;\n return this;\n }\n\n public RangeExtractor build() {\n RangeExtractor ret = new RangeExtractor();\n ret.setLogger(logStd);\n ret.setErrorLogger(logErr);\n\n if (output != null)\n ret.setOutput(output);\n ret.setSourceCompatibility(sourceVersion);\n ret.setBatchASTs(batch);\n\n libraries.forEach(ret::addLibrary);\n\n if (this.inputs.size() == 1)\n ret.setInput(this.inputs.get(0));\n else\n ret.setInput(new ChainedInputSupplier(this.inputs));\n\n if (this.enableMixins)\n ret.enableMixins();\n if (this.fatalMixins)\n ret.fatalMixins();\n if (this.logWarnings)\n ret.logWarnings();\n if (this.enablePreview)\n ret.enablePreview();\n\n if (this.cache != null) {\n try (InputStream fin = new FileInputStream(this.cache)) {\n ret.loadCache(fin);\n } catch (IOException e) {\n System.out.println(\"Error Loading Caching: \" + this.cache);\n e.printStackTrace();\n }\n }\n\n return ret;\n }\n}",
"public enum SourceVersion {\n JAVA_1_6(JavaCore.VERSION_1_6),\n JAVA_1_7(JavaCore.VERSION_1_7),\n JAVA_1_8(JavaCore.VERSION_1_8),\n JAVA_9(JavaCore.VERSION_9),\n JAVA_10(JavaCore.VERSION_10),\n JAVA_11(JavaCore.VERSION_11),\n JAVA_12(JavaCore.VERSION_12),\n JAVA_13(JavaCore.VERSION_13),\n JAVA_14(JavaCore.VERSION_14),\n JAVA_15(JavaCore.VERSION_15),\n JAVA_16(JavaCore.VERSION_16),\n JAVA_17(JavaCore.VERSION_17),\n ;\n\n private String spec;\n private SourceVersion(String spec) {\n this.spec = spec;\n }\n\n public String getSpec() {\n return spec;\n }\n\n public static SourceVersion parse(String name) {\n if (name == null)\n return null;\n\n for (SourceVersion v : SourceVersion.values()) {\n if (v.name().equals(name) || v.getSpec().equals(name))\n return v;\n }\n\n return null;\n }\n}",
"@SuppressWarnings(\"unused\")\npublic class RangeApplier extends ConfLogger<RangeApplier> {\n private static Pattern IMPORT = Pattern.compile(\"import\\\\s+((?<static>static)\\\\s+)?(?<class>[A-Za-z][A-Za-z0-9_\\\\.]*\\\\*?);.*\");\n\n private List<IMappingFile> srgs = new ArrayList<>();\n private Map<String, String> clsSrc2Internal = new HashMap<>();\n private Map<String, ExceptorClass> excs = Collections.emptyMap();\n private boolean keepImports = false; // Keep imports that are not referenced anywhere in code.\n private InputSupplier input = null;\n private OutputSupplier output = null;\n private Map<String, RangeMap> range = new HashMap<>();\n private ClassMeta meta = null;\n private Map<String, String> guessLambdas = null;\n private boolean guessLocals = false;\n private boolean sortImports = false;\n\n public void readSrg(Path srg) {\n try (InputStream in = Files.newInputStream(srg)) {\n IMappingFile map = IMappingFile.load(in);\n srgs.add(map); //TODO: Add merge function to SrgUtils?\n\n map.getClasses().forEach(cls -> {\n clsSrc2Internal.put(cls.getOriginal().replace('/', '.').replace('$', '.'), cls.getOriginal());\n\n if (guessLambdas != null) {\n cls.getMethods().stream()\n .filter(Objects::nonNull)\n .flatMap(mtd -> mtd.getParameters().stream())\n .filter(Objects::nonNull)\n .forEach(p -> this.guessLambdas.put(p.getOriginal(), p.getMapped()));\n }\n });\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to read SRG: \" + srg, e);\n }\n }\n\n public void readExc(Path value) {\n readExc(value, StandardCharsets.UTF_8);\n }\n\n public void readExc(Path value, Charset encoding) {\n try {\n this.excs = ExceptorClass.create(value, encoding, this.excs);\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to read EXC: \" + value, e);\n }\n }\n\n public void setGuessLambdas(boolean value) {\n if (!value) {\n this.guessLambdas = null;\n } else {\n this.guessLambdas = new HashMap<>();\n this.srgs.stream()\n .flatMap(srg -> srg.getClasses().stream())\n .flatMap(cls -> cls.getMethods().stream())\n .flatMap(mtd -> mtd.getParameters().stream())\n .forEach(p -> this.guessLambdas.put(p.getOriginal(), p.getMapped()));\n }\n }\n\n public void setGuessLocals(boolean value) {\n this.guessLocals = value;\n }\n\n public void setSortImports(boolean value) {\n this.sortImports = value;\n }\n\n public void setInput(InputSupplier value) {\n this.input = value;\n }\n\n public void setOutput(OutputSupplier value) {\n this.output = value;\n }\n\n public void readRangeMap(File value) {\n try (InputStream in = Files.newInputStream(value.toPath())) {\n this.range.putAll(RangeMap.readAll(in));\n } catch (IOException e) {\n throw new IllegalArgumentException(\"Invalid range map: \" + value);\n }\n }\n\n public void readRangeMap(Path value) {\n try (InputStream in = Files.newInputStream(value)) {\n this.range.putAll(RangeMap.readAll(in));\n } catch (IOException e) {\n throw new IllegalArgumentException(\"Invalid range map: \" + value);\n }\n }\n\n public void keepImports(boolean value) {\n this.keepImports = value;\n }\n\n public void run() throws IOException {\n if (input == null)\n throw new IllegalStateException(\"Missing Range Apply input\");\n if (output == null)\n throw new IllegalStateException(\"Missing Range Apply output\");\n if (range == null)\n throw new IllegalStateException(\"Missing Range Apply range\");\n\n meta = ClassMeta.create(this, range);\n\n List<String> paths = new ArrayList<>(range.keySet());\n Collections.sort(paths);\n\n log(\"Processing \" + paths.size() + \" files\");\n\n for (String filePath : paths) {\n log(\"Start Processing: \" + filePath);\n InputStream stream = input.getInput(filePath);\n\n //no stream? what?\n if (stream == null) {\n // yeah.. nope.\n log(\"Data not found: \" + filePath);\n continue;\n }\n Charset encoding = input.getEncoding(filePath);\n if (encoding == null)\n encoding = StandardCharsets.UTF_8;\n\n String data = new String(Util.readStream(stream), encoding);\n stream.close();\n\n // process\n List<String> out = processJavaSourceFile(filePath, data, range.get(filePath), meta);\n filePath = out.get(0);\n data = out.get(1);\n\n // write.\n if (data != null) {\n OutputStream outStream = output.getOutput(filePath);\n if (outStream == null)\n throw new IllegalStateException(\"Could not get output stream form: \" + filePath);\n outStream.write(data.getBytes(encoding));\n outStream.close();\n }\n\n log(\"End Processing: \" + filePath);\n log(\"\");\n }\n\n output.close();\n }\n\n private List<String> processJavaSourceFile(String fileName, String data, RangeMap rangeList, ClassMeta meta) throws IOException {\n StringBuilder outData = new StringBuilder();\n outData.append(data);\n\n Set<String> importsToAdd = new TreeSet<>();\n int shift = 0;\n\n // Existing package/class name (with package, internal) derived from filename\n String oldTopLevelClassFullName = Util.getTopLevelClassForFilename(fileName);\n int idx = oldTopLevelClassFullName.lastIndexOf('/');\n String oldTopLevelClassPackage = idx == -1 ? null : oldTopLevelClassFullName.substring(0, idx);\n String oldTopLevelClassName = idx == -1 ? oldTopLevelClassFullName : oldTopLevelClassFullName.substring(idx + 1);\n\n // New package/class name through mapping\n String newTopLevelClassFullName = mapClass(oldTopLevelClassFullName);\n idx = newTopLevelClassFullName.lastIndexOf('/');\n String newTopLevelClassPackage = idx == -1 ? null : newTopLevelClassFullName.substring(0, idx);\n String newTopLevelClassName = idx == -1 ? newTopLevelClassFullName : newTopLevelClassFullName.substring(idx + 1);\n\n //String newTopLevelQualifiedName = ((newTopLevelClassPackage == null ? \"\" : newTopLevelClassPackage + '/') + newTopLevelClassName).replace('\\\\', '/');\n\n // TODO: Track what code object we're in so we have more context?\n for (RangeEntry info : rangeList.getEntries()) {\n int start = info.getStart();\n int end = start + info.getLength();\n String expectedOldText = info.getText();\n String oldName = outData.substring(start + shift, end + shift);\n\n if (!oldName.equals(expectedOldText))\n throw new RuntimeException(\"Rename sanity check failed: expected '\" + expectedOldText +\n \"' at [\" + start + \",\" + end + \"] (shifted \" + shift + \" [\" + (start + shift) + \",\" + (end + shift) + \"]) \" +\n \"in \" + fileName + \", but found '\" + oldName + \"'\\n\" +\n \"Regenerate symbol map on latest sources or start with fresh source and try again\");\n\n String newName = null;\n switch (info.getType()) {\n case PACKAGE: // This should be OUR package reference, other packages are expressed as qualified class entries.\n newName = newTopLevelClassPackage.replace('/', '.'); //TODO: Support remapping to no package, thus removing this entirely. Problem is this doesn't reference the \"package\" text itself.\n break;\n case CLASS: {\n ClassReference ref = (ClassReference)info;\n //TODO: I am unsure how we should handle mappings that change the inner class level of a class.\n // Right now, the outer class is it's own ClassReference entry. So we have no way to figure out if we need to qualify/import it...\n String fullname = fixLocalClassName(mapClass(ref.getClassName()));\n idx = fullname.lastIndexOf('/');\n String packagename = idx == -1 ? null : fullname.substring(0, idx);\n String simplename = fullname.substring(idx + 1);\n idx = simplename.lastIndexOf('$');\n\n if (idx != -1) {\n if (oldName.indexOf('.') != -1)\n throw new IllegalStateException(\"Invalid Class mapping. Quialified inner class: Mapped: \" + fullname + \" \" + info);\n packagename = null;\n simplename = simplename.substring(idx + 1);\n }\n\n if (ref.isQualified() && oldName.indexOf('.') > 0) { // Top Level Includes package\n newName = fullname.replace('/', '.').replace('$', '.');\n } else {\n newName = simplename;\n if (!ref.isQualified()) {\n trackImport(importsToAdd, newTopLevelClassFullName,\n newTopLevelClassFullName, //TODO: pass in inner class names so we can check super?\n fullname);\n }\n }\n break;\n }\n case FIELD: {\n FieldReference ref = (FieldReference)info;\n newName = mapField(ref.getOwner(), ref.getName());\n break;\n }\n case METHOD: {\n MethodReference ref = (MethodReference)info;\n newName = mapMethod(ref.getOwner(), ref.getName(), ref.getDescriptor());\n break;\n }\n case PARAMETER: {\n ParameterReference ref = (ParameterReference)info;\n newName = mapParam(ref.getOwner(), ref.getName(), ref.getDescriptor(), ref.getIndex(), oldName);\n break;\n }\n case CLASS_LITERAL: {\n ClassLiteral ref = (ClassLiteral)info;\n newName = '\"' + mapClass(ref.getClassName()) + '\"';\n //Convert this to names used in code. Can either be internal, or source.\n //It can also technically be some other encoded format...\n //Should we care about changing text names/escape characters?\n if (ref.getText().indexOf('.') != -1)\n newName = newName.replace('/', '.'); // Source names.\n break;\n }\n case FIELD_LITERAL: {\n FieldLiteral ref = (FieldLiteral)info;\n newName = '\"' + mapField(ref.getOwner(), ref.getName()) + '\"';\n break;\n }\n case METHOD_LITERAL: {\n MethodLiteral ref = (MethodLiteral)info;\n newName = '\"' + mapMethod(ref.getOwner(), ref.getName(), ref.getDescriptor()) + '\"';\n break;\n }\n case LOCAL_VARIABLE: {\n LocalVariableReference ref = (LocalVariableReference)info;\n newName = mapLocal(ref.getOwner(), ref.getName(), ref.getDescriptor(), ref.getIndex(), ref.getVarType(), oldName);\n break;\n }\n default:\n throw new IllegalArgumentException(\"Unknown RangeEntry type: \" + info);\n }\n\n if (oldName.equals(newName))\n continue; //No rename? Skip the rest.\n\n log(\"Rename \" + info + \" Shift[\" + shift + \"] \" + oldName + \" -> \" + newName);\n\n // Rename algorithm:\n // 1. textually replace text at specified range with new text\n // 2. shift future ranges by difference in text length\n //data = data.substring(0, info.start + shift) + newName + data.substring(end + shift);\n outData.replace(start + shift, end + shift, newName);\n shift += (newName.length() - oldName.length());\n }\n\n // Lastly, update imports - this == separate from symbol range manipulation above\n String outString = updateImports(outData, importsToAdd);\n\n // rename?\n fileName = fileName.replace('\\\\', '/');\n String newFileName = newTopLevelClassFullName + \".java\";\n\n if (newFileName.charAt(0) != '/' && fileName.charAt(0) == '/')\n newFileName = '/' + newFileName;\n\n if (!fileName.equals(newFileName)) {\n log(\"Rename file \" + fileName + \" -> \" + newFileName);\n fileName = newFileName;\n }\n\n return Arrays.asList(fileName, outString);\n }\n\n private static String fixLocalClassName(String fullname) {\n int firstIdx = fullname.indexOf('$');\n if (firstIdx == -1)\n return fullname;\n\n StringBuilder builder = new StringBuilder(fullname.length());\n final String[] parts = fullname.split(\"\\\\$\");\n builder.append(parts[0]);\n for (int part = 1; part < parts.length; part++) {\n String piece = parts[part];\n int idx = 0;\n while (idx < piece.length() && !(Character.isJavaIdentifierStart(piece.codePointAt(idx)))) {\n idx+=Character.charCount(piece.codePointAt(idx));\n }\n if (idx == piece.length()) {\n builder.append(\"$\").append(piece);\n } else {\n builder.append(\"$\").append(piece.substring(idx));\n }\n }\n return builder.toString();\n }\n\n private static void trackImport(Set<String> imports, String topLevel, String self, String reference) {\n if (reference.startsWith(topLevel)) return; //This is a inner class, nested unknown amounts deep.... Just assume it's qualified correctly in code.\n\n int idx = topLevel.lastIndexOf('/');\n String tpkg = idx == -1 ? \"\" : topLevel.substring(0, idx);\n idx = reference.lastIndexOf('/');\n String rpkg = idx == -1 ? \"\" : reference.substring(0, idx);\n\n if (tpkg.equals(rpkg)) return; // We are in the same package, no import needed\n\n //This needs to be made better by taking into account inheritance, but I don't know of a simple way to hack inheritance into this,\n //so I think we're gunna have to live with some false positives. We just have to be careful when patching.\n imports.add(reference.replace('/', '.').replace('$', '.'));\n }\n\n /*\n * Parse the existing imports and find out where to add ours\n * TODO: Make RangeExtract pull import segments and remap in line? Can we support more layouts?\n * Imports syntax CAN be very complicated, we only support the most common layout:\n * import\\w+[static]\\w+(ClassName);\n * We can not support comments before the import.. anyone wanna try it?\n */\n private String updateImports(StringBuilder data, Set<String> newImports) {\n int lastIndex = 0;\n int nextIndex = getNextIndex(data.indexOf(\"\\n\"), data.length(), lastIndex);\n\n boolean addedNewImports = false;\n boolean sawImports = false;\n int packageLine = -1;\n String newline = data.indexOf(\"\\r\\n\") != -1 ? \"\\r\\n\" : \"\\n\";\n\n while (nextIndex > -1) {\n String line = data.substring(lastIndex, nextIndex);\n if (line.endsWith(\"\\r\"))\n line = line.substring(0, line.length() - 1);\n int comment = line.indexOf(\"//\");\n\n while ((comment == -1 ? line : line.substring(0, comment)).trim().isEmpty()) {\n lastIndex += line.length() == 0 ? 1 : line.length();\n nextIndex = getNextIndex(data.indexOf(\"\\n\", lastIndex), data.length(), lastIndex);\n if (nextIndex == -1) //EOF\n break;\n line = data.substring(lastIndex, nextIndex);\n if (line.endsWith(\"\\r\"))\n line = line.substring(0, line.length() - 1);\n comment = line.indexOf(\"//\");\n }\n\n if (nextIndex == -1) //EOF\n break;\n\n if (line.startsWith(\"package \"))\n packageLine = nextIndex + 1;\n else if (line.startsWith(\"import\")) {\n sawImports = true;\n\n Matcher match = IMPORT.matcher(line);\n if (!match.matches()) {\n error(\"Error: Invalid import line: \" + line); //Do we want to error out?\n lastIndex = nextIndex + 1;\n nextIndex = getNextIndex(data.indexOf(\"\\n\", nextIndex + 1), data.length(), nextIndex + 1);\n continue;\n }\n\n boolean isStatic = match.group(\"static\") != null;\n String old = match.group(\"class\");\n int cStart = match.start(\"class\");\n int cEnd = match.end(\"class\");\n boolean wildMatch = false;\n\n if (isStatic) {\n int idx = old.lastIndexOf('.');\n cEnd -= old.length() - idx;\n String name = old.substring(idx + 1);\n old = old.substring(0, idx);\n\n if (\"*\".equals(name)) {\n ; //Wildcard, but we just want to rename the class\n } else {\n error(\"Warning: Static Method/Field Imports not supported: \" + line); //Do we want to error out?\n lastIndex = nextIndex;\n nextIndex = getNextIndex(data.indexOf(\"\\n\", nextIndex + 1), data.length(), nextIndex + 1);\n }\n } else if (old.endsWith(\".*\")) {\n Set<String> remove = new HashSet<>();\n String starter = old.substring(0, old.length() - 1);\n for (String imp : newImports) {\n String impStart = imp.substring(0, imp.lastIndexOf('.') + 1);\n if (impStart.equals(starter)) {\n remove.add(imp);\n wildMatch = true;\n }\n }\n newImports.removeAll(remove);\n\n old = old.substring(0, old.length() - 2);\n cEnd -= 2;\n }\n\n String newClass = mapClass(clsSrc2Internal.getOrDefault(old, old)).replace('/', '.').replace('$', '.');\n\n //log(\"Import: \" + newClass);\n\n if (!wildMatch && !newImports.remove(newClass) && !isStatic) { // New file doesn't need the import, so delete the line.\n if (this.keepImports)\n lastIndex = nextIndex + 1;\n else {\n data.delete(lastIndex, nextIndex + 1);\n if (data.substring(lastIndex > 3 ? lastIndex - 3 : 0, lastIndex).endsWith('\\n' + newline) &&\n data.substring(lastIndex, lastIndex + newline.length()).equals(newline)) { // Collapse double empty lines\n data.delete(lastIndex - newline.length(), lastIndex);\n lastIndex -= newline.length();\n }\n }\n nextIndex = getNextIndex(data.indexOf(\"\\n\", lastIndex), data.length(), lastIndex);\n continue;\n }\n\n if (!old.equals(newClass)) { // Got renamed\n data.replace(lastIndex + cStart, lastIndex + cEnd, newClass);\n nextIndex = nextIndex - (old.length() - newClass.length());\n }\n } else if (sawImports && !addedNewImports) {\n filterImports(newImports);\n\n if (newImports.size() > 0) {\n // Add our new imports right after the last import\n CharSequence sub = data.subSequence(lastIndex, data.length()); // grab the rest of the string.\n data.setLength(lastIndex); // cut off the build there\n\n newImports.stream().sorted().forEach(imp -> data.append(\"import \").append(imp).append(\";\\n\"));\n\n if (newImports.size() > 0)\n data.append(newline);\n\n int change = data.length() - lastIndex; // get changed size\n lastIndex = data.length(); // reset the end to the actual end..\n nextIndex += change; // shift nextIndex accordingly..\n\n data.append(sub); // add on the rest if the string again\n }\n\n addedNewImports = true;\n break; //We've added out imports lets exit.\n }\n\n // next line.\n lastIndex = nextIndex + 1; // +1 to skip the \\n at the end of the line there\n nextIndex = getNextIndex(data.indexOf(\"\\n\", lastIndex), data.length(), lastIndex); // another +1 because otherwise it would just return lastIndex\n }\n\n // got through the whole file without seeing or adding any imports???\n if (!addedNewImports) {\n filterImports(newImports);\n\n if (newImports.size() > 0) {\n //If we saw the package line, add to it after that.\n //If not prepend to the start of the file\n int index = packageLine == -1 ? 0 : packageLine;\n\n CharSequence sub = data.subSequence(index, data.length()); // grab the rest of the string.\n data.setLength(index); // cut off the build there\n\n newImports.stream().sorted().forEach(imp -> data.append(newline).append(\"import \").append(imp).append(\";\"));\n\n if (newImports.size() > 0)\n data.append('\\n');\n\n data.append(sub); // add on the rest if the string again\n }\n }\n\n if (sortImports && (!newImports.isEmpty() || sawImports)) {\n int startIndex = data.indexOf(\"import \");\n int endIndex = data.indexOf(\"\\n\", startIndex);\n nextIndex = endIndex;\n if (startIndex != -1) {\n String line;\n\n while (endIndex != -1) {\n nextIndex = data.indexOf(\"\\n\", endIndex + 1);\n line = data.substring(endIndex + 1, nextIndex == -1 ? data.length() : nextIndex);\n if (line.startsWith(\"import \") || line.replaceAll(\"\\r?\\n\", \"\").trim().isEmpty())\n endIndex = nextIndex;\n else\n break;\n }\n if (endIndex == -1)\n endIndex = data.length();\n\n while (data.charAt(endIndex-1) == '\\n' || data.charAt(endIndex-1) == '\\r')\n endIndex--;\n\n String importData = data.substring(startIndex, endIndex);\n String imports = Stream.of(importData.split(\"\\r?\\n\"))\n .filter(i -> !i.trim().isEmpty())\n .map(i -> {\n i = i.substring(7, i.length() - 1);\n int idx = i.lastIndexOf('.');\n return new String[] { i.substring(0, idx), i.substring(idx + 1) };\n })\n .sorted((o1, o2) -> o1[0].equals(o2[0]) ? o1[1].compareTo(o2[1]) : o1[0].compareTo(o2[0]))\n .map(i -> \"import \" + i[0] + '.' + i[1] + ';')\n .collect(Collectors.joining(newline));\n data.replace(startIndex, endIndex, imports);\n }\n }\n\n return data.toString();\n }\n\n private int getNextIndex(int newLine, int dataLength, int oldIndex) {\n if (newLine == -1 && dataLength > oldIndex)\n return dataLength;\n return newLine;\n }\n\n private void filterImports(Set<String> newImports) {\n Iterator<String> itr = newImports.iterator();\n while (itr.hasNext()) {\n if (itr.next().startsWith(\"java.lang.\")) //java.lang classes can be referenced without imports\n itr.remove(); //We remove them here to allow for them to exist in src\n //But we will never ADD them\n }\n\n if (newImports.size() > 0) {\n log(\"Adding \" + newImports.size() + \" imports\");\n for (String imp : newImports) {\n log(\" \" + imp);\n //log(\" \" + HashCode.fromBytes(imp.getBytes()).toString());\n }\n }\n }\n\n // TODO: Decide how I want to manage multiple srg files? Chain them? Merge them?\n //Current usecase is Forge adding extra SRG lines. But honestly that shouldn't happen anymore.\n String mapClass(String name) {\n for (IMappingFile srg : srgs) {\n IMappingFile.IClass cls = srg.getClass(name);\n if (cls != null)\n return cls.getMapped();\n }\n return name;\n }\n\n String mapField(String owner, String name) {\n for (IMappingFile srg : srgs) {\n IMappingFile.IClass cls = srg.getClass(owner);\n if (cls != null) {\n String newName = cls.remapField(name);\n if (newName != name) // This is intentional instance equality. As remap methods return the same instance of not found.\n return newName;\n }\n }\n return name;\n }\n\n String mapMethod(String owner, String name, String desc) {\n if (\"<init>\".equals(name)) {\n String newName = fixLocalClassName(mapClass(owner));\n int idx = newName.lastIndexOf('$');\n idx = idx != -1 ? idx : newName.lastIndexOf('/');\n return idx == -1 ? newName : newName.substring(idx + 1);\n }\n\n for (IMappingFile srg : srgs) {\n IMappingFile.IClass cls = srg.getClass(owner);\n if (cls != null) {\n String newName = cls.remapMethod(name, desc);\n if (newName != name) // This is intentional instance equality. As remap methods return the same instance of not found.\n return newName;\n }\n }\n\n //There was no mapping for this specific method, so lets see if this is something in the metadata\n return meta == null ? name : meta.mapMethod(owner, name, desc);\n }\n\n private String mapParam(String owner, String name, String desc, int index, String old) {\n ExceptorClass exc = this.excs.get(owner);\n String ret = exc == null ? null : exc.mapParam(name, desc, index, old);\n if (ret == null) {\n for (IMappingFile srg : srgs) {\n IMappingFile.IClass cls = srg.getClass(owner);\n if (cls != null) {\n IMappingFile.IMethod mtd = cls.getMethod(name, desc);\n if (mtd != null) {\n String mapped = mtd.remapParameter(index, old);\n if (mapped != old) {\n ret = mapped;\n break;\n }\n }\n }\n }\n }\n if (ret == null && this.guessLambdas != null && name.startsWith(\"lambda$\"))\n ret = this.guessLambdas.get(old);\n\n return ret == null ? old : ret;\n }\n\n // Guess JAD style local variables, and some Fernflower quarks\n private String mapLocal(String owner, String name, String desc, int index, String type, String old) {\n if (!guessLocals || type.indexOf(';') == -1)\n return old;\n\n String prefix = \"\";\n\n // Arrays are 'a' + type name\n if (type.charAt(0) == '[') {\n prefix = \"a\";\n type = type.substring(type.indexOf('L') + 1, type.length() - 1);\n } else\n type = type.substring(1, type.length() - 1);\n\n\n // Typically it's the simple class name, including the outer class if the type is an inner\n int idx = type.lastIndexOf('/');\n String expected = prefix + (idx == -1 ? type : type.substring(idx + 1)).toLowerCase(Locale.ENGLISH);\n\n String newClass = mapClass(type);\n if (newClass.equals(type))\n return old;\n\n idx = newClass.lastIndexOf('/');\n if (idx != -1)\n newClass = newClass.substring(idx + 1);\n\n if (!old.startsWith(expected)) {\n idx = expected.lastIndexOf('$');\n int nidx = newClass.lastIndexOf('$');\n if (idx == -1 || nidx == -1)\n return old;\n\n String inner = prefix + expected.substring(idx + 1);\n String outer = expected.substring(0, idx);\n\n // Sometimes it's JUST the inner class name\n if (old.startsWith(inner)) {\n newClass = newClass.substring(nidx + 1);\n expected = inner;\n //I don't know why this happens, but BlockModelDefinition has a local var named the outer class instead of inner..\n } else if (old.startsWith(outer)) {\n newClass = newClass.substring(0, nidx);\n expected = outer;\n } else\n return old;\n }\n\n return prefix + newClass.toLowerCase(Locale.ENGLISH) + old.substring(expected.length());\n }\n}",
"public class RangeExtractor extends ConfLogger<RangeExtractor> {\n private static RangeExtractor INSTANCE = null;\n\n private PrintWriter output;\n private String sourceVersion;\n private boolean enableBatchedASTs = true;\n private final Set<File> libs = new LinkedHashSet<File>();\n private String[] libArray = null; //A cache of libs, so we don't have to re-build it over and over.\n\n private InputSupplier input;\n\n private Map<String, RangeMap> file_cache = new HashMap<>();\n private int cache_hits = 0;\n private boolean enableMixins = false;\n private boolean fatalMixins = false;\n private boolean logWarnings = false;\n private boolean enablePreview = false;\n\n public RangeExtractor(){}\n\n public void setOutput(PrintWriter value) {\n this.output = value;\n }\n\n public void setSourceCompatibility(SourceVersion value) {\n this.sourceVersion = value.getSpec();\n }\n\n public void setBatchASTs(boolean value) {\n this.enableBatchedASTs = value;\n }\n\n public void enableMixins() {\n this.enableMixins = true;\n }\n\n public void fatalMixins() {\n this.fatalMixins = true;\n }\n public boolean areMixinsFatal() {\n return this.fatalMixins;\n }\n public void logWarnings() {\n this.logWarnings = true;\n }\n public void enablePreview() {\n this.enablePreview = true;\n }\n\n public void addLibrary(File value) {\n String fileName = value.getPath().toLowerCase(Locale.ENGLISH);\n if (!value.exists()) {\n error(\"Missing Library: \" + value.getAbsolutePath());\n } else if (value.isDirectory()) {\n libArray = null;\n libs.add(value); // Root directories, for dev time classes.\n } else if (fileName.endsWith(\".jar\") || fileName.endsWith(\".jar\")) {\n libArray = null;\n libs.add(value);\n } else\n log(\"Unsupposrted library path: \" + value.getAbsolutePath());\n }\n\n public void setInput(InputSupplier supplier) {\n this.input = supplier;\n }\n\n public void loadCache(InputStream stream) throws IOException {\n this.file_cache = RangeMap.readAll(stream);\n }\n\n @Override //Log everything as a comment in case we merge the output and log as we used to do.\n public void log(String message) {\n super.log(\"# \" + message);\n }\n\n /**\n * Generates the rangemap.\n */\n public boolean run() {\n log(\"Symbol range map extraction starting\");\n\n String[] files = input.gatherAll(\".java\").stream()\n .map(f -> f.replaceAll(\"\\\\\\\\\", \"/\")) // Normalize directory separators.\n .sorted()\n .toArray(String[]::new);\n log(\"Processing \" + files.length + \" files\");\n\n if (files.length == 0) {\n // no files? well.. nothing to do then.\n cleanup();\n return true;\n }\n\n if (canBatchASTs())\n return batchGenerate(files);\n else\n return legacyGenerate(files);\n }\n\n private boolean legacyGenerate(String[] files) {\n try {\n for (String path : files) {\n Charset encoding = input.getEncoding(path);\n if (encoding == null)\n encoding = StandardCharsets.UTF_8;\n\n try (InputStream stream = input.getInput(path)) {\n String data = new String(Util.readStream(stream), encoding);\n String md5 = Util.md5(data, encoding);\n RangeMapBuilder builder = new RangeMapBuilder(this, path, md5);\n\n log(\"startProcessing \\\"\" + path + \"\\\" md5: \" + md5);\n\n RangeMap cache = this.file_cache.get(path);\n if (builder.loadCache(cache)) {\n log(\"Cache Hit!\");\n RangeExtractor.this.cache_hits++;\n } else {\n ASTParser parser = createParser(input.getRoot(path));\n parser.setUnitName(path);\n parser.setSource(data.toCharArray());\n CompilationUnit cu = (CompilationUnit)parser.createAST(null);\n if (cu.getProblems() != null && cu.getProblems().length > 0)\n Arrays.stream(cu.getProblems()).filter(p -> !p.isWarning()).forEach(p -> log(\" Compile Error! \" + p.toString()));\n\n SymbolReferenceWalker walker = new SymbolReferenceWalker(this, builder, enableMixins);\n walker.safeWalk(cu);\n }\n\n RangeMap range = builder.build();\n if (output != null)\n range.write(output, true);\n log(\"endProcessing \\\"\" + path + \"\\\"\");\n log(\"\");\n }\n }\n } catch (Exception e) {\n e.printStackTrace(getErrorLogger());\n }\n\n cleanup();\n return true;\n }\n\n private boolean batchGenerate(String[] files) {\n if (RangeExtractor.INSTANCE != null)\n throw new IllegalStateException(\"Can not do batched processing while another is running!\");\n RangeExtractor.INSTANCE = this;\n\n //TODO: Check org.eclipse.jdt.internal.compiler.batch.FileSystem.getClasspath(String, String, boolean, AccessRuleSet, String, Map<String, String>, String)\n // That is where it loads sourceDirs as classpath entries. Try and hijack to include InputSuppliers?\n ASTParser parser = createParser(null);\n\n FileASTRequestor requestor = new FileASTRequestor() {\n @Override\n public void acceptAST(String path, CompilationUnit cu) {\n path = path.replace(File.separatorChar, '/');\n\n Charset encoding = input.getEncoding(path);\n if (encoding == null)\n encoding = StandardCharsets.UTF_8;\n\n try (InputStream stream = input.getInput(path)) {\n String data = new String(Util.readStream(stream), encoding);\n String md5 = Util.md5(data, encoding);\n\n RangeMapBuilder builder = new RangeMapBuilder(RangeExtractor.this, path, md5);\n\n log(\"startProcessing \\\"\" + path + \"\\\" md5: \" + md5);\n\n RangeMap cache = RangeExtractor.this.file_cache.get(path);\n if (builder.loadCache(cache)) {\n log(\"Cache Hit!\");\n RangeExtractor.this.cache_hits++;\n } else {\n if (cu.getProblems() != null && cu.getProblems().length > 0)\n Arrays.stream(cu.getProblems()).filter(p -> logWarnings || !p.isWarning()).forEach(p -> log(\" Compile Error! \" + p.toString()));\n\n SymbolReferenceWalker walker = new SymbolReferenceWalker(RangeExtractor.this, builder, enableMixins);\n walker.safeWalk(cu);\n }\n\n RangeMap range = builder.build();\n if (output != null)\n range.write(output, true);\n log(\"endProcessing \\\"\" + path + \"\\\"\");\n log(\"\");\n } catch (IOException e) {\n e.printStackTrace(getErrorLogger());\n }\n }\n };\n\n IProgressMonitor monitor = new NullProgressMonitor();\n\n parser.createASTs(files, null, new String[0], requestor, monitor);\n\n cleanup();\n\n RangeExtractor.INSTANCE = null;\n return true;\n }\n\n private void cleanup() {\n try {\n input.close();\n } catch (IOException e) {\n e.printStackTrace(getErrorLogger());\n }\n\n if (output != null) {\n output.flush();\n output.close();\n output = null;\n }\n }\n\n private String[] getLibArray() {\n if (libArray == null)\n libArray = libs.stream().map(File::getAbsolutePath).toArray(String[]::new);\n return libArray;\n }\n\n public int getCacheHits() {\n return this.cache_hits;\n }\n\n public boolean canBatchASTs() {\n return hasBeenASMPatched() && enableBatchedASTs;\n }\n\n private ASTParser createParser(String srcRoot) {\n ASTParser parser = ASTParser.newParser(AST.getJLSLatest());\n parser.setEnvironment(getLibArray(), srcRoot == null ? null : new String[] {srcRoot}, null, true);\n return setOptions(parser);\n }\n\n private ASTParser setOptions(ASTParser parser) {\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n parser.setResolveBindings(true);\n parser.setBindingsRecovery(true);\n Hashtable<String, String> options = JavaCore.getDefaultOptions();\n JavaCore.setComplianceOptions(sourceVersion, options);\n if (enablePreview)\n options.put(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, JavaCore.ENABLED);\n parser.setCompilerOptions(options);\n return parser;\n }\n\n //ASM redirect for JDT's Util.getFileCharContent(File, String) to allow us to use our inputs\n public static char[] getFileCharContent(String path, String encoding) {\n RangeExtractor range = RangeExtractor.INSTANCE; //TODO: Find a way to make this non-static\n\n Charset charset = range.input.getEncoding(path);\n encoding = charset == null ? StandardCharsets.UTF_8.name() : charset.name();\n\n try(InputStream input = RangeExtractor.INSTANCE.input.getInput(path);\n BufferedReader reader = new BufferedReader(new InputStreamReader(input, encoding));\n ) {\n CharArrayWriter writer = new CharArrayWriter();\n char[] buf = new char[1024];\n int len;\n while ((len = reader.read(buf, 0, 1024)) > 0) {\n writer.write(buf, 0, len);\n }\n return writer.toCharArray();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * This is a marker function that should always return false in code.\n * But if the ASM transformation has run, which is needed for JDT batching,\n * it will also transform this to return true.\n *\n * Welcome to the world of magic ASM hacks!\n */\n public static boolean hasBeenASMPatched() {\n return false;\n }\n}",
"public class Util {\n /**\n * Get the top-level class required to be declared in a file by its given name, if in the main tree\n * This is an internal name, including slashes for packages components\n */\n public static String getTopLevelClassForFilename(String filename) {\n filename = filename.replace('\\\\', '/');\n if (filename.startsWith(\"/\"))\n filename = filename.substring(1);\n\n\n int lastSlash = filename.lastIndexOf('/');\n int lastDot = filename.lastIndexOf('.');\n if (lastDot > lastSlash)\n filename = filename.substring(0, lastDot);\n\n return filename;\n }\n\n public static int transferTo(InputStream input, OutputStream output) throws IOException {\n byte[] buf = new byte[1024];\n int total = 0;\n int cnt;\n\n while ((cnt = input.read(buf)) > 0) {\n output.write(buf, 0, cnt);\n total += cnt;\n }\n\n return total;\n }\n\n public static byte[] readStream(InputStream input) throws IOException {\n ByteArrayOutputStream output = new ByteArrayOutputStream();\n transferTo(input, output);\n return output.toByteArray();\n }\n\n public static String md5(String data, Charset encoding) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(data.getBytes(encoding));\n return hex(md.digest());\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n\n private static String hex(byte[] data) {\n return IntStream.range(0, data.length).collect(StringBuilder::new, (sb,i)->new Formatter(sb).format(\"%02x\", data[i] & 0xFF), StringBuilder::append).toString();\n }\n\n /*\n * Quotes a string if it either has a space, or it has a \" as the first character\n */\n public static String quote(String data) {\n if (data.indexOf(' ') != -1 || data.indexOf('\"') == 0)\n data = '\"' + data.replaceAll(\"\\\"\", \"\\\\\\\\\\\"\") + '\"';\n return data;\n }\n\n public static String quote(String... data) {\n return Arrays.stream(data).map(Util::quote).collect(Collectors.joining(\" \"));\n }\n\n /*\n * Will attempt to remove the specified number of quoted strings from the input.\n * The resulting list will have no more then `count` entries.\n */\n public static List<String> unquote(String data, int count) {\n List<String> ret = new ArrayList<>();\n for (int x = 0; x < count; x++) {\n if (data.charAt(0) != '\"') {\n int idx = data.indexOf(' ');\n if (idx == -1)\n break;\n ret.add(data.substring(0, idx));\n data = data.substring(idx + 1);\n } else {\n int idx = data.indexOf('\"', 1);\n while (idx != -1 && data.charAt(idx - 1) == '\\\\')\n idx = data.indexOf('\"', idx + 1);\n\n if (idx == -1 || data.charAt(idx -1) == '\\\\')\n throw new IllegalArgumentException(\"Improperly quoted string: \" + data);\n\n idx = data.indexOf(' ', idx);\n ret.add(data.substring(1, idx - 1).replace(\"\\\\\\\"\", \"\\\"\"));\n if (idx == -1) {\n data = null;\n break;\n } else\n data = data.substring(idx + 1);\n }\n }\n if (data != null)\n ret.add(data);\n return ret;\n }\n}",
"public class FolderSupplier implements InputSupplier, OutputSupplier {\n public static FolderSupplier create(Path root, @Nullable Charset encoding) throws IOException {\n if (!Files.exists(root))\n Files.createDirectories(root);\n return new FolderSupplier(root, encoding);\n }\n\n private final Path root;\n private final String sroot;\n @Nullable\n private final Charset encoding;\n\n protected FolderSupplier(Path root, @Nullable Charset encoding) {\n this.root = root;\n this.sroot = root.toAbsolutePath().toString();\n this.encoding = encoding;\n }\n\n @Override\n @Nullable\n public OutputStream getOutput(String relPath) {\n try {\n Path target = root.resolve(relPath);\n if (!Files.exists(target)) {\n Path parent = target.getParent();\n if (!Files.exists(parent))\n Files.createDirectories(parent);\n }\n return Files.newOutputStream(target);\n } catch (IOException e) {\n return null;\n }\n }\n\n @Override\n @Nullable\n public InputStream getInput(String relPath) {\n try {\n Path target = root.resolve(relPath);\n if (!Files.exists(target))\n return null;\n return Files.newInputStream(target, StandardOpenOption.READ);\n } catch (IOException e) {\n return null;\n }\n }\n\n @Override\n public List<String> gatherAll(String endFilter) {\n try {\n return Files.walk(root).filter(Files::isRegularFile)\n .map(root::relativize).map(Path::toString)\n .filter(p -> p.endsWith(endFilter))\n .sorted().collect(Collectors.toList());\n } catch (IOException e) {\n e.printStackTrace();\n return Collections.emptyList();\n }\n }\n\n @Override\n public void close() throws IOException {\n // they are files.. what do you want me to do?\n }\n\n @Override\n @Nullable\n public String getRoot(String resource) {\n return sroot;\n }\n\n @Override\n @Nullable\n public Charset getEncoding(String resource) {\n return encoding;\n }\n}"
] | import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.Assert;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import net.minecraftforge.srg2source.api.RangeApplierBuilder;
import net.minecraftforge.srg2source.api.RangeExtractorBuilder;
import net.minecraftforge.srg2source.api.SourceVersion;
import net.minecraftforge.srg2source.apply.RangeApplier;
import net.minecraftforge.srg2source.extract.RangeExtractor;
import net.minecraftforge.srg2source.util.Util;
import net.minecraftforge.srg2source.util.io.FolderSupplier; | /*
* Srg2Source
* Copyright (c) 2020.
*
* 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 version 2.1
* of the License.
*
* 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 net.minecraftforge.srg2source.test;
public abstract class SimpleTestBase {
private static final String FORGE_MAVEN = "https://maven.minecraftforge.net/";
protected abstract String getPrefix();
protected abstract List<String> getLibraries();
protected RangeExtractorBuilder customize(RangeExtractorBuilder builder) { return builder; }; | protected RangeApplierBuilder customize(RangeApplierBuilder builder) { return builder; }; | 0 |
kawasima/solr-jdbc | src/main/java/net/unit8/solr/jdbc/command/DeleteCommand.java | [
"public class Parameter implements Item {\n private static final String SQL_WILDCARD_CHARS = \"%_%_\";\n\n\tprivate SolrValue value;\n\tprivate int index;\n\tprivate boolean needsLikeEscape;\n\tprivate String likeEscapeChar = \"%\";\n\tprivate Expression targetColumn;\n\n\tpublic Parameter(int index) {\n\t\tthis.index = index;\n\t}\n\n\tpublic void setValue(SolrValue value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic SolrValue getValue() {\n\t\tif(value == null) {\n\t\t\treturn ValueNull.INSTANCE;\n\t\t}\n\t\treturn value;\n\t}\n\n\tpublic void setColumn(Expression column) {\n\t\tthis.targetColumn = column;\n\t}\n\tpublic SolrType getType() {\n\t\tif (value != null) {\n\t\t\treturn value.getType();\n\t\t}\n\t\treturn SolrType.UNKNOWN;\n\t}\n\n\tpublic String getQueryString() {\n\t\tif (value != null) {\n\t\t\tif (needsLikeEscape) {\n\t\t\t\tif (targetColumn != null && targetColumn.getType() == SolrType.TEXT) {\n StringBuilder sb = processWildcard(value.getString());\n // If the parameter matched partially in the middle,\n // trim the first & last wildcards for the syntax of proper solr query.\n if (sb.charAt(sb.length() - 1) == '*') {\n if (sb.charAt(0) == '*')\n sb.deleteCharAt(0);\n sb.deleteCharAt(sb.length() - 1);\n return sb.toString();\n } else {\n throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n \"In TEXT type, supports partial matching in the middle of words only.\");\n }\n\t\t\t\t} else if (targetColumn.getType() == SolrType.STRING) {\n StringBuilder sb = processWildcard(value.getString());\n if (sb.charAt(0) != '*' && sb.charAt(sb.length() - 1) == '*') {\n return sb.toString();\n } else {\n throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n \"In STRING type, supports partial matching in the beginning of words only.\");\n }\n\t\t\t\t} else {\n throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n \"Like is not supported in this type.\");\n }\n\t\t\t} else {\n\t\t\t\treturn value.getQueryString();\n\t\t\t}\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic int getIndex() {\n\t\treturn index;\n\t}\n\n\tpublic void setNeedsLikeEscape() {\n\t\tthis.needsLikeEscape = true;\n\t}\n\n\tpublic void setLikeEscapeChar(String likeEscapeChar) {\n\t\tthis.likeEscapeChar = likeEscapeChar;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getQueryString();\n\t}\n\n private StringBuilder processWildcard(String value) {\n String escapedValue = value\n .replaceAll(\"\\\\*\", \"\\\\\\\\*\")\n .replaceAll(\"(?<!\\\\\" + likeEscapeChar + \")[\" + SQL_WILDCARD_CHARS + \"]\", \"*\")\n .replaceAll(\"\\\\\" + likeEscapeChar + \"([\" + SQL_WILDCARD_CHARS + \"])\", \"$1\");\n\n String[] tokens = escapedValue.split(\"(?<!\\\\\\\\)\\\\*\", -1);\n StringBuilder sb = new StringBuilder(escapedValue.length() + 20);\n for (int i=0; i < tokens.length; i++) {\n sb.append(ClientUtils.escapeQueryChars(tokens[i].replaceAll(\"\\\\\\\\\\\\*\", \"*\")));\n if (i < tokens.length -1)\n sb.append(\"*\");\n }\n return sb;\n }\n}",
"public abstract class AbstractResultSet implements ResultSet {\n\tprotected SolrDocumentList docList;\n\tprotected int docIndex = -1;\n\tprotected ResultSetMetaDataImpl metaData;\n\tprotected boolean isClosed = false;\n\tprotected StatementImpl statement;\n\tprivate boolean wasNull;\n\n\t@Override\n\tpublic boolean absolute(int i) throws SQLException {\n\t\tcheckClosed();\n\t\tif (0 <= i && i < docList.size()) {\n\t\t\treturn false;\n\t\t}\n\t\tdocIndex = i;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void afterLast() throws SQLException {\n\t\tcheckClosed();\n\t\tdocIndex = docList.size();\n\t}\n\n\t@Override\n\tpublic void beforeFirst() throws SQLException {\n\t\tcheckClosed();\n\t\tdocIndex = -1;\n\t}\n\n\t@Override\n\tpublic void cancelRowUpdates() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void clearWarnings() throws SQLException {\n\t\tcheckClosed();\n\t}\n\n\t@Override\n\tpublic void close() throws SQLException {\n\t\tthis.docList = null;\n\t\tisClosed = true;\n\t}\n\n\t@Override\n\tpublic void deleteRow() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"deleteRow\");\n\t}\n\n\t@Override\n\tpublic int findColumn(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\treturn metaData.findColumn(columnLabel);\n\t}\n\n\t@Override\n\tpublic boolean first() throws SQLException {\n\t\tcheckClosed();\n\t\tdocIndex = 0;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean last() throws SQLException {\n\t\t// TODO TYPE_FORWARD_ONLYのときはSQLExceptionをだす\n\t\tdocIndex = docList.size() - 1;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean next() throws SQLException {\n\t\tcheckClosed();\n\n\t\tdocIndex +=1;\n\t\tif (docIndex >= docList.size()) {\n\t\t\tdocIndex = docList.size();\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean previous() throws SQLException {\n\t\t// TODO スクロールが不可能な場合はSQLException\n\t\tcheckClosed();\n\n\t\tdocIndex -= 1;\n\t\tif (docIndex < 0) {\n\t\t\tdocIndex = 0;\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isAfterLast() throws SQLException {\n\t\treturn (docIndex >= docList.size());\n\t}\n\n\t@Override\n\tpublic boolean isBeforeFirst() throws SQLException {\n\t\treturn (docIndex < 0);\n\t}\n\n\t@Override\n\tpublic boolean isClosed() throws SQLException {\n\t\treturn isClosed;\n\t}\n\n\t@Override\n\tpublic boolean isFirst() throws SQLException {\n\t\treturn docIndex == 0;\n\t}\n\n\t@Override\n\tpublic boolean isLast() throws SQLException {\n\t\treturn docIndex == docList.size() - 1;\n\t}\n\n\t@Override\n\tpublic ResultSetMetaData getMetaData() throws SQLException {\n\t\treturn metaData;\n\t}\n\n\t@Override\n\tpublic Array getArray(int columnIndex) throws SQLException {\n\t\tSolrValue v = get(columnIndex);\n\t\treturn v == ValueNull.INSTANCE ? null : new ArrayImpl(v);\n\t}\n\n\t@Override\n\tpublic Array getArray(String columnLabel) throws SQLException {\n\t\tSolrValue v = get(columnLabel);\n\n\t\treturn v == ValueNull.INSTANCE ? null : new ArrayImpl(v);\n\t}\n\n\t@Override\n\tpublic InputStream getAsciiStream(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getAsciiStream\");\n\t}\n\n\t@Override\n\tpublic InputStream getAsciiStream(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getAsciiStream\");\n\t}\n\n\t@Override\n\tpublic BigDecimal getBigDecimal(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getBigDecimal();\n\t}\n\n\t@Override\n\tpublic BigDecimal getBigDecimal(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getBigDecimal();\n\t}\n\n\t@Override\n\tpublic BigDecimal getBigDecimal(int columnIndex, int j) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getBigDecimal\");\n\t}\n\n\t@Override\n\tpublic BigDecimal getBigDecimal(String s, int i) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getBigDecimal\");\n\t}\n\n\t@Override\n\tpublic InputStream getBinaryStream(int i) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getBinaryStream\");\n\t}\n\n\t@Override\n\tpublic InputStream getBinaryStream(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getBinaryStream\");\n\t}\n\n\t@Override\n\tpublic Blob getBlob(int i) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getBlob\");\n\t}\n\n\t@Override\n\tpublic Blob getBlob(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getBlob\");\n\t}\n\n\t@Override\n\tpublic boolean getBoolean(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getBoolean();\n\t}\n\n\t@Override\n\tpublic boolean getBoolean(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getBoolean();\n\t}\n\n\t@Override\n\tpublic byte getByte(int i) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getByte\");\n\t}\n\n\t@Override\n\tpublic byte getByte(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getByte\");\n\t}\n\n\t@Override\n\tpublic byte[] getBytes(int i) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getBytes\");\n\t}\n\n\t@Override\n\tpublic byte[] getBytes(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getBytes\");\n\t}\n\n\t@Override\n\tpublic Reader getCharacterStream(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n String value = get(columnIndex).getString();\n return (value == null) ? null : new StringReader(value);\n\t}\n\n\t@Override\n\tpublic Reader getCharacterStream(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n String value = get(columnLabel).getString();\n return (value == null) ? null : new StringReader(value);\n\t}\n\n\t@Override\n\tpublic Clob getClob(int i) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getClob\");\n\t}\n\n\t@Override\n\tpublic Clob getClob(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getClob\");\n\t}\n\n\t@Override\n\tpublic Date getDate(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getDate();\n\t}\n\n\t@Override\n\tpublic Date getDate(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getDate();\n\t}\n\n\t@Override\n\tpublic Date getDate(int columnIndex, Calendar calendar) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Date getDate(String columnLabel, Calendar calendar) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic double getDouble(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getDouble();\n\t}\n\n\t@Override\n\tpublic double getDouble(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getDouble();\n\t}\n\n\t@Override\n\tpublic float getFloat(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn (float)get(columnIndex).getDouble();\n\t}\n\n\t@Override\n\tpublic float getFloat(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn (float)get(columnLabel).getDouble();\n\t}\n\n\t@Override\n\tpublic int getInt(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getInt();\n\t}\n\n\t@Override\n\tpublic int getInt(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getInt();\n\t}\n\n\t@Override\n\tpublic long getLong(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn (long)get(columnIndex).getInt();\n\t}\n\n\t@Override\n\tpublic long getLong(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn (long)get(columnLabel).getInt();\n\t}\n\n\t@Override\n\tpublic Reader getNCharacterStream(int i) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Reader getNCharacterStream(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic NClob getNClob(int i) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic NClob getNClob(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic String getNString(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getString();\n\t}\n\n\t@Override\n\tpublic String getNString(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getString();\n\t}\n\n\t@Override\n\tpublic Object getObject(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getObject();\n\t}\n\n\t@Override\n\tpublic Object getObject(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getObject();\n\t}\n\n\t@Override\n\tpublic Object getObject(int arg0, Map<String, Class<?>> arg1)\n\t\t\tthrows SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Object getObject(String arg0, Map<String, Class<?>> arg1)\n\t\t\tthrows SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Ref getRef(int i) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Ref getRef(String s) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic int getRow() throws SQLException {\n\t\tif (docIndex < 0 || docIndex >= docList.size()) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn docIndex+1;\n\t}\n\n\t@Override\n\tpublic RowId getRowId(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic RowId getRowId(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic SQLXML getSQLXML(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic SQLXML getSQLXML(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic short getShort(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn (short)get(columnIndex).getInt();\n\t}\n\n\t@Override\n\tpublic short getShort(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn (short)get(columnLabel).getInt();\n\t}\n\n\t@Override\n\tpublic Statement getStatement() throws SQLException {\n\t\treturn statement;\n\t}\n\n\t@Override\n\tpublic String getString(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getString();\n\t}\n\n\t@Override\n\tpublic String getString(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getString();\n\t}\n\n\t@Override\n\tpublic Time getTime(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Time getTime(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Time getTime(int columnIndex, Calendar calendar) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Time getTime(String columnLabel, Calendar calendar) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic Timestamp getTimestamp(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnIndex).getTimestamp();\n\t}\n\n\t@Override\n\tpublic Timestamp getTimestamp(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\treturn get(columnLabel).getTimestamp();\n\t}\n\n\t@Override\n\tpublic Timestamp getTimestamp(int i, Calendar calendar) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getTimestamp\");\n\t}\n\n\t@Override\n\tpublic Timestamp getTimestamp(String s, Calendar calendar)\n\t\t\tthrows SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getTimestamp\");\n\t}\n\n\t@Override\n\tpublic URL getURL(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getURL\");\n\t}\n\n\t@Override\n\tpublic URL getURL(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getURL\");\n\t}\n\n\t@Override\n\tpublic InputStream getUnicodeStream(int columnIndex) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getUnicodeStream\");\n\t}\n\n\t@Override\n\tpublic InputStream getUnicodeStream(String columnLabel) throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getUnicodeStream\");\n\t}\n\n\t@Override\n\tpublic int getType() throws SQLException {\n\t\tcheckClosed();\n\t\treturn (statement==null) ? ResultSet.TYPE_FORWARD_ONLY : statement.resultSetType;\n\t}\n\n\n\t@Override\n\tpublic int getConcurrency() throws SQLException {\n\t\tcheckClosed();\n\t\treturn ResultSet.CONCUR_READ_ONLY;\n\t}\n\n\t@Override\n\tpublic String getCursorName() throws SQLException {\n\t\tcheckClosed();\n\t\tcheckAvailable();\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getCursorName\");\n\t}\n\n\t@Override\n\tpublic void setFetchDirection(int fetchDirection) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"setFetchDirection\");\n\n\t}\n\n\t@Override\n\tpublic int getFetchDirection() throws SQLException {\n\t\tcheckClosed();\n\t\treturn ResultSet.FETCH_FORWARD;\n\t}\n\n\t@Override\n\tpublic void setFetchSize(int fetchSize) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"setFetchSize\");\n\t}\n\n\t@Override\n\tpublic int getFetchSize() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getHoldability() throws SQLException {\n\t\tcheckClosed();\n\t\tif(statement == null || statement.getConnection() == null) {\n\t\t\treturn ResultSet.HOLD_CURSORS_OVER_COMMIT;\n\t\t}\n\t\treturn statement.getConnection().getHoldability();\n\t}\n\n\t@Override\n\tpublic SQLWarning getWarnings() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getWarnings\");\n\t}\n\n\t@Override\n\tpublic void insertRow() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"insertRow\");\n\t}\n\n\t@Override\n\tpublic void moveToCurrentRow() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"moveToCurrentRow\");\n\t}\n\n\t@Override\n\tpublic void moveToInsertRow() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"moveToInsertRow\");\n\t}\n\n\t@Override\n\tpublic void refreshRow() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"refreshRow\");\n\n\t}\n\n\t@Override\n\tpublic boolean relative(int rowCount) throws SQLException {\n\t\tcheckClosed();\n\t\tint row = docIndex + rowCount + 1;\n\t\tif (row < 0) {\n\t\t\trow = 0;\n\t\t} else if (row > docList.size()) {\n\t\t\trow = docList.size() + 1;\n\t\t}\n\t\treturn absolute(row);\n\t}\n\n\t@Override\n\tpublic boolean rowDeleted() throws SQLException {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean rowInserted() throws SQLException {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean rowUpdated() throws SQLException {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void updateArray(int i, Array array) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateArray(String s, Array array) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateAsciiStream(int i, InputStream inputstream)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateAsciiStream(String s, InputStream inputstream)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateAsciiStream(int i, InputStream inputstream, int j)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateAsciiStream(String s, InputStream inputstream, int i)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateAsciiStream(int i, InputStream inputstream, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateAsciiStream(String s, InputStream inputstream, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBigDecimal(int i, BigDecimal bigdecimal)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBigDecimal(String s, BigDecimal bigdecimal)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBinaryStream(int i, InputStream inputstream)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBinaryStream(String s, InputStream inputstream)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBinaryStream(int i, InputStream inputstream, int j)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBinaryStream(String s, InputStream inputstream, int i)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBinaryStream(int i, InputStream inputstream, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBinaryStream(String s, InputStream inputstream, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBlob(int i, Blob blob) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBlob(String s, Blob blob) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBlob(int i, InputStream inputstream) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBlob(String s, InputStream inputstream)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBlob(int i, InputStream inputstream, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBlob(String s, InputStream inputstream, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBoolean(int i, boolean flag) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBoolean(String s, boolean flag) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateByte(int i, byte byte0) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateByte(String s, byte byte0) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBytes(int i, byte[] abyte0) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateBytes(String s, byte[] abyte0) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateCharacterStream(int i, Reader reader) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateCharacterStream(String s, Reader reader)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateCharacterStream(int i, Reader reader, int j)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateCharacterStream(String s, Reader reader, int i)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateCharacterStream(int i, Reader reader, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateCharacterStream(String s, Reader reader, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateClob(int i, Clob clob) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateClob(String s, Clob clob) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateClob(int i, Reader reader) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateClob(String s, Reader reader) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateClob(int i, Reader reader, long l) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateClob(String s, Reader reader, long l) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateDate(int i, Date date) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateDate(String s, Date date) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateDouble(int i, double d) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateDouble(String s, double d) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateFloat(int i, float f) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateFloat(String s, float f) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateInt(int i, int j) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateInt(String s, int i) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateLong(int i, long l) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateLong(String s, long l) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNCharacterStream(int i, Reader reader)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNCharacterStream(String s, Reader reader)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNCharacterStream(int i, Reader reader, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNCharacterStream(String s, Reader reader, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNClob(int i, NClob nclob) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNClob(String s, NClob nclob) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNClob(int i, Reader reader) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNClob(String s, Reader reader) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNClob(int i, Reader reader, long l) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNClob(String s, Reader reader, long l)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNString(int i, String s) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNString(String s, String s1) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNull(int i) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateNull(String s) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateObject(int i, Object obj) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateObject(String s, Object obj) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateObject(int i, Object obj, int j) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateObject(String s, Object obj, int i) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateRef(int i, Ref ref) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateRef(String s, Ref ref) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateRow() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateRowId(int i, RowId rowid) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateRowId(String s, RowId rowid) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED);\n\t}\n\n\t@Override\n\tpublic void updateSQLXML(int i, SQLXML sqlxml) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateSQLXML\");\n\t}\n\n\t@Override\n\tpublic void updateSQLXML(String s, SQLXML sqlxml) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateSQLXML\");\n\t}\n\n\t@Override\n\tpublic void updateShort(int i, short word0) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateShort\");\n\t}\n\n\t@Override\n\tpublic void updateShort(String s, short word0) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateShort\");\n\t}\n\n\t@Override\n\tpublic void updateString(int i, String s) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateString\");\n\t}\n\n\t@Override\n\tpublic void updateString(String s, String s1) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateString\");\n\t}\n\n\t@Override\n\tpublic void updateTime(int i, Time time) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateTime\");\n\t}\n\n\t@Override\n\tpublic void updateTime(String s, Time time) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateTime\");\n\t}\n\n\t@Override\n\tpublic void updateTimestamp(int i, Timestamp timestamp) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateTimestamp\");\n\t}\n\n\t@Override\n\tpublic void updateTimestamp(String s, Timestamp timestamp)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"updateTimestamp\");\n\t}\n\n\t@Override\n\tpublic boolean wasNull() throws SQLException {\n\t\tcheckClosed();\n\t\treturn wasNull;\n\t}\n\n\t@Override\n\tpublic boolean isWrapperFor(Class<?> arg0) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"isWrapperFor\");\n\t}\n\n\t@Override\n\tpublic <T> T unwrap(Class<T> arg0) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"unwrap\");\n\t}\n\n\tprivate SolrValue get(int columnIndex) throws SQLException{\n\t\tcheckClosed();\n\t\tExpression column = metaData.getColumn(columnIndex);\n\n\t\tString columnName = (column.getType() == SolrType.UNKNOWN) ? column.getResultName():column.getSolrColumnName();\n\n\t\tObject x;\n\t\tCollection<Object> objs = docList.get(docIndex).getFieldValues(columnName);\n\t\tif (objs == null) {\n\t\t\tx = null;\n\t\t} else if (objs.size() == 1) {\n\t\t\tx = objs.toArray()[0];\n\t\t} else {\n\t\t\tx = objs.toArray();\n\t\t}\n\n\t\tSolrValue value = DataType.convertToValue(x);\n\t\twasNull = (value == ValueNull.INSTANCE);\n\t\treturn value;\n\t}\n\n\tprivate SolrValue get(String columnLabel) throws SQLException {\n\t\tint columnIndex = findColumn(columnLabel);\n\t\treturn get(columnIndex);\n\t}\n\n\tprotected void checkClosed() throws SQLException {\n\t\tif (isClosed)\n\t\t\tthrow DbException.get(ErrorCode.OBJECT_CLOSED);\n\t}\n\n\tprotected void checkAvailable() throws SQLException {\n\t\tif (docIndex < 0 || docIndex >= docList.size()) {\n\t\t\tthrow DbException.get(ErrorCode.NO_DATA_AVAILABLE);\n\t\t}\n\t}\n}",
"public class DatabaseMetaDataImpl implements DatabaseMetaData {\n\tprivate final SolrConnection conn;\n\tprivate Map<String, List<Expression>> tableColumns = new HashMap<String, List<Expression>>();\n private Map<String, List<String>> tablePrimaryKeys = new HashMap<String, List<String>>();\n\tprivate Map<String, String> originalTables = new HashMap<String, String>();\n\n\tpublic DatabaseMetaDataImpl(SolrConnection conn) {\n\t\tthis.conn = conn;\n\t\tbuildMetadata();\n\t}\n\n\tprivate void buildMetadata() {\n\t\ttry {\n\t\t\tQueryResponse res = this.conn.getSolrServer().query(\n\t\t\t\t\tnew SolrQuery(\"meta.name:*\"));\n\n\t\t\tfor (SolrDocument doc : res.getResults()) {\n\t\t\t\tString tableName = doc.getFieldValue(\"meta.name\").toString();\n\t\t\t\tList<Expression> columns = new ArrayList<Expression>();\n\t\t\t\tfor (Object cols : doc.getFieldValues(\"meta.columns\")) {\n\t\t\t\t\tcolumns.add(new ColumnExpression(tableName + \".\"\n\t\t\t\t\t\t\t+ cols.toString()));\n\t\t\t\t}\n List<String> primaryKeys = new ArrayList<String>();\n Collection<Object> pkColumns = doc.getFieldValues(\"meta.primaryKeys\");\n if (pkColumns != null) {\n for (Object pkColumn : pkColumns) {\n primaryKeys.add(tableName + \".\" + pkColumn.toString());\n }\n }\n\t\t\t\ttableColumns.put(StringUtils.upperCase(tableName), columns);\n tablePrimaryKeys.put(StringUtils.upperCase(tableName), primaryKeys);\n\t\t\t\toriginalTables.put(StringUtils.upperCase(tableName), tableName);\n\t\t\t}\n\n\t\t} catch (Exception e) {\n\t\t\tthrow DbException.get(ErrorCode.IO_EXCEPTION, e, e.getLocalizedMessage());\n\t\t}\n\t}\n\n\tpublic Expression getSolrColumn(String tableName, String columnName) {\n\t\tfor (Expression solrColumn : this.tableColumns.get(StringUtils.upperCase(tableName))) {\n\t\t\tif (StringUtils.equals(solrColumn.getColumnName(), columnName)) {\n\t\t\t\treturn solrColumn;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\n\t}\n\n\tpublic List<Expression> getSolrColumns(String tableName) {\n\t\tif (tableColumns == null)\n\t\t\tbuildMetadata();\n\t\treturn this.tableColumns.get(StringUtils.upperCase(tableName));\n\t}\n\n\tpublic boolean hasTable(String tableName) {\n\t\treturn originalTables.containsKey(StringUtils.upperCase(tableName));\n\t}\n\n\tpublic String getOriginalTableName(String tableName) {\n\t\treturn originalTables.get(StringUtils.upperCase(tableName));\n\t}\n\n\t/**\n\t * Checks if all procedures callable.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean allProceduresAreCallable() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if it possible to query all tables returned by getTables.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean allTablesAreSelectable() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether an exception while auto commit is on closes all result\n\t * sets.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean autoCommitFailureClosesAllResultSets() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether data manipulation and CREATE/DROP is supported in\n\t * transactions.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean dataDefinitionCausesTransactionCommit() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether CREATE/DROP do not affect transactions.\n\t *\n\t * @return fasle\n\t */\n\t@Override\n\tpublic boolean dataDefinitionIgnoredInTransactions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether deletes are detected.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean deletesAreDetected(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether the maximum row size includes blobs.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean doesMaxRowSizeIncludeBlobs() throws SQLException {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic ResultSet getAttributes(String catalog, String schemaPattern,\n\t\t\tString typeNamePattern, String attributeNamePattern)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getAttributes\")\n\t\t\t\t.getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getBestRowIdentifier(String s, String s1, String s2,\n\t\t\tint i, boolean flag) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getBestRowIdentifier\").getSQLException();\n\t}\n\n\t@Override\n\tpublic String getCatalogSeparator() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getCatalogSeparator\").getSQLException();\n\t}\n\n\t@Override\n\tpublic String getCatalogTerm() throws SQLException {\n\t\tthrow DbException\n\t\t\t\t.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getCatalogTerm\")\n\t\t\t\t.getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getCatalogs() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getCatalogs\")\n\t\t\t\t.getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getClientInfoProperties() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getClientInfoProperties\").getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getColumnPrivileges(String s, String s1, String s2,\n\t\t\tString s3) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getColumnPrivileges\").getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getColumns(String catalog, String schema, String table,\n\t\t\tString columnNamePattern) throws SQLException {\n\t\tif (tableColumns == null) {\n\t\t\tbuildMetadata();\n\t\t}\n\n\t\tCollectionResultSet rs;\n\t\tString[] columns = { \"TABLE_CAT\", \"TABLE_SCHEM\", \"TABLE_NAME\",\n\t\t\t\t\"COLUMN_NAME\", \"DATA_TYPE\", \"TYPE_NAME\", \"COLUMN_SIZE\",\n\t\t\t\t\"BUFFER_LENGTH\", \"DECIMAL_DIGITS\", \"NUM_PREC_RADIX\",\n\t\t\t\t\"NULLABLE\", \"REMARKS\", \"COLUMN_DEF\", \"SQL_DATA_TYPE\",\n\t\t\t\t\"SQL_DATETIME_SUB\", \"CHAR_OCTET_LENGTH\", \"ORDINAL_POSITION\",\n\t\t\t\t\"IS_NULLABLE\", \"SCOPE_CATLOG\", \"SCOPE_SCHEMA\", \"SCOPE_TABLE\",\n\t\t\t\t\"SOURCE_DATA_TYPE\" };\n\t\trs = new CollectionResultSet();\n\t\trs.setColumns(Arrays.asList(columns));\n\n\t\tfor (Expression column : tableColumns.get(StringUtils.upperCase(table))) {\n\t\t\tObject[] columnMeta = new Object[22];\n\t\t\tcolumnMeta[1] = \"\"; // TABLE_SCHEM\n\t\t\tcolumnMeta[2] = column.getTableName();\n\t\t\tcolumnMeta[3] = column.getColumnName(); // COLUMN_NAME\n\n\t\t\tcolumnMeta[4] = DataType.getDataType(column.getType()).sqlType; // DATA_TYPE\n\t\t\tcolumnMeta[5] = column.getTypeName(); // TYPE_NAME\n\t\t\tcolumnMeta[6] = 0; // COLUMN_SIZE\n\t\t\tcolumnMeta[8] = 0; // DECIMAL_DIGITS\n\t\t\tcolumnMeta[10] = DatabaseMetaData.columnNullableUnknown; // NULLABLE\n\t\t\trs.add(Arrays.asList(columnMeta));\n\t\t}\n\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic Connection getConnection() throws SQLException {\n\t\treturn conn;\n\t}\n\n\t@Override\n\tpublic ResultSet getCrossReference(String s, String s1, String s2,\n\t\t\tString s3, String s4, String s5) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getCrossReference\");\n\t}\n\n\t@Override\n\tpublic String getDatabaseProductName() throws SQLException {\n\t\treturn \"solr\";\n\t}\n\n\t@Override\n\tpublic int getDatabaseMajorVersion() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getDatabaseMinorVersion() throws SQLException {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic String getDatabaseProductVersion() throws SQLException {\n\t\treturn \"0.1.4-SNAPSHOT\";\n\t}\n\n\t/**\n\t * Returns default transaction isolation.\n\t *\n\t * @return Connection.TRANSACTION_READ_COMMITTED\n\t */\n\t@Override\n\tpublic int getDefaultTransactionIsolation() throws SQLException {\n\t\treturn Connection.TRANSACTION_READ_COMMITTED;\n\t}\n\n\t@Override\n\tpublic int getDriverMajorVersion() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getDriverMinorVersion() {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic String getDriverName() throws SQLException {\n\t\treturn \"solr-jdbc\";\n\t}\n\n\t@Override\n\tpublic String getDriverVersion() throws SQLException {\n\t\treturn \"0.1.4-SNAPSHOT\";\n\t}\n\n\t@Override\n\tpublic ResultSet getExportedKeys(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getExportedKeys\");\n\t}\n\n\t@Override\n\tpublic String getExtraNameCharacters() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getExtraNameCharacters\");\n\t}\n\n\t@Override\n\tpublic ResultSet getFunctionColumns(String s, String s1, String s2,\n\t\t\tString s3) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getFunctionColumns\");\n\t}\n\n\t@Override\n\tpublic ResultSet getFunctions(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getFunctions\");\n\t}\n\n\t@Override\n\tpublic String getIdentifierQuoteString() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getFunctionColumns\");\n\t}\n\n\t@Override\n\tpublic ResultSet getImportedKeys(String catalog, String schema, String table)\n\t\t\tthrows SQLException {\n\t\tCollectionResultSet rs = new CollectionResultSet();\n\t\tString[] columns = { \"PKTABLE_CAT\", \"PKTABLE_SCHEM\", \"PKTABLE_NAME\",\n\t\t\t\t\"PKCOLUMN_NAME\", \"FKTABLE_CAT\", \"FKTABLE_SCHEM\",\n\t\t\t\t\"FKTABLE_NAME\", \"FKCOLUMN_NAME\", \"KEY_SEQ\", \"UPDATE_RULE\",\n\t\t\t\t\"DELETE_RULE\", \"FK_NAME\", \"PK_NAME\", \"DEFERRABILITY\" };\n\t\trs.setColumns(Arrays.asList(columns));\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic ResultSet getIndexInfo(String catalog, String schema, String table,\n\t\t\tboolean unique, boolean approximate) throws SQLException {\n\t\tCollectionResultSet rs = new CollectionResultSet();\n\t\tString[] columns = { \"TABLE_CAT\", \"TABLE_SCHEM\", \"TABLE_NAME\",\n\t\t\t\t\"NON_UNIQUE\", \"INDEX_QUALIFIER\", \"INDEX_NAME\", \"TYPE\",\n\t\t\t\t\"ORDINAL_POSITION\", \"COLUMN_NAME\", \"ASC_OR_DESC\",\n\t\t\t\t\"CARDINALITY\", \"PAGES\", \"FILTER_CONDITION\" };\n\t\trs.setColumns(Arrays.asList(columns));\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic int getJDBCMajorVersion() throws SQLException {\n\t\treturn 2;\n\t}\n\n\t@Override\n\tpublic int getJDBCMinorVersion() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxBinaryLiteralLength() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getMaxBinaryLiteralLength\");\n\t}\n\n\t/**\n\t * Returns the maximum length for a catalog name.\n\t *\n\t * @return 0 for limit is unknown.\n\t */\n\t@Override\n\tpublic int getMaxCatalogNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Returns the maximum length of literals.\n\t *\n\t * @return 0 for limit is unknown\n\t */\n\t@Override\n\tpublic int getMaxCharLiteralLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Returns the maximum length of column names.\n\t *\n\t * @return 0 for limit is unknown\n\t */\n\t@Override\n\tpublic int getMaxColumnNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * SolrのFacetの仕様のため、1を返す.\n\t *\n\t */\n\t@Override\n\tpublic int getMaxColumnsInGroupBy() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxColumnsInIndex() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxColumnsInOrderBy() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxColumnsInSelect() throws SQLException {\n\t\treturn 255;\n\t}\n\n\t@Override\n\tpublic int getMaxColumnsInTable() throws SQLException {\n\t\treturn 255;\n\t}\n\n\t@Override\n\tpublic int getMaxConnections() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxCursorNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxIndexLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxProcedureNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxRowSize() throws SQLException {\n\t\treturn 0; // No limitation\n\t}\n\n\t@Override\n\tpublic int getMaxSchemaNameLength() throws SQLException {\n\t\treturn 0; // No limitation\n\t}\n\n\t/**\n\t * Returns the maximum length of a statement.\n\t *\n\t * @return 0 for limit is unknown\n\t */\n\t@Override\n\tpublic int getMaxStatementLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Returns the maximum number of open statements.\n\t *\n\t * @return 0 for limit is unknown\n\t */\n\t@Override\n\tpublic int getMaxStatements() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxTableNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxTablesInSelect() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxUserNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic String getNumericFunctions() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getNumericFunctions\");\n\t}\n\n\t@Override\n\tpublic ResultSet getPrimaryKeys(String catalog, String schema, String table)\n\t\t\tthrows SQLException {\n\t\tCollectionResultSet rs;\n\t\tString[] columns = { \"TABLE_CAT\", \"TABLE_SCHEM\", \"TABLE_NAME\",\n\t\t\t\t\"COLUMN_NAME\", \"KEY_SEQ\", \"PK_NAME\" };\n\t\trs = new CollectionResultSet();\n\t\trs.setColumns(Arrays.asList(columns));\n\n\n short keySeq = 0;\n\t\tfor (String primaryKey : tablePrimaryKeys.get(StringUtils.upperCase(table))) {\n String[] pkTokens = StringUtils.split(primaryKey, \".\", 2);\n\t\t\tObject[] columnMeta = new Object[6];\n\t\t\tcolumnMeta[2] = pkTokens[0];\n\t\t\tcolumnMeta[3] = pkTokens[1]; //COLUMN_NAME\n\t\t\tcolumnMeta[4] = keySeq++; //KEY_SEQ\n\t\t\tcolumnMeta[5] = null; // PK_NAME\n\t\t\trs.add(Arrays.asList(columnMeta));\n\t\t}\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic ResultSet getProcedureColumns(String s, String s1, String s2,\n\t\t\tString s3) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getProcedureColumns\");\n\t}\n\n\t@Override\n\tpublic String getProcedureTerm() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getProcedureTerm\");\n\t}\n\n\t@Override\n\tpublic ResultSet getProcedures(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getProcedureTerm\");\n\t}\n\n\t@Override\n\tpublic int getResultSetHoldability() throws SQLException {\n\t\treturn ResultSet.HOLD_CURSORS_OVER_COMMIT;\n\t}\n\n\t@Override\n\tpublic RowIdLifetime getRowIdLifetime() throws SQLException {\n\t\treturn RowIdLifetime.ROWID_UNSUPPORTED;\n\t}\n\n\t@Override\n\tpublic String getSQLKeywords() throws SQLException {\n\t\tthrow DbException\n\t\t\t\t.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSQLKeywords\");\n\t}\n\n\t@Override\n\tpublic int getSQLStateType() throws SQLException {\n\t\treturn sqlStateXOpen;\n\t}\n\n\t@Override\n\tpublic String getSchemaTerm() throws SQLException {\n\t\treturn \"schema\";\n\t}\n\n\t@Override\n\tpublic ResultSet getSchemas() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSchemas\");\n\t}\n\n\t@Override\n\tpublic ResultSet getSchemas(String s, String s1) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSchemas\");\n\t}\n\n\t@Override\n\tpublic String getSearchStringEscape() throws SQLException {\n\t\treturn \"%\";\n\t}\n\n\t@Override\n\tpublic String getStringFunctions() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getStringFunctions\");\n\t}\n\n\t@Override\n\tpublic ResultSet getSuperTables(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException\n\t\t\t\t.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSuperTables\");\n\t}\n\n\t@Override\n\tpublic ResultSet getSuperTypes(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSuperTypes\");\n\t}\n\n\t@Override\n\tpublic String getSystemFunctions() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getSystemFunctions\");\n\t}\n\n\t@Override\n\tpublic ResultSet getTablePrivileges(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getTablePrivileges\");\n\t}\n\n\t@Override\n\tpublic ResultSet getTableTypes() throws SQLException {\n\t\tString[] columns = { \"TABLE_TYPE\" };\n\t\tCollectionResultSet rs = new CollectionResultSet();\n\t\trs.setColumns(Arrays.asList(columns));\n\t\tObject[] record = { \"TABLE\" };\n\t\trs.add(Arrays.asList(record));\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic ResultSet getTables(String catalog, String schema,\n\t\t\tString tableNamePattern, String[] types) throws SQLException {\n\t\tif (tableColumns == null) {\n\t\t\tbuildMetadata();\n\t\t}\n if (tableNamePattern == null)\n tableNamePattern = \"%\";\n\n\t\tCollectionResultSet rs;\n\t\tString[] columns = { \"TABLE_CAT\", \"TABLE_SCHEM\", \"TABLE_NAME\",\n\t\t\t\t\"TABLE_TYPE\", \"REMARKS\", \"TYPE_CAT\", \"TYPE_SCHEM\", \"TYPE_NAME\",\n\t\t\t\t\"SELF_REFERENCING_COL_NAME\", \"REF_GENERATION\" };\n\t\trs = new CollectionResultSet();\n\t\trs.setColumns(Arrays.asList(columns));\n\n\t\tPattern ptn = getPattern(tableNamePattern);\n\t\tfor (String tableName : tableColumns.keySet()) {\n\t\t\tif(ptn.matcher(tableName).matches()) {\n\t\t\t\tObject[] tableMeta = { null, \"\", tableName, \"TABLE\", \"\", null,\n\t\t\t\t\tnull, null, null, null };\n\t\t\t\trs.add(Arrays.asList(tableMeta));\n\t\t\t}\n\t\t}\n\n\t\treturn rs;\n\t}\n\n\tprotected Pattern getPattern(String ptnStr) {\n\t\tptnStr = ptnStr.replaceAll(\"(?<!\\\\\\\\)_\", \".?\").replaceAll(\"(?<!\\\\\\\\)%\", \".*?\");\n\t\treturn Pattern.compile(\"^\" + ptnStr + \"$\", Pattern.CASE_INSENSITIVE);\n\t}\n\n\t@Override\n\tpublic String getTimeDateFunctions() throws SQLException {\n\t\treturn \"\";\n\t}\n\n\t@Override\n\tpublic ResultSet getTypeInfo() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getTypeInfo\");\n\t}\n\n\t@Override\n\tpublic ResultSet getUDTs(String s, String s1, String s2, int[] ai)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getUDTs\");\n\t}\n\n\t@Override\n\tpublic String getURL() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getURL\");\n\t}\n\n\t@Override\n\tpublic String getUserName() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getUserName\");\n\t}\n\n\t@Override\n\tpublic ResultSet getVersionColumns(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getVersionColumns\");\n\t}\n\n\t/**\n\t * Returns whether inserts are detected.\n\t */\n\t@Override\n\tpublic boolean insertsAreDetected(int i) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether the catalog is at the beginning.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean isCatalogAtStart() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns the same as Connection.isReadOnly().\n\t *\n\t * @return if read only optimization is switched on\n\t */\n\t@Override\n\tpublic boolean isReadOnly() throws SQLException {\n\t\treturn conn.isReadOnly();\n\t}\n\n\t/**\n\t * Does the database make a copy before updating.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean locatorsUpdateCopy() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether NULL+1 is NULL or not.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean nullPlusNonNullIsNull() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if NULL is sorted at the beginning (no matter if ASC or DESC is used).\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean nullsAreSortedAtStart() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if NULL is sorted at the end (no matter if ASC or DESC is used).\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean nullsAreSortedAtEnd() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if NULL is sorted high (bigger than anything that is not null).\n\t */\n\t@Override\n\tpublic boolean nullsAreSortedHigh() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if NULL is sorted low (bigger than anything that is not null).\n\t */\n\t@Override\n\tpublic boolean nullsAreSortedLow() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether other deletes are visible.\n\t */\n\t@Override\n\tpublic boolean othersDeletesAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether other inserts are visible.\n\t */\n\t@Override\n\tpublic boolean othersInsertsAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether other updates are visible.\n\t */\n\t@Override\n\tpublic boolean othersUpdatesAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether own deletes are visible\n\t */\n\t@Override\n\tpublic boolean ownDeletesAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether own inserts are visible\n\t */\n\t@Override\n\tpublic boolean ownInsertsAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether own updates are visible\n\t */\n\t@Override\n\tpublic boolean ownUpdatesAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE Test(ID INT), getTables returns test as the\n\t * table name.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean storesLowerCaseIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE \"Test\"(ID INT), getTables returns test as the\n\t * table name.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean storesLowerCaseQuotedIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE Test(ID INT), getTables returns Test as the\n\t * table name\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean storesMixedCaseIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE \"Test\"(ID INT), getTables returns Test as the\n\t * table name.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean storesMixedCaseQuotedIdentifiers() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE Test(ID INT), getTables returns TEST as the\n\t * table name.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean storesUpperCaseIdentifiers() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE \"Test\"(ID INT), getTables returns TEST as the\n\t * table name.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean storesUpperCaseQuotedIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether SQL-92 entry level grammar is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsANSI92EntryLevelSQL() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether SQL-92 full level grammer is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsANSI92FullSQL() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether SQL-92 intermediate level grammar is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsANSI92IntermediateSQL() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsAlterTableWithAddColumn() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsAlterTableWithDropColumn() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether batch updates is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsBatchUpdates() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether the catalog name in INSERT, UPDATE, DELETE is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInDataManipulation() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInIndexDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInProcedureCalls() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInTableDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether column aliasing is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsColumnAliasing() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether CONVERT is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsConvert() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether CONVERT is supported for one datatype to another.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsConvert(int fromType, int toType) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether ODBC Core SQL grammar is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsCoreSQLGrammar() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCorrelatedSubqueries() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether data manipulation and CREATE/DROP is supported in\n\t * transactions.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsDataDefinitionAndDataManipulationTransactions()\n\t\t\tthrows SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether only data manipulations are supported in transactions.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsDataManipulationTransactionsOnly()\n\t\t\tthrows SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsDifferentTableCorrelationNames() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsExpressionsInOrderBy() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsExtendedSQLGrammar() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsFullOuterJoins() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsGetGeneratedKeys() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsGroupBy() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks whether a GROUP BY clause can use columns that are not in the\n\t * SELECT clause, provided that it specifies all the columns in the SELECT\n\t * clause.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsGroupByBeyondSelect() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether GROUP BY is supported if the column is not in the SELECT\n\t * list.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsGroupByUnrelated() throws SQLException {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean supportsIntegrityEnhancementFacility() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsLikeEscapeClause() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsLimitedOuterJoins() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether ODBC Minimum SQL grammar is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsMinimumSQLGrammar() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE Test(ID INT), getTables returns Test as the\n\t * table name.\n\t *\n\t * TODO case sensitiveに変更する。\n\t */\n\t@Override\n\tpublic boolean supportsMixedCaseIdentifiers() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if a table created with CREATE TABLE \"Test\"(ID INT) is a different\n\t * table than a table created with CREATE TABLE TEST(ID INT).\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Does the database support multiple open result sets.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsMultipleOpenResults() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether multiple result sets are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsMultipleResultSets() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether multiple transactions are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsMultipleTransactions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Does the database support named parameters.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsNamedParameters() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether columns with NOT NULL are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsNonNullableColumns() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether open result sets across commits are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsOpenCursorsAcrossCommit() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether open result sets across rollback are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsOpenCursorsAcrossRollback() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether open statements across commit are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsOpenStatementsAcrossCommit() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether open statements across rollback are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsOpenStatementsAcrossRollback() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether ORDER BY is supported if the column is not in the SELECT\n\t * list.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsOrderByUnrelated() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether outer joins are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsOuterJoins() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether positioned deletes are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsPositionedDelete() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether positioned updates are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsPositionedUpdate() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether a specific result set concurrency is supported.\n\t */\n\t@Override\n\tpublic boolean supportsResultSetConcurrency(int type, int concurrency)\n\t\t\tthrows SQLException {\n\t\treturn type != ResultSet.TYPE_SCROLL_SENSITIVE;\n\t}\n\n\t/**\n\t * Does this database supports a result set holdability.\n\t *\n\t * @return true if the holdability is ResultSet.CLOSE_CURSORS_AT_COMMIT\n\t */\n\t@Override\n\tpublic boolean supportsResultSetHoldability(int holdability)\n\t\t\tthrows SQLException {\n\t\treturn holdability == ResultSet.CLOSE_CURSORS_AT_COMMIT;\n\t}\n\n\t/**\n\t * Returns whether a specific result set type is supported.\n\t */\n\t@Override\n\tpublic boolean supportsResultSetType(int type) throws SQLException {\n\t\treturn type != ResultSet.TYPE_SCROLL_SENSITIVE;\n\t}\n\n\t/**\n\t * Returns wheter savepoints is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSavepoints() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether the schema name in INSERT, UPDATE, DELETE is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInDataManipulation() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether the schema name in CREATE INDEX is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInIndexDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInPrivilegeDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInProcedureCalls() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInTableDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSelectForUpdate() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Does the database support statement pooling.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsStatementPooling() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether the database supports calling functions using the call syntax.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether stored procedures are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsStoredProcedures() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether subqueries (SELECT) in comparisons are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSubqueriesInComparisons() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether SELECT in EXISTS is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSubqueriesInExists() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether IN(SELECT...) is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSubqueriesInIns() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether subqueries in quantified expression are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSubqueriesInQuantifieds() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether table correlation names (table alias) are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsTableCorrelationNames() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether a specific transaction isolation level.\n\t *\n\t * @return true, if level is TRANSACTION_READ_COMMITTED\n\t */\n\t@Override\n\tpublic boolean supportsTransactionIsolationLevel(int level)\n\t\t\tthrows SQLException {\n\t\tswitch (level) {\n\t\tcase Connection.TRANSACTION_READ_COMMITTED:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Returns whether transactions are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsTransactions() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether UNION SELECT is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsUnion() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether UNION ALL SELECT is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsUnionAll() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether updates are detected.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean updatesAreDetected(int i) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if this database use one file per table.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean usesLocalFilePerTable() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if this database store data in local files.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean usesLocalFiles() throws SQLException {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isWrapperFor(Class<?> iface) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"isWrapperFor\")\n\t\t\t\t.getSQLException();\n\t}\n\n\t@Override\n\tpublic <T> T unwrap(Class<T> iface) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"unwrap\")\n\t\t\t\t.getSQLException();\n\t}\n}",
"public class DbException extends RuntimeException {\n\tprivate static final long serialVersionUID = -2273043887990931388L;\n\tprivate static final ResourceBundle MESSAGES;\n\n\tstatic {\n\t\tMESSAGES = ResourceBundle.getBundle(\"net.unit8.solr.jdbc.message.messages\");\n\t}\n\n\tprivate DbException(SQLException e) {\n\t\tsuper(e.getMessage(), e);\n\t}\n\n\tpublic static DbException get(int errorCode) {\n\t\treturn get(errorCode, (String)null);\n\t}\n\n\tpublic static DbException get(int errorCode, Throwable cause, String...params) {\n\t\treturn new DbException(getSQLException(errorCode, cause, params));\n\t}\n\n public static DbException get(int errorCode, String... params) {\n return new DbException(getSQLException(errorCode, null, params));\n }\n\n\tprivate static String translate(String key, String ... params) {\n\t\tString message = null;\n\t\tif(MESSAGES != null) {\n\t\t\tmessage = MESSAGES.getString(key);\n\t\t}\n\t\tif (message == null) {\n\t\t\tmessage = \"(Message \" + key + \" not found)\";\n\t\t}\n\t\tif (params != null) {\n\t\t\tmessage = MessageFormat.format(message, (Object[])params);\n\t\t}\n\t\treturn message;\n\t}\n\n\tpublic SQLException getSQLException() {\n\t\treturn (SQLException) getCause();\n\t}\n\tprivate static SQLException getSQLException(int errorCode, Throwable cause, String ... params) {\n\t\tString sqlstate = ErrorCode.getState(errorCode);\n\t\tString message = translate(sqlstate, params);\n\t\tSQLException sqlException = new SQLException(message, sqlstate, errorCode);\n if (cause != null)\n sqlException.initCause(cause);\n return sqlException;\n\t}\n\n public static SQLException toSQLException(Exception e) {\n if (e instanceof SQLException) {\n return (SQLException) e;\n }\n return convert(e).getSQLException();\n }\n\n public static DbException convert(Throwable e) {\n if (e instanceof DbException) {\n return (DbException) e;\n } else if (e instanceof SQLException) {\n return new DbException((SQLException) e);\n } else if (e instanceof InvocationTargetException) {\n return convertInvocation((InvocationTargetException) e, null);\n } else if (e instanceof IOException) {\n return get(ErrorCode.IO_EXCEPTION, e, e.toString());\n } else if (e instanceof OutOfMemoryError) {\n return get(ErrorCode.OUT_OF_MEMORY, e);\n } else if (e instanceof StackOverflowError || e instanceof LinkageError) {\n return get(ErrorCode.GENERAL_ERROR, e, e.toString());\n } else if (e instanceof Error) {\n throw (Error) e;\n }\n return get(ErrorCode.GENERAL_ERROR, e, e.toString());\n }\n\n public static DbException convertInvocation(InvocationTargetException te, String message) {\n Throwable t = te.getTargetException();\n if (t instanceof SQLException || t instanceof DbException) {\n return convert(t);\n }\n message = message == null ? t.getMessage() : message + \": \" + t.getMessage();\n return get(ErrorCode.EXCEPTION_IN_FUNCTION, t, message);\n }\n\n\tpublic static DbException getInvalidValueException(String value, String param) {\n\t\treturn get(ErrorCode.INVALID_VALUE, value, param);\n\t}\n\n}",
"public class ErrorCode {\n\tpublic static final int NO_DATA_AVAILABLE = 2000;\n\tpublic static final int COLUMN_COUNT_DOES_NOT_MATCH = 21002;\n\tpublic static final int NUMERIC_VALUE_OUT_OF_RANGE = 22003;\n public static final int DATA_CONVERSION_ERROR_1 = 22018;\n\tpublic static final int DUPLICATE_KEY_1 = 23505;\n\n\tpublic static final int SYNTAX_ERROR = 42000;\n\tpublic static final int TABLE_OR_VIEW_ALREADY_EXISTS = 42101;\n\tpublic static final int TABLE_OR_VIEW_NOT_FOUND = 42102;\n\tpublic static final int COLUMN_NOT_FOUND = 42122;\n\n\tpublic static final int GENERAL_ERROR = 50000;\n\tpublic static final int UNKNOWN_DATA_TYPE = 50004;\n\tpublic static final int FEATURE_NOT_SUPPORTED = 50100;\n\n\tpublic static final int METHOD_NOT_ALLOWED_FOR_QUERY = 90001;\n\tpublic static final int METHOD_ONLY_ALLOWED_FOR_QUERY = 90002;\n\tpublic static final int NULL_NOT_ALLOWED = 90006;\n\tpublic static final int OBJECT_CLOSED = 90007;\n\tpublic static final int INVALID_VALUE = 90008;\n\tpublic static final int IO_EXCEPTION = 90028;\n public static final int URL_FORMAT_ERROR_2 = 90046;\n\tpublic static final int EXCEPTION_IN_FUNCTION = 90105;\n\tpublic static final int OUT_OF_MEMORY = 90108;\n\tpublic static final int METHOD_NOT_ALLOWED_FOR_PREPARED_STATEMENT = 90130;\n\n\tpublic static String getState(int errorCode) {\n\t\tswitch(errorCode) {\n\t\tcase NO_DATA_AVAILABLE: return \"02000\";\n\t\tcase COLUMN_COUNT_DOES_NOT_MATCH: return \"21S02\";\n\t\tcase SYNTAX_ERROR: return \"42000\";\n\t\tcase TABLE_OR_VIEW_ALREADY_EXISTS: return \"42S01\";\n\t\tcase TABLE_OR_VIEW_NOT_FOUND: return \"42S02\";\n\t\tcase COLUMN_NOT_FOUND: return \"42S22\";\n\t\tcase FEATURE_NOT_SUPPORTED: return \"HYC00\";\n\t\tcase GENERAL_ERROR: return \"HY000\";\n\t\tdefault:\n\t\t\treturn \"\"+errorCode;\n\t\t}\n\t}\n}",
"public class ConditionParser implements ExpressionVisitor {\n\n\tprivate final StringBuilder query;\n\tprivate List<Parameter> parameters;\n\tprivate String tableName;\n\tprivate final DatabaseMetaDataImpl metaData;\n\tprivate String likeEscapeChar;\n\tprivate ParseContext context = ParseContext.NONE;\n\tprivate Expression currentColumn = null;\n\tprivate static final Pattern pattern = Pattern.compile(\"\\\\?(\\\\d+)\");\n\n\tpublic ConditionParser(DatabaseMetaDataImpl metaData) {\n\t\tthis.metaData = metaData;\n\t\tquery = new StringBuilder();\n\t\tparameters = new ArrayList<Parameter>();\n\t}\n\n\tpublic ConditionParser(DatabaseMetaDataImpl metaData, List<Parameter> parameters) {\n\t\tthis(metaData);\n\t\tthis.parameters.addAll(parameters);\n\t}\n\n\tpublic void setTableName(String tableName) {\n\t\tthis.tableName = metaData.getOriginalTableName(tableName);\n\t}\n\n\tpublic List<Parameter> getParameters() {\n\t\treturn parameters;\n\t}\n\n\tpublic String getQuery(List<Parameter> params) {\n\t\tString queryString;\n\t\tif(query.length() == 0) {\n\t\t\tqueryString = \"id:@\"+tableName+\".*\";\n\t\t} else {\n\t\t\tqueryString = query.toString();\n\t\t}\n\n\t\tMatcher matcher = pattern.matcher(queryString);\n\t\tStringBuffer sb = new StringBuffer();\n\t\twhile(matcher.find()) {\n\t\t\tString index = matcher.group(1);\n\t\t\tint paramIndex = Integer.parseInt(index);\n\t\t\tString paramStr = params.get(paramIndex).getQueryString();\n\n // In appendReplacement method, '\\' is interpreted for escape sequence.\n matcher.appendReplacement(sb, StringUtils.replace(paramStr, \"\\\\\", \"\\\\\\\\\"));\n\t\t}\n\t\tmatcher.appendTail(sb);\n\n\t\treturn sb.toString();\n\t}\n\n\t@Override\n\tpublic void visit(SubSelect arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"subquery\");\n\t}\n\n\t@Override\n\tpublic void visit(NullValue arg0) {\n\t\tquery.append(\"\\\"\\\"\");\n\t}\n\n\t@Override\n\tpublic void visit(Function func) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, func.getName());\n\t}\n\n\t@Override\n\tpublic void visit(InverseExpression arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"-\");\n\t}\n\n\t@Override\n\tpublic void visit(JdbcParameter ph) {\n\t\tParameter p = new Parameter(parameters.size());\n\t\tif(context == ParseContext.LIKE) {\n\t\t\tp.setNeedsLikeEscape();\n\t\t\tif(StringUtils.isNotBlank(likeEscapeChar)) {\n\t\t\t\tp.setLikeEscapeChar(likeEscapeChar);\n\t\t\t}\n\t\t}\n\t\tp.setColumn(currentColumn);\n\t\tparameters.add(p);\n \t\tquery.append(\"?\").append(p.getIndex());\n\t}\n\n\t@Override\n\tpublic void visit(DoubleValue value) {\n\t\tquery.append(ValueDouble.get(value.getValue()).getQueryString());\n\t}\n\n\t@Override\n\tpublic void visit(LongValue value) {\n\t\tquery.append(ValueLong.get(value.getValue()).getQueryString());\n\t}\n\n\t@Override\n\tpublic void visit(DateValue value) {\n\t\tValueDate d = ValueDate.get(value.getValue());\n\t\tquery.append(d.getQueryString());\n\t}\n\n\t@Override\n\tpublic void visit(TimeValue value) {\n\t\tquery.append(value.getValue().toString());\n\t}\n\n\t@Override\n\tpublic void visit(TimestampValue value) {\n\t\tValueDate d = ValueDate.get(new Date(value.getValue().getTime()));\n\t\tquery.append(d.getQueryString());\n\t}\n\n\t@Override\n\tpublic void visit(Parenthesis expr) {\n\t\tquery.append(\"(\");\n\t\texpr.getExpression().accept(this);\n\t\tquery.append(\")\");\n\t}\n\n\t@Override\n\tpublic void visit(StringValue value) {\n\t\tquery.append(value.getValue());\n\t}\n\n\t@Override\n\tpublic void visit(Addition arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"+\");\n\t}\n\n\t@Override\n\tpublic void visit(Division arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"/\");\n\t}\n\n\t@Override\n\tpublic void visit(Multiplication arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"*\");\n\t}\n\n\t@Override\n\tpublic void visit(Subtraction arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"-\");\n\t}\n\n\t@Override\n\tpublic void visit(AndExpression expr) {\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\" AND \");\n\t\texpr.getRightExpression().accept(this);\n\t}\n\n\t@Override\n\tpublic void visit(OrExpression expr) {\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\" OR \");\n\t\texpr.getRightExpression().accept(this);\n\t}\n\n\t@Override\n\tpublic void visit(Between expr) {\n\t\tcontext = ParseContext.BETWEEN;\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\":[\");\n\t\texpr.getBetweenExpressionStart().accept(this);\n\t\tquery.append(\" TO \");\n\t\texpr.getBetweenExpressionEnd().accept(this);\n\t\tquery.append(\"] \");\n\t\tcontext = ParseContext.NONE;\n\t\tcurrentColumn = null;\n\t}\n\n\t@Override\n\tpublic void visit(EqualsTo expr) {\n\t\tcontext = ParseContext.EQUAL;\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\":\");\n\t\texpr.getRightExpression().accept(this);\n\t\tcontext = ParseContext.NONE;\n\t\tcurrentColumn = null;\n\t}\n\n\t@Override\n\tpublic void visit(GreaterThan expr) {\n\t\tcontext = ParseContext.GREATER_THAN;\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\":{\");\n\t\texpr.getRightExpression().accept(this);\n\t\tquery.append(\" TO *} \");\n\t\tcontext = ParseContext.NONE;\n\t\tcurrentColumn = null;\n\t}\n\n\t@Override\n\tpublic void visit(GreaterThanEquals expr) {\n\t\tcontext = ParseContext.GREATER_THAN_EQUAL;\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\":[\");\n\t\texpr.getRightExpression().accept(this);\n\t\tquery.append(\" TO *] \");\n\t\tcontext = ParseContext.NONE;\n\t\tcurrentColumn = null;\n\t}\n\n\t@Override\n\tpublic void visit(InExpression expr) {\n\t\tcontext = ParseContext.IN;\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\":(\");\n\t\tItemListParser itemListParser = new ItemListParser(parameters);\n\t\texpr.getItemsList().accept(itemListParser);\n\t\tparameters = itemListParser.getParameters();\n\n\t\tfor(Item item : itemListParser.getItemList()) {\n\t\t\tif(item instanceof Parameter) {\n\t\t\t\tquery.append(\"?\").append(((Parameter)item).getIndex());\n\t\t\t} else {\n\t\t\t\tquery.append(item.getValue().getQueryString()).append(\" \");\n\t\t\t}\n\t\t}\n\t\tquery.append(\") \");\n\t\tcontext = ParseContext.NONE;\n\t\tcurrentColumn = null;\n\t}\n\n\t@Override\n\tpublic void visit(IsNullExpression arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"is null\");\n\t}\n\n\t@Override\n\tpublic void visit(LikeExpression expr) {\n\t\tcontext = ParseContext.LIKE;\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\":\");\n\t\tlikeEscapeChar = expr.getEscape();\n\t\texpr.getRightExpression().accept(this);\n\t\tlikeEscapeChar = null;\n\t\tcontext = ParseContext.NONE;\n\t\tcurrentColumn = null;\n\t}\n\n\t@Override\n\tpublic void visit(MinorThan expr) {\n\t\tcontext = ParseContext.MINOR_THAN;\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\":{* TO \");\n\t\texpr.getRightExpression().accept(this);\n\t\tquery.append(\"}\");\n\t\tcontext = ParseContext.NONE;\n\t\tcurrentColumn = null;\n\t}\n\n\t@Override\n\tpublic void visit(MinorThanEquals expr) {\n\t\tcontext = ParseContext.MINOR_THAN_EQUAL;\n\t\texpr.getLeftExpression().accept(this);\n\t\tquery.append(\":[* TO \");\n\t\texpr.getRightExpression().accept(this);\n\t\tquery.append(\"]\");\n\t\tcontext = ParseContext.NONE;\n\t\tcurrentColumn = null;\n\t}\n\n\t@Override\n\tpublic void visit(NotEqualsTo arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"!=\");\n\t}\n\n\t@Override\n\tpublic void visit(Column column) {\n\t\tExpression solrColumn = metaData.getSolrColumn(tableName, column.getColumnName());\n\t\tif (solrColumn == null) {\n\t\t\tthrow DbException.get(ErrorCode.COLUMN_NOT_FOUND, column.getColumnName());\n\t\t}\n\t\tquery.append(solrColumn.getSolrColumnName());\n\t\tcurrentColumn = solrColumn;\n\n\t}\n\n\t@Override\n\tpublic void visit(CaseExpression arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"case\");\n\t}\n\n\t@Override\n\tpublic void visit(WhenClause arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"when\");\n\t}\n\n\t@Override\n\tpublic void visit(ExistsExpression arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"exists\");\n\t}\n\n\t@Override\n\tpublic void visit(AllComparisonExpression arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"all\");\n\t}\n\n\t@Override\n\tpublic void visit(AnyComparisonExpression arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"any\");\n\t}\n\n\t@Override\n\tpublic void visit(Concat arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"concat\");\n\t}\n\n\t@Override\n\tpublic void visit(Matches arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"matches\");\n\t}\n\n\t@Override\n\tpublic void visit(BitwiseAnd arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"&\");\n\t}\n\n\t@Override\n\tpublic void visit(BitwiseOr arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"|\");\n\t}\n\n\t@Override\n\tpublic void visit(BitwiseXor arg0) {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"^\");\n\t}\n\n\n}"
] | import net.sf.jsqlparser.statement.delete.Delete;
import net.unit8.solr.jdbc.expression.Parameter;
import net.unit8.solr.jdbc.impl.AbstractResultSet;
import net.unit8.solr.jdbc.impl.DatabaseMetaDataImpl;
import net.unit8.solr.jdbc.message.DbException;
import net.unit8.solr.jdbc.message.ErrorCode;
import net.unit8.solr.jdbc.parser.ConditionParser;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import java.io.IOException;
import java.util.ArrayList; | package net.unit8.solr.jdbc.command;
public class DeleteCommand extends Command {
private transient final Delete delStmt;
private ConditionParser conditionParser;
public DeleteCommand(Delete stmt) {
this.parameters = new ArrayList<Parameter>();
this.delStmt = stmt;
}
@Override
public AbstractResultSet executeQuery() { | throw DbException.get(ErrorCode.METHOD_ONLY_ALLOWED_FOR_QUERY); | 4 |
johndavidbustard/RoughWorld | src/utils/shapes/skinned/Animate.java | [
"public class GeneralMatrixDouble implements Serializable\r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic static final double EPSILON=5.9e-8f;\r\n\tpublic int width; //columns\r\n\tpublic int height; //rows\r\n\tpublic double[] value; //array of values\r\n\r\n\tpublic static void main(String[] list) throws Exception \r\n {\r\n\t\tGeneralMatrixDouble pose = new GeneralMatrixDouble(3,3);\r\n\t\tGeneralMatrixDouble vpose = new GeneralMatrixDouble(3,3);\r\n\t\tGeneralMatrixDouble euler = new GeneralMatrixDouble(3,1);\r\n\t\t\r\n\t\tGeneralMatrixDouble tests = new GeneralMatrixDouble(3);\r\n\r\n\t\tdouble v = Math.PI;\r\n\t\ttests.push_back_row(0.0,0.0,0.0);\r\n\t\ttests.push_back_row(v,0.0,0.0);\r\n\t\ttests.push_back_row(0.0,v,0.0);\r\n\t\ttests.push_back_row(v,v,0.0);\r\n\t\ttests.push_back_row(0.0,0.0,v);\r\n\t\ttests.push_back_row(v,0.0,v);\r\n\t\ttests.push_back_row(0.0,v,v);\r\n\t\ttests.push_back_row(v,v,v);\r\n\r\n\t\tfor(int i=0;i<tests.height;i++)\r\n\t\t{\r\n\t\t\tpose.set3DTransformRotationYXZ(tests.value[i*3+0], tests.value[i*3+1], tests.value[i*3+2]);\r\n\t\t\tGeneralMatrixDouble.getEulerYXZ(pose, euler);\r\n\t\t\tdouble errx = euler.value[0]-tests.value[i*3+0];\r\n\t\t\tdouble erry = euler.value[1]-tests.value[i*3+1];\r\n\t\t\tdouble errz = euler.value[2]-tests.value[i*3+2];\r\n\t\t\tSystem.out.println(\"err \"+i+\" x:\"+errx+\" y:\"+erry+\" z:\"+errz);\r\n\t\t\tvpose.set3DTransformRotationYXZ(euler.value[0], euler.value[1], euler.value[2]);\r\n\t\t\t\r\n\t\t}\r\n }\r\n\t\r\n\tpublic void printTransform2()\r\n\t{\r\n\t\tSystem.out.println(\"Xx:\"+value[0+0]+ \"\\tXy:\"+value[1+0]);\r\n\t\tSystem.out.println(\"Yx:\"+value[0+2]+ \"\\tYy:\"+value[1+2]);\r\n\t}\r\n\tpublic void printTransform()\r\n\t{\r\n\t\tSystem.out.println(\"Xx:\"+value[0+0]+ \"\\tXy:\"+value[1+0]+ \"\\tXz:\"+value[2+0]);\r\n\t\tSystem.out.println(\"Yx:\"+value[0+4]+ \"\\tYy:\"+value[1+4]+ \"\\tYz:\"+value[2+4]);\r\n\t\tSystem.out.println(\"Zx:\"+value[0+8]+ \"\\tZy:\"+value[1+8]+ \"\\tZz:\"+value[2+8]);\r\n\t\tSystem.out.println(\"Tx:\"+value[0+12]+\"\\tTy:\"+value[1+12]+\"\\tTz:\"+value[2+12]);\r\n\t}\r\n\tpublic void printProjection()\r\n\t{\r\n\t\tSystem.out.println(\"Xx:\"+value[0+0]+ \"\\tXy:\"+value[1+0]+ \"\\tXz:\"+value[2+0]);\r\n\t\tSystem.out.println(\"Yx:\"+value[0+4]+ \"\\tYy:\"+value[1+4]+ \"\\tYz:\"+value[2+4]);\r\n\t\tSystem.out.println(\"Zx:\"+value[0+8]+ \"\\tZy:\"+value[1+8]+ \"\\tZz:\"+value[2+8]);\r\n\t\tSystem.out.println(\"Tx:\"+value[0+12]+\"\\tTy:\"+value[1+12]+\"\\tTz:\"+value[2+12]);\r\n\t\tSystem.out.println(\"Hx:\"+value[3+0]+ \"\\tHy:\"+value[3+4]+ \"\\tHz:\"+value[3+8]+\"\\tHt:\"+value[3+12]);\r\n\t}\r\n\t\r\n\tpublic static double calculateMachineEpsilonDouble() \r\n\t{\r\n double machEps = 1.0f;\r\n \r\n do {\r\n machEps /= 2.0f;\r\n }\r\n while ((double)(1.0 + (machEps/2.0)) != 1.0);\r\n \r\n return machEps;\r\n }\r\n\t\r\n\tpublic GeneralMatrixDouble(double[] v)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = v.length;\r\n\t\tvalue = v;\r\n\t}\r\n\tpublic GeneralMatrixDouble(double a)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 1;\r\n\t\tvalue = new double[1];\r\n\t\tvalue[0] = a;\r\n\t}\r\n\tpublic GeneralMatrixDouble(double a,double b)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 2;\r\n\t\tvalue = new double[2];\r\n\t\tvalue[0] = a;\r\n\t\tvalue[1] = b;\r\n\t}\r\n\tpublic GeneralMatrixDouble(GeneralMatrixDouble a)\r\n\t{\r\n\t\tthis.width = a.width;\r\n\t\tthis.height = a.height;\r\n\t\tvalue = new double[a.width*a.height];\r\n\t\tset(a);\r\n\t}\r\n\tpublic GeneralMatrixDouble(GeneralMatrixFloat a)\r\n\t{\r\n\t\tthis.width = a.width;\r\n\t\tthis.height = a.height;\r\n\t\tvalue = new double[a.width*a.height];\r\n\t\tset(a);\r\n\t}\r\n\tpublic GeneralMatrixDouble(int width,int height)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = new double[width*height];\r\n\t}\r\n\tpublic GeneralMatrixDouble(int width,int height,double[] v)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = v;\r\n\t}\r\n\tpublic GeneralMatrixDouble()\r\n\t{\r\n\t\twidth = 0;\r\n\t\theight = 0;\r\n\t}\r\n\r\n\t public boolean isequal(GeneralMatrixDouble m)\r\n\t {\r\n\t\t if(width!=m.width)\r\n\t\t\t return false;\r\n\t\t if(height!=m.height)\r\n\t\t\t return false;\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t if(value[i]!=m.value[i])\r\n\t\t\t\t return false;\r\n\t\t }\t\t \r\n\t\t return true;\r\n\t }\r\n\r\n\t \r\n\tpublic void clear(double v)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = v;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic final double get(int i,int j)\r\n\t{\r\n\t\treturn value[j*width+i];\r\n\t}\r\n\r\n\tpublic void reshape(int nw,int nh)\r\n\t{\r\n\t\tensureCapacity(nw*nh);\r\n\t\tif(nw<width)\r\n\t\t{\r\n\t\t\tfor(int j=0;j<nh;j++)\r\n\t\t\t{\r\n\t\t\t\tfor(int i=0;i<nw;i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i+j*nw] = value[i+j*width];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor(int j=(nh-1);j>=0;j--)\r\n\t\t\t{\r\n\t\t\t\tfor(int i=(nw-1);i>=0;i--)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i+j*nw] = value[i+j*width];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\twidth = nw;\r\n\t\theight = nh;\r\n\t}\r\n\t\r\n\tpublic void reshapeleft(int nw,int nh)\r\n\t{\r\n\t\tensureCapacity(nw*nh);\r\n\t\tif(nw<width)\r\n\t\t{\r\n\t\t\tfor(int j=0;j<nh;j++)\r\n\t\t\t{\r\n\t\t\t\tfor(int i=0;i<nw;i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i+j*nw] = value[i+(width-nw)+j*width];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor(int j=(nh-1);j>=0;j--)\r\n\t\t\t{\r\n\t\t\t\tfor(int i=(nw-1);i>=0;i--)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i+(nw-width)+j*nw] = value[i+j*width];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\twidth = nw;\r\n\t\theight = nh;\r\n\t}\r\n\r\n\tpublic double getMirror(int x, int y)\r\n {\r\n if (x >= width)\r\n x = width - (x - width + 2);\r\n\r\n if (y >= height)\r\n y = height - (y - height + 2);\r\n\r\n if (x < 0)\r\n {\r\n int tmp = 0;\r\n int dir = 1;\r\n\r\n while (x < 0)\r\n {\r\n tmp += dir;\r\n if (tmp == width - 1 || tmp == 0)\r\n dir *= -1;\r\n x++;\r\n }\r\n x = tmp;\r\n }\r\n\r\n if (y < 0)\r\n {\r\n int tmp = 0;\r\n int dir = 1;\r\n\r\n while (y < 0)\r\n {\r\n tmp += dir;\r\n if (tmp == height - 1 || tmp == 0)\r\n dir *= -1;\r\n y++;\r\n }\r\n y = tmp;\r\n }\r\n\r\n return value[x+y*width];\r\n }\r\n\r\n\tpublic void set(int i,int j,double v)\r\n\t{\r\n\t\tvalue[j*width+i] = v;\r\n\t}\r\n\r\n\tpublic void add(int i,int j,double v)\r\n\t{\r\n\t\tvalue[j*width+i] += v;\r\n\t}\r\n\r\n\tpublic void set(float[] a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(GeneralMatrixFloat a)\r\n\t{\r\n\t\tensureCapacityNoCopy(a.width*a.height);\r\n\t\twidth = a.width;\r\n\t\theight = a.height;\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(GeneralMatrixDouble a)\r\n\t{\r\n\t\tensureCapacityNoCopy(a.width*a.height);\r\n\t\twidth = a.width;\r\n\t\theight = a.height;\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(double[] a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = (double)a[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(double[][] a)\r\n\t{\r\n\t\t for (int j = 0; j < height; j++)\r\n\t\t {\r\n\t\t\t for (int i = 0; i < width; i++)\r\n\t\t\t {\r\n\t\t\t\t value[i+j*width] = (double)a[j][i];\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic void setDiagonal(double v)\r\n\t{\r\n\t\t for (int i = 0; i < width; i++)\r\n\t\t {\r\n\t\t\t value[i+i*width] = v;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static double determinant(GeneralMatrixDouble m)\r\n\t{\r\n\t\tint n = m.width; \r\n\t\tif(n==1)\r\n\t\t\treturn m.value[0];\r\n\t\telse\r\n\t\tif(n==2)\r\n\t\t{\r\n\t\t\treturn m.value[0*2+0] * m.value[1*2+1] - m.value[1*2+0] * m.value[0*2+1];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat det = 0.0f;\r\n\t\t\tfor (int j1=0;j1<n;j1++) \r\n\t\t\t{\r\n\t\t if(m.value[0*n+j1]==0.0f)\r\n\t\t \t continue;\r\n\r\n\t\t GeneralMatrixDouble subm = new GeneralMatrixDouble(n-1,n-1);\r\n\r\n\t\t for (int i=1;i<n;i++) \r\n\t\t {\r\n\t\t int j2 = 0;\r\n\t\t for (int j=0;j<n;j++) \r\n\t\t {\r\n\t\t if (j == j1)\r\n\t\t continue;\r\n\t\t subm.value[(i-1)*(n-1)+j2] = m.value[i*n+j];\r\n\t\t j2++;\r\n\t\t }\r\n\t\t }\r\n\t\t int ind = 1+j1+1;\r\n\t\t \r\n\t\t if((ind%2)==0)\r\n\t\t \t det += m.value[0*n+j1] * determinant(subm);\r\n\t\t else\r\n\t\t \t det -= m.value[0*n+j1] * determinant(subm);\r\n\t\t\t}\r\n\t\t\treturn det;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void set3DTransformPosition(double x,double y,double z)\r\n\t{\r\n\t\tvalue[4*3+0] = x;\r\n\t\tvalue[4*3+1] = y;\r\n\t\tvalue[4*3+2] = z;\r\n\t}\r\n\tpublic void set3DTransformZRotation(double z)\r\n\t{\r\n\t\tdouble sin=(double)Math.sin(z);\r\n\t\tdouble cos=(double)Math.cos(z);\r\n\t\tvalue[width*0+0] = cos;\r\n\t\tvalue[width*0+1] = -sin;\r\n\t\tvalue[width*1+0] = sin;\r\n\t\tvalue[width*1+1] = cos;\r\n\t\tvalue[width*2+2] = 1.0f;\r\n\t}\r\n\tpublic void set3DTransformYRotation(double y)\r\n\t{\r\n\t\tdouble sin=(double)Math.sin(y);\r\n\t\tdouble cos=(double)Math.cos(y);\r\n\t\tvalue[width*0+0] = cos;\r\n\t\tvalue[width*0+2] = sin;\r\n\t\tvalue[width*2+0] = -sin;\r\n\t\tvalue[width*2+2] = cos;\r\n\t\tvalue[width*1+1] = 1.0f;\r\n\t}\r\n\tpublic void set3DTransformXRotation(double x)\r\n\t{\r\n\t\tdouble sin=(double)Math.sin(x);\r\n\t\tdouble cos=(double)Math.cos(x);\r\n\t\tvalue[width*1+1] = cos;\r\n\t\tvalue[width*1+2] = -sin;\r\n\t\tvalue[width*2+1] = sin;\r\n\t\tvalue[width*2+2] = cos;\r\n\t\tvalue[width*0+0] = 0.0f;\r\n\t}\r\n\r\n\tpublic void set3DTransformRotationYFirst(double x,double y,double z)\r\n\t{\r\n\t\t//Normal result\r\n\t\tdouble sx=(double)Math.sin(x);\r\n\t\tdouble cx=(double)Math.cos(x);\r\n\t\tdouble sy=(double)Math.sin(y);\r\n\t\tdouble cy=(double)Math.cos(y);\r\n\t\tdouble sz=(double)Math.sin(z);\r\n\t\tdouble cz=(double)Math.cos(z);\r\n\t\t\r\n\t\t//times this\r\n\t\t//0, 1, 0\r\n\t\t//-1, 0, 0\r\n\t\t//0, 0, 1\r\n\r\n//\t\tvalue[4*0+0] = cz*cy;\r\n//\t\tvalue[4*0+1] = (sy*sx*cz-cx*sz);\r\n//\t\tvalue[4*0+2] = (sy*cx*cz+sz*sx);\r\n//\r\n//\t\tvalue[4*1+0] = sz*cy;\r\n//\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n//\t\tvalue[4*1+2] = (sy*cx*sz-cz*sx);\r\n//\r\n//\t\tvalue[4*2+0] = -sy;\r\n//\t\tvalue[4*2+1] = cy*sx;\r\n//\t\tvalue[4*2+2] = cy*cx;\r\n\r\n\t\t\r\n\t\t//by this \r\n//\t\tvalue[4*0+0] = sz*cy;\r\n//\t\tvalue[4*0+1] = (sy*sx*sz+cx*cz);\r\n//\t\tvalue[4*0+2] = (sy*cx*sz-cz*sx);\r\n//\r\n//\t\tvalue[4*1+0] = -cz*cy;\r\n//\t\tvalue[4*1+1] = -(sy*sx*cz-cx*sz);\r\n//\t\tvalue[4*1+2] = -(sy*cx*cz+sz*sx);\r\n//\r\n//\t\tvalue[4*2+0] = -sy;\r\n//\t\tvalue[4*2+1] = cy*sx;\r\n//\t\tvalue[4*2+2] = cy*cx;\r\n\t\t\r\n\t\t//times this\r\n\t\t//0, -1, 0\r\n\t\t//1, 0, 0\r\n\t\t//0, 0, 1\r\n\r\n\t\t//First rotate by -90 z \t\t\r\n\t\t//x axis becomes y\r\n\t\t//y becomes -x\r\n\t\t\r\n//\t\tfor (int k=0; k<3; k++) \r\n//\t\t{\r\n//\t\tfor (int j=0; j<3; j++) \r\n//\t\t{\r\n//\t\t\trbmat.value[k*3+j] = \r\n//\t\t\t\tbmat.value[k*3+0] * procrustesTransform.value[0*4+j] +\r\n//\t\t\t\tbmat.value[k*3+1] * procrustesTransform.value[1*4+j] +\r\n//\t\t\t\tbmat.value[k*3+2] * procrustesTransform.value[2*4+j];\r\n//\t\t}\r\n//\t\t}\r\n\t\t\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[4*0+1] = -sz*cy;\r\n\t\t\tvalue[4*0+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[4*1+0] = -(sy*sx*cz-cx*sz);\r\n\t\t\tvalue[4*1+1] = cz*cy;\r\n\t\t\tvalue[4*1+2] = -(sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = cy*sx;\r\n\t\t\tvalue[4*2+1] = sy;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[3*0+1] = -sz*cy;\r\n\t\t\tvalue[3*0+2] = (sy*cx*sz-cz*sx);\r\n\r\n\t\t\tvalue[3*1+0] = -(sy*sx*cz-cx*sz);\r\n\t\t\tvalue[3*1+1] = cz*cy;\r\n\t\t\tvalue[3*1+2] = -(sy*cx*cz+sz*sx);\r\n\r\n\t\t\tvalue[3*2+0] = cy*sx;\r\n\t\t\tvalue[3*2+1] = sy;\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t//then rotate back +90 z\r\n\t\t//x axis becomes -y\r\n\t\t//y becomes x\r\n\t}\r\n\r\n\tpublic void set3DTransformRotation(double x,double y,double z)\r\n\t{\r\n\t\tdouble sx=(double)Math.sin(x);\r\n\t\tdouble cx=(double)Math.cos(x);\r\n\t\tdouble sy=(double)Math.sin(y);\r\n\t\tdouble cy=(double)Math.cos(y);\r\n\t\tdouble sz=(double)Math.sin(z);\r\n\t\tdouble cz=(double)Math.cos(z);\r\n\r\n\t if(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*0+1] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[4*0+2] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[4*1+0] = sz*cy;\r\n\t\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[4*1+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = -sy;\r\n\t\t\tvalue[4*2+1] = cy*sx;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cz*cy;\r\n\t\t\tvalue[3*0+1] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[3*0+2] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[3*1+0] = sz*cy;\r\n\t\t\tvalue[3*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[3*1+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[3*2+0] = -sy;\r\n\t\t\tvalue[3*2+1] = cy*sx;\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n//\t [ (cy*cz)+(sy*sx*sz) , (cy*(-(sz)))+(sy*sx*cz) ,sy*cx]\r\n//\t [ ]\r\n//\t [ cx*sz , cx*cz ,-(sx)]\r\n//\t [ ]\r\n//\t [((-(sy))*cz)+(cy*sx*sz),((-(sy))*(-(sz)))+(cy*sx*cz),cy*cx]\r\n\tpublic void set3DTransformRotationYXZ(double x,double y,double z)\r\n\t{\r\n\t\tdouble sx=(double)Math.sin(x);\r\n\t\tdouble cx=(double)Math.cos(x);\r\n\t\tdouble sy=(double)Math.sin(y);\r\n\t\tdouble cy=(double)Math.cos(y);\r\n\t\tdouble sz=(double)Math.sin(z);\r\n\t\tdouble cz=(double)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (cy*cz)+(sy*sx*sz);\r\n\t\t\tvalue[4*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n\t\t\tvalue[4*0+2] = sy*cx;\r\n\t\r\n\t\t\tvalue[4*1+0] = cx*sz;\r\n\t\t\tvalue[4*1+1] = cx*cz;\r\n\t\t\tvalue[4*1+2] = -(sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n\t\t\tvalue[4*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = (cy*cz)+(sy*sx*sz);\r\n\t\t\tvalue[3*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n\t\t\tvalue[3*0+2] = sy*cx;\r\n\t\r\n\t\t\tvalue[3*1+0] = cx*sz;\r\n\t\t\tvalue[3*1+1] = cx*cz;\r\n\t\t\tvalue[3*1+2] = -(sx);\r\n\t\r\n\t\t\tvalue[3*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n\t\t\tvalue[3*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static final void getEulerYXZ(GeneralMatrixFloat m, GeneralMatrixFloat euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\t\t\r\n\t\tdouble cx = Math.sqrt(m.value[j*w+i]*m.value[j*w+i] + m.value[j*w+j]*m.value[j*w+j]);\r\n\t\tif (cx > 16*EPSILON) {\r\n\t\t euler.value[0] = (float)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = (float)Math.atan2(m.value[i*w+k], m.value[k*w+k]);\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[j*w+i], m.value[j*w+j]);\r\n\t\t} else {\r\n\t\t\teuler.value[0] = (float)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = 0;\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[i*w+i], m.value[i*w+j]);\r\n\t\t}\r\n\t}\r\n\tpublic static final void getEulerYXZ(GeneralMatrixDouble m, GeneralMatrixDouble euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\t\t\r\n\t\tdouble cx = Math.sqrt(m.value[j*w+i]*m.value[j*w+i] + m.value[j*w+j]*m.value[j*w+j]);\r\n\t\tif (cx > 16*EPSILON) {\r\n\t\t euler.value[0] = (double)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = (double)Math.atan2(m.value[i*w+k], m.value[k*w+k]);\r\n\t\t euler.value[2] = (double)Math.atan2(m.value[j*w+i], m.value[j*w+j]);\r\n\t\t} else {\r\n\t\t\teuler.value[0] = (double)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = 0;\r\n\t\t euler.value[2] = (double)Math.atan2(m.value[i*w+i], m.value[i*w+j]);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static final void getEuler(GeneralMatrixFloat m, GeneralMatrixDouble euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+i]*m.value[i*w+i] + m.value[j*w+i]*m.value[j*w+i]);\r\n\t\tif (cy > 16*EPSILON) {\r\n\t\t euler.value[0] = (double)Math.atan2(m.value[k*w+j], m.value[k*w+k]);\r\n\t\t euler.value[1] = (double)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = (double)Math.atan2(m.value[j*w+i], m.value[i*w+i]);\r\n\t\t} else {\r\n\t\t euler.value[0] = (double)Math.atan2(-m.value[i*w+k], m.value[j*w+j]);\r\n\t\t euler.value[1] = (double)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void getEuler(GeneralMatrixDouble m, GeneralMatrixDouble euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+i]*m.value[i*w+i] + m.value[j*w+i]*m.value[j*w+i]);\r\n\t\tif (cy > 16*EPSILON) {\r\n\t\t euler.value[0] = (double)Math.atan2(m.value[k*w+j], m.value[k*w+k]);\r\n\t\t euler.value[1] = (double)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = (double)Math.atan2(m.value[j*w+i], m.value[i*w+i]);\r\n\t\t} else {\r\n\t\t euler.value[0] = (double)Math.atan2(-m.value[i*w+k], m.value[j*w+j]);\r\n\t\t euler.value[1] = (double)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void getEuler(GeneralMatrixDouble m, GeneralMatrixFloat euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+i]*m.value[i*w+i] + m.value[j*w+i]*m.value[j*w+i]);\r\n\t\tif (cy > 16*EPSILON) {\r\n\t\t euler.value[0] = (float)Math.atan2(m.value[k*w+j], m.value[k*w+k]);\r\n\t\t euler.value[1] = (float)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[j*w+i], m.value[i*w+i]);\r\n\t\t} else {\r\n\t\t euler.value[0] = (float)Math.atan2(-m.value[i*w+k], m.value[j*w+j]);\r\n\t\t euler.value[1] = (float)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void calcBasisFromY(double x,double y,double z,\r\n\t\t\tdouble Xx,double Xy,double Xz)\r\n\t{\r\n\t\tvalue[width*1+0] = x;\r\n\t\tvalue[width*1+1] = y;\r\n\t\tvalue[width*1+2] = z;\r\n\t\tdouble total = x*x;\r\n\t\ttotal += y*y;\r\n\t\ttotal += z*z;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*1+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[width*1+0] /= total;\r\n\t\tvalue[width*1+1] /= total;\r\n\t\tvalue[width*1+2] /= total;\r\n\t\t\r\n\t\ttotal = Xx*Xx;\r\n\t\ttotal += Xy*Xy;\r\n\t\ttotal += Xz*Xz;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*0+0] = Xx/total;\r\n\t\t\tvalue[width*0+1] = Xy/total;\r\n\t\t\tvalue[width*0+2] = Xz/total;\r\n\t\t}\r\n\r\n\t\t\r\n\t\tvalue[width*2+0] = -y*value[width*0+2]+value[width*0+1]*z;\r\n\t\tvalue[width*2+1] = -z*value[width*0+0]+value[width*0+2]*x;\r\n\t\tvalue[width*2+2] = -x*value[width*0+1]+value[width*0+0]*y;\r\n\r\n\t\t//Normalise\r\n\t\ttotal = value[width*2+0]*value[width*2+0];\r\n\t\ttotal += value[width*2+1]*value[width*2+1];\r\n\t\ttotal += value[width*2+2]*value[width*2+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*2+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*2+0] /= total;\r\n\t\t\tvalue[width*2+1] /= total;\r\n\t\t\tvalue[width*2+2] /= total;\r\n\t\t}\r\n\t\t\r\n\t\tvalue[width*0+0] = y*value[width*2+2]-value[width*2+1]*z;\r\n\t\tvalue[width*0+1] = z*value[width*2+0]-value[width*2+2]*x;\r\n\t\tvalue[width*0+2] = x*value[width*2+1]-value[width*2+0]*y;\r\n\r\n\t\ttotal = value[width*0+0]*value[width*0+0];\r\n\t\ttotal += value[width*0+1]*value[width*0+1];\r\n\t\ttotal += value[width*0+2]*value[width*0+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*0+0] /= total;\r\n\t\t\tvalue[width*0+1] /= total;\r\n\t\t\tvalue[width*0+2] /= total;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void calcBasisFromY(double x,double y,double z,\r\n\t\t\tdouble Xx,double Xy,double Xz,\r\n\t\t\tint width,int off)\r\n\t{\r\n\t\tvalue[width*1+0+off] = x;\r\n\t\tvalue[width*1+1+off] = y;\r\n\t\tvalue[width*1+2+off] = z;\r\n\t\tdouble total = x*x;\r\n\t\ttotal += y*y;\r\n\t\ttotal += z*z;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*1+0+off] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[width*1+0+off] /= total;\r\n\t\tvalue[width*1+1+off] /= total;\r\n\t\tvalue[width*1+2+off] /= total;\r\n\t\t\r\n\t\ttotal = Xx*Xx;\r\n\t\ttotal += Xy*Xy;\r\n\t\ttotal += Xz*Xz;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0+off] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*0+0+off] = Xx/total;\r\n\t\t\tvalue[width*0+1+off] = Xy/total;\r\n\t\t\tvalue[width*0+2+off] = Xz/total;\r\n\t\t}\r\n\r\n\t\t\r\n\t\tvalue[width*2+0+off] = -y*value[width*0+2+off]+value[width*0+1+off]*z;\r\n\t\tvalue[width*2+1+off] = -z*value[width*0+0+off]+value[width*0+2+off]*x;\r\n\t\tvalue[width*2+2+off] = -x*value[width*0+1+off]+value[width*0+0+off]*y;\r\n\r\n\t\t//Normalise\r\n\t\ttotal = value[width*2+0+off]*value[width*2+0+off];\r\n\t\ttotal += value[width*2+1+off]*value[width*2+1+off];\r\n\t\ttotal += value[width*2+2+off]*value[width*2+2+off];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*2+0+off] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*2+0+off] /= total;\r\n\t\t\tvalue[width*2+1+off] /= total;\r\n\t\t\tvalue[width*2+2+off] /= total;\r\n\t\t}\r\n\t\t\r\n\t\tvalue[width*0+0+off] = y*value[width*2+2+off]-value[width*2+1+off]*z;\r\n\t\tvalue[width*0+1+off] = z*value[width*2+0+off]-value[width*2+2+off]*x;\r\n\t\tvalue[width*0+2+off] = x*value[width*2+1+off]-value[width*2+0+off]*y;\r\n\r\n\t\ttotal = value[width*0+0+off]*value[width*0+0+off];\r\n\t\ttotal += value[width*0+1+off]*value[width*0+1+off];\r\n\t\ttotal += value[width*0+2+off]*value[width*0+2+off];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0+off] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*0+0+off] /= total;\r\n\t\t\tvalue[width*0+1+off] /= total;\r\n\t\t\tvalue[width*0+2+off] /= total;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void setSubset(GeneralMatrixDouble subset,int xs,int ys)\r\n\t{\r\n\t\tint maxy = ys+subset.height;\r\n\t\tint maxx = xs+subset.width;\r\n\t\tfor(int y=ys;y<maxy;y++)\r\n\t\t{\r\n\t\t\tfor(int x=xs;x<maxx;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[x+y*width] = subset.value[(x-xs)+(y-ys)*subset.width];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic void clearSubset(int xs,int ys,int sw,int sh,double v)\r\n\t{\r\n\t\tint maxy = ys+sh;\r\n\t\tint maxx = xs+sw;\r\n\t\tfor(int y=ys;y<maxy;y++)\r\n\t\t{\r\n\t\t\tfor(int x=xs;x<maxx;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[x+y*width] = v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//For setting a vec or mat from an array of vecs/mats\r\n\tpublic void setFromSubset(GeneralMatrixDouble full,int ys)\r\n\t{\r\n\t\tint i=0;\r\n\t\tint fi = ys*width;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = full.value[fi];\r\n\t\t\t\ti++;\r\n\t\t\t\tfi++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic void setFromSubset(GeneralMatrixFloat full,int ys)\r\n\t{\r\n\t\tint i=0;\r\n\t\tint fi = ys*width;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = full.value[fi];\r\n\t\t\t\ti++;\r\n\t\t\t\tfi++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n public void setRow(int r,GeneralMatrixDouble row)\r\n {\r\n \tSystem.arraycopy(row.value, 0, value, width*(r), width);\r\n }\r\n\t\r\n\tpublic static double norm(GeneralMatrixDouble a)\r\n\t{\r\n\t\tdouble total = 0.0f;\r\n\t\tfor (int i = 0; i < a.width*a.height; i++)\r\n\t\t{\r\n\t\t\ttotal += a.value[i]*a.value[i];\r\n\t\t}\r\n\t\ttotal = (double)Math.sqrt(total);\r\n\t\treturn total;\r\n\t}\r\n\r\n\tpublic void normalise()\r\n\t{\r\n\t\tdouble total = 0.0f;\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i]*value[i];\r\n\t\t}\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[0] = 1.0f;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ttotal = (double)Math.sqrt(total);\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] /= total;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void rowNormalise(int row)\r\n\t{\r\n\t\tdouble total = 0.0f;\r\n\t\tfor (int i = 0; i < width; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i+row*width]*value[i+row*width];\r\n\t\t}\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[0+row*width] = 1.0f;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ttotal = (double)Math.sqrt(total);\r\n\t\tfor (int i = 0; i < width; i++)\r\n\t\t{\r\n\t\t\tvalue[i+row*width] /= total;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void reverse()\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = -value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic void scale(double s)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = value[i]*s;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic void setIdentity()\r\n\t{\r\n\t\tint i=0;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tif(x==y)\r\n\t\t\t\t\tvalue[i] = 1.0f;\r\n\t\t\t\telse\r\n\t\t\t\t\tvalue[i] = 0.0f;\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//Must be square\r\n\tpublic static final boolean invert(GeneralMatrixDouble a,GeneralMatrixDouble ia)\r\n\t{\r\n\t\tGeneralMatrixDouble temp = new GeneralMatrixDouble(a.width,a.height);\r\n\t\ttemp.set(a);\r\n\r\n\t\tia.setIdentity();\r\n\t\tint i,j,k,swap;\r\n\t\tdouble t;\r\n\t\tfor(i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tswap = i;\r\n\t\t\tfor (j = i + 1; j < a.height; j++) {\r\n\t\t\t if (Math.abs(a.get(i, j)) > Math.abs(a.get(i, j)))\r\n\t\t\t {\r\n\t\t\t \tswap = j;\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t\tif (swap != i)\r\n\t\t\t{\r\n\t\t\t /*\r\n\t\t\t ** Swap rows.\r\n\t\t\t */\r\n\t\t\t for (k = 0; k < a.width; k++)\r\n\t\t\t {\r\n\t\t\t\t\tt = temp.get(k,i);\r\n\t\t\t\t\ttemp.set(k,i,temp.get(k, swap));\r\n\t\t\t\t\ttemp.set(k, swap,t);\r\n\r\n\t\t\t\t\tt = ia.get(k,i);\r\n\t\t\t\t\tia.set(k,i,ia.get(k, swap));\r\n\t\t\t\t\tia.set(k, swap,t);\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t\tt = temp.get(i,i);\r\n\t\t\tif (t == 0.0f)\r\n\t\t\t{\r\n\t\t\t /*\r\n\t\t\t ** No non-zero pivot. The matrix is singular, which shouldn't\r\n\t\t\t ** happen. This means the user gave us a bad matrix.\r\n\t\t\t */\r\n\t\t\t return false;\r\n\t\t\t}\r\n\r\n\t\t\tfor (k = 0; k < a.width; k++)\r\n\t\t\t{\r\n\t\t\t\ttemp.set(k,i,temp.get(k,i) / t);\r\n\t\t\t\tia.set(k,i,ia.get(k,i) / t);\r\n\t\t\t}\r\n\t\t\tfor (j = 0; j < a.width; j++)\r\n\t\t\t{\r\n\t\t\t if (j != i)\r\n\t\t\t {\r\n\t\t\t \tt = temp.get(i,j);\r\n\t\t\t \tfor (k = 0; k < a.width; k++)\r\n\t\t\t \t{\r\n\t\t\t \t\ttemp.set(k,j, temp.get(k,j) - temp.get(k,i)*t);\r\n\t\t\t \t\tia.set(k,j, ia.get(k,j) - ia.get(k,i)*t);\r\n\t\t\t \t}\r\n\t\t\t }\r\n\t\t\t}\r\n\t }\r\n\t return true;\r\n\t}\r\n\r\n\tpublic static final void invertTransform(GeneralMatrixDouble cameraTransformMatrix,GeneralMatrixDouble modelMatrix)\r\n\t{\r\n\t\t//GeneralMatrixFloat.invert(cameraTransformMatrix,modelMatrix);\r\n\t\t//*\r\n\t\tmodelMatrix.value[0*4+0] = cameraTransformMatrix.value[0*4+0];\r\n\t\tmodelMatrix.value[1*4+0] = cameraTransformMatrix.value[0*4+1];\r\n\t\tmodelMatrix.value[2*4+0] = cameraTransformMatrix.value[0*4+2];\r\n\r\n\t\tmodelMatrix.value[0*4+1] = cameraTransformMatrix.value[1*4+0];\r\n\t\tmodelMatrix.value[1*4+1] = cameraTransformMatrix.value[1*4+1];\r\n\t\tmodelMatrix.value[2*4+1] = cameraTransformMatrix.value[1*4+2];\r\n\r\n\t\tmodelMatrix.value[0*4+2] = cameraTransformMatrix.value[2*4+0];\r\n\t\tmodelMatrix.value[1*4+2] = cameraTransformMatrix.value[2*4+1];\r\n\t\tmodelMatrix.value[2*4+2] = cameraTransformMatrix.value[2*4+2];\r\n\r\n\t\tdouble x = -cameraTransformMatrix.value[3*4+0];\r\n\t\tdouble y = -cameraTransformMatrix.value[3*4+1];\r\n\t\tdouble z = -cameraTransformMatrix.value[3*4+2];\r\n\t\t\r\n\t\t//needs to be rotated like the rest of the points in space\r\n\t\tdouble tx = modelMatrix.value[0*4+0]*x+modelMatrix.value[1*4+0]*y+modelMatrix.value[2*4+0]*z;\r\n\t\tdouble ty = modelMatrix.value[0*4+1]*x+modelMatrix.value[1*4+1]*y+modelMatrix.value[2*4+1]*z;\r\n\t\tdouble tz = modelMatrix.value[0*4+2]*x+modelMatrix.value[1*4+2]*y+modelMatrix.value[2*4+2]*z;\r\n\t\tmodelMatrix.value[3*4+0] = tx;\r\n\t\tmodelMatrix.value[3*4+1] = ty;\r\n\t\tmodelMatrix.value[3*4+2] = tz;\t\t\r\n\t\t//*/\r\n\t}\r\n\r\n\t\r\n\tpublic static final void crossProduct3(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tc.value[0] = a.value[1]*b.value[2]-b.value[1]*a.value[2];\r\n\t\tc.value[1] = a.value[2]*b.value[0]-b.value[2]*a.value[0];\r\n\t\tc.value[2] = a.value[0]*b.value[1]-b.value[0]*a.value[1];\r\n\t}\r\n\r\n\tpublic static final void mult(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tint n = a.height;\r\n\t\tint p = a.width;\r\n\t\tint r = b.width;\r\n\r\n\t\tif(p!=b.height)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Mult error, matricies sizes dont match\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t double vdot;\r\n\t int i,j,k,m;\r\n\r\n\r\n int r5 = r*5;\r\n\t int rowI = 0;\r\n\t int crowI = 0;\r\n\t for (i = 0; i < n; i++) {\r\n\r\n\t for (j = 0; j < r; j++) {\r\n\r\n\t vdot = 0.0f;\r\n\r\n\t m = p%5;\r\n\r\n\t int rowK = 0;\r\n\t for (k = 0; k < m; k++) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j];\r\n\t rowK += r;\r\n\t }\r\n\r\n\t for (k = m; k < p; k += 5) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j] +\r\n\t a.value[rowI+k+1]*b.value[rowK+r+j] +\r\n\t a.value[rowI+k+2]*b.value[rowK+r*2+j] +\r\n\t a.value[rowI+k+3]*b.value[rowK+r*3+j] +\r\n\t a.value[rowI+k+4]*b.value[rowK+r*4+j];\r\n\r\n\t rowK += r5;\r\n\t }\r\n\r\n\t c.value[crowI+j] = vdot;\r\n\r\n\t }\r\n\t rowI += p;\r\n\t crowI += r;\r\n\t }\r\n\r\n\t}\r\n\r\n\tpublic static final void mult(GeneralMatrixDouble a,double[] x,double[] b)\r\n\t{\r\n\t\tint n = a.height;\r\n\t\tint p = a.width;\r\n\t\tint r = 1;\r\n\r\n\t\tif(p!=x.length)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Mult error, matricies sizes dont match\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t double vdot;\r\n\t int i,j,k,m;\r\n\r\n\r\n int r5 = r*5;\r\n\t int rowI = 0;\r\n\t int crowI = 0;\r\n\t for (i = 0; i < n; i++) {\r\n\r\n\t for (j = 0; j < r; j++) {\r\n\r\n\t vdot = 0.0f;\r\n\r\n\t m = p%5;\r\n\r\n\t int rowK = 0;\r\n\t for (k = 0; k < m; k++) {\r\n\r\n\t vdot += a.value[rowI+k]*x[rowK+j];\r\n\t rowK += r;\r\n\t }\r\n\r\n\t for (k = m; k < p; k += 5) {\r\n\r\n\t vdot += a.value[rowI+k]*x[rowK+j] +\r\n\t a.value[rowI+k+1]*x[rowK+r+j] +\r\n\t a.value[rowI+k+2]*x[rowK+r*2+j] +\r\n\t a.value[rowI+k+3]*x[rowK+r*3+j] +\r\n\t a.value[rowI+k+4]*x[rowK+r*4+j];\r\n\r\n\t rowK += r5;\r\n\t }\r\n\r\n\t b[crowI+j] = vdot;\r\n\r\n\t }\r\n\t rowI += p;\r\n\t crowI += r;\r\n\t }\r\n\r\n\t}\r\n\r\n\tpublic static final void rowmult(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tdouble vdot;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t //Apply the matrix to this vector\r\n\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t vdot = 0.0f;\r\n\t\t\t\t for (int k = 0; k < b.height; k++)\r\n\t\t\t\t {\r\n\t\t\t vdot += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t }\r\n\t\t\t\t c.value[i*a.width+j] = vdot;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void rowtransform(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t// wxh\r\n\t\t//a is 3xn (h value of 1.0 is implied)\r\n\t\t//B is 3x4 (or at least the other values are unused)\r\n\t\tdouble vdot;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t //Apply the matrix to this vector\r\n\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t vdot = 0.0f;\r\n\t\t\t\t for (int k = 0; k < a.width; k++)\r\n\t\t\t\t {\r\n\t\t\t vdot += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t }\r\n\t\t\t\t //Add what would be the homogenious value to translate correctly\r\n\t\t\t\t vdot += b.value[a.width*b.width+j];\r\n\t\t\t\t c.value[i*a.width+j] = vdot;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void rowproject(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t// wxh\r\n\t\t//a is 3xn (h value of 1.0 is implied)\r\n\t\t//B is 4x4 (or at least the other values are unused)\r\n\t\tdouble vdot;\r\n\t\tdouble h;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t //Apply the matrix to this vector\r\n\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t vdot = 0.0f;\r\n\t\t\t\t for (int k = 0; k < a.width; k++)\r\n\t\t\t\t {\r\n\t\t\t vdot += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t }\r\n\t\t\t\t //Add what would be the homogenious value to translate correctly\r\n\t\t\t\t vdot += b.value[a.width*b.width+j];\r\n\t\t\t\t c.value[i*a.width+j] = vdot;\r\n\t\t\t }\r\n\t\t\t h = 0.0f;\r\n\t\t\t for (int k = 0; k < a.width; k++)\r\n\t\t\t {\r\n\t\t h += a.value[i*a.width+k]*b.value[k*b.width+3];\r\n\t\t\t }\r\n\t\t\t //Add implicit h\r\n\t\t\t h += b.value[a.width*b.width+3];\r\n\t\t\t //Divide by h\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t c.value[i*a.width+j] /= h;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final double rowdot(GeneralMatrixDouble a,int ai,GeneralMatrixDouble b,int bi)\r\n\t{\r\n\t\tdouble result = 0.0f;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tresult += a.value[i+ai*a.width]*b.value[i+bi*b.width];\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic static final void add(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]+b.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void addWithScale(GeneralMatrixDouble a,GeneralMatrixDouble b,double s,GeneralMatrixDouble c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]+b.value[i]*s;\r\n\t\t }\r\n\t}\r\n\r\n\t\r\n\t\r\n\tpublic static final void rowadd(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tint ai = 0;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t c.value[ai] = a.value[ai]+b.value[j];\r\n\t\t\t\t ai++;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void sub(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]-b.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void rowsub(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tint ai = 0;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t c.value[ai] = a.value[ai]-b.value[j];\r\n\t\t\t\t ai++;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void scale(GeneralMatrixDouble a,double b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]*b;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void negate(GeneralMatrixDouble a,GeneralMatrixDouble b)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t b.value[i] = -a.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void transpose(GeneralMatrixDouble a,GeneralMatrixDouble at)\r\n\t{\r\n\t\tint i,j;\r\n\r\n\t\tint ai = 0;\r\n\t\tint atjR;\r\n\t for (i = 0; i < a.height; i++) {\r\n\r\n\t \t\tatjR = 0;\r\n\t for (j = 0; j < a.width; j++) {\r\n\r\n\t at.value[atjR+i] = a.value[ai];\r\n\t ai++;\r\n\t atjR += a.height;\r\n\t }\r\n\r\n\t }\r\n\t}\r\n\r\n\tpublic static final double trace(GeneralMatrixDouble a)\r\n\t{\r\n\t\tdouble sum = 0.0f;\r\n\t\tint index = 0;\r\n\t\tfor (int i = 0; i < a.height; i++)\r\n\t\t{\r\n\t\t\tsum += a.value[index];\r\n\t\t\tindex += a.height+1;\r\n\t\t}\r\n\t\treturn sum;\r\n\t}\r\n\r\n\tpublic double[][] getAs2DArray()\r\n\t{\r\n\t\tdouble[][] result = new double[height][width];\r\n\t\tint i=0;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tresult[y][x]=value[i];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic void setFrom2DArray(double[][] a)\r\n\t{\r\n\t\tint i=0;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i]=a[y][x];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t \r\n\t public GeneralMatrixDouble(int width)\r\n\t {\r\n\t\t this.width = width;\r\n\t }\r\n\r\n\t public int appendRows(int numRows)\r\n\t {\r\n\t \tint newSize = width*(height+numRows);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new double[newSize];\r\n\t\t\t\theight+=numRows;\r\n\t\t\t\treturn height-numRows;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\theight+=numRows;\r\n\t\t\treturn height-numRows;\r\n\t }\r\n\r\n\t public int appendRow()\r\n\t {\r\n\t \tint newSize = width*(height+1);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new double[newSize];\r\n\t\t\t\theight++;\r\n\t\t\t\treturn height-1;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\theight++;\r\n\t\t\treturn height-1;\r\n\t }\r\n\r\n\t public void ensureCapacityNoCopy(int mincap)\r\n\t {\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new double[mincap];\r\n\t \t}\r\n\t \telse\r\n\t \tif(mincap>value.length)\r\n\t \t{\r\n\t\t int newcap = (value.length * 3)/2 + 1;\r\n\t\t double[] olddata = value;\r\n\t\t value = new double[newcap < mincap ? mincap : newcap];\r\n\t \t}\r\n\t }\r\n\r\n\t public void ensureCapacity(int mincap)\r\n\t {\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new double[mincap];\r\n\t \t}\r\n\t \telse\r\n\t \tif(mincap>value.length)\r\n\t \t{\r\n\t\t int newcap = (value.length * 3)/2 + 1;\r\n\t\t double[] olddata = value;\r\n\t\t value = new double[newcap < mincap ? mincap : newcap];\r\n\t\t System.arraycopy(olddata,0,value,0,width*height);\r\n\t \t}\r\n\t }\r\n\r\n\t public void setDimensions(int w,int h)\r\n\t {\r\n\t \tensureCapacity(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public void setDimensionsNoCopy(int w,int h)\r\n\t {\r\n\t \tensureCapacityNoCopy(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\r\n\t public void push_back(double val)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind] = val;\r\n\t }\r\n\t public void push_back_row(double val1,double val2)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*2+0] = val1;\r\n\t \tvalue[ind*2+1] = val2;\r\n\t }\r\n\t public void push_back_row(double val1,double val2,double val3)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*3+0] = val1;\r\n\t \tvalue[ind*3+1] = val2;\r\n\t \tvalue[ind*3+2] = val3;\r\n\t }\r\n\t public void push_back_row(double val1,double val2,double val3,double val4)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*4+0] = val1;\r\n\t \tvalue[ind*4+1] = val2;\r\n\t \tvalue[ind*4+2] = val3;\r\n\t \tvalue[ind*4+3] = val4;\r\n\t }\r\n\t public void push_back_row(double val1,double val2,double val3,double val4,double val5,double val6)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*6+0] = val1;\r\n\t \tvalue[ind*6+1] = val2;\r\n\t \tvalue[ind*6+2] = val3;\r\n\t \tvalue[ind*6+3] = val4;\r\n\t \tvalue[ind*6+4] = val5;\r\n\t \tvalue[ind*6+5] = val6;\r\n\t }\r\n\r\n\t public int push_back_row(double[] row)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tSystem.arraycopy(row, 0, value, width*(height-1), width);\r\n\t \treturn ind;\r\n\t }\r\n\t public int push_back_row(float[] row)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tint off = width*ind;\r\n\t \tfor(int i=0;i<width;i++)\r\n\t \t\tvalue[off+i] = row[i];\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(double[] row, int off)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tSystem.arraycopy(row, off, value, width*(height-1), width);\r\n\t \treturn ind;\r\n\t }\r\n\t public void push_back_rows(GeneralMatrixDouble rows)\r\n\t {\r\n\t \tif(rows.height==0)\r\n\t \t\treturn;\r\n\t \tappendRows(rows.height);\r\n\t \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n\t }\r\n}\r",
"public class GeneralMatrixFloat implements Serializable\r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic static final float EPSILON = 0.000000001f;\r\n\t//public static final float EPSILON=5.9e-8f;\r\n\tpublic int width = 0; //columns\r\n\tpublic int height = 0; //rows\r\n\tpublic float[] value = null; //array of values\r\n\r\n\tpublic GeneralMatrixFloat()\r\n\t{\r\n\t\twidth = 0;\r\n\t\theight = 0;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float val)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 1;\r\n\t\tthis.value = new float[1];\r\n\t\tthis.value[0] = val;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float val0,float val1)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 2;\r\n\t\tthis.value = new float[2];\r\n\t\tthis.value[0] = val0;\r\n\t\tthis.value[1] = val1;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float val0,float val1,float val2)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 3;\r\n\t\tthis.value = new float[3];\r\n\t\tthis.value[0] = val0;\r\n\t\tthis.value[1] = val1;\r\n\t\tthis.value[2] = val2;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float val0,float val1,float val2,float val3)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 4;\r\n\t\tthis.value = new float[4];\r\n\t\tthis.value[0] = val0;\r\n\t\tthis.value[1] = val1;\r\n\t\tthis.value[2] = val2;\r\n\t\tthis.value[3] = val3;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float[] vals)\r\n\t{\r\n\t\tthis.width = vals.length;\r\n\t\tthis.height = 1;\r\n\t\tthis.value = vals;\r\n\t}\r\n\tpublic GeneralMatrixFloat(int width)\r\n\t{\r\n\t\tthis.width = width;\r\n\t}\r\n\tpublic GeneralMatrixFloat(int width,int height)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = new float[width*height];\r\n\t}\r\n\tpublic GeneralMatrixFloat(int width,int height,float[] vals)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = vals;\r\n\t}\r\n\tpublic GeneralMatrixFloat(GeneralMatrixFloat o)\r\n\t{\r\n\t\twidth = o.width;\r\n\t\theight = o.height;\r\n\t\tvalue = new float[width*height];\r\n\t\tset(o);\r\n\t}\r\n\tpublic GeneralMatrixFloat(GeneralMatrixDouble o)\r\n\t{\r\n\t\twidth = o.width;\r\n\t\theight = o.height;\r\n\t\tvalue = new float[width*height];\r\n\t\tset(o);\r\n\t}\r\n\r\n\tpublic boolean isequal(GeneralMatrixFloat o)\r\n\t{\r\n\t\tboolean is = true;\r\n\t\tis = is && (width==o.width);\r\n\t\tis = is && (height==o.height);\r\n\t\tif(is)\r\n\t\t{\r\n\t\t\tfor(int i=0;i<width*height;i++)\r\n\t\t\t{\r\n\t\t\t\tis = is && (value[i]==o.value[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(!is)\r\n\t\t\tSystem.out.println(\"diff!\");\r\n\t\treturn is;\r\n\t}\r\n\t\r\n\tpublic boolean includesNAN()\r\n\t{\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tif(Float.isNaN(value[i]))\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\tpublic void clear(float v)\r\n\t{\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] = v;\r\n\t\t}\r\n\t}\r\n\tpublic void clearSubset(int xs,int ys,int sw,int sh,float v)\r\n\t{\r\n\t\tint maxy = ys+sh;\r\n\t\tint maxx = xs+sw;\r\n\t\tfor(int y=ys;y<maxy;y++)\r\n\t\t{\r\n\t\t\tfor(int x=xs;x<maxx;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[x+y*width] = v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic final float get(int i,int j)\r\n\t{\r\n\t\treturn value[j*width+i];\r\n\t}\r\n\t\r\n\tpublic float getMirror(int x, int y)\r\n {\r\n if (x >= width)\r\n x = width - (x - width + 2);\r\n\r\n if (y >= height)\r\n y = height - (y - height + 2);\r\n\r\n if (x < 0)\r\n {\r\n int tmp = 0;\r\n int dir = 1;\r\n\r\n while (x < 0)\r\n {\r\n tmp += dir;\r\n if (tmp == width - 1 || tmp == 0)\r\n dir *= -1;\r\n x++;\r\n }\r\n x = tmp;\r\n }\r\n\r\n if (y < 0)\r\n {\r\n int tmp = 0;\r\n int dir = 1;\r\n\r\n while (y < 0)\r\n {\r\n tmp += dir;\r\n if (tmp == height - 1 || tmp == 0)\r\n dir *= -1;\r\n y++;\r\n }\r\n y = tmp;\r\n }\r\n\r\n return value[x+y*width];\r\n }\t\r\n\tpublic void set(int i,int j,float v)\r\n\t{\r\n\t\tvalue[j*width+i] = v;\r\n\t}\r\n\r\n\tpublic void set(GeneralMatrixFloat a)\r\n\t{\r\n\t\tensureCapacityNoCopy(a.width*a.height);\r\n\t\twidth = a.width;\r\n\t\theight = a.height;\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(GeneralMatrixInt a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t value[i] = a.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(GeneralMatrixDouble a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t value[i] = (float)a.value[i];\r\n\t\t }\r\n\t}\r\n\t\r\n\tpublic void set(float[] a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(double[] a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = (float)a[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(double[][] a)\r\n\t{\r\n\t\t for (int j = 0; j < height; j++)\r\n\t\t {\r\n\t\t\t for (int i = 0; i < width; i++)\r\n\t\t\t {\r\n\t\t\t\t value[i+j*width] = (float)a[j][i];\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\t public int find(float v0,float v1,float eps)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=2)\r\n\t\t {\r\n\t\t\t if((Math.abs(value[i]-v0)<=eps)&&(Math.abs(value[i+1]-v1)<=eps))\r\n\t\t\t\t return i/2;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int find(float v0,float v1,float v2,float eps)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=3)\r\n\t\t {\r\n\t\t\t if((Math.abs(value[i]-v0)<=eps)&&(Math.abs(value[i+1]-v1)<=eps)&&(Math.abs(value[i+2]-v2)<=eps))\r\n\t\t\t\t return i/3;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int find(float v0,float v1,float v2,float v3,float v4,float eps)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=5)\r\n\t\t {\r\n\t\t\t if((Math.abs(value[i]-v0)<=eps)&&(Math.abs(value[i+1]-v1)<=eps)&&(Math.abs(value[i+2]-v2)<=eps)&&(Math.abs(value[i+3]-v3)<=eps)&&(Math.abs(value[i+4]-v4)<=eps))\r\n\t\t\t\t return i/5;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\r\n\t//Insertion and deletion\r\n public int appendRow()\r\n {\r\n \tint newSize = width*(height+1);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[newSize];\r\n\t\t\theight++;\r\n\t\t\treturn height-1;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight++;\r\n\t\treturn height-1;\r\n }\r\n\r\n public int appendRows(int size)\r\n {\r\n \tint newSize = width*(height+size);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[newSize];\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight+=size;\r\n\t\treturn height-size;\r\n }\r\n \r\n public int appendRows(int size,float defaultValue)\r\n {\r\n \tint newSize = width*(height+size);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[newSize];\r\n\t\t\theight+=size;\r\n\t\t\tclear(defaultValue);\r\n\t\t\treturn height-size;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\tfor(int i=width*height;i<(width*(height+size));i++)\r\n\t\t{\r\n\t\t\tvalue[i] = defaultValue;\r\n\t\t}\r\n\t\theight+=size;\r\n\t\treturn height-size;\r\n }\r\n \r\n public void removeRow(int index)\r\n {\r\n \tif(index>=height)\r\n \t{\r\n \t\tSystem.out.println(\"Row being removed larger than matrix\");\r\n \t}\r\n \tfor(int i=index*width;i<((height-1))*width;i++)\r\n \t{\r\n \t\tvalue[i] = value[(i+width)];\r\n \t}\r\n \theight--;\r\n }\r\n\r\n public void insertRowAfter(int index)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(value, (index+1)*width, value, (index+2)*width, (height-1-(index+1))*width);\r\n }\r\n\r\n public void insertRowBefore(int index)\r\n {\r\n \tint srcind = (index)*width;\r\n \tint destind = (index+1)*width;\r\n \tint length = (height-1-(index))*width;\r\n \ttry{\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(value, srcind, value, destind, length);\t \t\t\r\n \t}\r\n \tcatch(Exception e)\r\n \t{\r\n \t\tSystem.out.println(\"insertRowBefore error\");\r\n \t}\r\n }\r\n \r\n public void ensureCapacityNoCopy(int mincap)\r\n {\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[mincap];\r\n \t}\r\n \telse\r\n \tif(mincap>value.length)\r\n \t{\r\n\t int newcap = mincap;//(value.length * 3)/2 + 1;\r\n\t //float[] olddata = value;\r\n\t value = new float[newcap < mincap ? mincap : newcap];\r\n \t}\r\n }\r\n\r\n public void ensureCapacity(int mincap)\r\n {\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[mincap];\r\n \t}\r\n \telse\r\n \tif(mincap>value.length)\r\n \t{\r\n\t int newcap = (value.length * 3)/2 + 1;\r\n\t float[] olddata = value;\r\n\t value = new float[newcap < mincap ? mincap : newcap];\r\n\t System.arraycopy(olddata,0,value,0,olddata.length);\r\n \t}\r\n }\r\n public void setDimensions(int w,int h)\r\n {\r\n \tensureCapacity(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n }\r\n public void setDimensionsNoCopy(int w,int h)\r\n {\r\n \tensureCapacityNoCopy(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n }\r\n public int push_back(float val)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind] = val;\r\n \treturn ind;\r\n }\r\n \r\n public void set_row(int row,float val1,float val2)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n } \r\n public int push_back_row(float val1,float val2)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*2+0] = val1;\r\n \tvalue[ind*2+1] = val2;\r\n \treturn ind;\r\n }\r\n public void set_row(int row,float val1,float val2,float val3)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n \tvalue[ind+2] = val3; \t\r\n } \r\n public int push_back_row(float val1,float val2,float val3)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*width+0] = val1;\r\n \tvalue[ind*width+1] = val2;\r\n \tvalue[ind*width+2] = val3;\r\n \treturn ind;\r\n }\r\n public void set_row(int row,float val1,float val2,float val3,float val4)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n \tvalue[ind+2] = val3; \t\r\n \tvalue[ind+3] = val4; \t\r\n } \r\n public int push_back_row(float val1,float val2,float val3,float val4)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*4+0] = val1;\r\n \tvalue[ind*4+1] = val2;\r\n \tvalue[ind*4+2] = val3;\r\n \tvalue[ind*4+3] = val4;\r\n \treturn ind;\r\n }\r\n public void set_row(int row,float val1,float val2,float val3,float val4,float val5)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n \tvalue[ind+2] = val3; \t\r\n \tvalue[ind+3] = val4; \t\r\n \tvalue[ind+4] = val5; \t\r\n } \r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*5+0] = val1;\r\n \tvalue[ind*5+1] = val2;\r\n \tvalue[ind*5+2] = val3;\r\n \tvalue[ind*5+3] = val4;\r\n \tvalue[ind*5+4] = val5;\r\n }\r\n public void set_row(int row,float val1,float val2,float val3,float val4,float val5,float val6)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n \tvalue[ind+2] = val3; \t\r\n \tvalue[ind+3] = val4; \t\r\n \tvalue[ind+4] = val5; \t\r\n \tvalue[ind+5] = val6; \t\r\n } \r\n public int push_back_row(float val1,float val2,float val3,float val4,float val5,float val6)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*6+0] = val1;\r\n \tvalue[ind*6+1] = val2;\r\n \tvalue[ind*6+2] = val3;\r\n \tvalue[ind*6+3] = val4;\r\n \tvalue[ind*6+4] = val5;\r\n \tvalue[ind*6+5] = val6;\r\n \treturn ind;\r\n }\r\n public int push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*7+0] = val1;\r\n \tvalue[ind*7+1] = val2;\r\n \tvalue[ind*7+2] = val3;\r\n \tvalue[ind*7+3] = val4;\r\n \tvalue[ind*7+4] = val5;\r\n \tvalue[ind*7+5] = val6;\r\n \tvalue[ind*7+6] = val7;\r\n \treturn ind;\r\n }\r\n public int push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*8+0] = val1;\r\n \tvalue[ind*8+1] = val2;\r\n \tvalue[ind*8+2] = val3;\r\n \tvalue[ind*8+3] = val4;\r\n \tvalue[ind*8+4] = val5;\r\n \tvalue[ind*8+5] = val6;\r\n \tvalue[ind*8+6] = val7;\r\n \tvalue[ind*8+7] = val8;\r\n \treturn ind;\r\n }\r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8,float val9)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*9+0] = val1;\r\n \tvalue[ind*9+1] = val2;\r\n \tvalue[ind*9+2] = val3;\r\n \tvalue[ind*9+3] = val4;\r\n \tvalue[ind*9+4] = val5;\r\n \tvalue[ind*9+5] = val6;\r\n \tvalue[ind*9+6] = val7;\r\n \tvalue[ind*9+7] = val8;\r\n \tvalue[ind*9+8] = val9;\r\n }\r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8,float val9,float val10,float val11)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*11+0] = val1;\r\n \tvalue[ind*11+1] = val2;\r\n \tvalue[ind*11+2] = val3;\r\n \tvalue[ind*11+3] = val4;\r\n \tvalue[ind*11+4] = val5;\r\n \tvalue[ind*11+5] = val6;\r\n \tvalue[ind*11+6] = val7;\r\n \tvalue[ind*11+7] = val8;\r\n \tvalue[ind*11+8] = val9;\r\n \tvalue[ind*11+9] = val10;\r\n \tvalue[ind*11+10] = val11;\r\n }\r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8,float val9,float val10,float val11,float val12,float val13,float val14)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*14+0] = val1;\r\n \tvalue[ind*14+1] = val2;\r\n \tvalue[ind*14+2] = val3;\r\n \tvalue[ind*14+3] = val4;\r\n \tvalue[ind*14+4] = val5;\r\n \tvalue[ind*14+5] = val6;\r\n \tvalue[ind*14+6] = val7;\r\n \tvalue[ind*14+7] = val8;\r\n \tvalue[ind*14+8] = val9;\r\n \tvalue[ind*14+9] = val10;\r\n \tvalue[ind*14+10] = val11;\r\n \tvalue[ind*14+11] = val12;\r\n \tvalue[ind*14+12] = val13;\r\n \tvalue[ind*14+13] = val14;\r\n }\r\n\r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8,float val9,float val10,float val11,float val12,float val13,float val14,float val15,float val16)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*16+0] = val1;\r\n \tvalue[ind*16+1] = val2;\r\n \tvalue[ind*16+2] = val3;\r\n \tvalue[ind*16+3] = val4;\r\n \tvalue[ind*16+4] = val5;\r\n \tvalue[ind*16+5] = val6;\r\n \tvalue[ind*16+6] = val7;\r\n \tvalue[ind*16+7] = val8;\r\n \tvalue[ind*16+8] = val9;\r\n \tvalue[ind*16+9] = val10;\r\n \tvalue[ind*16+10] = val11;\r\n \tvalue[ind*16+11] = val12;\r\n \tvalue[ind*16+12] = val13;\r\n \tvalue[ind*16+13] = val14;\r\n \tvalue[ind*16+14] = val15;\r\n \tvalue[ind*16+15] = val16;\r\n }\r\n\r\n public void push_back_row(GeneralMatrixFloat row)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(row.value, 0, value, width*(height-1), width);\r\n }\r\n\r\n public void push_back_row_from_matrix(GeneralMatrixFloat row,int i)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(row.value, i*width, value, width*(height-1), width);\r\n }\r\n\r\n public void push_back_row(GeneralMatrixDouble row)\r\n {\r\n \tappendRow();\r\n \tint off = width*(height-1); \r\n \tfor(int i=0;i<width;i++)\r\n \t{\r\n \t\tvalue[off+i] = (float)row.value[i];\r\n \t}\r\n }\r\n\r\n public int push_back_row(float[] row)\r\n {\r\n \tint ind = appendRow();\r\n \tSystem.arraycopy(row, 0, value, width*(height-1), width);\r\n \treturn ind;\r\n }\r\n public int push_back_row(float[] row,int off)\r\n {\r\n \tint ind = appendRow();\r\n \tSystem.arraycopy(row, off, value, width*(height-1), width);\r\n \treturn ind;\r\n }\r\n public int push_back_row(float[] row,int off,int w)\r\n {\r\n \tint ind = appendRow();\r\n \tint inoff = width*(height-1);\r\n \tSystem.arraycopy(row, off, value, inoff, Math.min(width,w));\r\n \tfor(int i=w;i<width;i++)\r\n \t{\r\n \t\tvalue[inoff+i] = 0.0f;\r\n \t}\r\n \treturn ind;\r\n }\r\n public void push_back_row_from_block(GeneralMatrixFloat row,int yFromFull)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(row.value, yFromFull*width, value, width*(height-1), width);\r\n }\r\n \r\n public void push_back_rows(GeneralMatrixFloat rows)\r\n {\r\n \tif(rows.height==0)\r\n \t\treturn;\r\n \tappendRows(rows.height);\r\n \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n }\r\n\r\n public void push_back_matrices_as_row(GeneralMatrixFloat m0,GeneralMatrixFloat m1)\r\n {\r\n \tint ind = appendRow();\r\n \tint m0num = m0.width*m0.height;\r\n \tSystem.arraycopy(m0.value, 0, value, width*ind, m0num);\r\n \tint m1num = m1.width*m1.height;\r\n \tSystem.arraycopy(m1.value, 0, value, width*ind+m0num, m1num); \t\r\n }\r\n \r\n\tpublic void swapRows(int r1,int r2,float[] buffer)\r\n\t{\r\n\t\tSystem.arraycopy(value, r1*width, buffer, 0, width);\r\n\t\tSystem.arraycopy(value, r2*width, value, r1*width, width);\r\n\t\tSystem.arraycopy(buffer, 0, value, r2*width, width);\r\n\t}\r\n\r\n public void setRow(int r,GeneralMatrixFloat row)\r\n {\r\n \tSystem.arraycopy(row.value, 0, value, width*(r), width);\r\n }\r\n\r\n public void setRow(int r,GeneralMatrixDouble row)\r\n {\r\n \tfor(int i=0;i<width;i++)\r\n \t\tvalue[width*r+i] = (float)row.value[i];\r\n }\r\n \r\n public void setRowFromSubset(int r,GeneralMatrixFloat full,int ys)\r\n {\r\n \tSystem.arraycopy(full.value, ys*width, value, width*(r), width);\r\n }\r\n\r\n\t//For setting a vec or mat from an array of vecs/mats\r\n\tpublic void setFromSubset(GeneralMatrixFloat full,int ys)\r\n\t{\r\n\t\tint i=0;\r\n\t\tint fi = ys*width;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = full.value[fi];\r\n\t\t\t\ti++;\r\n\t\t\t\tfi++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic void setFromSubset(GeneralMatrixDouble full,int ys)\r\n\t{\r\n\t\tint i=0;\r\n\t\tint fi = ys*width;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = (float)full.value[fi];\r\n\t\t\t\ti++;\r\n\t\t\t\tfi++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void setSubset(GeneralMatrixFloat subset,int xs,int ys)\r\n\t{\r\n\t\tint maxy = ys+subset.height;\r\n\t\tint maxx = xs+subset.width;\r\n\t\tfor(int y=ys;y<maxy;y++)\r\n\t\t{\r\n\t\t\tfor(int x=xs;x<maxx;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[x+y*width] = subset.value[(x-xs)+(y-ys)*subset.width];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//Setup matrix transforms\r\n\t\r\n\tpublic void set3DTransformPosition(float x,float y,float z)\r\n\t{\r\n\t\tvalue[4*3+0] = x;\r\n\t\tvalue[4*3+1] = y;\r\n\t\tvalue[4*3+2] = z;\r\n\t}\r\n\tpublic void calcBasisFromNormal(float x,float y,float z)\r\n\t{\r\n\t\tvalue[4*2+0] = x;\r\n\t\tvalue[4*2+1] = y;\r\n\t\tvalue[4*2+2] = z;\r\n\r\n\t\tif(\r\n\t\t\t\t(Math.abs(x)<=Math.abs(y))&&(Math.abs(x)<=Math.abs(z))\r\n\t\t )\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = 1.0f;\r\n\t\t\tvalue[4*0+1] = 0.0f;\r\n\t\t\tvalue[4*0+2] = 0.0f;\r\n\t\t}\t\r\n\t\telse\r\n\t\tif(Math.abs(y)<Math.abs(z))\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = 0.0f;\r\n\t\t\tvalue[4*0+1] = 1.0f;\r\n\t\t\tvalue[4*0+2] = 0.0f;\t\t\t\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = 0.0f;\r\n\t\t\tvalue[4*0+1] = 0.0f;\r\n\t\t\tvalue[4*0+2] = 1.0f;\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tvalue[4*1+0] = y*value[4*0+2]-value[4*0+1]*z;\r\n\t\tvalue[4*1+1] = z*value[4*0+0]-value[4*0+2]*x;\r\n\t\tvalue[4*1+2] = x*value[4*0+1]-value[4*0+0]*y;\r\n\r\n\t\t//Normalise\r\n\t\tfloat total = value[4*1+0]*value[4*1+0];\r\n\t\ttotal += value[4*1+1]*value[4*1+1];\r\n\t\ttotal += value[4*1+2]*value[4*1+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[4*1+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[4*1+0] /= total;\r\n\t\tvalue[4*1+1] /= total;\r\n\t\tvalue[4*1+2] /= total;\r\n\t\t\r\n\t\tvalue[4*0+0] = y*value[4*1+2]-value[4*1+1]*z;\r\n\t\tvalue[4*0+1] = z*value[4*1+0]-value[4*1+2]*x;\r\n\t\tvalue[4*0+2] = x*value[4*1+1]-value[4*1+0]*y;\r\n\r\n\t\ttotal = value[4*0+0]*value[4*0+0];\r\n\t\ttotal += value[4*0+1]*value[4*0+1];\r\n\t\ttotal += value[4*0+2]*value[4*0+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[4*0+0] /= total;\r\n\t\tvalue[4*0+1] /= total;\r\n\t\tvalue[4*0+2] /= total;\r\n\t}\r\n\tpublic void calcBasisFromY(float x,float y,float z)\r\n\t{\r\n\t\tif((Math.abs(x)<=EPSILON)&&(Math.abs(y)<=EPSILON)&&(Math.abs(z)<=EPSILON))\r\n\t\t{\r\n\t\t\tsetIdentity();\r\n\t\t}\r\n\t\telse\r\n\t\tif(\r\n\t\t\t\t(Math.abs(x)<=Math.abs(y))&&(Math.abs(x)<=Math.abs(z))\r\n\t\t )\r\n\t\t{\r\n\t\t\tcalcBasisFromY(x, y, z, 1.0f, 0.0f, 0.0f);\r\n\t\t}\t\r\n\t\telse\r\n\t\tif(Math.abs(y)<=Math.abs(z))\r\n\t\t{\r\n\t\t\tcalcBasisFromY(x, y, z, 0.0f, 1.0f, 0.0f);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tcalcBasisFromY(x, y, z, 0.0f, 0.0f, 1.0f);\r\n\t\t}\r\n\r\n\t}\r\n\tpublic void calcBasisFromY(float x,float y,float z,\r\n\t\t\tfloat Xx,float Xy,float Xz)\r\n\t{\r\n\t\tvalue[width*1+0] = x;\r\n\t\tvalue[width*1+1] = y;\r\n\t\tvalue[width*1+2] = z;\r\n\t\tfloat total = x*x;\r\n\t\ttotal += y*y;\r\n\t\ttotal += z*z;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*1+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[width*1+0] /= total;\r\n\t\tvalue[width*1+1] /= total;\r\n\t\tvalue[width*1+2] /= total;\r\n\t\t\r\n\t\ttotal = Xx*Xx;\r\n\t\ttotal += Xy*Xy;\r\n\t\ttotal += Xz*Xz;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t\tvalue[width*0+0] = Xx/total;\r\n\t\t\tvalue[width*0+1] = Xy/total;\r\n\t\t\tvalue[width*0+2] = Xz/total;\r\n\t\t}\r\n\r\n\t\t\r\n\t\tvalue[width*2+0] = -y*value[width*0+2]+value[width*0+1]*z;\r\n\t\tvalue[width*2+1] = -z*value[width*0+0]+value[width*0+2]*x;\r\n\t\tvalue[width*2+2] = -x*value[width*0+1]+value[width*0+0]*y;\r\n\r\n\t\t//Normalise\r\n\t\ttotal = value[width*2+0]*value[width*2+0];\r\n\t\ttotal += value[width*2+1]*value[width*2+1];\r\n\t\ttotal += value[width*2+2]*value[width*2+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*2+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t\tvalue[width*2+0] /= total;\r\n\t\t\tvalue[width*2+1] /= total;\r\n\t\t\tvalue[width*2+2] /= total;\r\n\t\t}\r\n\t\t\r\n\t\tvalue[width*0+0] = y*value[width*2+2]-value[width*2+1]*z;\r\n\t\tvalue[width*0+1] = z*value[width*2+0]-value[width*2+2]*x;\r\n\t\tvalue[width*0+2] = x*value[width*2+1]-value[width*2+0]*y;\r\n\r\n\t\ttotal = value[width*0+0]*value[width*0+0];\r\n\t\ttotal += value[width*0+1]*value[width*0+1];\r\n\t\ttotal += value[width*0+2]*value[width*0+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t\tvalue[width*0+0] /= total;\r\n\t\t\tvalue[width*0+1] /= total;\r\n\t\t\tvalue[width*0+2] /= total;\r\n\t\t}\r\n\t}\r\n\tpublic void flipX()\r\n\t{\r\n\t\tvalue[4*0+0] = -value[4*0+0];\r\n\t\tvalue[4*0+1] = -value[4*0+1];\r\n\t\tvalue[4*0+2] = -value[4*0+2];\r\n\t}\r\n\tpublic void flipY()\r\n\t{\r\n\t\tvalue[4*1+0] = -value[4*1+0];\r\n\t\tvalue[4*1+1] = -value[4*1+1];\r\n\t\tvalue[4*1+2] = -value[4*1+2];\r\n\t}\r\n\tpublic void flipZ()\r\n\t{\r\n\t\tvalue[4*2+0] = -value[4*2+0];\r\n\t\tvalue[4*2+1] = -value[4*2+1];\r\n\t\tvalue[4*2+2] = -value[4*2+2];\r\n\t}\r\n\tpublic void set3DBasis(GeneralMatrixFloat basis)\r\n\t{\r\n\t\tvalue[4*0+0] = basis.value[3*0+0];\r\n\t\tvalue[4*0+1] = basis.value[3*0+1];\r\n\t\tvalue[4*0+2] = basis.value[3*0+2];\r\n\r\n\t\tvalue[4*1+0] = basis.value[3*1+0];\r\n\t\tvalue[4*1+1] = basis.value[3*1+1];\r\n\t\tvalue[4*1+2] = basis.value[3*1+2];\r\n\r\n\t\tvalue[4*2+0] = basis.value[3*2+0];\r\n\t\tvalue[4*2+1] = basis.value[3*2+1];\r\n\t\tvalue[4*2+2] = basis.value[3*2+2];\r\n\t}\r\n\tpublic void set3DTransformScale(float scale)\r\n\t{\r\n\t\tvalue[4*0+0] *= scale;\r\n\t\tvalue[4*0+1] *= scale;\r\n\t\tvalue[4*0+2] *= scale;\r\n\t\t\r\n\t\tvalue[4*1+0] *= scale;\r\n\t\tvalue[4*1+1] *= scale;\r\n\t\tvalue[4*1+2] *= scale;\r\n\t\t\r\n\t\tvalue[4*2+0] *= scale;\r\n\t\tvalue[4*2+1] *= scale;\r\n\t\tvalue[4*2+2] *= scale;\r\n\t}\r\n\tpublic void set3DBasis(float Xx,float Xy,float Xz,\r\n\t\t\t\t\t\t\tfloat Yx,float Yy,float Yz,\r\n\t\t\t\t\t\t\tfloat Zx,float Zy,float Zz)\r\n\t{\r\n\t\tvalue[4*0+0] = Xx;\r\n\t\tvalue[4*0+1] = Xy;\r\n\t\tvalue[4*0+2] = Xz;\r\n\r\n\t\tvalue[4*1+0] = Yx;\r\n\t\tvalue[4*1+1] = Yy;\r\n\t\tvalue[4*1+2] = Yz;\r\n\r\n\t\tvalue[4*2+0] = Zx;\r\n\t\tvalue[4*2+1] = Zy;\r\n\t\tvalue[4*2+2] = Zz;\r\n\t}\r\n\tpublic void set3DBasis(float[] basis, int offset)\r\n\t{\r\n\t\tvalue[4*0+0] = basis[3*0+0+offset];\r\n\t\tvalue[4*0+1] = basis[3*0+1+offset];\r\n\t\tvalue[4*0+2] = basis[3*0+2+offset];\r\n\r\n\t\tvalue[4*1+0] = basis[3*1+0+offset];\r\n\t\tvalue[4*1+1] = basis[3*1+1+offset];\r\n\t\tvalue[4*1+2] = basis[3*1+2+offset];\r\n\r\n\t\tvalue[4*2+0] = basis[3*2+0+offset];\r\n\t\tvalue[4*2+1] = basis[3*2+1+offset];\r\n\t\tvalue[4*2+2] = basis[3*2+2+offset];\r\n\t}\r\n\tpublic void get3DBasis(float[] basis, int offset)\r\n\t{\r\n\t\tbasis[3*0+0+offset] = value[4*0+0];\r\n\t\tbasis[3*0+1+offset] = value[4*0+1];\r\n\t\tbasis[3*0+2+offset] = value[4*0+2];\r\n\r\n\t\tbasis[3*1+0+offset] = value[4*1+0];\r\n\t\tbasis[3*1+1+offset] = value[4*1+1];\r\n\t\tbasis[3*1+2+offset] = value[4*1+2];\r\n\r\n\t\tbasis[3*2+0+offset] = value[4*2+0];\r\n\t\tbasis[3*2+1+offset] = value[4*2+1];\r\n\t\tbasis[3*2+2+offset] = value[4*2+2];\r\n\t}\r\n\tpublic void set2DTransformZRotation(float z)\r\n\t{\r\n\t\tfloat sin=(float)Math.sin(z);\r\n\t\tfloat cos=(float)Math.cos(z);\r\n\t\tvalue[2*0+0] = cos;\r\n\t\tvalue[2*0+1] = -sin;\r\n\t\tvalue[2*1+0] = sin;\r\n\t\tvalue[2*1+1] = cos;\r\n\t}\r\n\r\n\tpublic void set3DTransformZRotation(float z)\r\n\t{\r\n\t\tfloat sin=(float)Math.sin(z);\r\n\t\tfloat cos=(float)Math.cos(z);\r\n\t\tvalue[4*0+0] = cos;\r\n\t\tvalue[4*0+1] = -sin;\r\n\t\tvalue[4*1+0] = sin;\r\n\t\tvalue[4*1+1] = cos;\r\n\t\tvalue[4*2+2] = 1.0f;\r\n\t}\r\n\tpublic void set3DTransformYRotation(float y)\r\n\t{\r\n\t\tfloat sin=(float)Math.sin(y);\r\n\t\tfloat cos=(float)Math.cos(y);\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cos;\r\n\t\t\tvalue[4*0+2] = sin;\r\n\t\t\tvalue[4*2+0] = -sin;\r\n\t\t\tvalue[4*2+2] = cos;\r\n\t\t\tvalue[4*1+1] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cos;\r\n\t\t\tvalue[3*0+2] = sin;\r\n\t\t\tvalue[3*2+0] = -sin;\r\n\t\t\tvalue[3*2+2] = cos;\r\n\t\t\tvalue[3*1+1] = 1.0f;\r\n\t\t}\r\n\t}\r\n\tpublic void set3DTransformXRotation(float x)\r\n\t{\r\n\t\tsetIdentity();\r\n\t\tfloat sin=(float)Math.sin(x);\r\n\t\tfloat cos=(float)Math.cos(x);\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*1+1] = cos;\r\n\t\t\tvalue[4*1+2] = -sin;\r\n\t\t\tvalue[4*2+1] = sin;\r\n\t\t\tvalue[4*2+2] = cos;\r\n\t\t\tvalue[4*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*1+1] = cos;\r\n\t\t\tvalue[3*1+2] = -sin;\r\n\t\t\tvalue[3*2+1] = sin;\r\n\t\t\tvalue[3*2+2] = cos;\r\n\t\t\tvalue[3*0+0] = 1.0f;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void set3DTransformRotation(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*0+1] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[4*0+2] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[4*1+0] = sz*cy;\r\n\t\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[4*1+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = -sy;\r\n\t\t\tvalue[4*2+1] = cy*sx;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cz*cy;\r\n\t\t\tvalue[3*0+1] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[3*0+2] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[3*1+0] = sz*cy;\r\n\t\t\tvalue[3*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[3*1+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[3*2+0] = -sy;\r\n\t\t\tvalue[3*2+1] = cy*sx;\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\t\r\n//\t[ cz*cy ,-(sz), cz*sy ]\r\n//\t[ ]\r\n//\t[(cx*sz*cy)+((-(sx))*(-(sy))),cx*cz,(cx*sz*sy)+((-(sx))*cy)]\r\n//\t[ ]\r\n//\t[ (sx*sz*cy)+(cx*(-(sy))) ,sx*cz, (sx*sz*sy)+(cx*cy) ]\r\n\tpublic void set3DTransformRotationXZY(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*0+1] = -(sz);\r\n\t\t\tvalue[4*0+2] = cz*sy;\r\n\t\r\n\t\t\tvalue[4*1+0] = (cx*sz*cy)+((-(sx))*(-(sy)));\r\n\t\t\tvalue[4*1+1] = cx*cz;\r\n\t\t\tvalue[4*1+2] = (cx*sz*sy)+((-(sx))*cy);\r\n\t\r\n\t\t\tvalue[4*2+0] = (sx*sz*cy)+(cx*(-(sy)));\r\n\t\t\tvalue[4*2+1] = sx*cz;\r\n\t\t\tvalue[4*2+2] = (sx*sz*sy)+(cx*cy);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cz*cy;\r\n\t\t\tvalue[3*0+1] = -(sz);\r\n\t\t\tvalue[3*0+2] = cz*sy;\r\n\t\r\n\t\t\tvalue[3*1+0] = (cx*sz*cy)+((-(sx))*(-(sy)));\r\n\t\t\tvalue[3*1+1] = cx*cz;\r\n\t\t\tvalue[3*1+2] = (cx*sz*sy)+((-(sx))*cy);\r\n\t\r\n\t\t\tvalue[3*2+0] = (sx*sz*cy)+(cx*(-(sy)));\r\n\t\t\tvalue[3*2+1] = sx*cz;\r\n\t\t\tvalue[3*2+2] = (sx*sz*sy)+(cx*cy);\r\n\t\t}\r\n\t}\r\n\t\r\n//\t [ (cy*cz)+(sy*sx*sz) , (cy*(-(sz)))+(sy*sx*cz) ,sy*cx]\r\n//\t [ ]\r\n//\t [ cx*sz , cx*cz ,-(sx)]\r\n//\t [ ]\r\n//\t [((-(sy))*cz)+(cy*sx*sz),((-(sy))*(-(sz)))+(cy*sx*cz),cy*cx]\r\n\tpublic void set3DTransformRotationYXZ(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (cy*cz)+(sy*sx*sz);\r\n\t\t\tvalue[4*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n\t\t\tvalue[4*0+2] = sy*cx;\r\n\t\r\n\t\t\tvalue[4*1+0] = cx*sz;\r\n\t\t\tvalue[4*1+1] = cx*cz;\r\n\t\t\tvalue[4*1+2] = -(sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n\t\t\tvalue[4*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = (cy*cz)+(sy*sx*sz);\r\n\t\t\tvalue[3*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n\t\t\tvalue[3*0+2] = sy*cx;\r\n\t\r\n\t\t\tvalue[3*1+0] = cx*sz;\r\n\t\t\tvalue[3*1+1] = cx*cz;\r\n\t\t\tvalue[3*1+2] = -(sx);\r\n\t\r\n\t\t\tvalue[3*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n\t\t\tvalue[3*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n//\t[ cy*cz , (cy*(-(sz))*cx)+(sy*sx) , ((cy*(-(sz)))*(-(sx)))+(sy*cx) ]\r\n//\t[ ]\r\n//\t[ sz , cz*cx , cz*(-(sx)) ]\r\n//\t[ ]\r\n//\t[(-(sy))*cz,((-(sy))*(-(sz))*cx)+(cy*sx),(((-(sy))*(-(sz)))*(-(sx)))+(cy*cx)]\t\r\n\tpublic void set3DTransformRotationYZX(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cy*cz;\r\n\t\t\tvalue[4*0+1] = (cy*(-(sz))*cx)+(sy*sx);\r\n\t\t\tvalue[4*0+2] = ((cy*(-(sz)))*(-(sx)))+(sy*cx);\r\n\t\r\n\t\t\tvalue[4*1+0] = sz;\r\n\t\t\tvalue[4*1+1] = cz*cx;\r\n\t\t\tvalue[4*1+2] = cz*(-(sx));\r\n\t\r\n\t\t\tvalue[4*2+0] = (-(sy))*cz;\r\n\t\t\tvalue[4*2+1] = ((-(sy))*(-(sz))*cx)+(cy*sx);\r\n\t\t\tvalue[4*2+2] = (((-(sy))*(-(sz)))*(-(sx)))+(cy*cx);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cy*cz;\r\n\t\t\tvalue[3*0+1] = (cy*(-(sz))*cx)+(sy*sx);\r\n\t\t\tvalue[3*0+2] = ((cy*(-(sz)))*(-(sx)))+(sy*cx);\r\n\t\r\n\t\t\tvalue[3*1+0] = sz;\r\n\t\t\tvalue[3*1+1] = cz*cx;\r\n\t\t\tvalue[3*1+2] = cz*(-(sx));\r\n\t\r\n\t\t\tvalue[3*2+0] = (-(sy))*cz;\r\n\t\t\tvalue[3*2+1] = ((-(sy))*(-(sz))*cx)+(cy*sx);\r\n\t\t\tvalue[3*2+2] = (((-(sy))*(-(sz)))*(-(sx)))+(cy*cx);\r\n\t\t}\r\n\t}\r\n\r\n\t///*\r\n\tpublic void set3DTransformRotationZXY(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (cz*cx-sz*sy*sx);\r\n\t\t\tvalue[4*0+1] = -sx*cy;\r\n\t\t\tvalue[4*0+2] = (sz*cx+cz*sy*sx);\r\n\t\r\n\t\t\tvalue[4*1+0] = cx*sy*sz+sx*cz;\r\n\t\t\tvalue[4*1+1] = cx*cy;\r\n\t\t\tvalue[4*1+2] = sz*sx-cz*sy*cx;\r\n\t\r\n\t\t\tvalue[4*2+0] = -cy*sz;\r\n\t\t\tvalue[4*2+1] = sy;\r\n\t\t\tvalue[4*2+2] = cy*cz;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = (cz*cx-sz*sy*sx);\r\n\t\t\tvalue[3*0+1] = -sx*cy;\r\n\t\t\tvalue[3*0+2] = (sz*cx+cz*sy*sx);\r\n\t\r\n\t\t\tvalue[3*1+0] = cx*sy*sz+sx*cz;\r\n\t\t\tvalue[3*1+1] = cx*cy;\r\n\t\t\tvalue[3*1+2] = sz*sx-cz*sy*cx;\r\n\t\r\n\t\t\tvalue[3*2+0] = -cy*sz;\r\n\t\t\tvalue[3*2+1] = sy;\r\n\t\t\tvalue[3*2+2] = cy*cz;\r\n//\t\t\tvalue[3*0+0] = (cz*cx-sz*sy*sx);\r\n//\t\t\tvalue[3*0+1] = -sz*cy;\r\n//\t\t\tvalue[3*0+2] = (sz*sx+cz*sy*cx);\r\n//\t\r\n//\t\t\tvalue[3*1+0] = cz*sy*sx+sz*cz;\r\n//\t\t\tvalue[3*1+1] = cz*cy;\r\n//\t\t\tvalue[3*1+2] = sz*sx-cz*sy*cx;\r\n//\t\r\n//\t\t\tvalue[3*2+0] = -cy*sx;\r\n//\t\t\tvalue[3*2+1] = sy;\r\n//\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n//\t[cz*cy,((-(sz))*cx)+(cz*sy*sx),((-(sz))*(-(sx)))+(cz*sy*cx)]\r\n//\t[ ]\r\n//\t[sz*cy, (cz*cx)+(sz*sy*sx) , (cz*(-(sx)))+(sz*sy*cx) ]\r\n//\t[ ]\r\n//\t[-(sy), cy*sx , cy*cx ]\r\n\tpublic void set3DTransformRotationZYX(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*0+1] = ((-(sz))*cx)+(cz*sy*sx);\r\n\t\t\tvalue[4*0+2] = ((-(sz))*(-(sx)))+(cz*sy*cx);\r\n\t\r\n\t\t\tvalue[4*1+0] = sz*cy;\r\n\t\t\tvalue[4*1+1] = (cz*cx)+(sz*sy*sx);\r\n\t\t\tvalue[4*1+2] = (cz*(-(sx)))+(sz*sy*cx);\r\n\t\r\n\t\t\tvalue[4*2+0] = -(sy);\r\n\t\t\tvalue[4*2+1] = cy*sx;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cz*cy;\r\n\t\t\tvalue[3*0+1] = ((-(sz))*cx)+(cz*sy*sx);\r\n\t\t\tvalue[3*0+2] = ((-(sz))*(-(sx)))+(cz*sy*cx);\r\n\t\r\n\t\t\tvalue[3*1+0] = sz*cy;\r\n\t\t\tvalue[3*1+1] = (cz*cx)+(sz*sy*sx);\r\n\t\t\tvalue[3*1+2] = (cz*(-(sx)))+(sz*sy*cx);\r\n\t\r\n\t\t\tvalue[3*2+0] = -(sy);\r\n\t\t\tvalue[3*2+1] = cy*sx;\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void set3DTransformRotationZXY_opengl(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (cz*cx-sz*sy*sx);\r\n\t\t\tvalue[4*1+0] = -sx*cy;\r\n\t\t\tvalue[4*2+0] = (sz*cx+cz*sy*sx);\r\n\t\r\n\t\t\tvalue[4*0+1] = cx*sy*sz+sx*cz;\r\n\t\t\tvalue[4*1+1] = cx*cy;\r\n\t\t\tvalue[4*2+1] = sz*sx-cz*sy*cx;\r\n\t\r\n\t\t\tvalue[4*0+2] = -cy*sz;\r\n\t\t\tvalue[4*1+2] = sy;\r\n\t\t\tvalue[4*2+2] = cy*cz;\r\n\t\t}\r\n\t}\r\n\t//*/\r\n\tpublic void set3DTransformRotation_opengl(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*1+0] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[4*2+0] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[4*0+1] = sz*cy;\r\n\t\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[4*2+1] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[4*0+2] = -sy;\r\n\t\t\tvalue[4*1+2] = cy*sx;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic boolean isIdentity()\r\n\t{\r\n\t\tfloat maxdif = 0.000001f;\r\n\t\tint ind = 0;\r\n\t\tfor(int j=0;j<height;j++)\r\n\t\t{\r\n\t\t\tfor(int i=0;i<width;i++)\r\n\t\t\t{\r\n\t\t\t\tif(i==j)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(Math.abs(value[ind]-1.0f)>maxdif)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif(Math.abs(value[ind]-0.0f)>maxdif)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tind++;\r\n\t\t\t}\t\t\t\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic boolean orthonormalTransform()\r\n\t{\r\n\t\tint mw = width;\r\n\t\tfloat maxdif = 0.001f;\r\n\t\tfloat len;\r\n\t\tlen = value[mw*0+0]*value[mw*0+0]+value[mw*0+1]*value[mw*0+1]+value[mw*0+2]*value[mw*0+2];\r\n\t\tif(Math.abs(len-1.0f)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tlen = value[mw*1+0]*value[mw*1+0]+value[mw*1+1]*value[mw*1+1]+value[mw*1+2]*value[mw*1+2];\r\n\t\tif(Math.abs(len-1.0f)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tlen = value[mw*2+0]*value[mw*2+0]+value[mw*2+1]*value[mw*2+1]+value[mw*2+2]*value[mw*2+2];\r\n\t\tif(Math.abs(len-1.0f)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t\tfloat dot;\r\n\t\tdot = value[mw*0+0]*value[mw*1+0]+value[mw*0+1]*value[mw*1+1]+value[mw*0+2]*value[mw*1+2];\r\n\t\tif(Math.abs(dot)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tdot = value[mw*0+0]*value[mw*2+0]+value[mw*0+1]*value[mw*2+1]+value[mw*0+2]*value[mw*2+2];\r\n\t\tif(Math.abs(dot)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tdot = value[mw*1+0]*value[mw*2+0]+value[mw*1+1]*value[mw*2+1]+value[mw*1+2]*value[mw*2+2];\r\n\t\tif(Math.abs(dot)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic static final void getEulerZXY(GeneralMatrixFloat m, GeneralMatrixFloat euler) \r\n\t{\r\n//\t\tvalue[4*0+0] = (cz*cx-sz*sy*sx);\r\n//\t\tvalue[4*0+1] = -sx*cy;\r\n//\t\tvalue[4*0+2] = (sz*cx+cz*sy*sx);\r\n//\r\n//\t\tvalue[4*1+0] = cx*sy*sz+sx*cz;\r\n//\t\tvalue[4*1+1] = cx*cy;\r\n//\t\tvalue[4*1+2] = sz*sx-cz*sy*cx;\r\n//\r\n//\t\tvalue[4*2+0] = -cy*sz;\r\n//\t\tvalue[4*2+1] = sy;\r\n//\t\tvalue[4*2+2] = cy*cz;\r\n\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\t\t\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+j]*m.value[i*w+j] + m.value[j*w+j]*m.value[j*w+j]);\r\n\t\tif (cy > 16*EPSILON) \r\n\t\t{\r\n\t\t euler.value[0] = (float)Math.atan2(-m.value[i*w+j], m.value[j*w+j]);\r\n\t\t euler.value[1] = (float)Math.atan2(m.value[k*w+j], cy);\r\n\t\t euler.value[2] = (float)Math.atan2(-m.value[k*w+i], m.value[k*w+k]);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t euler.value[0] = 0.0f;\r\n\t\t euler.value[1] = (float)Math.atan2(m.value[k*w+j], cy);\t\t\t\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[i*w+k], m.value[i*w+i]);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void getEulerYXZ(GeneralMatrixFloat m, GeneralMatrixFloat euler) \r\n\t{\r\n//\t\tvalue[4*0+0] = (cy*cz)+(sy*sx*sz);\r\n//\t\tvalue[4*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n//\t\tvalue[4*0+2] = sy*cx;\r\n//\r\n//\t\tvalue[4*1+0] = cx*sz;\r\n//\t\tvalue[4*1+1] = cx*cz;\r\n//\t\tvalue[4*1+2] = -(sx);\r\n//\r\n//\t\tvalue[4*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n//\t\tvalue[4*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n//\t\tvalue[4*2+2] = cy*cx;\r\n\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\t\t\r\n\t\tdouble cx = Math.sqrt(m.value[j*w+i]*m.value[j*w+i] + m.value[j*w+j]*m.value[j*w+j]);\r\n\t\tif (cx > 16*EPSILON) {\r\n\t\t euler.value[0] = (float)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = (float)Math.atan2(m.value[i*w+k], m.value[k*w+k]);\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[j*w+i], m.value[j*w+j]);\r\n\t\t} else {\r\n\t\t\teuler.value[0] = (float)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = 0;\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[i*w+i], m.value[i*w+j]);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static final void getEuler(GeneralMatrixFloat m, GeneralMatrixFloat euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n//\t\tvalue[4*0+0] = cz*cy;\r\n//\t\tvalue[4*0+1] = (sy*sx*cz-cx*sz);\r\n//\t\tvalue[4*0+2] = (sy*cx*cz+sz*sx);\r\n//\r\n//\t\tvalue[4*1+0] = sz*cy;\r\n//\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n//\t\tvalue[4*1+2] = (sy*cx*sz-cz*sx);\r\n//\r\n//\t\tvalue[4*2+0] = -sy;\r\n//\t\tvalue[4*2+1] = cy*sx;\r\n//\t\tvalue[4*2+2] = cy*cx;\r\n\t\t\r\n\t\tfinal int w=m.width;\r\n\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+i]*m.value[i*w+i] + m.value[j*w+i]*m.value[j*w+i]);\r\n\t\tif (cy > 16*EPSILON) {\r\n\t\t euler.value[0] = (float)Math.atan2(m.value[k*w+j], m.value[k*w+k]);\r\n\t\t euler.value[1] = (float)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[j*w+i], m.value[i*w+i]);\r\n\t\t} else {\r\n\t\t\t//pretty much pointing down x\r\n\t\t\tif(Math.abs(m.value[4*2+0]-(1.0f))<EPSILON)\r\n\t\t\t{\r\n\t\t\t\teuler.value[0] = 0.0f;\r\n\t\t\t\teuler.value[2] = 0.0f;\r\n\t\t\t\teuler.value[1] = (float)(Math.PI*0.5);\r\n//\t\t\t\tvalue[4*0+1] = (-sx*cz-cx*sz);\r\n//\t\t\t\tvalue[4*0+2] = (-cx*cz+sz*sx);\r\n//\t\t\t\tvalue[4*1+1] = (-sx*sz+cx*cz);\r\n//\t\t\t\tvalue[4*1+2] = (-cx*sz-cz*sx);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\tif(Math.abs(m.value[4*2+0]-(-1.0f))<EPSILON)\r\n\t\t\t{\r\n\t\t\t\teuler.value[0] = 0.0f;\r\n\t\t\t\teuler.value[2] = 0.0f;\r\n\t\t\t\teuler.value[1] = -(float)(Math.PI*0.5);\r\n//\t\t\t\tvalue[4*0+1] = (sx*cz-cx*sz);\r\n//\t\t\t\tvalue[4*0+2] = (cx*cz+sz*sx);\r\n//\t\t\t\tvalue[4*1+1] = (sx*sz+cx*cz);\r\n//\t\t\t\tvalue[4*1+2] = (cx*sz-cz*sx);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t euler.value[0] = (float)Math.atan2(-m.value[i*w+k], m.value[j*w+j]);\r\n\t\t\t euler.value[1] = (float)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t\t euler.value[2] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic static final void rowtransform(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t// wxh\r\n\t\t//a is 3xn (h value of 1.0 is implied)\r\n\t\t//B is 3x4 (or at least the other values are unused)\r\n\t\t//float vdot;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t //Apply the matrix to this vector\r\n\r\n\t\t\t //for (int j = 0; j < a.width; j++)\r\n\t\t\t //{\r\n\t\t\t int j = 0;\r\n\t\t\t\tfloat x = 0.0f;\r\n\t\t\t\tfor (int k = 0; k < a.width; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\tx += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t}\r\n\t\t\t\t x += b.value[a.width*b.width+j];\r\n\t\t\t\tj++;\r\n\t\t\t\tfloat y = 0.0f;\r\n\t\t\t\tfor (int k = 0; k < a.width; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\ty += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t}\r\n\t\t\t\t y += b.value[a.width*b.width+j];\r\n\t\t\t\tj++;\r\n\t\t\t\tfloat z = 0.0f;\r\n\t\t\t\tfor (int k = 0; k < a.width; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\tz += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t}\r\n\t\t\t\t z += b.value[a.width*b.width+j];\r\n\t\t\t\t //Add what would be the homogenious value to translate correctly\r\n\t\t\t //}\r\n\t\t\t \r\n\t\t\t c.value[i*a.width+0] = x;\r\n\t\t\t c.value[i*a.width+1] = y;\r\n\t\t\t c.value[i*a.width+2] = z;\r\n\t\t }\r\n\t}\r\n\tpublic float norm()\r\n\t{\r\n\t\tfloat total = 0.0f;\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i]*value[i];\r\n\t\t}\r\n\t\ttotal = (float)Math.sqrt(total);\r\n\t\treturn total;\r\n\t}\r\n\t\r\n\tpublic static float sqrdist(GeneralMatrixFloat a,GeneralMatrixFloat b)\r\n\t{\r\n\t\tint s = a.width*b.width;\r\n\t\tfloat d = 0.0f;\r\n\t\tfor(int i=0;i<s;i++)\r\n\t\t{\r\n\t\t\tfloat dv = b.value[i]-a.value[i];\r\n\t\t\td += dv*dv;\r\n\t\t}\r\n\t\treturn d;//(float)Math.sqrt(d);\r\n\t}\r\n\r\n\tpublic static float rowdist(GeneralMatrixFloat a,int rowa,GeneralMatrixFloat b,int rowb)\r\n\t{\r\n\t\tint offa = rowa*a.width;\r\n\t\tint offb = rowb*b.width;\r\n\t\tfloat d = 0.0f;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tfloat dv = b.value[offb+i]-a.value[offa+i];\r\n\t\t\td += dv*dv;\r\n\t\t}\r\n\t\treturn (float)Math.sqrt(d);\r\n\t}\r\n\t\r\n\tpublic void normalise()\r\n\t{\r\n\t\tfloat total = 0.0f;\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i]*value[i];\r\n\t\t}\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[0] = 1.0f;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ttotal = (float)Math.sqrt(total);\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] /= total;\r\n\t\t}\r\n\t}\r\n\tpublic void normaliseRow(int row,float len)\r\n\t{\r\n\t\tint ind = row*width;\r\n\t\tfloat total = 0.0f;\r\n\t\tfor (int i = 0; i < width; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i+ind]*value[i+ind];\r\n\t\t}\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[0+ind] = 1.0f;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ttotal = (float)Math.sqrt(total)/len;\r\n\t\tfor (int i = 0; i < width; i++)\r\n\t\t{\r\n\t\t\tvalue[i+ind] /= total;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void scale(float s)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = value[i]*s;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic void setIdentity()\r\n\t{\r\n\t\tint i=0;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tif(x==y)\r\n\t\t\t\t\tvalue[i] = 1.0f;\r\n\t\t\t\telse\r\n\t\t\t\t\tvalue[i] = 0.0f;\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tpublic static final boolean invert3x3(GeneralMatrixFloat a,GeneralMatrixFloat ia)\r\n\t{\r\n//\t\t| a11 a12 a13 |-1 | a33a22-a32a23 -(a33a12-a32a13) a23a12-a22a13 |\r\n//\t\t| a21 a22 a23 | = 1/DET * | -(a33a21-a31a23) a33a11-a31a13 -(a23a11-a21a13) |\r\n//\t\t| a31 a32 a33 | | a32a21-a31a22 -(a32a11-a31a12) a22a11-a21a12 |\r\n//\r\n//\t\twith DET = a11(a33a22-a32a23)-a21(a33a12-a32a13)+a31(a23a12-a22a13)\r\n\r\n//\t\tfloat det = a.value[0*3+0]*(a.value[0*3+0]*a.value[0*3+0]-a.value[0*3+0]*a.value[0*3+0]);\r\n//\t\tdet -= a.value[0*3+0]*(a.value[0*3+0]*a.value[0*3+0]-a.value[0*3+0]*a.value[0*3+0]);\r\n//\t\tdet += a.value[0*3+0]*(a.value[0*3+0]*a.value[0*3+0]-a.value[0*3+0]*a.value[0*3+0]);\r\n\t\tia.value[0*3+0] = (a.value[2*3+2]*a.value[1*3+1]-a.value[2*3+1]*a.value[1*3+2]);\r\n\t\tia.value[0*3+1] =-(a.value[2*3+2]*a.value[0*3+1]-a.value[2*3+1]*a.value[0*3+2]);\r\n\t\tia.value[0*3+2] = (a.value[1*3+2]*a.value[0*3+1]-a.value[1*3+1]*a.value[0*3+2]);\r\n\r\n\t\tia.value[1*3+0] = (a.value[2*3+2]*a.value[1*3+0]-a.value[2*3+0]*a.value[1*3+2]);\r\n\t\tia.value[1*3+1] = (a.value[2*3+2]*a.value[0*3+0]-a.value[2*3+0]*a.value[0*3+2]);\r\n\t\tia.value[1*3+2] =-(a.value[1*3+2]*a.value[0*3+0]-a.value[1*3+0]*a.value[0*3+2]);\r\n\r\n\t\tia.value[2*3+0] = (a.value[2*3+1]*a.value[1*3+0]-a.value[2*3+0]*a.value[1*3+1]);\r\n\t\tia.value[2*3+1] =-(a.value[2*3+1]*a.value[0*3+0]-a.value[2*3+0]*a.value[0*3+1]);\r\n\t\tia.value[2*3+2] = (a.value[1*3+1]*a.value[0*3+0]-a.value[1*3+0]*a.value[0*3+1]);\r\n\t\t\r\n\t\tfloat odet = GeneralMatrixFloat.determinant(a);\r\n\t\tfloat det = a.value[0*0+0]*ia.value[0*3+0]+a.value[1*0+0]*ia.value[0*3+1]+a.value[2*0+0]*ia.value[0*3+2];\r\n\t\tif(Math.abs(det)<EPSILON)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"matrix invert failed\");\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tfloat idet = 1.0f/det;\r\n\t\tia.value[0] *= idet;\r\n\t\tia.value[1] *= idet;\r\n\t\tia.value[2] *= idet;\r\n\t\tia.value[3] *= idet;\r\n\t\tia.value[4] *= idet;\r\n\t\tia.value[5] *= idet;\r\n\t\tia.value[6] *= idet;\r\n\t\tia.value[7] *= idet;\r\n\t\tia.value[8] *= idet;\r\n\t\treturn true;\r\n\t}\r\n\t*/\r\n\t\r\n\tpublic static final void invertTransform(GeneralMatrixFloat cameraTransformMatrix,GeneralMatrixFloat modelMatrix)\r\n\t{\r\n\t\t//GeneralMatrixFloat.invert(cameraTransformMatrix,modelMatrix);\r\n\t\t//*\r\n\t\tmodelMatrix.value[0*4+0] = cameraTransformMatrix.value[0*4+0];\r\n\t\tmodelMatrix.value[1*4+0] = cameraTransformMatrix.value[0*4+1];\r\n\t\tmodelMatrix.value[2*4+0] = cameraTransformMatrix.value[0*4+2];\r\n\r\n\t\tmodelMatrix.value[0*4+1] = cameraTransformMatrix.value[1*4+0];\r\n\t\tmodelMatrix.value[1*4+1] = cameraTransformMatrix.value[1*4+1];\r\n\t\tmodelMatrix.value[2*4+1] = cameraTransformMatrix.value[1*4+2];\r\n\r\n\t\tmodelMatrix.value[0*4+2] = cameraTransformMatrix.value[2*4+0];\r\n\t\tmodelMatrix.value[1*4+2] = cameraTransformMatrix.value[2*4+1];\r\n\t\tmodelMatrix.value[2*4+2] = cameraTransformMatrix.value[2*4+2];\r\n\r\n\t\tfloat x = -cameraTransformMatrix.value[3*4+0];\r\n\t\tfloat y = -cameraTransformMatrix.value[3*4+1];\r\n\t\tfloat z = -cameraTransformMatrix.value[3*4+2];\r\n\t\t\r\n\t\t//needs to be rotated like the rest of the points in space\r\n\t\tfloat tx = modelMatrix.value[0*4+0]*x+modelMatrix.value[1*4+0]*y+modelMatrix.value[2*4+0]*z;\r\n\t\tfloat ty = modelMatrix.value[0*4+1]*x+modelMatrix.value[1*4+1]*y+modelMatrix.value[2*4+1]*z;\r\n\t\tfloat tz = modelMatrix.value[0*4+2]*x+modelMatrix.value[1*4+2]*y+modelMatrix.value[2*4+2]*z;\r\n\t\tmodelMatrix.value[3*4+0] = tx;\r\n\t\tmodelMatrix.value[3*4+1] = ty;\r\n\t\tmodelMatrix.value[3*4+2] = tz;\t\t\r\n\t\t//*/\r\n\t}\r\n\r\n\tpublic static final boolean invert(GeneralMatrixFloat a,GeneralMatrixFloat ia)\r\n\t{\r\n\t\tGeneralMatrixFloat temp = new GeneralMatrixFloat(a.width,a.height);\r\n\t\ttemp.set(a);\r\n\r\n\t\tia.setIdentity();\r\n\t\tint i,j,k,swap;\r\n\t\tfloat t;\r\n\t\tfor(i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tswap = i;\r\n\t\t\tfor (j = i + 1; j < a.height; j++) {\r\n\t\t\t if (Math.abs(a.get(i, j)) > Math.abs(a.get(i, j)))\r\n\t\t\t {\r\n\t\t\t \tswap = j;\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t\tif (swap != i)\r\n\t\t\t{\r\n\t\t\t /*\r\n\t\t\t ** Swap rows.\r\n\t\t\t */\r\n\t\t\t for (k = 0; k < a.width; k++)\r\n\t\t\t {\r\n\t\t\t\t\tt = temp.get(k,i);\r\n\t\t\t\t\ttemp.set(k,i,temp.get(k, swap));\r\n\t\t\t\t\ttemp.set(k, swap,t);\r\n\r\n\t\t\t\t\tt = ia.get(k,i);\r\n\t\t\t\t\tia.set(k,i,ia.get(k, swap));\r\n\t\t\t\t\tia.set(k, swap,t);\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t\tt = temp.get(i,i);\r\n\t\t\tif (t == 0.0f)\r\n\t\t\t{\r\n\t\t\t /*\r\n\t\t\t ** No non-zero pivot. The matrix is singular, which shouldn't\r\n\t\t\t ** happen. This means the user gave us a bad matrix.\r\n\t\t\t */\r\n\t\t\t\tSystem.out.println(\"inverse failed\");\r\n\t\t\t return false;\r\n\t\t\t}\r\n\r\n\t\t\tfor (k = 0; k < a.width; k++)\r\n\t\t\t{\r\n\t\t\t\ttemp.set(k,i,temp.get(k,i) / t);\r\n\t\t\t\tia.set(k,i,ia.get(k,i) / t);\r\n\t\t\t}\r\n\t\t\tfor (j = 0; j < a.width; j++)\r\n\t\t\t{\r\n\t\t\t if (j != i)\r\n\t\t\t {\r\n\t\t\t \tt = temp.get(i,j);\r\n\t\t\t \tfor (k = 0; k < a.width; k++)\r\n\t\t\t \t{\r\n\t\t\t \t\ttemp.set(k,j, temp.get(k,j) - temp.get(k,i)*t);\r\n\t\t\t \t\tia.set(k,j, ia.get(k,j) - ia.get(k,i)*t);\r\n\t\t\t \t}\r\n\t\t\t }\r\n\t\t\t}\r\n\t }\r\n\t return true;\r\n\t}\r\n\r\n\tpublic static final float dotProduct(GeneralMatrixFloat a,int arow,GeneralMatrixFloat b,int brow)\r\n\t{\r\n\t\tint aind = arow*a.width;\r\n\t\tint bind = brow*b.width;\r\n\t\tfloat result = 0.0f;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tresult += a.value[aind]*b.value[bind];\r\n\t\t\taind++;\r\n\t\t\tbind++;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\tpublic static final float dotProduct3(GeneralMatrixFloat a,GeneralMatrixFloat b)\r\n\t{\r\n\t\treturn a.value[0]*b.value[0]+a.value[1]*b.value[1]+a.value[2]*b.value[2];\r\n\t}\r\n\t\r\n\tpublic static final void crossProduct3(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\tc.value[0] = a.value[1]*b.value[2]-b.value[1]*a.value[2];\r\n\t\tc.value[1] = a.value[2]*b.value[0]-b.value[2]*a.value[0];\r\n\t\tc.value[2] = a.value[0]*b.value[1]-b.value[0]*a.value[1];\r\n\t}\r\n\r\n\tpublic static final void multInPlace(GeneralMatrixFloat a,GeneralMatrixFloat b)\r\n\t{\r\n\t\tGeneralMatrixFloat c = new GeneralMatrixFloat(a.width,1);\r\n\r\n\t\tint n = a.height;\r\n\t\tint p = a.width;\r\n\t\tint r = b.width;\r\n\r\n\t\tif(a.width!=b.height)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Mult error, matricies sizes dont match\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t float vdot;\r\n\t int i,j,k,m;\r\n\r\n\r\n int r5 = r*5;\r\n\t int rowI = 0;\r\n\t int crowI = 0;\r\n\t for (i = 0; i < n; i++) {\r\n\r\n\t for (j = 0; j < r; j++) {\r\n\r\n\t vdot = 0.0f;\r\n\r\n\t m = p%5;\r\n\r\n\t int rowK = 0;\r\n\t for (k = 0; k < m; k++) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j];\r\n\t rowK += r;\r\n\t }\r\n\r\n\t for (k = m; k < p; k += 5) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j] +\r\n\t a.value[rowI+k+1]*b.value[rowK+r+j] +\r\n\t a.value[rowI+k+2]*b.value[rowK+r*2+j] +\r\n\t a.value[rowI+k+3]*b.value[rowK+r*3+j] +\r\n\t a.value[rowI+k+4]*b.value[rowK+r*4+j];\r\n\r\n\t rowK += r5;\r\n\t }\r\n\r\n\t c.value[j] = vdot;\r\n\r\n\t }\r\n\t //now overright the a rowI\r\n\t for (j = 0; j < r; j++) \r\n\t {\r\n\t \t a.value[rowI+j] = c.value[j];\r\n\t }\r\n\t rowI += p;\r\n\t crowI += r;\r\n\t }\r\n\t}\r\n\t\r\n\tpublic static final void mult(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\tint n = a.height;\r\n\t\tint p = a.width;\r\n\t\tint r = b.width;\r\n\r\n\t\tif(a.width!=b.height)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Mult error, matricies sizes dont match\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t float vdot;\r\n\t int i,j,k,m;\r\n\r\n\r\n int r5 = r*5;\r\n\t int rowI = 0;\r\n\t int crowI = 0;\r\n\t for (i = 0; i < n; i++) {\r\n\r\n\t for (j = 0; j < r; j++) {\r\n\r\n\t vdot = 0.0f;\r\n\r\n\t m = p%5;\r\n\r\n\t int rowK = 0;\r\n\t for (k = 0; k < m; k++) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j];\r\n\t rowK += r;\r\n\t }\r\n\r\n\t for (k = m; k < p; k += 5) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j] +\r\n\t a.value[rowI+k+1]*b.value[rowK+r+j] +\r\n\t a.value[rowI+k+2]*b.value[rowK+r*2+j] +\r\n\t a.value[rowI+k+3]*b.value[rowK+r*3+j] +\r\n\t a.value[rowI+k+4]*b.value[rowK+r*4+j];\r\n\r\n\t rowK += r5;\r\n\t }\r\n\r\n\t c.value[crowI+j] = vdot;\r\n\r\n\t }\r\n\t rowI += p;\r\n\t crowI += r;\r\n\t }\r\n\r\n\t}\r\n\r\n\tpublic static final void add(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]+b.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic static final void add(GeneralMatrixFloat a,int arow,GeneralMatrixFloat b,int brow,GeneralMatrixFloat c,int crow)\r\n\t{\r\n\t\tint aoff = a.width*arow;\r\n\t\tint boff = b.width*brow;\r\n\t\tint coff = c.width*crow;\r\n\t\t for (int i = 0; i < a.width; i++)\r\n\t\t {\r\n\t\t\t c.value[coff+i] = a.value[aoff+i]+b.value[boff+i];\r\n\t\t }\r\n\t}\r\n\tpublic static final void addsqa(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]*a.value[i]+b.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void transpose(GeneralMatrixFloat a,GeneralMatrixFloat at)\r\n\t{\r\n\t\tint i,j;\r\n\r\n\t\tint ai = 0;\r\n\t\tint atjR;\r\n\t for (i = 0; i < a.height; i++) {\r\n\r\n\t \t\tatjR = 0;\r\n\t for (j = 0; j < a.width; j++) {\r\n\r\n\t at.value[atjR+i] = a.value[ai];\r\n\t ai++;\r\n\t atjR += a.height;\r\n\t }\r\n\r\n\t }\r\n\t}\r\n\r\n\tpublic final float trace()\r\n\t{\r\n\t\tfloat sum = 0.0f;\r\n\t\tint index = 0;\r\n\t\tfor (int i = 0; i < height; i++)\r\n\t\t{\r\n\t\t\tsum += value[index];\r\n\t\t\tindex += height+1;\r\n\t\t}\r\n\t\treturn sum;\r\n\t}\r\n\r\n\tpublic static float determinant(GeneralMatrixFloat m)\r\n\t{\r\n\t\tint n = m.width; \r\n\t\tif(n==1)\r\n\t\t\treturn m.value[0];\r\n\t\telse\r\n\t\tif(n==2)\r\n\t\t{\r\n\t\t\treturn m.value[0*2+0] * m.value[1*2+1] - m.value[1*2+0] * m.value[0*2+1];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat det = 0.0f;\r\n\t\t\tfor (int j1=0;j1<n;j1++) \r\n\t\t\t{\r\n\t\t if(m.value[0*n+j1]==0.0f)\r\n\t\t \t continue;\r\n\r\n\t\t GeneralMatrixFloat subm = new GeneralMatrixFloat(n-1,n-1);\r\n\r\n\t\t for (int i=1;i<n;i++) \r\n\t\t {\r\n\t\t int j2 = 0;\r\n\t\t for (int j=0;j<n;j++) \r\n\t\t {\r\n\t\t if (j == j1)\r\n\t\t continue;\r\n\t\t subm.value[(i-1)*(n-1)+j2] = m.value[i*n+j];\r\n\t\t j2++;\r\n\t\t }\r\n\t\t }\r\n\t\t int ind = 1+j1+1;\r\n\t\t \r\n\t\t if((ind%2)==0)\r\n\t\t \t det += m.value[0*n+j1] * determinant(subm);\r\n\t\t else\r\n\t\t \t det -= m.value[0*n+j1] * determinant(subm);\r\n\t\t\t}\r\n\t\t\treturn det;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void sub(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]-b.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic static final void sub(GeneralMatrixFloat a,int arow,GeneralMatrixFloat b,int brow,GeneralMatrixFloat c,int crow)\r\n\t{\r\n\t\tint aoff = a.width*arow;\r\n\t\tint boff = b.width*brow;\r\n\t\tint coff = c.width*crow;\r\n\t\t for (int i = 0; i < a.width; i++)\r\n\t\t {\r\n\t\t\t c.value[coff+i] = a.value[aoff+i]-b.value[boff+i];\r\n\t\t }\r\n\t}\r\n\tpublic static final void subsqb(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]-b.value[i]*b.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void rowsub(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\tint ai = 0;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t c.value[ai] = a.value[ai]-b.value[j];\r\n\t\t\t\t ai++;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void setRow(int row,GeneralMatrixFloat a,GeneralMatrixFloat target)\r\n\t{\r\n\t\tint ind = row*a.width;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\ttarget.value[ind+i] = a.value[ind+i];\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void blendRow(int row,float mag0,float mag1,GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat target)\r\n\t{\r\n\t\tint ind = row*a.width;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\ttarget.value[ind+i] = a.value[ind+i]*mag0+b.value[ind+i]*mag1;\r\n\t\t}\r\n\t}\r\n\t\r\n//\tpublic static final void blendRotations(GeneralMatrixFloat a,GeneralMatrixFloat b,float f,GeneralMatrixFloat c)\r\n//\t{\r\n//\t\tfloat[] qa = new float[4];\r\n//\t\tfloat[] qb = new float[4];\r\n//\t\tfloat[] qc = new float[4];\r\n//\t\t\r\n//\t\tQuaternion.MatrixtoQuaternion(a.value, qa);\r\n//\t\tQuaternion.MatrixtoQuaternion(b.value, qb);\r\n//\t\tQuaternion.slerp(qa, qb, f, qc);\r\n//\t\tQuaternion.QuaterniontoMatrix(qc, c.value);\r\n//\t}\r\n}\r",
"public class GeneralMatrixInt implements Serializable \r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic int width=0; //columns\r\n\tpublic int height=0; //rows\r\n\tpublic int[] value=null; //array of values\r\n\r\n\tpublic GeneralMatrixInt()\r\n\t{\r\n\t\twidth = 0;\r\n\t\theight = 0;\r\n\t}\t\r\n\tpublic GeneralMatrixInt(int val0,int val1,int val2,int val3)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 4;\r\n\t\tthis.value = new int[4];\r\n\t\tthis.value[0] = val0;\r\n\t\tthis.value[1] = val1;\r\n\t\tthis.value[2] = val2;\r\n\t\tthis.value[3] = val3;\r\n\t}\r\n\r\n\tpublic GeneralMatrixInt(int[] vals)\r\n\t{\r\n\t\tthis.width = vals.length;\r\n\t\tthis.height = 1;\r\n\t\tthis.value = vals;\r\n\t}\r\n\tpublic GeneralMatrixInt(int[] vals,int h)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = h;\r\n\t\tthis.value = vals;\r\n\t}\r\n\tpublic GeneralMatrixInt(int width)\r\n\t{\r\n\t\tthis.width = width;\r\n\t}\r\n\tpublic GeneralMatrixInt(int width,int height)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = new int[width*height];\r\n\t}\r\n\tpublic GeneralMatrixInt(int width,int height,int[] vals)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tthis.value = vals;\r\n\t}\r\n\tpublic GeneralMatrixInt(int width,int height,int val)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tthis.value = new int[width*height];\r\n\t\tfor(int i=0;i<value.length;i++)\r\n\t\t\tvalue[i] = val;\r\n\t}\r\n\tpublic GeneralMatrixInt(GeneralMatrixInt o)\r\n\t{\r\n\t\tthis.width = o.width;\r\n\t\tthis.height = o.height;\r\n\t\tvalue = new int[width*height];\r\n\t\tset(o);\r\n\t}\r\n\r\n\t public boolean isequal(GeneralMatrixInt m)\r\n\t {\r\n\t\t if(width!=m.width)\r\n\t\t\t return false;\r\n\t\t if(height!=m.height)\r\n\t\t\t return false;\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t if(value[i]!=m.value[i])\r\n\t\t\t\t return false;\r\n\t\t }\t\t \r\n\t\t return true;\r\n\t }\r\n\r\n\t public boolean isequal(int[] m)\r\n\t {\r\n\t\t if(width!=1)\r\n\t\t\t return false;\r\n\t\t if(height!=m.length)\r\n\t\t\t return false;\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t if(value[i]!=m[i])\r\n\t\t\t\t return false;\r\n\t\t }\t\t \r\n\t\t return true;\r\n\t }\r\n//\tpublic boolean isequal(GeneralMatrixInt o)\r\n//\t{\r\n//\t\tboolean is = true;\r\n//\t\tis = is && (width==o.width);\r\n//\t\tis = is && (height==o.height);\r\n//\t\tif(is)\r\n//\t\t{\r\n//\t\t\tfor(int i=0;i<width*height;i++)\r\n//\t\t\t{\r\n//\t\t\t\tis = is && (value[i]==o.value[i]);\r\n//\t\t\t}\r\n//\t\t}\r\n//\t\tif(!is)\r\n//\t\t\tSystem.out.println(\"diff!\");\r\n//\t\treturn is;\r\n//\t}\r\n\t\r\n\t\tpublic void enumerate()\r\n\t\t{\r\n\t\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tpublic void enumerate(int from)\r\n\t\t{\r\n\t\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = i+from;\r\n\t\t\t}\r\n\t\t}\r\n\t\tpublic void denumerate(int from)\r\n\t\t{\t\t\t\r\n\t\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t\t{\r\n\t\t\t\tint v = (width*height-1)-i;\r\n\t\t\t\tvalue[i] = i+from;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\tpublic void clear(int v)\r\n\t{\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] = v;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic final int get(int i,int j)\r\n\t{\r\n\t\treturn value[j*width+i];\r\n\t}\r\n\tpublic void set(int i,int j,int v)\r\n\t{\r\n\t\tvalue[j*width+i] = v;\r\n\t}\r\n\tpublic void set(final GeneralMatrixInt rb)\r\n\t{\r\n\t\tsetDimensionsNoCopy(rb.width, rb.height);\r\n\t\tint s = width*height;\r\n\t\tif(s>0)\r\n\t\t\tSystem.arraycopy(rb.value,0,value,0,s);\r\n\t}\r\n\tpublic void setInto(final GeneralMatrixInt rb)\r\n\t{\r\n\t\tif(\r\n\t\t\t\t(rb.width==0)||(rb.height==0)\r\n\t\t )\r\n\t\t{\r\n\t\t}\r\n\t\telse\r\n\t\tif(\r\n\t\t\t\t(rb.width==width)&&\r\n\t\t\t\t(rb.height==height)\r\n\t\t )\r\n\t\t{\r\n\t\t\tSystem.arraycopy(rb.value,0,value,0,width*height);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfinal int minHeight = Math.min(rb.height, height);\r\n\t\t\tfinal int minWidth = Math.min(rb.width, width);\r\n\t\t\tfor(int y=0;y<minHeight;y++)\r\n\t\t\t{\r\n\t\t\t\tSystem.arraycopy(rb.value,y*rb.width,value,y*width,minWidth);\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic void set(final int[] vals)\r\n\t{\r\n\t\tSystem.arraycopy(vals, 0, value, 0, width*height);\r\n\t}\r\n\t public boolean equals(GeneralMatrixInt m)\r\n\t {\r\n\t\t if(width!=m.width)\r\n\t\t\t return false;\r\n\t\t if(height!=m.height)\r\n\t\t\t return false;\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t if(value[i]!=m.value[i])\r\n\t\t\t\t return false;\r\n\t\t }\t\t \r\n\t\t return true;\r\n\t }\r\n\t \r\n\t public boolean contains(int v)\r\n\t {\r\n\t\t for(int i=(width*height-1);i>=0;i--)\r\n\t\t {\r\n\t\t\t if(value[i]==v)\r\n\t\t\t\t return true;\r\n\t\t }\r\n\t\t return false;\r\n\t }\r\n\t \r\n\t public int find(int[] v)\r\n\t {\r\n\t\t int ind = 0;\r\n\t\t for(int j=0;j<(height);j++)\r\n\t\t {\r\n\t\t\t boolean found = true;\r\n\t\t\t for(int i=0;i<(width);i++)\r\n\t\t\t {\r\n\t\t\t\t if(value[ind+i]!=v[i])\r\n\t\t\t\t {\r\n\t\t\t\t\t found = false;\r\n\t\t\t\t\t break;\r\n\t\t\t\t }\r\n\t\t\t }\r\n\t\t\t if(found)\r\n\t\t\t\t return j;\r\n\t\t\t ind+=width;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int find(int v)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i++)\r\n\t\t {\r\n\t\t\t if(value[i]==v)\r\n\t\t\t\t return i;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int find(int v0,int v1)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=2)\r\n\t\t {\r\n\t\t\t if((value[i]==v0)&&(value[i+1]==v1))\r\n\t\t\t\t return i/2;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\r\n\t public int find_thresh(int v0,int v1,int t)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=2)\r\n\t\t {\r\n\t\t\t if((Math.abs(value[i]-v0)<=t)&&(Math.abs(value[i+1]-v1)<=t))\r\n\t\t\t\t return i/2;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\r\n\t public int find(int v0,int v1,int v2,int v3)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=4)\r\n\t\t {\r\n\t\t\t if((value[i]==v0)&&(value[i+1]==v1)&&(value[i+2]==v2)&&(value[i+3]==v3))\r\n\t\t\t\t return i/4;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t \r\n\t public int findincolumn(int c,int v)\r\n\t {\r\n\t\t for(int i=0;i<(height);i++)\r\n\t\t {\r\n\t\t\t if(value[width*i+c]==v)\r\n\t\t\t\t return i;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int findinrow(int v,int row)\r\n\t {\r\n\t\t for(int i=width*row;i<(width*(row+1));i++)\r\n\t\t {\r\n\t\t\t if(value[i]==v)\r\n\t\t\t\t return i;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t \r\n\t\t//Insertion and deletion\r\n\t public int appendRow()\r\n\t {\r\n\t \tint newSize = width*(height+1);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[newSize];\r\n\t\t\t\theight++;\r\n\t\t\t\treturn height-1;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\theight++;\r\n\t\t\treturn height-1;\r\n\t }\r\n\r\n\t public int appendRows(int size)\r\n\t {\r\n\t \tint newSize = width*(height+size);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[newSize];\r\n\t\t\t\theight+=size;\r\n\t\t\t\treturn height-size;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n\t }\r\n\t \r\n\t public int appendRows(int size,int defaultValue)\r\n\t {\r\n\t \tint newSize = width*(height+size);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[newSize];\r\n\t\t\t\theight+=size;\r\n\t\t\t\tclear(defaultValue);\r\n\t\t\t\treturn height-size;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\tfor(int i=width*height;i<(width*(height+size));i++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = defaultValue;\r\n\t\t\t}\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n\t }\r\n\t \r\n\t public void removeRow(int index)\r\n\t {\r\n\t \tif(index>=height)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"Row being removed larger than matrix\");\r\n\t \t}\r\n\t \tfor(int i=index*width;i<((height-1))*width;i++)\r\n\t \t{\r\n\t \t\tvalue[i] = value[(i+width)];\r\n\t \t}\r\n\t \theight--;\r\n\t }\r\n\t public void removeRows(int index,int size)\r\n\t {\r\n\t \tfor(int i=index*width;i<((height-size))*width;i++)\r\n\t \t{\r\n\t \t\tvalue[i] = value[i+width*size];\r\n\t \t}\r\n\t \theight-=size;\r\n\t }\r\n\r\n\t public void insertRowAfter(int index)\r\n\t {\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(value, (index+1)*width, value, (index+2)*width, (height-1-(index+1))*width);\r\n\t }\r\n\r\n\t public void insertRowBefore(int index)\r\n\t {\r\n\t \tint srcind = (index)*width;\r\n\t \tint destind = (index+1)*width;\r\n\t \tint length = (height-(index))*width;\r\n\t \ttry{\r\n\t\t \tappendRow();\r\n\t\t \tSystem.arraycopy(value, srcind, value, destind, length);\t \t\t\r\n\t \t}\r\n\t \tcatch(Exception e)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"insertRowBefore error\");\r\n\t \t}\r\n\t }\r\n\t \r\n\t public void insertRowsBefore(int index,GeneralMatrixInt rows)\r\n\t {\r\n\t \tint srcind = (index)*width;\r\n\t \tint destind = (index+rows.height)*width;\r\n\t \tint length = (height-(index))*width;\r\n\t \ttry{\r\n\t\t \tappendRows(rows.height);\r\n\t\t \tSystem.arraycopy(value, srcind, value, destind, length);\t \t\t\r\n\t\t \tSystem.arraycopy(rows.value, 0, value, srcind, rows.width*rows.height);\t \t\t\r\n\t \t}\r\n\t \tcatch(Exception e)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"insertRowBefore error\");\r\n\t \t}\r\n\t }\r\n\t \r\n\t public void ensureCapacityNoCopy(int mincap)\r\n\t {\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[mincap];\r\n\t \t}\r\n\t \telse\r\n\t \tif(mincap>value.length)\r\n\t \t{\r\n\t\t int newcap = (value.length * 3)/2 + 1;\r\n\t\t //int[] olddata = value;\r\n\t\t value = new int[newcap < mincap ? mincap : newcap];\r\n\t \t}\r\n\t }\r\n\r\n\t public void ensureCapacity(int mincap)\r\n\t {\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[mincap];\r\n\t \t}\r\n\t \telse\r\n\t \tif(mincap>value.length)\r\n\t \t{\r\n\t\t int newcap = (value.length * 3)/2 + 1;\r\n\t\t \tif(newcap>100000000)\r\n\t\t \t{\r\n\t\t \t\tnewcap = mincap+1000000;\r\n\t\t \t}\r\n\t\t int[] olddata = value;\r\n\t\t value = new int[newcap < mincap ? mincap : newcap];\r\n\t\t System.arraycopy(olddata,0,value,0,olddata.length);\r\n\t \t}\r\n\t }\r\n\t \r\n\t public void setDimensions(int w,int h)\r\n\t {\r\n\t \tensureCapacity(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public void setDimensionsAndClearNew(int w,int h,int init)\r\n\t {\r\n\t \tint oldl = width*height;\r\n\t \tensureCapacity(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t \tint newl = w*h;\r\n\t \tfor(int i=oldl;i<newl;i++)\r\n\t \t{\r\n\t \t\tvalue[i] = init;\r\n\t \t}\r\n\t }\r\n\t public void setDimensionsNoCopy(int w,int h)\r\n\t {\r\n\t \tensureCapacityNoCopy(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public void setDimensionsExact(int w,int h)\r\n\t {\r\n\t \tint[] oldv = value;\r\n\t \tvalue = new int[w*h];\r\n\t \tint min = value.length;\r\n\t \tif(oldv.length<min)\r\n\t \t\tmin = oldv.length;\r\n\t \tSystem.arraycopy(oldv, 0, value, 0, min);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public void setDimensionsExactNoCopy(int w,int h)\r\n\t {\r\n\t \tvalue = new int[w*h];\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public int pop_back()\r\n\t {\r\n\t \theight--;\r\n\t \treturn value[height];\r\n\t }\r\n\t public int push_back(int val)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind] = val;\r\n\t \treturn ind;\r\n\t }\r\n\t \r\n\t public void set_row(int row,int val1,int val2)\r\n\t {\r\n\t \tint ind = row*width;\r\n\t \tvalue[ind+0] = val1;\r\n\t \tvalue[ind+1] = val2; \t\r\n\t } \r\n\t public int push_back_row(int val1,int val2)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*2+0] = val1;\r\n\t \tvalue[ind*2+1] = val2;\r\n\t \treturn ind;\r\n\t }\r\n\t public int push_back_row(int val1,int val2,int val3)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*3+0] = val1;\r\n\t \tvalue[ind*3+1] = val2;\r\n\t \tvalue[ind*3+2] = val3;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int val1,int val2,int val3,int val4)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*4+0] = val1;\r\n\t \tvalue[ind*4+1] = val2;\r\n\t \tvalue[ind*4+2] = val3;\r\n\t \tvalue[ind*4+3] = val4;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int val1,int val2,int val3,int val4,int val5)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*5+0] = val1;\r\n\t \tvalue[ind*5+1] = val2;\r\n\t \tvalue[ind*5+2] = val3;\r\n\t \tvalue[ind*5+3] = val4;\r\n\t \tvalue[ind*5+4] = val5;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int val1,int val2,int val3,int val4,int val5,int val6)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*6+0] = val1;\r\n\t \tvalue[ind*6+1] = val2;\r\n\t \tvalue[ind*6+2] = val3;\r\n\t \tvalue[ind*6+3] = val4;\r\n\t \tvalue[ind*6+4] = val5;\r\n\t \tvalue[ind*6+5] = val6;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int val1,int val2,int val3,int val4,int val5,int val6,int val7,int val8)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*8+0] = val1;\r\n\t \tvalue[ind*8+1] = val2;\r\n\t \tvalue[ind*8+2] = val3;\r\n\t \tvalue[ind*8+3] = val4;\r\n\t \tvalue[ind*8+4] = val5;\r\n\t \tvalue[ind*8+5] = val6;\r\n\t \tvalue[ind*8+6] = val7;\r\n\t \tvalue[ind*8+7] = val8;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int[] row)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tSystem.arraycopy(row, 0, value, width*(height-1), width);\r\n\t \treturn ind;\r\n\t }\r\n\t public void push_back_row(GeneralMatrixInt row)\r\n\t {\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(row.value, 0, value, width*(height-1), width);\r\n\t }\r\n\t public void push_back_row_from_block(GeneralMatrixInt row,int yFromFull)\r\n\t {\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(row.value, yFromFull*width, value, width*(height-1), width);\r\n\t }\r\n\t \r\n\t public void push_back_rows(GeneralMatrixInt rows)\r\n\t {\r\n\t \tif(rows.height==0)\r\n\t \t\treturn;\r\n\t \tappendRows(rows.height);\r\n\t \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n\t }\r\n\t\r\n\t\tpublic void appendColumn(int defaultvalue)\r\n\t\t{\r\n\t\t\tint newSize = (width+1)*height;\r\n\t \tif(value==null)\r\n\t \t{\r\n\t\t\t\twidth++;\r\n\t\t\t\treturn;\r\n\t \t}\r\n\t \t//if(newSize>value.length)\r\n\t \t{\r\n\t \t\tint[] oldv = value;\r\n\t \t\tvalue = new int[newSize];\r\n\t \t\twidth++;\r\n\t \t\tclear(defaultvalue);\r\n\t \t\tfor(int i=0;i<height;i++)\r\n\t \t\t{\r\n\t \t\t\tSystem.arraycopy(oldv, i*(width-1), value, i*(width), (width-1));\r\n\t \t\t}\r\n\t \t}\r\n\t\t}\r\n\t\r\n\t public void removeBlock(int column,int size)\r\n\t {\r\n\t \tif(width!=1)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"Block removal only possible on 1d arrays\");\r\n\t \t}\r\n\t \tfor(int i=column;i<(height-size);i++)\r\n\t \t{\r\n\t \t\tvalue[i] = value[i+size];\r\n\t \t}\r\n\t \theight-=size;\r\n\t \tif(height<0)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"Removal from nothing!\");\r\n\t \t}\r\n\t }\r\n\t \r\n\t public void insertBlockAfter(int index,int size)\r\n\t {\r\n\t \tinsertBlockBefore(index+1,size);\r\n\t }\t \r\n\t public void insertBlockBefore(int index,int size)\r\n\t {\r\n\t \tif(width!=1)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"Block additions only possible on 1d arrays\");\r\n\t \t}\r\n\r\n\t \tint oldwidth = height;\r\n\t \tint newSize = height+size;\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[newSize];\r\n\t \t}\r\n\t \telse\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t \theight = newSize;\r\n\t \tSystem.arraycopy(value, index, value, index+size, (oldwidth-index));\r\n\t }\r\n\r\n\t //For rectangles\r\n\t public void scaleAroundCenter(float f)\r\n\t {\r\n\t\t\tint y = (int)(value[1]-((float)value[3]*f-value[3])/2);\r\n\t\t\tif (y < 0) y = 0;\r\n\t\t\tint x = (int)(value[0]-((float)value[2]*f-value[2])/2);\r\n\t\t\tif (x < 0) x = 0;\r\n\t\t\tint h = (int)(value[3]*f);\r\n\t\t\tint w = (int)(value[2]*f);\r\n\t\t\tvalue[0] = x;\r\n\t\t\tvalue[1] = y;\r\n\t\t\tvalue[2] = w;\r\n\t\t\tvalue[3] = h;\r\n\t }\r\n}\r",
"public class GeneralMatrixObject implements Serializable \r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic int width;\r\n\tpublic int height;\r\n\tpublic Object[] value;\r\n\r\n public GeneralMatrixObject()\r\n {\r\n \twidth = 0;\r\n \theight = 0;\r\n \tvalue = new Object[8];\r\n }\r\n public GeneralMatrixObject(Object a)\r\n {\r\n \twidth = 1;\r\n \theight = 1;\r\n \tvalue = new Object[1];\r\n \tvalue[0] = a;\r\n }\r\n public GeneralMatrixObject(GeneralMatrixObject o)\r\n {\r\n \tthis.width = o.width;\r\n \tthis.height = o.height;\r\n \tvalue = new Object[width*height];\r\n \tif(value.length>0)\r\n \t\tSystem.arraycopy(o.value, 0, value, 0, value.length);\r\n }\r\n public GeneralMatrixObject(Object[] o)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = o.length;\r\n \tvalue = new Object[width*height];\r\n \tif(value.length>0)\r\n \t\tSystem.arraycopy(o, 0, value, 0, value.length);\r\n }\r\n public GeneralMatrixObject(int width)\r\n {\r\n \tthis.width = width;\r\n \theight = 0;\r\n \tvalue = new Object[8];\r\n }\r\n public GeneralMatrixObject(int width,int height)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = new Object[width*height];\r\n }\r\n public GeneralMatrixObject(int width,int height,int mincap)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = new Object[mincap];\r\n }\r\n \r\n public Object clone()\r\n {\r\n \tGeneralMatrixObject o = new GeneralMatrixObject(width,height);\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tObject v = value[i];\r\n \t\tif(v instanceof GeneralMatrixObject)\r\n \t\t{\r\n \t\t\tv = ((GeneralMatrixObject)v).clone();\r\n \t\t}\r\n \t\telse\r\n \t\tif(v instanceof GeneralMatrixString)\r\n \t\t{\r\n \t\t\tv = ((GeneralMatrixString)v).clone(); \t\t\t\r\n \t\t}\r\n \t\to.value[i] = v;\r\n \t}\r\n \treturn o;\r\n }\r\n\r\n \r\n public int push_back(Object o)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind] = o;\r\n \treturn ind;\r\n }\r\n \r\n public int appendRow()\r\n {\r\n \tint newSize = width*(height+1);\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight++;\r\n\t\treturn height-1;\r\n }\r\n \r\n public int appendRows(int size)\r\n {\r\n \tint newSize = width*(height+size);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new Object[newSize];\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight+=size;\r\n\t\treturn height-size;\r\n }\r\n\r\n public void removeRow(int index)\r\n {\r\n \tfor(int i=index*width;i<((height-1))*width;i++)\r\n \t{\r\n \t\tvalue[i] = value[i+width];\r\n \t}\r\n \theight--;\r\n }\r\n\r\n public void ensureCapacity(int mincap)\r\n {\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new Object[mincap];\r\n \t}\r\n \telse\r\n \tif(mincap>value.length)\r\n \t{\r\n\t int newcap = (value.length * 3)/2 + 1;\r\n\t Object[] olddata = value;\r\n\t value = new Object[newcap < mincap ? mincap : newcap];\r\n\t System.arraycopy(olddata,0,value,0,olddata.length);\r\n \t}\r\n }\r\n// public void ensureCapacity(int mincap)\r\n// {\r\n// int newcap = (value.length * 3)/2 + 1;\r\n// Object[] olddata = value;\r\n// value = new Object[newcap < mincap ? mincap : newcap];\r\n// System.arraycopy(olddata,0,value,0,olddata.length); \t\t\r\n// }\r\n\r\n\r\n public void clear()\r\n\t{\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] = null;\r\n\t\t}\r\n\t}\r\n\r\n\t public int find(Object v)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i++)\r\n\t\t {\r\n\t\t\t if(value[i]==v)\r\n\t\t\t\t return i;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n \r\n\t public void set(GeneralMatrixObject o)\r\n\t {\r\n\t\t setDimensions(o.width, o.height);\r\n\t\t int len = o.width*o.height;\r\n \t if(len>0)\r\n \t\t System.arraycopy(o.value, 0, value, 0, len);\r\n\t }\r\n\t\tpublic void setFromSubset(GeneralMatrixObject full,int ys)\r\n\t\t{\r\n\t\t\tint i=0;\r\n\t\t\tint fi = ys*width;\r\n\t\t\tfor(int y=0;y<height;y++)\r\n\t\t\t{\r\n\t\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i] = full.value[fi];\r\n\t\t\t\t\ti++;\r\n\t\t\t\t\tfi++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n public void setDimensions(int w,int h)\r\n {\r\n \tensureCapacity(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n }\r\n\r\n public void setDimensionsAndClearNew(int w,int h)\r\n {\r\n \tint oldl = width*height;\r\n \tensureCapacity(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n \tint newl = w*h;\r\n \tfor(int i=oldl;i<newl;i++)\r\n \t{\r\n \t\tvalue[i] = null;\r\n \t}\r\n }\r\n \r\n public int push_back_row(Object val1,Object val2)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*2+0] = val1;\r\n \tvalue[ind*2+1] = val2;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*3+0] = val1;\r\n \tvalue[ind*3+1] = val2;\r\n \tvalue[ind*3+2] = val3;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*4+0] = val1;\r\n \tvalue[ind*4+1] = val2;\r\n \tvalue[ind*4+2] = val3;\r\n \tvalue[ind*4+3] = val4;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4,Object val5)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*5+0] = val1;\r\n \tvalue[ind*5+1] = val2;\r\n \tvalue[ind*5+2] = val3;\r\n \tvalue[ind*5+3] = val4;\r\n \tvalue[ind*5+4] = val5;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4,Object val5,Object val6)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*6+0] = val1;\r\n \tvalue[ind*6+1] = val2;\r\n \tvalue[ind*6+2] = val3;\r\n \tvalue[ind*6+3] = val4;\r\n \tvalue[ind*6+4] = val5;\r\n \tvalue[ind*6+5] = val6;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4,Object val5,Object val6,Object val7,Object val8,Object val9)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*9+0] = val1;\r\n \tvalue[ind*9+1] = val2;\r\n \tvalue[ind*9+2] = val3;\r\n \tvalue[ind*9+3] = val4;\r\n \tvalue[ind*9+4] = val5;\r\n \tvalue[ind*9+5] = val6;\r\n \tvalue[ind*9+6] = val7;\r\n \tvalue[ind*9+7] = val8;\r\n \tvalue[ind*9+8] = val9;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4,Object val5,Object val6,Object val7,Object val8,Object val9,Object val10)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*10+0] = val1;\r\n \tvalue[ind*10+1] = val2;\r\n \tvalue[ind*10+2] = val3;\r\n \tvalue[ind*10+3] = val4;\r\n \tvalue[ind*10+4] = val5;\r\n \tvalue[ind*10+5] = val6;\r\n \tvalue[ind*10+6] = val7;\r\n \tvalue[ind*10+7] = val8;\r\n \tvalue[ind*10+8] = val9;\r\n \tvalue[ind*10+9] = val10;\r\n \treturn ind;\r\n }\r\n\r\n public void push_back_rows(GeneralMatrixObject rows)\r\n {\r\n \tif(rows.height==0)\r\n \t\treturn;\r\n \tappendRows(rows.height);\r\n \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n }\r\n\r\n public void push_back_row_from_block(GeneralMatrixObject row,int yFromFull)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(row.value, yFromFull*width, value, width*(height-1), width);\r\n }\r\n\r\n }\r",
"public class GeneralMatrixString implements Serializable \r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic int width = 0;\r\n\tpublic int height = 0;\r\n\tpublic String[] value;\r\n\r\n public GeneralMatrixString()\r\n {\r\n }\r\n public GeneralMatrixString(int width)\r\n {\r\n \tthis.width = width;\r\n \theight = 0;\r\n \tvalue = new String[8];\r\n }\r\n public GeneralMatrixString(int width,int height)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = new String[height*width];\r\n }\r\n public GeneralMatrixString(int width,int height,int mincap)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = new String[mincap];\r\n }\r\n public GeneralMatrixString(String val)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 1;\r\n \tvalue = new String[1];\r\n \tvalue[0] = val;\r\n }\r\n public GeneralMatrixString(String val0,String val1)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 2;\r\n \tvalue = new String[2];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 3;\r\n \tvalue = new String[3];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 4;\r\n \tvalue = new String[4];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 5;\r\n \tvalue = new String[5];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 6;\r\n \tvalue = new String[6];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5,String val6)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 7;\r\n \tvalue = new String[7];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n \tvalue[6] = val6;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5,String val6,String val7)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 8;\r\n \tvalue = new String[8];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n \tvalue[6] = val6;\r\n \tvalue[7] = val7;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 9;\r\n \tvalue = new String[9];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n \tvalue[6] = val6;\r\n \tvalue[7] = val7;\r\n \tvalue[8] = val8;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8,String val9,String val10,String val11,String val12)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 13;\r\n \tvalue = new String[13];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n \tvalue[6] = val6;\r\n \tvalue[7] = val7;\r\n \tvalue[8] = val8;\r\n \tvalue[9] = val9;\r\n \tvalue[10] = val10;\r\n \tvalue[11] = val11;\r\n \tvalue[12] = val12;\r\n }\r\n public GeneralMatrixString(final GeneralMatrixString val)\r\n {\r\n \tthis.width = val.width;\r\n \tthis.height = val.height;\r\n \tif(val.value!=null)\r\n \t\tvalue = val.value.clone();\r\n }\r\n public GeneralMatrixString(int width,int height,String[] val)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = val;\r\n }\r\n public GeneralMatrixString(int width,int height,String val)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tint mincap = width*height;\r\n \tvalue = new String[mincap];\r\n \tfor(int i=0;i<mincap;i++)\r\n \t\tvalue[i] = \"\"+val;\r\n }\r\n public GeneralMatrixString(String[] val)\r\n {\r\n \tthis.width = 1;\r\n \tif(val==null)\r\n \t{\r\n \t\tthis.height = 0;\r\n \t\tvalue = null;\r\n \t\treturn;\r\n \t}\r\n \tthis.height = val.length;\r\n \tvalue = val;\r\n }\r\n\r\n public Object clone()\r\n {\r\n \treturn new GeneralMatrixString(this);\r\n }\r\n \r\n\tpublic boolean isequal(GeneralMatrixString o)\r\n\t{\r\n\t\tif(!(width==o.width))\r\n\t\t\treturn false;\r\n\t\tif(!(height==o.height))\r\n\t\t\treturn false;\r\n\t\tfor(int i=0;i<width*height;i++)\r\n\t\t{\r\n\t\t\tif(!(value[i]).contentEquals(o.value[i]))\r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\r\n//\t\tboolean is = true;\r\n//\t\tis = is && (width==o.width);\r\n//\t\tis = is && (height==o.height);\r\n//\t\tif(is)\r\n//\t\t{\r\n//\t\t\tfor(int i=0;i<width*height;i++)\r\n//\t\t\t{\r\n//\t\t\t\tis = is && (value[i].contentEquals(o.value[i]));\r\n//\t\t\t}\r\n//\t\t}\r\n//\t\tif(!is)\r\n//\t\t\tSystem.out.println(\"diff!\");\r\n//\t\treturn is;\r\n\t}\r\n\t\r\n public void clear(String s)\r\n {\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tvalue[i] = \"\"+s;\r\n \t} \t\r\n }\r\n \r\n public int contains(String v)\r\n {\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tif(value[i].contains(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1; \t\r\n }\r\n public int find(String v)\r\n {\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tif(value[i].equalsIgnoreCase(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1;\r\n }\r\n public boolean includes(GeneralMatrixString subset)\r\n {\r\n \tfor(int j=0;j<(subset.width*subset.height);j++)\r\n \t{\r\n \t\tboolean found = false;\r\n\t \tfor(int i=0;i<(width*height);i++)\r\n\t \t{\r\n\t \t\tif(value[i].equalsIgnoreCase(subset.value[j]))\r\n\t \t\t{\r\n\t \t\t\tfound = true;\r\n\t \t\t\tbreak;\r\n\t \t\t}\r\n\t \t}\r\n\t\t\tif(!found)\r\n\t\t\t\treturn false;\r\n \t}\r\n \treturn true;\r\n }\r\n public int findContaining(String v)\r\n {\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tif(value[i].contains(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1;\r\n }\r\n \r\n public void set(GeneralMatrixString o)\r\n {\r\n \twidth = o.width;\r\n\t\theight = o.height;\r\n\t\tensureCapacity(height*width);\t\r\n\t\tSystem.arraycopy(o.value, 0, value, 0, height*width);\r\n }\r\n public void set(String[] o,int h)\r\n {\r\n\t\tensureCapacity(h);\t\r\n \twidth = 1;\r\n\t\theight = h;\r\n\t\tSystem.arraycopy(o, 0, value, 0, height*width);\r\n }\r\n public int push_back(String o)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind] = o;\r\n \treturn ind;\r\n }\r\n \r\n public int appendRow()\r\n {\r\n \t\r\n \tint newSize = width*(height+1);\r\n \tif((value == null)||(newSize>value.length))\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight++;\r\n\t\treturn height-1;\r\n }\r\n \r\n public int appendRows(int size)\r\n {\r\n \tint newSize = width*(height+size);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new String[newSize];\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight+=size;\r\n\t\treturn height-size;\r\n }\r\n\r\n public void removeRow(int index)\r\n {\r\n \tfor(int i=index*width;i<((height-1))*width;i++)\r\n \t{\r\n \t\tvalue[i] = value[i+width];\r\n \t}\r\n \theight--;\r\n }\r\n\r\n public void ensureCapacity(int mincap)\r\n {\r\n \tif(value == null)\r\n \t{\r\n \t\tvalue = new String[mincap];\r\n \t\treturn;\r\n \t}\r\n \tif(mincap<=value.length)\r\n \t\treturn;\r\n int newcap = (value.length * 3)/2 + 1;\r\n String[] olddata = value;\r\n value = new String[newcap < mincap ? mincap : newcap];\r\n System.arraycopy(olddata,0,value,0,olddata.length); \t\t\r\n }\r\n \r\n\r\n\tpublic static int find(String[] value,String v)\r\n {\r\n\t\tint height = value.length;\r\n \tfor(int i=0;i<(height);i++)\r\n \t{\r\n \t\tif(value[i].equalsIgnoreCase(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1;\r\n }\r\n\tpublic static int find(String[] value,int height,String v)\r\n {\r\n \tfor(int i=0;i<(height);i++)\r\n \t{\r\n \t\tif(value[i].equalsIgnoreCase(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1;\r\n }\r\n\r\n public void push_back_row(String o1,String o2)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*2+0] = o1;\r\n \tvalue[ind*2+1] = o2;\r\n }\r\n \r\n public void push_back_row(String o1,String o2,String o3)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*3+0] = o1;\r\n \tvalue[ind*3+1] = o2;\r\n \tvalue[ind*3+2] = o3;\r\n }\r\n \r\n public void push_back_row(String o1,String o2,String o3,String o4)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*4+0] = o1;\r\n \tvalue[ind*4+1] = o2;\r\n \tvalue[ind*4+2] = o3;\r\n \tvalue[ind*4+3] = o4;\r\n }\r\n \r\n public void push_back_row(String o1,String o2,String o3,String o4,String o5)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*5+0] = o1;\r\n \tvalue[ind*5+1] = o2;\r\n \tvalue[ind*5+2] = o3;\r\n \tvalue[ind*5+3] = o4;\r\n \tvalue[ind*5+4] = o5;\r\n }\r\n \r\n public void push_back_rows(GeneralMatrixString rows)\r\n {\r\n \tappendRows(rows.height);\r\n \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n }\r\n\r\n public void setDimensions(int w,int h)\r\n {\r\n \tensureCapacity(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n }\r\n\r\n public void insertRowAfter(int index)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(value, (index+1)*width, value, (index+2)*width, (height-1-(index+1))*width);\r\n }\r\n \r\n public void insertRowBefore(int index)\r\n {\r\n \tint srcind = (index);\r\n \tint destind = (index+1);\r\n \tint length = (height-1-(index));\r\n \ttry{\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(value, srcind, value, destind, length);\t \t\t\r\n \t}\r\n \tcatch(Exception e)\r\n \t{\r\n \t\tSystem.out.println(\"insertRowBefore error\");\r\n \t}\r\n }\r\n}\r",
"public class Quaternion implements Serializable \r\n{\r\n\tpublic static void MatrixtoQuaternion(float[] m,float[] a)\r\n\t{\r\n\t\t// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\r\n\t\t// article \"Quaternion Calculus and Fast Animation\".\r\n\r\n\t\tfinal float trace = m[3*0+0] + m[3*1+1] + m[3*2+2];\r\n\r\n\t\tif (trace>0)\r\n\t\t{\r\n\t\t\t// |w| > 1/2, may as well choose w > 1/2\r\n\r\n\t\t\tfloat root = (float)Math.sqrt(trace + 1.0f); // 2w\r\n\t\t\ta[3] = 0.5f * root;\r\n\t\t\troot = 0.5f / root; // 1/(4w)\r\n\t\t\ta[0] = (m[3*2+1]-m[3*1+2]) * root;\r\n\t\t\ta[1] = (m[3*0+2]-m[3*2+0]) * root;\r\n\t\t\ta[2] = (m[3*1+0]-m[3*0+1]) * root;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// |w| <= 1/2\r\n\r\n\t\t\tfinal int[] next = { 1, 2, 0 };\r\n\t\t\t\r\n\t\t\tint i = 1;\r\n\t\t\tif (m[3*1+1]>m[3*0+0]) i = 2;\r\n\t\t\tif (m[3*2+2]>m[3*i+i]) i = 3;\r\n\t\t\tint j = next[i];\r\n\t\t\tint k = next[j];\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tfloat root = (float)Math.sqrt(m[3*i+i]-m[3*j+j]-m[3*k+k] + 1.0f);\r\n\t\t\t//float *quaternion[3] = { &x, &y, &z };\r\n\t\t\ta[i] = 0.5f * root;\r\n\t\t\troot = 0.5f / root;\r\n\t\t\ta[3] = (m[3*k+j]-m[3*j+k])*root;\r\n\t\t\ta[j] = (m[3*j+i]+m[3*i+j])*root;\r\n\t\t\ta[k] = (m[3*k+i]+m[3*i+k])*root;\r\n\t\t}\r\n\t}\r\n\tpublic static void MatrixtoQuaternion(float[] m,int mo,float[] a)\r\n\t{\r\n\t\t// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\r\n\t\t// article \"Quaternion Calculus and Fast Animation\".\r\n\r\n\t\tfinal float trace = m[mo+3*0+0] + m[mo+3*1+1] + m[mo+3*2+2];\r\n\r\n\t\tif (trace>0)\r\n\t\t{\r\n\t\t\t// |w| > 1/2, may as well choose w > 1/2\r\n\r\n\t\t\tfloat root = (float)Math.sqrt(trace + 1.0f); // 2w\r\n\t\t\ta[3] = 0.5f * root;\r\n\t\t\troot = 0.5f / root; // 1/(4w)\r\n\t\t\ta[0] = (m[mo+3*2+1]-m[mo+3*1+2]) * root;\r\n\t\t\ta[1] = (m[mo+3*0+2]-m[mo+3*2+0]) * root;\r\n\t\t\ta[2] = (m[mo+3*1+0]-m[mo+3*0+1]) * root;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// |w| <= 1/2\r\n\r\n\t\t\tfinal int[] next = { 1, 2, 0 };\r\n\t\t\t\r\n\t\t\tint i = 0;\r\n\t\t\tif (m[mo+3*1+1]>m[mo+3*0+0]) i = 1;\r\n\t\t\tif (m[mo+3*2+2]>m[mo+3*i+i]) i = 2;\r\n\t\t\tint j = next[i];\r\n\t\t\tint k = next[j];\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tfloat root = (float)Math.sqrt(m[mo+3*i+i]-m[mo+3*j+j]-m[mo+3*k+k] + 1.0f);\r\n\t\t\t//float *quaternion[3] = { &x, &y, &z };\r\n\t\t\ta[i] = 0.5f * root;\r\n\t\t\troot = 0.5f / root;\r\n\t\t\ta[3] = (m[mo+3*k+j]-m[mo+3*j+k])*root;\r\n\t\t\ta[j] = (m[mo+3*j+i]+m[mo+3*i+j])*root;\r\n\t\t\ta[k] = (m[mo+3*k+i]+m[mo+3*i+k])*root;\r\n\t\t}\r\n\t}\r\n\tpublic static void QuaterniontoMatrix(float[] a,float[] m)\r\n\t{\r\n\t\tfloat fTx = 2.0f*a[0];\r\n\t\tfloat fTy = 2.0f*a[1];\r\n\t\tfloat fTz = 2.0f*a[2];\r\n\t\tfloat fTwx = fTx*a[3];\r\n\t\tfloat fTwy = fTy*a[3];\r\n\t\tfloat fTwz = fTz*a[3];\r\n\t\tfloat fTxx = fTx*a[0];\r\n\t\tfloat fTxy = fTy*a[0];\r\n\t\tfloat fTxz = fTz*a[0];\r\n\t\tfloat fTyy = fTy*a[1];\r\n\t\tfloat fTyz = fTz*a[1];\r\n\t\tfloat fTzz = fTz*a[2];\r\n\r\n\t\tm[0] = 1.0f-(fTyy+fTzz);\tm[1] = fTxy-fTwz;\t\t\tm[2] = fTxz+fTwy;\r\n\t\tm[0+3] = fTxy+fTwz;\t\t\tm[1+3] = 1.0f-(fTxx+fTzz);\tm[2+3] = fTyz-fTwx;\r\n\t\tm[0+6] = fTxz-fTwy;\t\t\tm[1+6] = fTyz+fTwx;\t\t\tm[2+6] = 1.0f-(fTxx+fTyy);\r\n\t}\r\n\tpublic static void QuaterniontoMatrix(float[] a,float[] m,int mo)\r\n\t{\r\n\t\tfloat fTx = 2.0f*a[0];\r\n\t\tfloat fTy = 2.0f*a[1];\r\n\t\tfloat fTz = 2.0f*a[2];\r\n\t\tfloat fTwx = fTx*a[3];\r\n\t\tfloat fTwy = fTy*a[3];\r\n\t\tfloat fTwz = fTz*a[3];\r\n\t\tfloat fTxx = fTx*a[0];\r\n\t\tfloat fTxy = fTy*a[0];\r\n\t\tfloat fTxz = fTz*a[0];\r\n\t\tfloat fTyy = fTy*a[1];\r\n\t\tfloat fTyz = fTz*a[1];\r\n\t\tfloat fTzz = fTz*a[2];\r\n\r\n\t\tm[mo+0] = 1.0f-(fTyy+fTzz);\t\tm[mo+1] = fTxy-fTwz;\t\t\tm[mo+2] = fTxz+fTwy;\r\n\t\tm[mo+0+3] = fTxy+fTwz;\t\t\tm[mo+1+3] = 1.0f-(fTxx+fTzz);\tm[mo+2+3] = fTyz-fTwx;\r\n\t\tm[mo+0+6] = fTxz-fTwy;\t\t\tm[mo+1+6] = fTyz+fTwx;\t\t\tm[mo+2+6] = 1.0f-(fTxx+fTyy);\r\n\t}\r\n\tpublic static void slerp(float[] a, float[] b, float t, float[] c) \r\n\t{\r\n\t\tassert(t>=0);\r\n\t\tassert(t<=1);\r\n\t\t\t\t\r\n\t\tfloat flip = 1;\r\n\r\n\t\tfloat cosine = a[3]*b[3] + a[0]*b[0] + a[1]*b[1] + a[2]*b[2];\r\n\t\t\r\n\t\tif (cosine<0) \r\n\t\t{ \r\n\t\t\tcosine = -cosine; \r\n\t\t\tflip = -1; \r\n\t\t} \r\n\t\t\r\n\t\tif ((1-cosine)<GeneralMatrixFloat.EPSILON)\r\n\t\t{\r\n\t\t\tfloat it = (1-t);\r\n\t\t\tfloat tf = (t*flip);\r\n\t\t\tc[0] = a[0]*it+b[0]*tf;\r\n\t\t\tc[1] = a[1]*it+b[1]*tf;\r\n\t\t\tc[2] = a[2]*it+b[2]*tf;\r\n\t\t\tc[3] = a[3]*it+b[3]*tf;\r\n\t\t\treturn; \r\n\t\t}\r\n\t\t\r\n\t\tfloat theta = (float)Math.acos(cosine); \r\n\t\tfloat sine = (float)Math.sin(theta); \r\n\t\tfloat beta = (float)Math.sin((1-t)*theta) / sine; \r\n\t\tfloat alpha = (float)Math.sin(t*theta) / sine * flip; \r\n\t\t\r\n\t\tc[0] = a[0]*beta+b[0]*alpha;\r\n\t\tc[1] = a[1]*beta+b[1]*alpha;\r\n\t\tc[2] = a[2]*beta+b[2]*alpha;\r\n\t\tc[3] = a[3]*beta+b[3]*alpha;\r\n\t} \r\n\r\n}\r",
"public class HumanBones \n{\n\tpublic static int[] bones=\n\t{\n\t\t21,18,\n\t\t//18,21,\n\t\t18,19,\n\t\t19,20,\n\t\t20,2,\n\t\t2,1,\n\t\t1,0,\n\t\t21,100,\n\t\t100,101,\n\t\t101,102,\n\t\t102,103,\n\t\t103,104,\n\t\t21,76,\n\t\t76,77,\n\t\t77,78,\n\t\t78,79,\n\t\t79,80,\n\t\t0,4,\n\t\t0,11,\n\t\t0,15,\n\t\t2,22,\n\t\t2,49,\n\t\t4,3,\n\t\t11,12,\n\t\t15,16,\n\t\t11,9,\n\t\t11,10,\n\t\t15,13,\n\t\t15,14,\n\t\t49,51,\n\t\t51,52,\n\t\t52,53,\n\t\t53,68,\n\t\t53,55,\n\t\t53,54,\n\t\t53,56,\n\t\t55,60,\n\t\t55,68,\n\t\t54,64,\n\t\t54,72,\n\t\t22,24,\n\t\t24,25,\n\t\t25,26,\n\t\t26,41,\n\t\t26,28,\n\t\t26,27,\n\t\t26,29,\n\t\t28,33,\n\t\t28,41,\n\t\t27,37,\n\t\t27,45,\n\t\t56,57,\n\t\t57,58,\n\t\t58,59,\n\t\t60,61,\n\t\t61,62,\n\t\t62,63,\n\t\t68,69,\n\t\t69,70,\n\t\t70,71,\n\t\t64,65,\n\t\t65,66,\n\t\t66,67,\n\t\t72,73,\n\t\t73,74,\n\t\t74,75,\n\t\t29,30,\n\t\t30,31,\n\t\t31,32,\n\t\t33,34,\n\t\t34,35,\n\t\t35,36,\n\t\t41,42,\n\t\t42,43,\n\t\t43,44,\n\t\t37,38,\n\t\t38,39,\n\t\t39,40,\n\t\t45,46,\n\t\t46,47,\n\t\t47,48,\n\t\t3,5,\n\t\t5,6,\n\t\t6,7,\n\t\t7,8,\n\t};\n\n\tpublic static final float DEG2RAD = ((float)Math.PI)/180.0f;\n\t\n\tpublic static float[] bjlimits=\n\t{\n\t\t//Spine\n//\t\t\"joint-pelvistojoint-spine3\",\n\t\t-180.0f*DEG2RAD,180.0f*DEG2RAD,-180.0f*DEG2RAD,180.0f*DEG2RAD,-180.0f*DEG2RAD,180.0f*DEG2RAD,\n//\t\t-180.0f*DEG2RAD,180.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-180.0f*DEG2RAD,180.0f*DEG2RAD,\n\t\t//\"joint-spine3tojoint-pelvis\",\n\t\t//-180.0f*DEG2RAD,180.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-180.0f*DEG2RAD,180.0f*DEG2RAD,\n//\t\t\"joint-spine3tojoint-spine2\",\n\t\t-40.0f*DEG2RAD,50.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,\n//\t\t\"joint-spine2tojoint-spine1\",\n\t\t-70.0f*DEG2RAD,60.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-50.0f*DEG2RAD,50.0f*DEG2RAD,\n//\t\t\"joint-spine1tojoint-neck\",\n\t\t-20.0f*DEG2RAD,20.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\n\t\t//neck\n//\t\t\"joint-necktojoint-head\",\n\t\t-10.0f*DEG2RAD,20.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-40.0f*DEG2RAD,40.0f*DEG2RAD,\n//\t\t\"joint-headtojoint-head2\",\n\t\t-30.0f*DEG2RAD,40.0f*DEG2RAD,-74.0f*DEG2RAD,74.0f*DEG2RAD,-30.0f*DEG2RAD,30.0f*DEG2RAD,\n\n\n\t\t//right leg\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-110.0f*DEG2RAD,30.0f*DEG2RAD,-90.0f*DEG2RAD,90.0f*DEG2RAD,-90.0f*DEG2RAD,110.0f*DEG2RAD,\n\t\t-130.0f*DEG2RAD,20.0f*DEG2RAD,-25.0f*DEG2RAD,35.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-50.0f*DEG2RAD,50.0f*DEG2RAD,-30.0f*DEG2RAD,30.0f*DEG2RAD,-45.0f*DEG2RAD,45.0f*DEG2RAD,\n\t\t-35.0f*DEG2RAD,45.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,-10.0f*DEG2RAD,10.0f*DEG2RAD,\n\n\t\t//left leg\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-30.0f*DEG2RAD,110.0f*DEG2RAD,-90.0f*DEG2RAD,90.0f*DEG2RAD,-90.0f*DEG2RAD,110.0f*DEG2RAD,\n\t\t-130.0f*DEG2RAD,20.0f*DEG2RAD,-35.0f*DEG2RAD,25.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-50.0f*DEG2RAD,50.0f*DEG2RAD,-3.0f*DEG2RAD,30.0f*DEG2RAD,-45.0f*DEG2RAD,45.0f*DEG2RAD,\n\t\t-35.0f*DEG2RAD,45.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,-10.0f*DEG2RAD,10.0f*DEG2RAD,\n\n\t\t//head to mouth\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//head to leye\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//head to reye\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//neck to lclavicle\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//neck to rclavicle\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//jaw\n\t\t-30.0f*DEG2RAD,0.0f*DEG2RAD,-1.0f*DEG2RAD,1.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t//leye\n\t\t-50.0f*DEG2RAD,30.0f*DEG2RAD,-30.0f*DEG2RAD,30.0f*DEG2RAD,-35.0f*DEG2RAD,30.0f*DEG2RAD,\n\t\t//reye\n\t\t-50.0f*DEG2RAD,30.0f*DEG2RAD,-30.0f*DEG2RAD,30.0f*DEG2RAD,-30.0f*DEG2RAD,35.0f*DEG2RAD,\n\t\t//llid\n\t\t-25.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,5.0f*DEG2RAD,\n\t\t-10.0f*DEG2RAD,5.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,5.0f*DEG2RAD,\n\t\t//rlid\n\t\t-25.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-5.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-5.0f*DEG2RAD,10.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-5.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//rshoulder\n\t\t-45.0f*DEG2RAD,17.0f*DEG2RAD,-3.0f*DEG2RAD,3.0f*DEG2RAD,-16.0f*DEG2RAD,30.0f*DEG2RAD,\n\t\t-90.0f*DEG2RAD,90.0f*DEG2RAD,-110.0f*DEG2RAD,110.0f*DEG2RAD,-100.0f*DEG2RAD,70.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,130.0f*DEG2RAD,-40.0f*DEG2RAD,80.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-45.0f*DEG2RAD,45.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,90.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-5.0f*DEG2RAD,50.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-35.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//lshoulder\n\t\t-17.0f*DEG2RAD,45.0f*DEG2RAD,-3.0f*DEG2RAD,3.0f*DEG2RAD,-16.0f*DEG2RAD,30.0f*DEG2RAD,\n\t\t-90.0f*DEG2RAD,90.0f*DEG2RAD,-110.0f*DEG2RAD,110.0f*DEG2RAD,-100.0f*DEG2RAD,70.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,130.0f*DEG2RAD,-80.0f*DEG2RAD,40.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-45.0f*DEG2RAD,45.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,90.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-50.0f*DEG2RAD,5.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-35.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t-3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//rthumb\n\t\t-20.0f*DEG2RAD,50.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-80.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//lthumb\n\t\t-50.0f*DEG2RAD,20.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,80.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//73 - problem with base\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//tongue\n\t\t-60.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-20.0f*DEG2RAD,30.0f*DEG2RAD,-5.0f*DEG2RAD,5.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t-20.0f*DEG2RAD,30.0f*DEG2RAD,-5.0f*DEG2RAD,5.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t-20.0f*DEG2RAD,30.0f*DEG2RAD,-5.0f*DEG2RAD,5.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\t};\n\t\n\tpublic static int[] bprnts=\n\t{\n\t\t-1,\n\t\t//0,\n\t\t0,\n\t\t1,\n\t\t2,\n\t\t3,\n\t\t4,\n\t\t0,\n\t\t6,\n\t\t7,\n\t\t8,\n\t\t9,\n\t\t0,\n\t\t11,\n\t\t12,\n\t\t13,\n\t\t14,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t3,\n\t\t3,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t3,\n\t\t28,\n\t\t29,\n\t\t30,\n\t\t31,\n\t\t31,\n\t\t31,\n\t\t32,\n\t\t32,\n\t\t33,\n\t\t33,\n\t\t3,\n\t\t39,\n\t\t40,\n\t\t41,\n\t\t42,\n\t\t42,\n\t\t42,\n\t\t43,\n\t\t43,\n\t\t44,\n\t\t44,\n\t\t34,\n\t\t50,\n\t\t51,\n\t\t35,\n\t\t53,\n\t\t54,\n\t\t36,\n\t\t56,\n\t\t57,\n\t\t37,\n\t\t59,\n\t\t60,\n\t\t38,\n\t\t62,\n\t\t63,\n\t\t45,\n\t\t65,\n\t\t66,\n\t\t46,\n\t\t68,\n\t\t69,\n\t\t47,\n\t\t71,\n\t\t72,\n\t\t48,\n\t\t74,\n\t\t75,\n\t\t49,\n\t\t77,\n\t\t78,\n\t\t21,\n\t\t21,\n\t\t81,\n\t\t82,\n\t};\n\t\n\tpublic static String[] snames=\n\t{\n\t\t\"joint-pelvistojoint-spine3\",\n\t\t//\"joint-spine3tojoint-pelvis\",\n\t\t\"joint-spine3tojoint-spine2\",\n\t\t\"joint-spine2tojoint-spine1\",\n\t\t\"joint-spine1tojoint-neck\",\n\t\t\"joint-necktojoint-head\",\n\t\t\"joint-headtojoint-head2\",\n\t\t\"joint-pelvistojoint-r-upper-leg\",\n\t\t\"joint-r-upper-legtojoint-r-knee\",\n\t\t\"joint-r-kneetojoint-r-ankle\",\n\t\t\"joint-r-ankletojoint-r-foot-1\",\n\t\t\"joint-r-foot-1tojoint-r-foot-2\",\n\t\t\"joint-pelvistojoint-l-upper-leg\",\n\t\t\"joint-l-upper-legtojoint-l-knee\",\n\t\t\"joint-l-kneetojoint-l-ankle\",\n\t\t\"joint-l-ankletojoint-l-foot-1\",\n\t\t\"joint-l-foot-1tojoint-l-foot-2\",\n\t\t\"joint-head2tojoint-mouth\",\n\t\t\"joint-head2tojoint-l-eye\",\n\t\t\"joint-head2tojoint-r-eye\",\n\t\t\"joint-necktojoint-l-clavicle\",\n\t\t\"joint-necktojoint-r-clavicle\",\n\t\t\"joint-mouthtojoint-jaw\",\n\t\t\"joint-l-eyetojoint-l-eye-target\",\n\t\t\"joint-r-eyetojoint-r-eye-target\",\n\t\t\"joint-l-eyetojoint-l-upperlid\",\n\t\t\"joint-l-eyetojoint-l-lowerlid\",\n\t\t\"joint-r-eyetojoint-r-upperlid\",\n\t\t\"joint-r-eyetojoint-r-lowerlid\",\n\t\t\"joint-r-clavicletojoint-r-shoulder\",\n\t\t\"joint-r-shouldertojoint-r-elbow\",\n\t\t\"joint-r-elbowtojoint-r-hand\",\n\t\t\"joint-r-handtojoint-r-finger-3-1\",\n\t\t\"joint-r-handtojoint-r-hand-3\",\n\t\t\"joint-r-handtojoint-r-hand-2\",\n\t\t\"joint-r-handtojoint-r-finger-1-1\",\n\t\t\"joint-r-hand-3tojoint-r-finger-2-1\",\n\t\t\"joint-r-hand-3tojoint-r-finger-3-1\",\n\t\t\"joint-r-hand-2tojoint-r-finger-4-1\",\n\t\t\"joint-r-hand-2tojoint-r-finger-5-1\",\n\t\t\"joint-l-clavicletojoint-l-shoulder\",\n\t\t\"joint-l-shouldertojoint-l-elbow\",\n\t\t\"joint-l-elbowtojoint-l-hand\",\n\t\t\"joint-l-handtojoint-l-finger-3-1\",\n\t\t\"joint-l-handtojoint-l-hand-3\",\n\t\t\"joint-l-handtojoint-l-hand-2\",\n\t\t\"joint-l-handtojoint-l-finger-1-1\",\n\t\t\"joint-l-hand-3tojoint-l-finger-2-1\",\n\t\t\"joint-l-hand-3tojoint-l-finger-3-1\",\n\t\t\"joint-l-hand-2tojoint-l-finger-4-1\",\n\t\t\"joint-l-hand-2tojoint-l-finger-5-1\",\n\t\t\"joint-r-finger-1-1tojoint-r-finger-1-2\",\n\t\t\"joint-r-finger-1-2tojoint-r-finger-1-3\",\n\t\t\"joint-r-finger-1-3tojoint-r-finger-1-4\",\n\t\t\"joint-r-finger-2-1tojoint-r-finger-2-2\",\n\t\t\"joint-r-finger-2-2tojoint-r-finger-2-3\",\n\t\t\"joint-r-finger-2-3tojoint-r-finger-2-4\",\n\t\t\"joint-r-finger-3-1tojoint-r-finger-3-2\",\n\t\t\"joint-r-finger-3-2tojoint-r-finger-3-3\",\n\t\t\"joint-r-finger-3-3tojoint-r-finger-3-4\",\n\t\t\"joint-r-finger-4-1tojoint-r-finger-4-2\",\n\t\t\"joint-r-finger-4-2tojoint-r-finger-4-3\",\n\t\t\"joint-r-finger-4-3tojoint-r-finger-4-4\",\n\t\t\"joint-r-finger-5-1tojoint-r-finger-5-2\",\n\t\t\"joint-r-finger-5-2tojoint-r-finger-5-3\",\n\t\t\"joint-r-finger-5-3tojoint-r-finger-5-4\",\n\t\t\"joint-l-finger-1-1tojoint-l-finger-1-2\",\n\t\t\"joint-l-finger-1-2tojoint-l-finger-1-3\",\n\t\t\"joint-l-finger-1-3tojoint-l-finger-1-4\",\n\t\t\"joint-l-finger-2-1tojoint-l-finger-2-2\",\n\t\t\"joint-l-finger-2-2tojoint-l-finger-2-3\",\n\t\t\"joint-l-finger-2-3tojoint-l-finger-2-4\",\n\t\t\"joint-l-finger-3-1tojoint-l-finger-3-2\",\n\t\t\"joint-l-finger-3-2tojoint-l-finger-3-3\",\n\t\t\"joint-l-finger-3-3tojoint-l-finger-3-4\",\n\t\t\"joint-l-finger-4-1tojoint-l-finger-4-2\",\n\t\t\"joint-l-finger-4-2tojoint-l-finger-4-3\",\n\t\t\"joint-l-finger-4-3tojoint-l-finger-4-4\",\n\t\t\"joint-l-finger-5-1tojoint-l-finger-5-2\",\n\t\t\"joint-l-finger-5-2tojoint-l-finger-5-3\",\n\t\t\"joint-l-finger-5-3tojoint-l-finger-5-4\",\n\t\t\"joint-jawtojoint-tongue-1\",\n\t\t\"joint-tongue-1tojoint-tongue-2\",\n\t\t\"joint-tongue-2tojoint-tongue-3\",\n\t\t\"joint-tongue-3tojoint-tongue-4\",\n\t};\n\t\n\tpublic static final int BONE_HipstoChest0=0;\n\t//\"Hips=;\n\tpublic static final int BONE_HipstoChest1=1;\n\tpublic static final int BONE_HipstoChest2=2;\n\tpublic static final int BONE_ChesttoNeck=3;\n\tpublic static final int BONE_NecktoHead=4;\n\tpublic static final int BONE_HeadtoHeadend=5;\n\tpublic static final int BONE_Hip_L=6;\n\tpublic static final int BONE_LeftUpLegtoLeftLowLeg=7;\n\tpublic static final int BONE_LeftLowLegtoLeftFoot=8;\n\tpublic static final int BONE_LeftFoottoLeftFootend=9;\n\tpublic static final int BONE_Toe_L=10;\n\tpublic static final int BONE_Hip_R=11;\n\tpublic static final int BONE_RightUpLegtoRightLowLeg=12;\n\tpublic static final int BONE_RightLowLegtoRightFoot=13;\n\tpublic static final int BONE_RightFoottoRightFootend=14;\n\tpublic static final int BONE_Toe_R=15;\n\tpublic static final int BONE_HeadtoMouth=16;\n\tpublic static final int BONE_HeadtoLEye=17;\n\tpublic static final int BONE_HeadtoREye=18;\n\tpublic static final int BONE_Spine3toLClavicle=19;\n\tpublic static final int BONE_Spine3toRClavicle=20;\n\tpublic static final int BONE_Jaw=21;\n\tpublic static final int BONE_Eye_R=22;\n\tpublic static final int BONE_Eye_L=23;\n\tpublic static final int BONE_UpLid_R=24;\n\tpublic static final int BONE_LoLid_R=25;\n\tpublic static final int BONE_UpLid_L=26;\n\tpublic static final int BONE_LoLid_L=27;\n\tpublic static final int BONE_LeftCollartoLeftUpArm=28;\n\tpublic static final int BONE_LeftUpArmtoLeftLowArm=29;\n\tpublic static final int BONE_LeftLowArmtoLeftHand=30;\n\tpublic static final int BONE_LeftHandtoLeftHandend=31;\n\tpublic static final int BONE_Wrist_1_L=32;\n\tpublic static final int BONE_Wrist_2_L=33;\n\tpublic static final int BONE_Palm_1_L=34;\n\tpublic static final int BONE_Palm_2_L=35;\n\tpublic static final int BONE_Palm_3_L=36;\n\tpublic static final int BONE_Palm_4_L=37;\n\tpublic static final int BONE_Palm_5_L=38;\n\tpublic static final int BONE_RightCollartoRightUpArm=39;\n\tpublic static final int BONE_RightUpArmtoRightLowArm=40;\n\tpublic static final int BONE_RightLowArmtoRightHand=41;\n\tpublic static final int BONE_RightHandtoRightHandend=42;\n\tpublic static final int BONE_Wrist_1_R=43;\n\tpublic static final int BONE_Wrist_2_R=44;\n\tpublic static final int BONE_Palm_1_R=45;\n\tpublic static final int BONE_Palm_2_R=46;\n\tpublic static final int BONE_Palm_3_R=47;\n\tpublic static final int BONE_Palm_4_R=48;\n\tpublic static final int BONE_Palm_5_R=49;\n\tpublic static final int BONE_Finger_1_1_L=50;\n\tpublic static final int BONE_Finger_1_2_L=51;\n\tpublic static final int BONE_Finger_1_3_L=52;\n\tpublic static final int BONE_Finger_2_1_L=53;\n\tpublic static final int BONE_Finger_2_2_L=54;\n\tpublic static final int BONE_Finger_2_3_L=55;\n\tpublic static final int BONE_Finger_3_1_L=56;\n\tpublic static final int BONE_Finger_3_2_L=57;\n\tpublic static final int BONE_Finger_3_3_L=58;\n\tpublic static final int BONE_Finger_4_1_L=59;\n\tpublic static final int BONE_Finger_4_2_L=60;\n\tpublic static final int BONE_Finger_4_3_L=61;\n\tpublic static final int BONE_Finger_5_1_L=62;\n\tpublic static final int BONE_Finger_5_2_L=63;\n\tpublic static final int BONE_Finger_5_3_L=64;\n\tpublic static final int BONE_Finger_1_1_R=65;\n\tpublic static final int BONE_Finger_1_2_R=66;\n\tpublic static final int BONE_Finger_1_3_R=67;\n\tpublic static final int BONE_Finger_2_1_R=68;\n\tpublic static final int BONE_Finger_2_2_R=69;\n\tpublic static final int BONE_Finger_2_3_R=70;\n\tpublic static final int BONE_Finger_3_1_R=71;\n\tpublic static final int BONE_Finger_3_2_R=72;\n\tpublic static final int BONE_Finger_3_3_R=73;\n\tpublic static final int BONE_Finger_4_1_R=74;\n\tpublic static final int BONE_Finger_4_2_R=75;\n\tpublic static final int BONE_Finger_4_3_R=76;\n\tpublic static final int BONE_Finger_5_1_R=77;\n\tpublic static final int BONE_Finger_5_2_R=78;\n\tpublic static final int BONE_Finger_5_3_R=79;\n\tpublic static final int BONE_JawtoTongue=80;\n\tpublic static final int BONE_TongueBase=81;\n\tpublic static final int BONE_TongueMid=82;\n\tpublic static final int BONE_TongueTip=83;\n\t\n\t\n\tpublic static String[] names=\n\t{\n\t\t\"HipstoChest0\",\n\t\t//\"Hips\",\n\t\t\"HipstoChest1\",\n\t\t\"HipstoChest2\",\n\t\t\"ChesttoNeck\",\n\t\t\"NecktoHead\",\n\t\t\"HeadtoHeadend\",\n\t\t\"Hip_L\",\n\t\t\"LeftUpLegtoLeftLowLeg\",\n\t\t\"LeftLowLegtoLeftFoot\",\n\t\t\"LeftFoottoLeftFootend\",\n\t\t\"Toe_L\",\n\t\t\"Hip_R\",\n\t\t\"RightUpLegtoRightLowLeg\",\n\t\t\"RightLowLegtoRightFoot\",\n\t\t\"RightFoottoRightFootend\",\n\t\t\"Toe_R\",\n\t\t\"HeadtoMouth\",\n\t\t\"HeadtoLEye\",\n\t\t\"HeadtoREye\",\n\t\t\"Spine3toLClavicle\",\n\t\t\"Spine3toRClavicle\",\n\t\t\"Jaw\",\n\t\t\"Eye_R\",\n\t\t\"Eye_L\",\n\t\t\"UpLid_R\",\n\t\t\"LoLid_R\",\n\t\t\"UpLid_L\",\n\t\t\"LoLid_L\",\n\t\t\"LeftCollartoLeftUpArm\",\n\t\t\"LeftUpArmtoLeftLowArm\",\n\t\t\"LeftLowArmtoLeftHand\",\n\t\t\"LeftHandtoLeftHandend\",\n\t\t\"Wrist-1_L\",\n\t\t\"Wrist-2_L\",\n\t\t\"Palm-1_L\",\n\t\t\"Palm-2_L\",\n\t\t\"Palm-3_L\",\n\t\t\"Palm-4_L\",\n\t\t\"Palm-5_L\",\n\t\t\"RightCollartoRightUpArm\",\n\t\t\"RightUpArmtoRightLowArm\",\n\t\t\"RightLowArmtoRightHand\",\n\t\t\"RightHandtoRightHandend\",\n\t\t\"Wrist-1_R\",\n\t\t\"Wrist-2_R\",\n\t\t\"Palm-1_R\",\n\t\t\"Palm-2_R\",\n\t\t\"Palm-3_R\",\n\t\t\"Palm-4_R\",\n\t\t\"Palm-5_R\",\n\t\t\"Finger-1-1_L\",\n\t\t\"Finger-1-2_L\",\n\t\t\"Finger-1-3_L\",\n\t\t\"Finger-2-1_L\",\n\t\t\"Finger-2-2_L\",\n\t\t\"Finger-2-3_L\",\n\t\t\"Finger-3-1_L\",\n\t\t\"Finger-3-2_L\",\n\t\t\"Finger-3-3_L\",\n\t\t\"Finger-4-1_L\",\n\t\t\"Finger-4-2_L\",\n\t\t\"Finger-4-3_L\",\n\t\t\"Finger-5-1_L\",\n\t\t\"Finger-5-2_L\",\n\t\t\"Finger-5-3_L\",\n\t\t\"Finger-1-1_R\",\n\t\t\"Finger-1-2_R\",\n\t\t\"Finger-1-3_R\",\n\t\t\"Finger-2-1_R\",\n\t\t\"Finger-2-2_R\",\n\t\t\"Finger-2-3_R\",\n\t\t\"Finger-3-1_R\",\n\t\t\"Finger-3-2_R\",\n\t\t\"Finger-3-3_R\",\n\t\t\"Finger-4-1_R\",\n\t\t\"Finger-4-2_R\",\n\t\t\"Finger-4-3_R\",\n\t\t\"Finger-5-1_R\",\n\t\t\"Finger-5-2_R\",\n\t\t\"Finger-5-3_R\",\n\t\t\"JawtoTongue\",\n\t\t\"TongueBase\",\n\t\t\"TongueMid\",\n\t\t\"TongueTip\",\n\t};\n\t\n\tpublic static int[] mirror =\n\t{\n\t\t-1,\n\t\t//\"Hips\",\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t\tBONE_Hip_R,\n\t\tBONE_RightUpLegtoRightLowLeg,\n\t\tBONE_RightLowLegtoRightFoot,\n\t\tBONE_RightFoottoRightFootend,\n\t\tBONE_Toe_R,\n\t\tBONE_Hip_L,\n\t\tBONE_LeftUpLegtoLeftLowLeg,\n\t\tBONE_LeftLowLegtoLeftFoot,\n\t\tBONE_LeftFoottoLeftFootend,\n\t\tBONE_Toe_L,\n\t\t-1,\n\t\tBONE_HeadtoREye,\n\t\tBONE_HeadtoLEye,\n\t\tBONE_Spine3toRClavicle,\n\t\tBONE_Spine3toLClavicle,\n\t\t-1,\n\t\tBONE_Eye_L,\n\t\tBONE_Eye_R,\n\t\tBONE_UpLid_L,\n\t\tBONE_LoLid_L,\n\t\tBONE_UpLid_R,\n\t\tBONE_LoLid_R,\n\t\tBONE_RightCollartoRightUpArm,\n\t\tBONE_RightUpArmtoRightLowArm,\n\t\tBONE_RightLowArmtoRightHand,\n\t\tBONE_RightHandtoRightHandend,\n\t\tBONE_Wrist_1_R,\n\t\tBONE_Wrist_2_R,\n\t\tBONE_Palm_1_R,\n\t\tBONE_Palm_2_R,\n\t\tBONE_Palm_3_R,\n\t\tBONE_Palm_4_R,\n\t\tBONE_Palm_5_R,\n\t\tBONE_LeftCollartoLeftUpArm,\n\t\tBONE_LeftUpArmtoLeftLowArm,\n\t\tBONE_LeftLowArmtoLeftHand,\n\t\tBONE_LeftHandtoLeftHandend,\n\t\tBONE_Wrist_1_L,\n\t\tBONE_Wrist_2_L,\n\t\tBONE_Palm_1_L,\n\t\tBONE_Palm_2_L,\n\t\tBONE_Palm_3_L,\n\t\tBONE_Palm_4_L,\n\t\tBONE_Palm_5_L,\n\t\tBONE_Finger_1_1_R,\n\t\tBONE_Finger_1_2_R,\n\t\tBONE_Finger_1_3_R,\n\t\tBONE_Finger_2_1_R,\n\t\tBONE_Finger_2_2_R,\n\t\tBONE_Finger_2_3_R,\n\t\tBONE_Finger_3_1_R,\n\t\tBONE_Finger_3_2_R,\n\t\tBONE_Finger_3_3_R,\n\t\tBONE_Finger_4_1_R,\n\t\tBONE_Finger_4_2_R,\n\t\tBONE_Finger_4_3_R,\n\t\tBONE_Finger_5_1_R,\n\t\tBONE_Finger_5_2_R,\n\t\tBONE_Finger_5_3_R,\n\t\tBONE_Finger_1_1_L,\n\t\tBONE_Finger_1_2_L,\n\t\tBONE_Finger_1_3_L,\n\t\tBONE_Finger_2_1_L,\n\t\tBONE_Finger_2_2_L,\n\t\tBONE_Finger_2_3_L,\n\t\tBONE_Finger_3_1_L,\n\t\tBONE_Finger_3_2_L,\n\t\tBONE_Finger_3_3_L,\n\t\tBONE_Finger_4_1_L,\n\t\tBONE_Finger_4_2_L,\n\t\tBONE_Finger_4_3_L,\n\t\tBONE_Finger_5_1_L,\n\t\tBONE_Finger_5_2_L,\n\t\tBONE_Finger_5_3_L,\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t};\n}"
] | import utils.GeneralMatrixDouble;
import utils.GeneralMatrixFloat;
import utils.GeneralMatrixInt;
import utils.GeneralMatrixObject;
import utils.GeneralMatrixString;
import utils.Quaternion;
import utils.shapes.human.HumanBones; | float f0 = 1.0f-f1;
apos = pPose+f1;
if(f1==0.0f)
{
for(int li=0;li<lposes.width;li++)
{
lpos.value[li] = lposes.value[pPose*lposes.width+li];
}
}
else
{
for(int li=0;li<lposes.width;li++)
{
lpos.value[li] = lposes.value[pPose*lposes.width+li]*f0+lposes.value[nPose*lposes.width+li]*f1;
}
}
}
public static float animate(float times,GeneralMatrixFloat frames,GeneralMatrixFloat lposes,
GeneralMatrixFloat lpos)
{
float apos = 0.0f;
int olw = lpos.width;
int olh = lpos.height;
lpos.setDimensions(lposes.width, 1);
float pFrame = 0.0f;
float nFrame = 0.0f;
int pPose = -1;
int nPose = -1;
for(int i=0;i<frames.height;i++)
{
float f = frames.value[i];
if(f<times)
{
pFrame = f;
pPose = i;
}
else
{
nFrame = f;
nPose = i;
break;
}
}
if(pPose==-1)
{
apos = nPose;
for(int li=0;li<lposes.width;li++)
{
lpos.value[li] = lposes.value[nPose*lposes.width+li];
}
}
else
if(nPose==-1)
{
apos = pPose;
for(int li=0;li<lposes.width;li++)
{
lpos.value[li] = lposes.value[pPose*lposes.width+li];
}
}
else
{
float dp = times-pFrame;
float dn = nFrame-times;
float d = nFrame-pFrame;
if(d<GeneralMatrixFloat.EPSILON)
{
if(dp<dn)
{
apos = pPose;
for(int li=0;li<lposes.width;li++)
{
lpos.value[li] = lposes.value[pPose*lposes.width+li];
}
}
else
{
apos = nPose;
for(int li=0;li<lposes.width;li++)
{
lpos.value[li] = lposes.value[nPose*lposes.width+li];
}
}
}
//*
else
{
float f1 = dp/d;
float f0 = 1.0f-f1;
apos = pPose+f1;
for(int li=0;li<lposes.width;li++)
{
lpos.value[li] = lposes.value[pPose*lposes.width+li]*f0+lposes.value[nPose*lposes.width+li]*f1;
}
}
}
lpos.width = olw;
lpos.height = olh;
return apos;
}
public static void blend(float f,GeneralMatrixFloat pbmats,GeneralMatrixFloat nbmats,GeneralMatrixFloat bmats)
{
float[] qa = new float[4];
float[] qb = new float[4];
float[] qc = new float[4];
for(int i=0;i<nbmats.height;i++)
{
int mo = i*9;
Quaternion.MatrixtoQuaternion(pbmats.value,mo, qa);
Quaternion.MatrixtoQuaternion(nbmats.value,mo, qb);
Quaternion.slerp(qa, qb, f, qc);
Quaternion.QuaterniontoMatrix(qc, bmats.value, mo);
}
}
| public static void updateVposFromBmats(GeneralMatrixInt bones, | 2 |
OpenIchano/Viewer | src/com/zhongyun/viewer/MyViewerHelper.java | [
"public class CameraInfo {\n\n\tprivate long cid;\n\tprivate String cameraName;\n\tprivate String cameraUser;\n\tprivate String cameraPwd;\n\tprivate Bitmap cameraThumb;\n\tprivate boolean isOnline;\n\tprivate boolean pwdIsRight;\n\tprivate String os;\n\t\n\tpublic void setCid(long cid){\n\t\tthis.cid = cid;\n\t}\n\t\n\tpublic long getCid(){\n\t\treturn cid;\n\t}\n\t\n\tpublic void setCameraUser(String cameraUser){\n\t\tthis.cameraUser = cameraUser;\n\t}\n\t\n\tpublic String getCameraUser(){\n\t\treturn cameraUser;\n\t}\n\t\n\tpublic void setCameraName(String cameraName){\n\t\tthis.cameraName = cameraName;\n\t}\n\t\n\tpublic String getCameraName(){\n\t\treturn cameraName;\n\t}\n\t\n\tpublic void setCameraPwd(String cameraPwd){\n\t\tthis.cameraPwd = cameraPwd;\n\t}\n\t\n\tpublic String getCameraPwd(){\n\t\treturn cameraPwd;\n\t}\n\t\n\tpublic void setCameraThumb(Bitmap cameraThumb){\n\t\tthis.cameraThumb = cameraThumb;\n\t}\n\t\n\tpublic Bitmap getCameraThumb(){\n\t\treturn cameraThumb;\n\t}\n\t\n\tpublic void setIsOnline(boolean isOnline){\n\t\tthis.isOnline = isOnline;\n\t}\n\t\n\tpublic boolean getIsOnline(){\n\t\treturn isOnline;\n\t}\n\t\n\tpublic void setPwdIsRight(boolean pwdIsRight){\n\t\tthis.pwdIsRight = pwdIsRight;\n\t}\n\t\n\tpublic boolean getPwdIsRight(){\n\t\treturn pwdIsRight;\n\t}\n\t\n\tpublic void setOS(String os){\n\t\tthis.os = os;\n\t}\n\t\n\tpublic String getOS(){\n\t\treturn os;\n\t}\n}",
"public class CameraInfoManager extends SQLiteOpenHelper{\n\n\tprivate static final int DATABASE_VERSION = 1;\n\tprivate static final String DATABASE_NAME = \"camerainfomanager.db\";\n\t\n\tprivate static final String TABLE_NAME = \"camerainfo\";\n\tprivate static final String _ID = \"id\";\n\tprivate static final String _CID = \"cid\";\n\tprivate static final String _NAME = \"name\";\n\tprivate static final String _USER = \"user\";\n\tprivate static final String _PASSWORD = \"password\";\n\tprivate static final String _THUMB = \"thumb\";\n\tprivate static final String _OS = \"os\";\n\t\n\tprivate String[] mColumns = new String[]{_ID, _CID, _NAME, _USER, _PASSWORD, _THUMB, _OS};\n\tpublic CameraInfoManager(Context context) {\n\t\tsuper(context, DATABASE_NAME, null, DATABASE_VERSION);\n\t}\n\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tdb.execSQL(\"CREATE TABLE \" + TABLE_NAME + \"(\"+ \n\t\t\t\t _ID + \" INTEGER PRIMARY KEY,\" + \n\t\t\t\t _CID + \" LONG,\"+ \n\t\t\t\t _NAME + \" TEXT,\" + \n\t\t\t\t _USER + \" TEXT,\" + \n\t\t\t\t _PASSWORD + \" TEXT,\" + \n\t\t\t\t _THUMB + \" BLOB,\" + \n\t\t\t\t _OS + \" TEXT\" + \n\t\t\t\t \")\");\n\t}\n\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME);\n onCreate(db);\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tsuper.close();\n\t}\n\t\n\tpublic byte[] Bitmap2Bytes(Bitmap bitmap){\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\t\tbitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);\n\t\tbyte[] bytes = baos.toByteArray();\n\t\ttry {\n\t\t\tbaos.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn bytes;\n\t}\n\t\n\tpublic long addCameraInfo(CameraInfo info){\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tlong rowID = 0;\n\t\tCameraInfo temp = getCameraInfo(db, info.getCid(), rowID);\n\t\tif(null == temp){\n\t\t\tContentValues values = new ContentValues();\n\t\t\tvalues.put(_CID, info.getCid());\n\t\t\tvalues.put(_NAME, info.getCameraName());\n\t\t\tvalues.put(_USER, info.getCameraUser());\n\t\t\tvalues.put(_PASSWORD, info.getCameraPwd());\n\t\t\tvalues.put(_THUMB, Bitmap2Bytes(info.getCameraThumb()));\n\t\t\tvalues.put(_OS, info.getOS());\n\t\t\tlong ret = db.insert(TABLE_NAME, null, values);\n\t\t\tdb.close();\n\t\t\treturn ret;\n\t\t}else{\n\t\t\tupdate(info);\n\t\t\treturn rowID;\n\t\t}\n\t}\n\t\n\tprivate CameraInfo getCameraInfo(SQLiteDatabase db, long cid, long rowID){\n\t\tCursor cur = db.query(TABLE_NAME, mColumns, _CID + \"=?\", \n\t\t\t\tnew String[]{String.valueOf(cid)}, null, null, null);\n\t\tif(null != cur && cur.getCount() > 0) {\n\t\t\tcur.moveToFirst();\n\t\t\trowID = cur.getPosition();\n\t\t}else {\n\t\t\tif(null != cur) cur.close();\n\t\t\treturn null;\n\t\t}\n\t\tCameraInfo info = new CameraInfo();\n\t\tinfo.setCid(cur.getLong(cur.getColumnIndex(_CID)));\n\t\tinfo.setCameraName(cur.getString(cur.getColumnIndex(_NAME)));\n\t\tinfo.setCameraUser(cur.getString(cur.getColumnIndex(_USER)));\n\t\tinfo.setCameraPwd(cur.getString(cur.getColumnIndex(_PASSWORD)));\n\t\tbyte[] bmp = cur.getBlob(cur.getColumnIndex(_THUMB));\n\t\tinfo.setCameraThumb(BitmapFactory.decodeByteArray(bmp, 0, bmp.length));\n\t\tinfo.setOS(cur.getString(cur.getColumnIndex(_OS)));\n\t\tinfo.setIsOnline(false);\n\t\tinfo.setPwdIsRight(true);\n\t\tcur.close();\n\t\treturn info;\n\t}\n\t\n\tpublic CameraInfo getCameraInfo(long cid){\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tlong rowID = 0;\n\t\treturn getCameraInfo(db, cid, rowID);\n\t}\n\t\n\tpublic ArrayList<CameraInfo> getAllCameraInfos(){\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tArrayList<CameraInfo> infos = new ArrayList<CameraInfo>();\n\t\tCursor cur = db.query(TABLE_NAME, mColumns, null, null, null, null, null);\n\t\tif(null != cur && cur.getCount() > 0) {\n\t\t\tcur.moveToFirst();\n\t\t\tdo{\n\t\t\t\tCameraInfo info = new CameraInfo();\n\t\t\t\tinfo.setCid(cur.getLong(cur.getColumnIndex(_CID)));\n\t\t\t\tinfo.setCameraName(cur.getString(cur.getColumnIndex(_NAME)));\n\t\t\t\tinfo.setCameraUser(cur.getString(cur.getColumnIndex(_USER)));\n\t\t\t\tinfo.setCameraPwd(cur.getString(cur.getColumnIndex(_PASSWORD)));\n\t\t\t\tbyte[] bmp = cur.getBlob(cur.getColumnIndex(_THUMB));\n\t\t\t\tinfo.setCameraThumb(BitmapFactory.decodeByteArray(bmp, 0, bmp.length));\n\t\t\t\tinfo.setOS(cur.getString(cur.getColumnIndex(_OS)));\n\t\t\t\tinfo.setIsOnline(false);\n\t\t\t\tinfo.setPwdIsRight(true);\n\t\t\t\tinfos.add(info);\n\t\t\t}while(cur.moveToNext());\n\t\t\tcur.close();\n\t\t\treturn infos;\n\t\t}else {\n\t\t\tif(null != cur) cur.close();\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic int update(CameraInfo info){\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(_CID, info.getCid());\n\t\tvalues.put(_NAME, info.getCameraName());\n\t\tvalues.put(_USER, info.getCameraUser());\n\t\tvalues.put(_PASSWORD, info.getCameraPwd());\n\t\tvalues.put(_THUMB, Bitmap2Bytes(info.getCameraThumb()));\n\t\tvalues.put(_OS, info.getOS());\n\t\tint ret = db.update(TABLE_NAME, values, _CID + \"=?\", new String[]{String.valueOf(info.getCid())});\n\t\tdb.close();\n\t\treturn ret;\n\t}\n\t\n\tpublic int delete(CameraInfo info){\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tint ret = db.delete(TABLE_NAME, _CID + \"=?\", new String[]{String.valueOf(info.getCid())});\n\t\tdb.close();\n\t\treturn ret;\n\t}\n\t\n\tpublic int deleteAll(){\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tint ret = db.delete(TABLE_NAME, null, null);\n\t\tdb.close();\n\t\treturn ret;\n\t}\n}",
"public class UserInfo {\n\n\tpublic static final String CLIENT_CID = \"CLIENT_CID\";\n\tpublic static final String IS_LOGIN = \"IS_LOGIN\";\n\tpublic static final String USER_NAME = \"USER_NAME\";\n\tpublic static final String USER_SESSION_ID = \"USER_SESSION_ID\";\n\tpublic static final String USER_RECOMMAND_URL = \"USER_RECOMMAND_URL\";\n\tpublic static final String TS = \"TS\";\n\t\n\tprivate static UserInfo mUserInfo;\n\tprivate Context mContext;\n\tpublic boolean isLogin;\n\tpublic long clientCid = 0;\n\tpublic String name;\n\tpublic String sessionId;\n\tpublic String recommandURL;\n\tpublic String ts = \"\";\n\t\n\tprivate UserInfo(Context context){\n\t\tmContext = context;\n\t\tString str = PrefUtils.getString(mContext, CLIENT_CID);\n\t\tif(!StringUtils.isEmpty(str)){\n\t\t\tclientCid = Long.parseLong(str);\n\t\t}\n\t\t\n\t\tSharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n\t\tisLogin = sp.getBoolean(IS_LOGIN, false);\n\t\tname = sp.getString(USER_NAME, \"\");\n\t\tsessionId = sp.getString(USER_SESSION_ID, \"\");\n\t\trecommandURL = sp.getString(USER_RECOMMAND_URL, \"\");\n\t\tts = sp.getString(TS, \"\");\n\t}\n\t\n\tpublic static UserInfo getUserInfo(Context context){\n\t\tif(null == mUserInfo){\n\t\t\tmUserInfo = new UserInfo(context);\n\t\t}\n\t\treturn mUserInfo;\n\t}\n\t\n\tpublic void saveClientCid(long cid){\n\t\tif(cid > 0){\n\t\t\tif(cid != clientCid)\n\t\t\t\tclientCid = cid;\n\t\t\t\tPrefUtils.putString(mContext, CLIENT_CID, String.valueOf(cid));\n\t\t}\n\t}\n\t\n\tpublic void setLoginInfo(boolean isLogin, String name, String sessionId, String recommandURL){\n\t\tthis.isLogin = isLogin;\n\t\tthis.name = name;\n\t\tthis.sessionId = sessionId;\n\t\tthis.recommandURL = recommandURL;\n\t\t\n\t\tSharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);\n\t\tEditor editor = sp.edit();\n\t\teditor.putBoolean(IS_LOGIN, isLogin);\n\t\teditor.putString(USER_NAME, name);\n\t\teditor.putString(USER_SESSION_ID, sessionId);\n\t\teditor.putString(USER_RECOMMAND_URL, recommandURL);\n\t\teditor.commit();\n\t}\n\t\n\tpublic void setTS(String ts){\n\t\tif(!ts.equals(this.ts)){\n\t\t\tthis.ts = ts;\n\t\t\tPrefUtils.putString(mContext, TS, ts);\n\t\t}\n\t}\n}",
"public class Constants {\n\n\tpublic static final String INTENT_CID = \"cid\";\n\tpublic static final String INTENT_CAMERA_NAME = \"camera_name\";\n\t\n\tpublic static final String BARCODE_SPLITER = \"&\";\n\tpublic static final String BARCODE_DEVICE_ID = \"deviceid=\";\n\tpublic static final String BARCODE_CID = \"cid=\";\n\tpublic static final String BARCODE_NAME = \"name=\";\n\tpublic static final String BARCODE_USER_NAME = \"username=\";\n\tpublic static final String BARCODE_PASSWORD = \"password=\";\n\n\tpublic static final String VIDEO_MP4 = \".mp4\";\n\tpublic static final String IMG_JPG = \".jpg\";\n\tpublic static final String RECORD_VIDEO_PATH = \"ZhongYun/recordVideo\";\n\tpublic static final String CAPTURE_IAMGE_PATH = \"ZhongYun/capture\";\n\tpublic static final String LOCAL_ICON_PATH = \"ZhongYun/icon\";\n\tpublic static final String LOCAL_CID_ICON_PATH = \"ZhongYun/cid_icon\";\n\t\n\tpublic static final String CONNECTIVITY_CHANGE_ACTION = \"android.net.conn.CONNECTIVITY_CHANGE\";\n\tpublic static final String CONNECTIVITY_SESSION_STATE = \"zhongyun.viewer.session_state\";\n}",
"public class ImageDownloader {\n private LruCache<String, Bitmap> mMemoryCache;\n private LruCache<String, Bitmap> mMemoryCache_sd;\n private final BitmapFactory.Options options = new BitmapFactory.Options();\n // List<String> list = new ArrayList<String>();\n long sendRequestId;\n Context context;\n private static ImageDownloader instance;\n ListView listvew;\n File cacheDir;\n\n public static ImageDownloader getInstance() {\n if (null == instance) {\n instance = new ImageDownloader();\n }\n return instance;\n }\n\n public ImageDownloader() {\n options.inJustDecodeBounds = false;\n cacheDir = FileUtils.createFile(Constants.LOCAL_CID_ICON_PATH);\n\n int MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory() / 1024);\n if (null == mMemoryCache) {\n mMemoryCache = new LruCache<String, Bitmap>(MAXMEMONRY / 8) {\n @Override\n protected int sizeOf(String key, Bitmap bitmap) {\n return bitmap.getRowBytes() * bitmap.getHeight() / 1024;\n }\n\n @Override\n protected void entryRemoved(boolean evicted, String key,\n Bitmap oldValue, Bitmap newValue) {\n if (oldValue != null && !oldValue.isRecycled()) {\n oldValue.recycle();\n oldValue = null;\n }\n\n }\n };\n }\n\n if (null == mMemoryCache_sd) {\n mMemoryCache_sd = new LruCache<String, Bitmap>(MAXMEMONRY / 8) {\n @Override\n protected int sizeOf(String key, Bitmap bitmap) {\n return bitmap.getRowBytes() * bitmap.getHeight() / 1024;\n }\n\n @Override\n protected void entryRemoved(boolean evicted, String key,\n Bitmap oldValue, Bitmap newValue) {\n if (oldValue != null && !oldValue.isRecycled()) {\n oldValue.recycle();\n oldValue = null;\n }\n\n }\n };\n }\n }\n\n public Bitmap getBitmapFromCache(String load_cid) {\n Bitmap currBitmap = null;\n if (null != mMemoryCache) {\n currBitmap = mMemoryCache.get(load_cid);\n if (currBitmap != null)\n return currBitmap;\n }\n currBitmap = getBitmapFromFile(load_cid);\n return currBitmap;\n }\n\n public Bitmap getDefaultBmp(Context context){\n return BitmapFactory.decodeResource(context.getResources(), R.drawable.avs_type_android);\n }\n public Bitmap putBitmapData(final String cid, final byte[] data) {\n Bitmap bitmap =null;\n if (null != data && data.length > 0) {\n options.inSampleSize = 1;\n bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,\n options);\n if (null != bitmap) {\n if (null != mMemoryCache) {\n mMemoryCache.put(cid, bitmap);\n }\n setBitmapToFile(cid, bitmap);\n removeImageCache(cid);\n }\n }\n return bitmap;\n\n }\n\n public void destory() {\n try {\n clearCache();\n // list.clear();\n // instance = null;\n } catch (IllegalArgumentException e) {\n\n }\n }\n\n public void clearCache() {\n if (mMemoryCache != null) {\n if (mMemoryCache.size() > 0) {\n mMemoryCache.evictAll();\n }\n mMemoryCache = null;\n }\n\n if (mMemoryCache_sd != null) {\n if (mMemoryCache_sd.size() > 0) {\n mMemoryCache_sd.evictAll();\n }\n mMemoryCache_sd = null;\n }\n }\n\n public synchronized void removeImageCache(String key) {\n if (key != null) {\n if (mMemoryCache_sd != null) {\n Bitmap bm = mMemoryCache_sd.remove(key);\n if (bm != null)\n bm.recycle();\n }\n }\n }\n\n /**\n * 从文件中拿图片\n * \n * @param mActivity\n * @param imageName\n * 图片名字\n * @param path\n * 图片路径\n * @return\n */\n private Bitmap getBitmapFromFile(String cid) {\n if (FileUtils.hasSDCard()) {\n if (cid != null) {\n try {\n Bitmap fileBitmap = mMemoryCache_sd.get(cid);\n if (null != fileBitmap) {\n return fileBitmap;\n } else {\n options.inSampleSize = 1;\n Bitmap bitmap = BitmapFactory.decodeFile(cacheDir + \"/\"\n + cid.hashCode(), options);\n if (null != bitmap) {\n mMemoryCache_sd.put(cid, bitmap);\n }\n return bitmap;\n }\n } catch (Exception e) {\n\n return null;\n } catch (OutOfMemoryError e) {\n return null;\n }\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n\n FileOutputStream fos = null;\n\n private void setBitmapToFile(String cid, Bitmap bitmap) {\n if (FileUtils.hasSDCard()) {\n File file = null;\n try {\n file = new File(cacheDir, String.valueOf(cid.hashCode()));\n file.createNewFile();\n fos = new FileOutputStream(file);\n bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);\n fos.flush();\n if (fos != null) {\n fos.close();\n }\n } catch (Exception e) {\n\n }\n }\n }\n}",
"public class PrefUtils {\n\t\n\tpublic static final String HAVE_SHOW_GUIDE = \"have_show_guide\";\n\n\tpublic static void putBoolean(Context context, String key, boolean value){\n\t\tSharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n\t\tEditor editor = sp.edit();\n\t\teditor.putBoolean(key, value);\n\t\teditor.commit();\n\t}\n\t\n\tpublic static boolean getBoolean(Context context, String key){\n\t\tSharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n\t\treturn sp.getBoolean(key, false);\n\t}\n\t\n\tpublic static void putString(Context context, String key, String value){\n\t\tSharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n\t\tEditor editor = sp.edit();\n\t\teditor.putString(key, value);\n\t\teditor.commit();\n\t}\n\t\n\tpublic static String getString(Context context, String key){\n\t\tSharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n\t\treturn sp.getString(key, \"\");\n\t}\n}"
] | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.Toast;
import com.ichano.rvs.viewer.Viewer;
import com.ichano.rvs.viewer.bean.StreamerInfo;
import com.ichano.rvs.viewer.callback.RecvJpegListener;
import com.ichano.rvs.viewer.constant.LoginError;
import com.ichano.rvs.viewer.constant.LoginState;
import com.ichano.rvs.viewer.constant.RvsJpegType;
import com.ichano.rvs.viewer.constant.RvsSessionState;
import com.ichano.rvs.viewer.constant.StreamerConfigState;
import com.ichano.rvs.viewer.constant.StreamerPresenceState;
import com.ichano.rvs.viewer.ui.ViewerInitHelper;
import com.zhongyun.viewer.db.CameraInfo;
import com.zhongyun.viewer.db.CameraInfoManager;
import com.zhongyun.viewer.login.UserInfo;
import com.zhongyun.viewer.utils.Constants;
import com.zhongyun.viewer.utils.ImageDownloader;
import com.zhongyun.viewer.utils.PrefUtils; | /*
* Copyright (C) 2015 iChano incorporation's 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 com.zhongyun.viewer;
public class MyViewerHelper extends ViewerInitHelper{
private static final String TAG = "MyViewerHelper";
private static MyViewerHelper mViewer;
private UserInfo mUserInfo;
private LoginListener mLoginListener;
private List<CameraStateListener> mCameraStateListeners = new ArrayList<CameraStateListener>();
private static List<CameraInfo> mCameraInfos; | private static CameraInfoManager mCameraInfoManager; | 1 |
w-shackleton/droidpad-android | src/uk/digitalsquid/droidpad/layout/XmlDecoder.java | [
"public interface LogTag {\n\tstatic final String TAG = \"droidpad\";\n}",
"public class Button extends Item {\n\tprivate static final long serialVersionUID = -7921469580817352801L;\n\t\n\tpublic final String text;\n\tpublic final int textSize;\r\n\t\r\n\tprivate boolean resetButton;\r\n\t\n\tprotected boolean tmpSelected = false;\r\n\t\n\t/**\r\n\t * When set, keeps the current selected state for one cycle.\r\n\t * This is reset every cycle.\r\n\t */\n\tprotected boolean selectedOverride = false;\n\n\tpublic Button(int x, int y, int sx, int sy, String text) {\n\t\tthis(x, y, sx, sy, text, TEXT_SIZE);\n\t}\n\n\tpublic Button(int x, int y, int sx, int sy, String text, int textSize) {\n\t\tsuper(x, y, sx, sy);\n\t\tthis.text = text;\n\t\tthis.textSize = textSize == 0 ? TEXT_SIZE : textSize;\n\t}\n\tpublic Button(float x, float y, float sx, float sy, boolean free, String text, int textSize) {\n\t\tsuper(x, y, sx, sy, free);\n\t\tthis.text = text;\n\t\tthis.textSize = textSize == 0 ? TEXT_SIZE : textSize;\n\t}\n\n\t@Override\n\tpublic void drawInArea(Canvas c, RectF area, PointF centre, boolean landscape) {\n\t\tpTextS.setTextSize(textSize);\n\t\tpText.setTextSize(textSize);\n\t\tif(landscape) {\n\t\t\tc.rotate(90, centre.x, centre.y);\n\t\t\tc.drawText(text, centre.x, centre.y + (TEXT_SIZE / 2), isSelected() ? pTextS : pText);\n\t\t\tc.rotate(-90, centre.x, centre.y);\n\t\t} else\n\t\t\tc.drawText(text, centre.x, centre.y + (TEXT_SIZE / 2), isSelected() ? pTextS : pText);\n\t}\n\n\t@Override\n\tpublic String getOutputString() {\n\t\treturn selected ? \"1\" : \"0\";\n\t}\n\n\t@Override\n\tpublic void resetStickyLock() {\n\t\ttmpSelected = false;\n\t}\n\n\t@Override\n\tpublic void finaliseState() {\r\n\t\tif(!selectedOverride) {\n\t\t\tselected = tmpSelected;\r\n\t\t} else {\r\n\t\t\tselected = true;\r\n\t\t}\r\n\t}\n\n\t@Override\n\tpublic void onMouseOn(ScreenInfo info, float x, float y) {\n\t\ttmpSelected = true;\n\t}\n\n\t@Override\n\tpublic void onMouseOff() {\n\t\t\n\t}\r\n\r\n\t@Override\r\n\tint getFlags() {\r\n\t\treturn FLAG_BUTTON | (resetButton ? FLAG_IS_RESET : 0);\r\n\t}\r\n\r\n\t/**\r\n\t * Data 1 is the button's on/off state\r\n\t */\r\n\t@Override\r\n\tint getData1() {\r\n\t\tint result = selected ? 1 : 0;\r\n\t\tif(selectedOverride) {\r\n\t\t\tselectedOverride = false;\r\n\t\t\tselected = false;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tint getData2() {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t@Override\r\n\tint getData3() {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tpublic boolean isResetButton() {\r\n\t\treturn resetButton;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns this for chaining\r\n\t * @param resetButton\r\n\t * @return this\r\n\t */\r\n\tpublic Button setResetButton(boolean resetButton) {\r\n\t\tthis.resetButton = resetButton;\r\n\t\treturn this;\r\n\t}\n}",
"public class Layout extends LinkedList<Item> implements ButtonPresses, Serializable, LogTag {\n\n\tprivate static final long serialVersionUID = -7330556550048198609L;\n\t\n\tprivate String title;\n\tprivate String description;\r\n\t\r\n\t/**\r\n\t * Extra details, specific to each layout type\r\n\t */\r\n\tprivate int extraDetail;\r\n\t\r\n\tpublic static final int EXTRA_MOUSE_ABSOLUTE = 1;\n\tpublic static final int EXTRA_MOUSE_TRACKPAD = 2;\n\t\n\tpublic final int titleId, descriptionId;\n\t\r\n\t/**\r\n\t * The default X size\r\n\t */\n\tpublic static final int BUTTONS_X = 4;\r\n\t/**\r\n\t * The default Y size\r\n\t */\n\tpublic static final int BUTTONS_Y = 5;\n\tprivate final int width;\r\n\r\n\tprivate final int height;\n\t\r\n\tprivate transient UICallbacks uiCallbacks;\n\n\tpublic Layout() {\n\t\tthis(BUTTONS_X, BUTTONS_Y, new Item[0]);\n\t}\n\n\tpublic Layout(Item[] items) {\n\t\tthis(BUTTONS_X, BUTTONS_Y, items);\n\t}\n\t\n\tpublic Layout(int width, int height, Item[] items) {\n\t\tthis(-1, -1, width, height, items);\n\t}\r\n\t\r\n\tpublic Layout(String title, String description, int width, int height) {\r\n\t\tsetTitle(title);\r\n\t\tsetDescription(description);\r\n\t\ttitleId = -2; // -2 indicates already set\r\n\t\tdescriptionId = -2;\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t}\n\t\n\tpublic Layout(int titleId, int descriptionId, int width, int height, Item[] items) {\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\t\n\t\tthis.titleId = titleId;\n\t\tthis.descriptionId = descriptionId;\n\t\t\n\t\tfor(Item item : items) {\n\t\t\tadd(item);\n\t\t}\n\t}\n\n\tpublic Layout(int titleId, int descriptionId, int extraDetail, int width, int height, Item[] items) {\n\t\tthis.width = width;\n\t\tthis.height = height;\r\n\t\t\r\n\t\tthis.extraDetail = extraDetail;\n\t\t\n\t\tthis.titleId = titleId;\n\t\tthis.descriptionId = descriptionId;\n\t\t\n\t\tfor(Item item : items) {\n\t\t\tadd(item);\n\t\t}\n\t}\n\t\r\n\t@Override\r\n\tpublic boolean add(Item object) {\r\n\t\tsuper.add(object);\n\t\tobject.setCallbacks(this);\n\t\treturn true;\r\n\t}\n\t@Override\r\n\tpublic void add(int location, Item object) {\r\n\t\tsuper.add(location, object);\n\t\tobject.setCallbacks(this);\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\r\n\r\n\tpublic void setExtraDetail(int extraDetail) {\r\n\t\tthis.extraDetail = extraDetail;\r\n\t}\r\n\r\n\tpublic int getExtraDetail() {\r\n\t\treturn extraDetail;\r\n\t}\r\n\r\n\tpublic int getWidth() {\r\n\t\treturn width;\r\n\t}\r\n\r\n\tpublic int getHeight() {\r\n\t\treturn height;\r\n\t}\r\n\r\n\tprivate UICallbacks getUiCallbacks() {\r\n\t\treturn uiCallbacks != null ? uiCallbacks : UICallbacks.NULL_UI_CALLBACKS;\r\n\t}\r\n\r\n\tpublic void setUiCallbacks(UICallbacks uiCallbacks) {\r\n\t\tthis.uiCallbacks = uiCallbacks;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void tapDefaultButton() {\n\t\tfor(Item item : this) {\r\n\t\t\tif(item instanceof Button && !(item instanceof ToggleButton)) {\r\n\t\t\t\t((Button)item).selectedOverride = true;\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void resetOverrides() {\r\n\t\tfor(Item item : this) {\r\n\t\t\tif(item instanceof Button && !(item instanceof ToggleButton)) {\r\n\t\t\t\t((Button)item).selectedOverride = false;\n\t\t\t}\r\n\t\t}\n\t\tgetUiCallbacks().refreshScreen();\r\n\t}\r\n\t\r\n\tprivate boolean activityHorizontal = false;\r\n\t\r\n\t/**\r\n\t * If <code>true</code>, then the whole activity will be set to horizontal.\r\n\t * This is different to just drawing the widgets sideways.\r\n\t */\r\n\tpublic boolean isActivityHorizontal() {\r\n\t\treturn activityHorizontal;\r\n\t}\r\n\t\r\n\tpublic void setActivityHorizontal(boolean horizontal) {\r\n\t\tactivityHorizontal = horizontal;\r\n\t}\r\n}",
"public class ModeSpec implements Serializable {\n\n\tprivate static final long serialVersionUID = 4294164511803037163L;\n\n\tprivate Layout layout;\n\t\n\tprivate int mode;\n\t\r\n\tprivate boolean landscape;\r\n\t\r\n\tpublic static final int LAYOUTS_SLIDE = 4;\n\tpublic static final int LAYOUTS_MOUSE = 3;\r\n\t/**\r\n\t * Absolute mouse positioning\r\n\t */\n\tpublic static final int LAYOUTS_MOUSE_ABS = 2;\n\tpublic static final int LAYOUTS_JS = 1;\n\tpublic Layout getLayout() {\n\t\treturn layout;\n\t}\n\tpublic void setLayout(Layout layout) {\n\t\tthis.layout = layout;\n\t}\r\n\tpublic int getMode() {\n\t\treturn mode;\n\t}\n\tpublic String getModeString() {\n\t\tswitch(mode) {\n\t\tcase LAYOUTS_JS:\n\t\t\treturn \"1\"; // Compatibility - old version assumes number = js mode\n\t\tcase LAYOUTS_MOUSE:\n\t\t\treturn \"mouse\";\n\t\tcase LAYOUTS_MOUSE_ABS:\n\t\t\treturn \"absmouse\";\n\t\tcase LAYOUTS_SLIDE:\n\t\t\treturn \"slide\";\n\t\t}\n\t\treturn \"other\";\n\t}\n\tpublic void setMode(int mode) {\n\t\tthis.mode = mode;\n\t}\r\n\tpublic boolean isLandscape() {\r\n\t\treturn landscape;\r\n\t}\r\n\tpublic void setLandscape(boolean landscape) {\r\n\t\tthis.landscape = landscape;\r\n\t}\r\n}",
"public enum Orientation {\n\tX,\n\tY,\n\tBoth\n}",
"public class Slider extends Item {\n\t\n\tprivate static final long serialVersionUID = -7180651801411890289L;\n\n\tpublic static final int SLIDER_TOT = 16384;\n\tpublic static final int SLIDER_CUTOFF = 700;\n\t\n\tpublic static final int SLIDER_GAP = 16;\n\tpublic static final int SLIDER_SIZE = 10;\n\t\n\tpublic final Orientation type;\n\t\n\t/**\n\t * Axis X direction thing\n\t */\n\tpublic int ax;\n\t/**\n\t * Axis Y direction thing\n\t */\n\tpublic int ay;\n\t\n\tprivate float tmpAx, tmpAy;\n\n\tpublic Slider(int x, int y, int sx, int sy, Orientation type) {\n\t\tsuper(x, y, sx, sy);\n\t\tthis.type = type;\n\t}\n\n\tpublic Slider(float x, float y, float sx, float sy, boolean free, Orientation type) {\n\t\tsuper(x, y, sx, sy, free);\n\t\tthis.type = type;\n\t}\n\n\t@Override\n\tpublic void drawInArea(Canvas c, RectF area, PointF centre, boolean landscape) {\n\t\tfloat tempXw = area.width() - (2 * SLIDER_GAP);\n\t\tfloat tempYw = area.height() - (2 * SLIDER_GAP);\n\n\t\tfloat posOnScreenX = ((float)ax / (float)SLIDER_TOT * tempXw / 2f) + centre.x;\n\t\tfloat posOnScreenY = ((float)ay / (float)SLIDER_TOT * tempYw / 2) + centre.y;\n\n\t\tif(type == Orientation.X || type == Orientation.Both)\n\t\t\tc.drawLine(posOnScreenX, area.top, posOnScreenX, area.bottom, pGrayBG);\n\t\t\n\t\tif(type == Orientation.Y || type == Orientation.Both)\n\t\t\tc.drawLine(area.left, posOnScreenY, area.right, posOnScreenY, pGrayBG);\n\t\t\n\t\tc.drawCircle(posOnScreenX, posOnScreenY, SLIDER_SIZE, pText);\n\t}\n\n\t@Override\n\tpublic String getOutputString() {\n\t\tswitch(type) {\n\t\tcase X:\n\t\t\treturn \"{S\" + ax + \"}\";\n\t\tcase Y:\n\t\t\treturn \"{S\" + ay + \"}\";\n\t\tcase Both:\n\t\tdefault:\n\t\t\treturn \"{A\" + ax + \",\" + ay + \"}\";\n\t\t}\n\t}\n\t\n\tprivate boolean axesFloat = false;\n\t\n\t/**\n\t * When axes are floating, they don't reset when let go of\n\t * @param axesFloat If true, axes will float.\n\t */\n\tpublic void setAxesFloat(boolean axesFloat) {\n\t\tthis.axesFloat = axesFloat;\n\t}\n\n\t@Override\n\tpublic void resetStickyLock() {\n\t\tif(!axesFloat) {\n\t\t\ttmpAx = 0;\n\t\t\ttmpAy = 0;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void finaliseState() {\n\t\tax = (int) tmpAx;\n\t\tay = (int) tmpAy;\n\t}\n\n\t@Override\n\tpublic void onMouseOn(ScreenInfo info, float x, float y) {\n\t\tPointF centre = pos.computeCentre(info);\n\t\tRectF area = pos.computeArea(info);\n\t\tfloat tempXw = area.width() - (2 * SLIDER_GAP);\n\t\tfloat tempYw = area.height() - (2 * SLIDER_GAP);\n\t\t\n\t\tif(type == Orientation.X || type == Orientation.Both)\n\t\t{\n\t\t\ttmpAx = ((float)(x - centre.x) / tempXw * 2f * SLIDER_TOT);\n\t\t\tif(tmpAx < -SLIDER_TOT)\n\t\t\t\ttmpAx = -SLIDER_TOT;\n\t\t\telse if(tmpAx > SLIDER_TOT)\n\t\t\t\ttmpAx = SLIDER_TOT;\n\t\t\tax = (int) tmpAx;\n\t\t}\n\t\tif(type == Orientation.Y || type == Orientation.Both)\n\t\t{\n\t\t\ttmpAy = ((y - centre.y) / tempYw * 2 * SLIDER_TOT);\n\t\t\tif(tmpAy < -SLIDER_TOT)\n\t\t\t\ttmpAy = -SLIDER_TOT;\n\t\t\telse if(tmpAy > SLIDER_TOT)\n\t\t\t\ttmpAy = SLIDER_TOT;\n\t\t\tay = (int) tmpAy;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onMouseOff() {\n\t}\r\n\r\n\t@Override\r\n\tint getFlags() {\r\n\t\tint extraFlags = 0;\r\n\t\t\r\n\t\tswitch(type) {\r\n\t\tcase X:\r\n\t\t\textraFlags = FLAG_HAS_X_AXIS;\r\n\t\t\tbreak;\r\n\t\tcase Y:\r\n\t\t\textraFlags = FLAG_HAS_Y_AXIS;\r\n\t\t\tbreak;\r\n\t\tcase Both:\r\n\t\t\textraFlags = FLAG_HAS_X_AXIS | FLAG_HAS_Y_AXIS;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t\treturn FLAG_SLIDER | extraFlags;\r\n\t}\r\n\r\n\t@Override\r\n\tint getData1() {\r\n\t\tswitch(type) {\r\n\t\tcase X:\r\n\t\tcase Both:\r\n\t\t\treturn ax;\r\n\t\tdefault:\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tint getData2() {\r\n\t\tswitch(type) {\r\n\t\tcase Y:\r\n\t\tcase Both:\r\n\t\t\treturn ay;\r\n\t\tdefault:\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tint getData3() {\r\n\t\treturn 0;\r\n\t}\n}",
"public class ToggleButton extends Button implements LogTag {\n\n\tprivate static final long serialVersionUID = -6001760405211069340L;\n\n\tpublic ToggleButton(int x, int y, int sx, int sy, String text) {\n\t\tsuper(x, y, sx, sy, text);\n\t}\n\n\tpublic ToggleButton(int x, int y, int sx, int sy, String text, int textSize) {\n\t\tsuper(x, y, sx, sy, text, textSize);\n\t}\r\n\t\n\tpublic ToggleButton(float x, float y, float sx, float sy, boolean free, String text, int textSize) {\n\t\tsuper(x, y, sx, sy, free, text, textSize);\n\t}\n\t\n\t@Override\n\tpublic void drawInArea(Canvas c, RectF area, PointF centre, boolean landscape) {\n\t\tsuper.drawInArea(c, area, centre, landscape);\n\t\t\n\t\tc.drawCircle(area.right - 10, area.bottom - 10, 5, isSelected() ? pTextS : pThinBorder);\n\t}\n\t\n\t@Override\n\tpublic void onMouseOn(ScreenInfo info, float x, float y) {\n\t\t// Do nothing.\n\t}\n\t\n\t@Override\n\tpublic void onMouseOff() {\n\t\tsuper.onMouseOff();\n\t\ttmpSelected = !tmpSelected;\n\t\tselected = !selected;\n\t\tLog.v(TAG, \"Released\");\n\t}\n\t\n\t@Override\n\tpublic void resetStickyLock() {\n\t\t\n\t}\r\n\t\n\t@Override\r\n\tint getFlags() {\r\n\t\treturn FLAG_TOGGLE_BUTTON;\r\n\t}\r\n}",
"public class TouchPanel extends Item implements LogTag {\n\t\n\tprivate static final long serialVersionUID = -8300732746587169324L;\n\n\tstatic final int SLIDER_TOT = 16384;\n\t\n\tstatic final int SLIDER_GAP = 16;\r\n\t\r\n\t/**\r\n\t * The maximum travelable distance for DP to consider\r\n\t * this event as a click on the first button. (A tap.)\r\n\t */\r\n\tstatic final int CLICK_THRESHOLD = 250;\r\n\t\r\n\t/**\r\n\t * The maximum time for DP to consider this event as a\r\n\t * click on the first button (short taps only).\r\n\t */\r\n\tstatic final float CLICK_TIME = 100f / 1000f;\n\t\n\tpublic final Orientation type;\n\t\n\t/**\n\t * Axis X direction thing\n\t */\n\tpublic int ax;\n\t/**\n\t * Axis Y direction thing\n\t */\n\tpublic int ay;\n\t\n\tprivate float tmpAx, tmpAy;\n\tprivate float startX, startY;\n\t\r\n\t// Used to calculate total distance onscreen.\r\n\tprivate float startTmpAx, startTmpAy;\n\t\r\n\tprivate long startTime;\n\n\tpublic TouchPanel(int x, int y, int sx, int sy, Orientation type) {\n\t\tsuper(x, y, sx, sy);\n\t\tthis.type = type;\n\t}\r\n\t\n\tpublic TouchPanel(float x, float y, float sx, float sy, boolean free, Orientation type) {\n\t\tsuper(x, y, sx, sy, free);\n\t\tthis.type = type;\n\t}\n\n\t@Override\n\tpublic void drawInArea(Canvas c, RectF area, PointF centre, boolean landscape) { }\n\n\t@Override\n\tpublic String getOutputString() {\n\t\tswitch(type) {\n\t\tcase X:\n\t\t\treturn \"{C\" + ax + \"}\";\n\t\tcase Y:\n\t\t\treturn \"{C\" + ay + \"}\";\n\t\tcase Both:\n\t\tdefault:\n\t\t\treturn \"{T\" + ax + \",\" + ay + \"}\";\n\t\t}\n\t}\n\t\n\tprivate boolean newRun = true, tmpNewRun = true;\n\n\t@Override\n\tpublic void resetStickyLock() {\n\t\ttmpNewRun = true;\n\t}\n\n\t@Override\n\tpublic void finaliseState() {\n\t\tnewRun = tmpNewRun;\n\t\tax = (int) (tmpAx + startX);\n\t\tay = (int) (tmpAy + startY);\n\t}\n\n\t@Override\n\tpublic void onMouseOn(ScreenInfo info, float x, float y) {\n\t\tPointF centre = pos.computeCentre(info);\n\t\tRectF area = pos.computeArea(info);\n\t\tfinal float tempXw = area.width() - (2 * SLIDER_GAP);\n\t\tfinal float tempYw = area.height() - (2 * SLIDER_GAP);\n\t\t\n\t\tif(type == Orientation.X || type == Orientation.Both) {\n\t\t\ttmpAx = ((float)(x - centre.x) / tempXw * 2f * SLIDER_TOT);\n\t\t\tif(tmpAx < -SLIDER_TOT)\n\t\t\t\ttmpAx = -SLIDER_TOT;\n\t\t\telse if(tmpAx > SLIDER_TOT)\n\t\t\t\ttmpAx = SLIDER_TOT;\n\t\t}\n\t\tif(type == Orientation.Y || type == Orientation.Both) {\n\t\t\ttmpAy = ((float)(y - centre.y) / tempYw * 2 * SLIDER_TOT);\n\t\t\tif(tmpAy < -SLIDER_TOT)\n\t\t\t\ttmpAy = -SLIDER_TOT;\n\t\t\telse if(tmpAy > SLIDER_TOT)\n\t\t\t\ttmpAy = SLIDER_TOT;\n\t\t}\n\t\t\n\t\tif(newRun) { // Reset, starting fresh if the start position wasn't anything\n\t\t\tnewRun = false;\n\t\t\tstartX = ax - tmpAx;\n\t\t\tstartY = ay - tmpAy;\n\t\t\tstartTmpAx = tmpAx;\r\n\t\t\tstartTmpAy = tmpAy;\r\n\t\t\tstartTime = System.nanoTime();\n\t\t}\n\t\ttmpNewRun = newRun;\n\t}\n\n\t@Override\n\tpublic void onMouseOff() {\n\t\tfloat dx = startTmpAx - tmpAx;\r\n\t\tfloat dy = startTmpAy - tmpAy;\r\n\t\tfloat dist = FloatMath.sqrt(dx * dx + dy * dy);\r\n\t\tfloat totalTime = (float)(System.nanoTime() - startTime) / 1000f / 1000f / 1000f;\r\n\t\tif(dist < CLICK_THRESHOLD && totalTime < CLICK_TIME) {\r\n\t\t\tif(callbacks != null)\r\n\t\t\t\tcallbacks.tapDefaultButton();\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tint getFlags() {\r\n\t\tint extraFlags = 0;\r\n\t\t\r\n\t\tswitch(type) {\r\n\t\tcase X:\r\n\t\t\textraFlags = FLAG_HAS_X_AXIS;\r\n\t\t\tbreak;\r\n\t\tcase Y:\r\n\t\t\textraFlags = FLAG_HAS_Y_AXIS;\r\n\t\t\tbreak;\r\n\t\tcase Both:\r\n\t\t\textraFlags = FLAG_HAS_X_AXIS | FLAG_HAS_Y_AXIS;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t\treturn FLAG_TRACKPAD | extraFlags;\r\n\t}\r\n\r\n\t@Override\r\n\tint getData1() {\r\n\t\tswitch(type) {\r\n\t\tcase X:\r\n\t\tcase Both:\r\n\t\t\treturn ax;\r\n\t\tdefault:\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tint getData2() {\r\n\t\tswitch(type) {\r\n\t\tcase Y:\r\n\t\tcase Both:\r\n\t\t\treturn ay;\r\n\t\tdefault:\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tint getData3() {\r\n\t\treturn 0;\r\n\t}\n}"
] | import java.io.IOException;
import java.io.Reader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import uk.digitalsquid.droidpad.LogTag;
import uk.digitalsquid.droidpad.buttons.Button;
import uk.digitalsquid.droidpad.buttons.Layout;
import uk.digitalsquid.droidpad.buttons.ModeSpec;
import uk.digitalsquid.droidpad.buttons.Orientation;
import uk.digitalsquid.droidpad.buttons.Slider;
import uk.digitalsquid.droidpad.buttons.ToggleButton;
import uk.digitalsquid.droidpad.buttons.TouchPanel;
import android.sax.Element;
import android.sax.ElementListener;
import android.sax.RootElement;
import android.sax.TextElementListener;
| /* This file is part of DroidPad.
*
* DroidPad 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 3 of the License, or
* (at your option) any later version.
*
* DroidPad 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 DroidPad. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.digitalsquid.droidpad.layout;
public class XmlDecoder implements LogTag {
private XmlDecoder() {}
private static final SAXParserFactory factory = SAXParserFactory.newInstance();
| public static final ModeSpec decodeLayout(Reader stream) throws IOException {
| 3 |
berlinguyinca/spectra-hash | core/src/main/java/edu/ucdavis/fiehnlab/spectra/hash/core/impl/SplashVersion1.java | [
"public interface Spectrum {\n\n /**\n * ion of a spectra\n * @return\n */\n public List<Ion> getIons();\n\n /**\n * convmerts the spectrum to a relative spectra\n * @return\n * @param scale\n */\n Spectrum toRelative(int scale);\n\n /**\n *\n * @return\n */\n String getOrigin();\n\n /**\n * what kind of a spectra do we have\n * @return\n */\n public SpectraType getType();\n}",
"public interface Splash {\n\n /**\n * generates a new spectra hash based on the given spectrum\n * @return\n */\n String splashIt(Spectrum spectrum);\n\n /**\n * adds an optional listener to the\n * @param listener\n */\n void addListener(SplashListener listener);\n}",
"public enum SplashBlock {\n FIRST,\n SECOND,\n THIRD\n}",
"public interface SplashListener {\n\n /**\n * let's listener know that a new hash was created\n * @param e\n */\n void eventReceived(SplashingEvent e);\n\n /**\n * notificaton that the hashing is finished\n * @param spectrum\n * @param splash\n */\n void complete(Spectrum spectrum, String splash);\n}",
"public class SplashingEvent {\n\n private final Spectrum spectrum;\n private final String processedValue;\n\n public SplashingEvent(String processedValue, String rawValue, SplashBlock block, Spectrum spectrum) {\n this.processedValue = processedValue;\n this.rawValue = rawValue;\n this.block = block;\n this.spectrum = spectrum;\n }\n\n private final String rawValue;\n\n public SplashBlock getBlock() {\n return block;\n }\n\n\n public String getRawValue() {\n return rawValue;\n }\n\n public String getProcessedValue() {\n return processedValue;\n }\n\n private final SplashBlock block;\n\n\n public Spectrum getSpectrum() {\n return spectrum;\n }\n}",
"public class MassThenIntensityComparator implements Comparator<Ion> {\n public int compare(Ion o1, Ion o2) {\n int result = o1.getMass().compareTo(o2.getMass());\n\n if (result == 0) {\n result = o2.getIntensity().compareTo(o1.getIntensity());\n }\n\n return result;\n }\n}",
"public class Ion implements Comparable<Ion> {\n private static String SEPERATOR = \":\";\n private static int PRECESSION = 6;\n\n private Double mass;\n private Double intensity;\n\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Ion)) return false;\n\n Ion ion = (Ion) o;\n\n if (!getMass().equals(ion.getMass())) return false;\n return getIntensity().equals(ion.getIntensity());\n\n }\n\n @Override\n public int hashCode() {\n int result = getMass().hashCode();\n result = 31 * result + getIntensity().hashCode();\n return result;\n }\n\n public Ion() {}\n\n public Ion(double mass, double intensity) {\n this.mass = mass;\n this.intensity = intensity;\n }\n\n public Double getIntensity() {\n return intensity;\n }\n\n public void setIntensity(Double intensity) {\n this.intensity = intensity;\n }\n\n public Double getMass() {\n return mass;\n }\n\n public void setMass(Double mass) {\n this.mass = mass;\n }\n\n public String toString() {\n return String.format(\"%.\"+PRECESSION+\"f\",this.getMass()) + SEPERATOR + String.format(\"%.\" + PRECESSION + \"f\", this.getIntensity());\n }\n\n public int compareTo(Ion o) {\n return getMass().compareTo(o.getMass());\n }\n}",
"public enum SpectraType {\n MS('1'),\n NMR('2'),\n UV('3'),\n IR('4'),\n RAMAN('5');\n\n /**\n * identifier has to be a single character\n */\n private final char identifier;\n\n /**\n * creates a new spectra type with the assoicated reference number\n *\n * @param referenceNumber\n */\n SpectraType(char referenceNumber) {\n this.identifier = referenceNumber;\n }\n\n /**\n * access to it's identifier\n *\n * @return\n */\n public char getIdentifier() {\n return this.identifier;\n }\n}",
"public class SpectrumImpl implements Spectrum {\n\n private String origin;\n private List<Ion> ions;\n private SpectraType type;\n\n public SpectrumImpl(List<Ion> ions, String origin, SpectraType type) {\n this.ions = ions;\n this.origin = origin;\n this.type = type;\n }\n\n\n protected SpectrumImpl(){\n\n }\n\n public SpectrumImpl(List<Ion> ions, SpectraType ms) {\n this(ions,\"unknown\",ms);\n\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n }\n\n public SpectraType getType() {\n return type;\n }\n\n public void setType(SpectraType type) {\n this.type = type;\n }\n\n public List<Ion> getIons() {\n return ions;\n }\n\n public void setIons(List<Ion> ions) {\n this.ions = ions;\n }\n\n\n public Spectrum toRelative(int scale) {\n double max = 0;\n\n for (Ion ion : getIons()) {\n if (ion.getIntensity() > max) {\n max = ion.getIntensity();\n }\n }\n\n ArrayList<Ion> ions = new ArrayList<Ion>(getIons().size());\n for (Ion ion : getIons()) {\n ions.add(new Ion(ion.getMass(), ion.getIntensity() / max * scale));\n }\n return new SpectrumImpl(ions, getOrigin(), getType());\n }\n\n}"
] | import edu.ucdavis.fiehnlab.spectra.hash.core.Spectrum;
import edu.ucdavis.fiehnlab.spectra.hash.core.Splash;
import edu.ucdavis.fiehnlab.spectra.hash.core.listener.SplashBlock;
import edu.ucdavis.fiehnlab.spectra.hash.core.listener.SplashListener;
import edu.ucdavis.fiehnlab.spectra.hash.core.listener.SplashingEvent;
import edu.ucdavis.fiehnlab.spectra.hash.core.sort.IntensityThenMassComparator;
import edu.ucdavis.fiehnlab.spectra.hash.core.sort.MassThenIntensityComparator;
import edu.ucdavis.fiehnlab.spectra.hash.core.types.Ion;
import edu.ucdavis.fiehnlab.spectra.hash.core.types.SpectraType;
import edu.ucdavis.fiehnlab.spectra.hash.core.types.SpectrumImpl;
import org.apache.commons.codec.digest.DigestUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque; | package edu.ucdavis.fiehnlab.spectra.hash.core.impl;
/**
* the reference implementation of the Spectral Hash Key
*/
public class SplashVersion1 implements Splash {
private static final int PREFILTER_BASE = 3;
private static final int PREFILTER_LENGTH = 10;
private static final int PREFILTER_BIN_SIZE = 5;
private static final int SIMILARITY_BASE = 10;
private static final int SIMILARITY_LENGTH = 10;
private static final int SIMILARITY_BIN_SIZE = 100;
private static final char[] BASE_36_MAP = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
};
/**
* how to scale the spectrum
*/
public static final int scalingOfRelativeIntensity = 100;
/**
* how should ions in the string representation be separeted
*/
private static final String ION_SEPERATOR = " ";
/**
* how many character should be in the spectrum block. Basically this reduces the SHA256 code down
* to a fixed length of N characater
*/
private static final int maxCharactersForSpectrumBlockTruncation = 20;
/**
* Fixed precission of masses
*/
private static final int fixedPrecissionOfMasses = 6;
/**
* factor to scale m/z floating point values
*/
private static final long MZ_PRECISION_FACTOR = (long)Math.pow(10, fixedPrecissionOfMasses);
/**
* Fixed precission of intensites
*/
private static final int fixedPrecissionOfIntensities = 0;
/**
* factor to scale m/z floating point values
*/
private static final long INTENSITY_PRECISION_FACTOR = (long)Math.pow(10, fixedPrecissionOfIntensities);
/**
* Correction factor to avoid floating point issues between implementations
* and processor architectures
*/
private static final double EPS_CORRECTION = 1.0e-7;
/**
* registered listeneres
*/
private ConcurrentLinkedDeque<SplashListener> listeners = new ConcurrentLinkedDeque<SplashListener>();
/**
* adds a new listener
*
* @param listener listener
*/
public void addListener(SplashListener listener) {
this.listeners.add(listener);
}
/**
* notify listeners
*
* @param e event
*/ | protected void notifyListener(SplashingEvent e) { | 4 |
piyell/NeteaseCloudMusic | app/src/main/java/com/zsorg/neteasecloudmusic/activities/ConfigActivity.java | [
"public class ConfigAdapter extends RecyclerView.Adapter<ConfigHolder> implements OnItemCLickListener {\n\n private final LayoutInflater mInflater;\n private List<ConfigBean> mList;\n private OnItemCLickListener onItemCLickListener;\n\n public ConfigAdapter(LayoutInflater layoutInflater) {\n super();\n mInflater = layoutInflater;\n }\n\n @Override\n public ConfigHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n ConfigHolder holder = new ConfigHolder(mInflater.inflate(R.layout.config_item, parent, false));\n holder.setOnItemClickListener(this);\n return holder;\n }\n\n @Override\n public void onBindViewHolder(final ConfigHolder holder, int position) {\n final ConfigBean bean = mList.get(position);\n\n if (bean.isSwitchVisible()) {\n holder.setSwitchVisible(true);\n holder.scRight.setChecked(bean.isSwitchChecked());\n } else {\n holder.setSwitchVisible(false);\n holder.tvRight.setText(bean.getItemRight());\n }\n holder.tvGroup.setVisibility(bean.getGroupTitle()==null? View.GONE: View.VISIBLE);\n holder.tvGroup.setText(bean.getGroupTitle());\n holder.tvTitle.setText(bean.getItemTitle());\n holder.bottom.setVisibility(bean.isBottomVisible()? View.VISIBLE: View.GONE);\n holder.tvContent.setText(bean.getItemContent());\n holder.tvContent.setVisibility(bean.getItemContent() == null ? View.GONE : View.VISIBLE);\n\n holder.scRight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton compoundButton, boolean b) {\n ConfigModel.getInstance(holder.tvTitle.getContext()).setIsFilter60s(b);\n }\n });\n\n }\n\n\n\n public void setDataList(List<ConfigBean> list) {\n mList = list;\n notifyDataSetChanged();\n }\n\n public ConfigBean getDataAtPos(int position) {\n return mList==null?null:mList.get(position);\n }\n\n @Override\n public int getItemCount() {\n return mList==null?0:mList.size();\n }\n\n public void setOnItemClickListener(OnItemCLickListener listener) {\n onItemCLickListener = listener;\n }\n\n @Override\n public void onItemClick(View view, int position) {\n AlertUtil.showChooseMusicOrderDialog(view.getContext());\n if (null != onItemCLickListener) {\n onItemCLickListener.onItemClick(view,position);\n }\n }\n}",
"public class LineItemDecorator extends RecyclerView.ItemDecoration {\n\n private static LineItemDecorator lineItemDecorator;\n private int dimension;\n private boolean isDrawHorizontal=false;\n private boolean isDrawVertical=true;\n\n public LineItemDecorator() {\n super();\n }\n\n public void recycle() {\n lineItemDecorator = null;\n }\n\n public void setDrawHorizontal(boolean isDraw) {\n isDrawHorizontal = isDraw;\n }\n\n public void setDrawVertical(boolean isDraw) {\n isDrawVertical = isDraw;\n }\n\n public static LineItemDecorator getInstance() {\n if (null == lineItemDecorator) {\n synchronized (LineItemDecorator.class) {\n lineItemDecorator = new LineItemDecorator();\n }\n }\n return lineItemDecorator;\n }\n\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {\n super.getItemOffsets(outRect, view, parent, state);\n if (isDrawVertical) {\n outRect.top = 1;\n// outRect.left = dimension;\n// outRect.right = dimension;\n outRect.bottom = 1;\n }\n if (isDrawHorizontal){\n outRect.left = 1;\n// outRect.left = dimension;\n// outRect.right = dimension;\n outRect.right = 1;\n }\n }\n\n\n @Override\n public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {\n super.onDraw(c, parent, state);\n if (isDrawHorizontal) {\n drawHrozontal(c, parent);\n }\n if (isDrawVertical){\n drawVertical(c, parent);\n }\n }\n\n\n\n private void drawVertical(Canvas c, RecyclerView parent) {\n int childCount = parent.getChildCount();\n if (childCount<1)return;\n// int left = parent.getPaddingLeft()+leftView.getLeft()+leftView.getPaddingLeft();\n int left = parent.getPaddingLeft();\n int right = parent.getWidth() - parent.getPaddingRight();\n\n Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);\n paint.setColor(Color.LTGRAY);\n for (int i = 0; i < childCount; i++) {\n View child = parent.getChildAt(i);\n RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child\n .getLayoutParams();\n int top = child.getBottom()+params.bottomMargin;\n int bottom = top + 1;\n c.drawRect(left, top, right, bottom, paint);\n }\n }\n\n private void drawHrozontal(Canvas c, RecyclerView parent) {\n int childCount = parent.getChildCount();\n if (childCount<1)return;\n// int left = parent.getPaddingLeft()+leftView.getLeft()+leftView.getPaddingLeft();\n int top = parent.getPaddingTop();\n int bottom = parent.getHeight() - parent.getPaddingBottom();\n\n Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);\n paint.setColor(Color.LTGRAY);\n for (int i = 0; i < childCount-1; i++) {\n View child = parent.getChildAt(i);\n RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child\n .getLayoutParams();\n int left = child.getRight()+params.rightMargin;\n int right = left + 1;\n c.drawRect(left, top, right, bottom, paint);\n\n }\n }\n\n}",
"public class ConfigBean {\n private String mGroupTitle;\n private String mItemTitle;\n private String mItemContent;\n private String mItemRight;\n private boolean mSwitchVisible;\n private boolean mIsSwitchChecked;\n private boolean mIsBottomVisible;\n\n public ConfigBean(String groupTitle, String itemTitle, String content, String itemRight, boolean isSwitchVisible, boolean isSwitchChecked, boolean isBottomVisible) {\n mGroupTitle = groupTitle;\n mItemTitle = itemTitle;\n mItemContent = content;\n mItemRight = itemRight;\n mSwitchVisible = isSwitchVisible;\n mIsSwitchChecked = isSwitchChecked;\n mIsBottomVisible = isBottomVisible;\n }\n\n public String getGroupTitle() {\n return mGroupTitle;\n }\n\n public void setGroupTitle(String mGroupTitle) {\n this.mGroupTitle = mGroupTitle;\n }\n\n public String getItemTitle() {\n return mItemTitle;\n }\n\n public void setItemTitle(String mItemTitle) {\n this.mItemTitle = mItemTitle;\n }\n\n public String getItemContent() {\n return mItemContent;\n }\n\n public void setItemContent(String mItemContent) {\n this.mItemContent = mItemContent;\n }\n\n public String getItemRight() {\n return mItemRight;\n }\n\n public void setItemRight(String mItemRight) {\n this.mItemRight = mItemRight;\n }\n\n public boolean isSwitchVisible() {\n return mSwitchVisible;\n }\n\n public void setRightVisible(boolean mRightVisible) {\n this.mSwitchVisible = mRightVisible;\n }\n\n public void setSwitchChecked(boolean isChecked) {\n this.mIsSwitchChecked = isChecked;\n }\n\n public boolean isSwitchChecked() {\n return mIsSwitchChecked;\n }\n\n public boolean isBottomVisible() {\n return mIsBottomVisible;\n }\n\n public void setIsBottomVisible(boolean mIsBottomVisible) {\n this.mIsBottomVisible = mIsBottomVisible;\n }\n}",
"public class ConfigPresenter implements ConfigCallback {\n\n private final IConfigView configView;\n private ConfigModel mModel;\n\n public ConfigPresenter(IConfigView configView) {\n this.configView = configView;\n }\n\n public void requestLoadingList() {\n Observable.create(new ObservableOnSubscribe<List<ConfigBean>>() {\n @Override\n public void subscribe(ObservableEmitter<List<ConfigBean>> e) throws Exception {\n mModel = ConfigModel.getInstance(configView.getContext());\n e.onNext(mModel.getConfigList());\n mModel.setConfigCallback(ConfigPresenter.this);\n }\n })\n .observeOn(Schedulers.io())\n .subscribeOn(AndroidSchedulers.mainThread())\n .subscribe(new Consumer<List<ConfigBean>>() {\n @Override\n public void accept(List<ConfigBean> list) throws Exception {\n configView.displayConfigList(list);\n }\n });\n\n }\n\n public void setMusicOrder(int order) {\n mModel.setMusicOrder(order);\n }\n\n public int getMusicOrder() {\n return mModel.getMusicOrder();\n }\n\n public void setIsFilter60s(boolean isFilter) {\n mModel.setIsFilter60s(isFilter);\n }\n\n @Override\n public void onMusicOrderConfigChanged(int newOrder) {\n configView.displayConfigList(mModel.getConfigList());\n }\n\n @Override\n public void onIsShow60sConfigChanged(boolean isShow) {\n configView.displayConfigList(mModel.getConfigList());\n }\n}",
"public interface IConfigView {\n void displayConfigList(List<ConfigBean> list);\n\n Context getContext();\n}"
] | import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.zsorg.neteasecloudmusic.adapters.ConfigAdapter;
import com.zsorg.neteasecloudmusic.LineItemDecorator;
import com.zsorg.neteasecloudmusic.R;
import com.zsorg.neteasecloudmusic.models.beans.ConfigBean;
import com.zsorg.neteasecloudmusic.presenters.ConfigPresenter;
import com.zsorg.neteasecloudmusic.views.IConfigView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife; | package com.zsorg.neteasecloudmusic.activities;
public class ConfigActivity extends AppCompatActivity implements View.OnClickListener, IConfigView {
@BindView(R.id.rv_config)
RecyclerView rvConfig;
private ConfigAdapter mAdapter;
private ConfigPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_config);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (null!=actionBar) {
actionBar.setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(this);
}
ButterKnife.bind(this);
rvConfig.setLayoutManager(new LinearLayoutManager(this)); | rvConfig.addItemDecoration(LineItemDecorator.getInstance()); | 1 |
ykaragol/checkersmaster | CheckersMaster/test/checkers/algorithm/TestGreedyAlgorithm.java | [
"public class CalculationContext{\r\n\r\n\tprivate int depth;\r\n\tprivate Player player;\r\n\tprivate IEvaluation evaluationFunction;\r\n\tprivate ISuccessor successorFunction;\r\n\tprivate IAlgorithm algorithm;\r\n\r\n\r\n\tpublic void setDepth(int depth) {\r\n\t\tthis.depth = depth;\r\n\t}\r\n\r\n\tpublic int getDepth() {\r\n\t\treturn depth;\r\n\t}\r\n\r\n\tpublic void setEvaluationFunction(IEvaluation evaluation) {\r\n\t\tthis.evaluationFunction = evaluation;\r\n\t}\r\n\r\n\tpublic IEvaluation getEvaluationFunction() {\r\n\t\treturn evaluationFunction;\r\n\t}\r\n\r\n\tpublic Player getPlayer() {\r\n\t\treturn player;\r\n\t}\r\n\r\n\tpublic void setPlayer(Player player) {\r\n\t\tthis.player = player;\r\n\t}\r\n\r\n\tpublic void setSuccessorFunction(ISuccessor successor) {\r\n\t\tthis.successorFunction = successor;\r\n\t}\r\n\r\n\tpublic ISuccessor getSuccessorFunction() {\r\n\t\treturn successorFunction;\r\n\t}\r\n\r\n\tpublic void setAlgorithm(IAlgorithm algorithm) {\r\n\t\tthis.algorithm = algorithm;\r\n\t}\r\n\r\n\tpublic IAlgorithm getAlgorithm() {\r\n\t\treturn algorithm;\r\n\t}\r\n\r\n}\r",
"public class Model {\r\n\t\r\n\tpublic SquareState state[][];\r\n\tprivate GameCenter callBack;\r\n\r\n\tpublic void baslat(){\r\n\t\tSquareState ilk[][] = {\r\n\t\t\t\t{SquareState.WHITE,SquareState.BLANK,SquareState.WHITE,SquareState.BLANK,SquareState.WHITE,SquareState.BLANK,SquareState.WHITE,SquareState.BLANK},\r\n\t\t\t\t{SquareState.BLANK,SquareState.WHITE,SquareState.BLANK,SquareState.WHITE,SquareState.BLANK,SquareState.WHITE,SquareState.BLANK,SquareState.WHITE},\r\n\t\t\t\t{SquareState.WHITE,SquareState.BLANK,SquareState.WHITE,SquareState.BLANK,SquareState.WHITE,SquareState.BLANK,SquareState.WHITE,SquareState.BLANK},\r\n\t\t\t\t{SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK},\r\n\t\t\t\t{SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK,SquareState.BLANK},\r\n\t\t\t\t{SquareState.BLANK,SquareState.BLACK,SquareState.BLANK,SquareState.BLACK,SquareState.BLANK,SquareState.BLACK,SquareState.BLANK,SquareState.BLACK},\r\n\t\t\t\t{SquareState.BLACK,SquareState.BLANK,SquareState.BLACK,SquareState.BLANK,SquareState.BLACK,SquareState.BLANK,SquareState.BLACK,SquareState.BLANK},\r\n\t\t\t\t{SquareState.BLANK,SquareState.BLACK,SquareState.BLANK,SquareState.BLACK,SquareState.BLANK,SquareState.BLACK,SquareState.BLANK,SquareState.BLACK},\r\n\t\t};\r\n\t\tstate = ilk;\r\n\t}\r\n\r\n\tpublic void bos(){\r\n\t\tSquareState[][] bos = new SquareState[8][8];\r\n\t\tfor (int i = 0; i < bos.length; i++) {\r\n\t\t\tfor (int j = 0; j < bos[i].length; j++) {\r\n\t\t\t\tbos[i][j] = SquareState.BLANK;\r\n\t\t\t}\r\n\t\t}\r\n\t\tstate = bos;\r\n\t}\r\n\t\r\n\tpublic void tryMove(Move move) {\r\n\t\tstate[move.toX][move.toY]=state[move.fromX][move.fromY];\r\n\t\tstate[move.fromX][move.fromY] = SquareState.BLANK;\r\n\t\tif(move.must){\r\n\t\t\tmove.eat = state[(move.toX+move.fromX)/2][(move.toY+move.fromY)/2];\r\n\t\t\tstate[(move.toX+move.fromX)/2][(move.toY+move.fromY)/2] = SquareState.BLANK;\r\n\t\t}\r\n\t\tif(move.toX>move.fromX)\r\n\t\t\tif(move.toX == 7 && (state[move.toX][move.toY]==SquareState.BLACK || state[move.toX][move.toY]==SquareState.WHITE)){\r\n\t\t\t\tstate[move.toX][move.toY]=state[move.toX][move.toY].convertKing();\r\n\t\t\t\tmove.convert = true;\r\n\t\t\t}\r\n\t\tif(move.toX<move.fromX)\r\n\t\t\tif(move.toX == 0 && (state[move.toX][move.toY]==SquareState.BLACK || state[move.toX][move.toY]==SquareState.WHITE)){\r\n\t\t\t\tstate[move.toX][move.toY]=state[move.toX][move.toY].convertKing();\r\n\t\t\t\tmove.convert = true;\r\n\t\t\t}\r\n\t\tif(move.nextMustMove != null)\r\n\t\t\ttryMove(move.nextMustMove);\r\n\t}\r\n\r\n\tpublic void doMove(Move move) {\r\n\t\tstate[move.toX][move.toY]=state[move.fromX][move.fromY];\r\n\t\tstate[move.fromX][move.fromY] = SquareState.BLANK;\r\n\t\tif(Math.abs(move.toX-move.fromX)>1){\r\n\t\t\tmove.eat = state[(move.toX+move.fromX)/2][(move.toY+move.fromY)/2];\r\n\t\t\tstate[(move.toX+move.fromX)/2][(move.toY+move.fromY)/2] = SquareState.BLANK;\r\n\t\t}\r\n\t\tif(move.toX>move.fromX)\r\n\t\t\tif(move.toX == 7 )\r\n\t\t\t\tstate[move.toX][move.toY]=state[move.toX][move.toY].convertKing();\r\n\t\tif(move.toX<move.fromX)\r\n\t\t\tif(move.toX == 0 )\r\n\t\t\t\tstate[move.toX][move.toY]=state[move.toX][move.toY].convertKing();\r\n\t\tif(move.nextMustMove != null)\r\n\t\t\tdoMove(move.nextMustMove);\r\n\t\telse\r\n\t\t\tcallBack.update();\r\n\t}\r\n\t\r\n\t\r\n\tpublic void undoTryMove(Move move) {\r\n\t\tif(move.nextMustMove != null)\r\n\t\t\tundoTryMove(move.nextMustMove);\r\n\t\tundoTryMoveHelper(move);\r\n\t}\r\n\r\n\tprivate void undoTryMoveHelper(Move move) {\r\n\t\tstate[move.fromX][move.fromY]=state[move.toX][move.toY];\r\n\t\tstate[move.toX][move.toY] = SquareState.BLANK;\r\n\t\tif(move.eat != null){\r\n\t\t\tstate[(move.toX+move.fromX)/2][(move.toY+move.fromY)/2] = move.eat;\r\n\t\t}\r\n\t\tif(move.toX>move.fromX)\r\n\t\t\tif(move.toX == 7 && move.convert)\r\n\t\t\t\tstate[move.fromX][move.fromY]=state[move.fromX][move.fromY].convertNormal();\r\n\t\tif(move.toX<move.fromX)\r\n\t\t\tif(move.toX == 0 && move.convert)\r\n\t\t\t\tstate[move.fromX][move.fromY]=state[move.fromX][move.fromY].convertNormal();\r\n\t}\r\n\t\r\n\tpublic void setCallback(GameCenter gameCenter){\r\n\t\tthis.callBack = gameCenter;\r\n\t}\r\n}\r",
"public class Move {\r\n\tprivate double value = Double.NEGATIVE_INFINITY;\r\n\tpublic int fromX;\r\n\tpublic int fromY;\r\n\tpublic int toX;\r\n\tpublic int toY;\r\n\tpublic boolean must = false;\r\n\tpublic SquareState eat;\r\n\tpublic Move next;\r\n\tpublic boolean convert;\r\n\tpublic Move nextMustMove;\r\n\r\n\tpublic double getValue() {\r\n\t\treturn value;\r\n\t}\r\n\r\n\tpublic void setValue(double value) {\r\n\t\tthis.value = value;\r\n\t}\r\n\r\n}\r",
"public enum Player {\r\n\tWHITE,\r\n\tBLACK;\r\n\r\n\tpublic Player opposite() {\r\n\t\treturn this==WHITE ? BLACK : WHITE;\r\n\t}\r\n}\r",
"public class MenCountEvaluation implements IEvaluation{\r\n\t\r\n\t@Override\r\n\tpublic double evaluate(Model m, Player player){\r\n\t\tint count = 0;\r\n\t\tSquareState[][] state = m.state;\r\n\t\tfor (int i = 0; i < state.length; i++) {\r\n\t\t\tfor (int j = 0; j < state[i].length; j++) {\r\n\t\t\t\tSquareState currentSquare = state[i][j];\r\n\t\t\t\tif(currentSquare == null){\r\n\t\t\t\t\tString msg = String.format(\"Cell [%d,%d] is null\", i,j);\r\n\t\t\t\t\tthrow new IllegalStateException(msg);\r\n\t\t\t\t}\r\n\t\t\t\tswitch (currentSquare) {\r\n\t\t\t\t\tcase BLACK:\r\n\t\t\t\t\t\tcount ++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase KING_BLACK:\r\n\t\t\t\t\t\tcount ++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase WHITE:\r\n\t\t\t\t\t\tcount --;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase KING_WHITE:\r\n\t\t\t\t\t\tcount --;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn count * (player==Player.BLACK ? 1:-1);\r\n\t}\t\t\r\n}\r",
"public class Successors implements ISuccessor{\r\n\t\r\n\t@Override\r\n\tpublic List<Move> getSuccessors(Model model, Player player) {\r\n\t\tLinkedList<Move> list = new LinkedList<Move>();\r\n\t\tSquareState[][] state = model.state;\r\n\t\tfor (int i=0; i<state.length; i++){\r\n\t\t\tfor (int j=0; j<state[i].length; j++){\r\n\t\t\t\tif(state[i][j].owner == player)\r\n\t\t\t\t\thandleStone(list, model, i, j);\r\n\t\t\t}\r\n\t\t}\r\n\t\thandleList(list);\r\n\t\treturn list;\r\n\t}\r\n\r\n\tprivate boolean handleList(LinkedList<Move> list) {\r\n\t\tboolean hasMust = false;\r\n\t\tfor (Move move : list) {\r\n\t\t\tif(move.must){\r\n\t\t\t\thasMust = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(hasMust){\r\n\t\t\tLinkedList<Move> linkedList = new LinkedList<Move>(list);\r\n\t\t\tfor (Move move : linkedList) {\r\n\t\t\t\tif(!move.must){\r\n\t\t\t\t\tlist.remove(move);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn hasMust;\r\n\t}\r\n\t\r\n\r\n\tpublic void handleStone(LinkedList<Move> list, Model model, int i, int j){\r\n\t\tSquareState[][] state = model.state;\r\n\t\tif(state[i][j] == SquareState.BLANK)\r\n\t\t\treturn;\r\n\t\tList<Move> eatList = eatMoveList(model, i, j);\r\n\t\tif(eatList != null && eatList.size()>0){\r\n\t\t\tlist.addAll(eatList);\r\n\t\t}else{\r\n\t\t\tList<Move> moveList = normalMoveList(model, i, j);\r\n\t\t\tlist.addAll(moveList);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate List<Move> normalMoveList(Model model, int i, int j) {\r\n\t\tLinkedList<Move> moveList = new LinkedList<Move>();\r\n\t\tSquareState[][] state = model.state;\r\n\t\tSquareState currentSquare = state[i][j];\r\n\t\tDirection[] directions = getDirections(currentSquare);\r\n\t\tfor (Direction direction : directions) {\r\n\t\t\tSquareState next = null;\r\n\t\t\tint toX = -1, toY = -1;\r\n\t\t\tswitch (direction) {\r\n\t\t\t\tcase RIGHT_BUTTOM:\r\n\t\t\t\t\tnext = rightButtom(state, i, j);\r\n\t\t\t\t\ttoX = i-1;\r\n\t\t\t\t\ttoY = j+1;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase RIGHT_FORWARD:\r\n\t\t\t\t\tnext = rightForward(state, i, j);\r\n\t\t\t\t\ttoX = i+1;\r\n\t\t\t\t\ttoY = j+1;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase LEFT_BUTTOM:\r\n\t\t\t\t\tnext = leftButtom(state, i, j);\r\n\t\t\t\t\ttoX = i-1;\r\n\t\t\t\t\ttoY = j-1;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase LEFT_FORWARD:\r\n\t\t\t\t\tnext = leftForward(state, i, j);\r\n\t\t\t\t\ttoX = i+1;\r\n\t\t\t\t\ttoY = j-1;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault: \r\n\t\t\t\t\tthrow new IllegalStateException(\"No default value\");\r\n\t\t\t}\r\n\t\t\tboolean canGo = next==SquareState.BLANK;\r\n\t\t\tif(canGo){\r\n\t\t\t\tMove move = createNormalMove(i, j, toX, toY);\r\n\t\t\t\tmoveList.add(move);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\treturn moveList;\r\n\t}\r\n\r\n\t//Gelen elemanın (i,j) bir taş olduğunu kabullenir.\r\n\tprivate List<Move> eatMoveList(Model model, int i, int j) {\r\n\t\tLinkedList<Move> eatList = new LinkedList<Move>();\r\n\t\tSquareState[][] state = model.state;\r\n\t\tSquareState currentSquare = state[i][j];\r\n\t\tDirection[] directions = getDirections(currentSquare);\r\n\t\tfor (Direction direction : directions) {\r\n\t\t\tSquareState twoNext = null, next = null;\r\n\t\t\tint toX = -1, toY = -1;\r\n\t\t\tswitch (direction) {\r\n\t\t\t\tcase RIGHT_BUTTOM:\r\n\t\t\t\t\ttwoNext = twoRightButtom(state, i, j);\r\n\t\t\t\t\tnext = rightButtom(state, i, j);\r\n\t\t\t\t\ttoX = i-2;\r\n\t\t\t\t\ttoY = j+2;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase RIGHT_FORWARD:\r\n\t\t\t\t\ttwoNext = twoRightForward(state, i, j);\r\n\t\t\t\t\tnext = rightForward(state, i, j);\r\n\t\t\t\t\ttoX = i+2;\r\n\t\t\t\t\ttoY = j+2;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase LEFT_BUTTOM:\r\n\t\t\t\t\ttwoNext = twoLeftButtom(state, i, j);\r\n\t\t\t\t\tnext = leftButtom(state, i, j);\r\n\t\t\t\t\ttoX = i-2;\r\n\t\t\t\t\ttoY = j-2;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase LEFT_FORWARD:\r\n\t\t\t\t\ttwoNext = twoLeftForward(state, i, j);\r\n\t\t\t\t\tnext = leftForward(state, i, j);\r\n\t\t\t\t\ttoX = i+2;\r\n\t\t\t\t\ttoY = j-2;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tthrow new IllegalStateException(\"No default value\");\r\n\t\t\t}\r\n\t\t\tif(twoNext != null && next != null){\r\n\t\t\t\tboolean canEat = next.owner != null && \r\n\t\t\t\t\t\tnext.owner != currentSquare.owner && \r\n\t\t\t\t\t\ttwoNext == SquareState.BLANK;\r\n\t\t\t\tif(canEat){\r\n\t\t\t\t\tMove move = createEatMove(i, j, toX, toY);\r\n\t\t\t\t\tmodel.tryMove(move);\r\n\t\t\t\t\tList<Move> nextList = eatMoveList(model, toX, toY);\r\n\t\t\t\t\tif(nextList != null && nextList.size()>0){\r\n\t\t\t\t\t\tfor (Move nextMove : nextList) {\r\n\t\t\t\t\t\t\tMove currentMove = createEatMove(i, j, toX, toY);\r\n\t\t\t\t\t\t\tcurrentMove.nextMustMove = nextMove;\r\n\t\t\t\t\t\t\t//currentMove.convert = move.convert;\r\n\t\t\t\t\t\t\teatList.add(currentMove);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tMove currentMove = createEatMove(i, j, toX, toY);\r\n\t\t\t\t\t\tcurrentMove.nextMustMove = null;\r\n\t\t\t\t\t\t//currentMove.convert = move.convert;\r\n\t\t\t\t\t\teatList.add(currentMove);\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\tmodel.undoTryMove(move);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn eatList;\r\n\t}\r\n\r\n\tprivate Move createNormalMove(int i, int j, int toX, int toY) {\r\n\t\tMove move = createMove(i, j, toX, toY);\r\n\t\tmove.must = false;\r\n\t\treturn move;\r\n\t}\r\n\r\n\tprivate Move createEatMove(int i, int j, int toX, int toY) {\r\n\t\tMove move = createMove(i, j, toX, toY);\r\n\t\tmove.must = true;\r\n\t\treturn move;\r\n\t}\r\n\r\n\tprivate Move createMove(int i, int j, int toX, int toY) {\r\n\t\tMove move = new Move();\r\n\t\tmove.fromX = i;\r\n\t\tmove.fromY = j;\r\n\t\tmove.toX = toX;\r\n\t\tmove.toY = toY;\r\n\t\treturn move;\r\n\t}\r\n\t\r\n\tprivate Direction[] getDirections(SquareState squareState) {\r\n\t\tif(squareState.owner == null)\r\n\t\t\treturn null;\r\n\t\tif(squareState.isKing()){\r\n\t\t\treturn kingDirections;\r\n\t\t}\r\n\t\tif(squareState.owner == Player.WHITE){\r\n\t\t\treturn whiteDirections;\r\n\t\t}\r\n\t\tif(squareState.owner == Player.BLACK){\r\n\t\t\treturn blackDirections;\r\n\t\t}\r\n\t\tthrow new IllegalStateException(\"bu durum gerçekleşemez!\");\r\n\t}\r\n\r\n\tenum Direction{\r\n\t\tRIGHT_FORWARD,\r\n\t\tLEFT_FORWARD,\r\n\t\tRIGHT_BUTTOM,\r\n\t\tLEFT_BUTTOM\r\n\t}\r\n\t\r\n\tprivate final static Direction[] kingDirections = Direction.values();\r\n\tprivate final static Direction[] whiteDirections = new Direction[]{Direction.RIGHT_FORWARD, Direction.LEFT_FORWARD};\r\n\tprivate final static Direction[] blackDirections = new Direction[]{Direction.RIGHT_BUTTOM, Direction.LEFT_BUTTOM};\r\n\t\r\n\t\r\n\t//iki sol altın değerini getirir\r\n\tprivate SquareState twoLeftButtom(SquareState[][] state, int i, int j) {\r\n\t\tif(i-2>=0 && j-2 >= 0){\r\n\t\t\treturn state[i-2][j-2];\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t//sol altın değerini getirir\r\n\tprivate SquareState leftButtom(SquareState[][] state, int i, int j) {\r\n\t\tif(i-1>=0 && j-1 >= 0){\r\n\t\t\treturn state[i-1][j-1];\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t//iki sağ altın değerini getirir\r\n\tprivate SquareState twoRightButtom(SquareState[][] state, int i, int j) {\r\n\t\tif(buttomCheck(state, i)){\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif( i-2 >= 0 && j+2 < state[i].length){\r\n\t\t\treturn state[i-2][j+2];\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t//sağ altın değerini getirir\r\n\tprivate SquareState rightButtom(SquareState[][] state, int i, int j) {\r\n\t\tif(buttomCheck(state, i)){\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif(i-1>=0 && j+1 < state[i].length){\r\n\t\t\treturn state[i-1][j+1];\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprivate SquareState twoRightForward(SquareState[][] state, int i, int j) {\r\n\t\tif( i+2 < state.length && j+2 < state[i].length){\r\n\t\t\treturn state[i+2][j+2];\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tprivate SquareState twoLeftForward(SquareState[][] state, int i, int j) {\r\n\t\tif( i+2 < state.length && j-2 >= 0){\r\n\t\t\treturn state[i+2][j-2];\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\r\n\t//sol önün değerini getirir..\r\n\tprivate SquareState leftForward(SquareState[][] state, int i, int j) {\r\n\t\tif(forwardCheck(state, i)){\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif(j-1 >= 0){\r\n\t\t\treturn state[i+1][j-1];\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t//sağ önün değerini getirir..\r\n\tprivate SquareState rightForward(SquareState[][] state, int i, int j) {\r\n\t\tif(forwardCheck(state, i)){\r\n\t\t\treturn null;\r\n\t\t}\t\t\t\r\n\t\tif(j+1 < state[i].length){\r\n\t\t\treturn state[i+1][j+1];\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t//ileriye gidebilir mi?\r\n\tprivate boolean forwardCheck(SquareState[][] state, int i) {\r\n\t\treturn i+1 >= state.length;\r\n\t}\r\n\t\r\n\t//ileriye gidebilir mi?\r\n\tprivate boolean buttomCheck(SquareState[][] state, int i) {\r\n\t\treturn i-1 < 0;\r\n\t}\r\n}\r",
"public enum SquareState{\r\n\tBLANK (null),\r\n\tWHITE (Player.WHITE),\r\n\tBLACK (Player.BLACK),\r\n\tKING_WHITE (Player.WHITE),\r\n\tKING_BLACK (Player.BLACK);\r\n\t\r\n\tpublic final Player owner;\r\n\t\r\n\tprivate SquareState(Player owner){\r\n\t\tthis.owner = owner;\r\n\t}\r\n\r\n\tpublic SquareState convertKing() {\r\n\t\tif(this==WHITE || this==BLACK)\r\n\t\t\treturn values()[this.ordinal()+2];\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic SquareState convertNormal() {\r\n\t\tif(this==KING_WHITE || this==KING_BLACK)\r\n\t\t\treturn values()[this.ordinal()-2];\r\n\t\treturn this;\r\n\t}\r\n\t\r\n\tpublic boolean isKing(){\r\n\t\treturn (this==KING_BLACK || this==KING_WHITE);\r\n\t}\r\n}\r"
] | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import checkers.domain.CalculationContext;
import checkers.domain.Model;
import checkers.domain.Move;
import checkers.domain.Player;
import checkers.evaluation.MenCountEvaluation;
import checkers.rules.Successors;
import checkers.sandbox.SquareState;
| package checkers.algorithm;
public class TestGreedyAlgorithm {
private GreedyAlgorithm algorithm;
| private CalculationContext context;
| 0 |
sfPlayer1/Matcher | src/matcher/type/ClassInstance.java | [
"public enum NameType {\n\tPLAIN(true, false, false, 0),\n\tMAPPED(false, true, false, 0),\n\tAUX(false, false, false, 1),\n\tAUX2(false, false, false, 2),\n\n\tMAPPED_PLAIN(true, true, false, 0),\n\tMAPPED_AUX_PLAIN(true, true, false, 1),\n\tMAPPED_AUX2_PLAIN(true, true, false, 2),\n\tMAPPED_TMP_PLAIN(true, true, true, 0),\n\tMAPPED_LOCTMP_PLAIN(true, true, false, 0),\n\n\tUID_PLAIN(true, false, false, 0),\n\tTMP_PLAIN(true, false, true, 0),\n\tLOCTMP_PLAIN(true, false, false, 0),\n\tAUX_PLAIN(true, false, false, 1),\n\tAUX2_PLAIN(true, false, false, 2);\n\n\tNameType(boolean plain, boolean mapped, boolean tmp, int aux) {\n\t\tthis.plain = plain;\n\t\tthis.mapped = mapped;\n\t\tthis.tmp = tmp;\n\t\tthis.aux = aux;\n\t}\n\n\tpublic NameType withPlain(boolean value) {\n\t\tif (plain == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn VALUES[AUX_PLAIN.ordinal() + aux - 1];\n\t\t} else if (this == MAPPED_PLAIN) {\n\t\t\treturn MAPPED;\n\t\t} else if (aux > 0 && !mapped && !tmp) {\n\t\t\treturn VALUES[AUX.ordinal() + aux - 1];\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\t}\n\n\tpublic NameType withMapped(boolean value) {\n\t\tif (mapped == value) return this;\n\n\t\tif (value) {\n\t\t\tif (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];\n\t\t\tif (tmp) return MAPPED_TMP_PLAIN;\n\t\t\tif (plain) return MAPPED_PLAIN;\n\n\t\t\treturn MAPPED;\n\t\t} else {\n\t\t\tif (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];\n\t\t\tif (tmp) return TMP_PLAIN;\n\t\t\tif (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\tpublic NameType withAux(int index, boolean value) {\n\t\tif ((aux - 1 == index) == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];\n\t\t\tif (plain) return VALUES[AUX_PLAIN.ordinal() + index];\n\n\t\t\treturn VALUES[AUX.ordinal() + index];\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\tpublic NameType withTmp(boolean value) {\n\t\tif (tmp == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_TMP_PLAIN;\n\n\t\t\treturn TMP_PLAIN;\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\t// transform between tmp <-> loctmp\n\tpublic NameType withUnmatchedTmp(boolean value) {\n\t\tboolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;\n\n\t\tif (value == locTmp || !tmp && !locTmp) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_LOCTMP_PLAIN;\n\n\t\t\treturn LOCTMP_PLAIN;\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_TMP_PLAIN;\n\n\t\t\treturn TMP_PLAIN;\n\t\t}\n\t}\n\n\tpublic boolean isAux() {\n\t\treturn aux > 0;\n\t}\n\n\tpublic int getAuxIndex() {\n\t\tif (aux == 0) throw new NoSuchElementException();\n\n\t\treturn aux - 1;\n\t}\n\n\tpublic static NameType getAux(int index) {\n\t\tObjects.checkIndex(index, AUX_COUNT);\n\n\t\treturn VALUES[NameType.AUX.ordinal() + index];\n\t}\n\n\tpublic static final int AUX_COUNT = 2;\n\n\tprivate static final NameType[] VALUES = values();\n\n\tpublic final boolean plain;\n\tpublic final boolean mapped;\n\tpublic final boolean tmp;\n\tprivate final int aux;\n}",
"public final class SimilarityChecker {\n\tpublic static float compare(ClassInstance a, ClassInstance b) {\n\t\tif (a.getMatch() != b) return 0;\n\n\t\tfloat ret = 0;\n\n\t\tfor (MethodInstance m : a.getMethods()) {\n\t\t\tif (m.getMatch() != null) {\n\t\t\t\tret += compare(m, m.getMatch());\n\t\t\t}\n\t\t}\n\n\t\tfor (FieldInstance m : a.getFields()) {\n\t\t\tif (m.getMatch() != null) {\n\t\t\t\tret += compare(m, m.getMatch());\n\t\t\t}\n\t\t}\n\n\t\tint div = a.getMethods().length + a.getFields().length;\n\n\t\tfor (MethodInstance m : b.getMethods()) {\n\t\t\tif (m.getMatch() == null) {\n\t\t\t\tdiv++;\n\t\t\t}\n\t\t}\n\n\t\tfor (FieldInstance m : b.getFields()) {\n\t\t\tif (m.getMatch() == null) {\n\t\t\t\tdiv++;\n\t\t\t}\n\t\t}\n\n\t\treturn div > 0 ? ret / div : 1;\n\t}\n\n\tpublic static <T extends MemberInstance<T>> float compare(MemberInstance<T> a, MemberInstance<T> b) {\n\t\tif (a instanceof MethodInstance) {\n\t\t\treturn compare((MethodInstance) a, (MethodInstance) b);\n\t\t} else {\n\t\t\treturn compare((FieldInstance) a, (FieldInstance) b);\n\t\t}\n\t}\n\n\tpublic static float compare(MethodInstance a, MethodInstance b) {\n\t\tif (a.getMatch() != b) return 0;\n\n\t\tif (a.getAsmNode() == null || b.getAsmNode() == null) {\n\t\t\treturn (a.getAsmNode() == null) == (b.getAsmNode() == null) ? 1 : 0;\n\t\t}\n\n\t\tfloat retTypeScore = ClassifierUtil.checkPotentialEquality(a.getRetType(), b.getRetType()) ? 1 : 0;\n\t\tfloat argTypeScore = 0;\n\n\t\tfor (MethodVarInstance v : a.getArgs()) {\n\t\t\tif (v.getMatch() != null) {\n\t\t\t\targTypeScore += compare(v, v.getMatch());\n\t\t\t}\n\t\t}\n\n\t\tint div = a.getArgs().length;\n\n\t\tfor (MethodVarInstance v : b.getArgs()) {\n\t\t\tif (v.getMatch() == null) {\n\t\t\t\tdiv++;\n\t\t\t}\n\t\t}\n\n\t\targTypeScore = div > 0 ? argTypeScore / div : 1;\n\n\t\tfloat contentScore = 0;\n\t\tint[] insnMap = ClassifierUtil.mapInsns(a, b);\n\n\t\tfor (int i = 0; i < insnMap.length; i++) {\n\t\t\tif (insnMap[i] >= 0) contentScore++;\n\t\t}\n\n\t\tdiv = Math.max(insnMap.length, b.getAsmNode().instructions.size());\n\t\tcontentScore = div > 0 ? contentScore / div : 1;\n\n\t\treturn retTypeScore * METHOD_RETTYPE_WEIGHT + argTypeScore * METHOD_ARGS_WEIGHT + contentScore * METHOD_CONTENT_WEIGHT;\n\t}\n\n\tpublic static float compare(FieldInstance a, FieldInstance b) {\n\t\tif (a.getMatch() != b) return 0;\n\n\t\treturn ClassifierUtil.checkPotentialEquality(a.getType(), b.getType()) ? 1 : SIMILARITY_MATCHED_TYPE_MISMATCH;\n\t}\n\n\tpublic static float compare(MethodVarInstance a, MethodVarInstance b) {\n\t\tif (a.getMatch() != b) return 0;\n\n\t\treturn ClassifierUtil.checkPotentialEquality(a.getType(), b.getType()) ? 1 : SIMILARITY_MATCHED_TYPE_MISMATCH;\n\t}\n\n\tprivate static final float SIMILARITY_MATCHED_TYPE_MISMATCH = 0.5f;\n\n\tprivate static final float METHOD_RETTYPE_WEIGHT = 0.05f;\n\tprivate static final float METHOD_ARGS_WEIGHT = 0.2f;\n\tprivate static final float METHOD_CONTENT_WEIGHT = 1 - METHOD_RETTYPE_WEIGHT - METHOD_ARGS_WEIGHT;\n}",
"public class Util {\n\tpublic static <T> Set<T> newIdentityHashSet() {\n\t\treturn Collections.newSetFromMap(new IdentityHashMap<>());//new IdentityHashSet<>();\n\t}\n\n\tpublic static <T> Set<T> newIdentityHashSet(Collection<? extends T> c) {\n\t\tSet<T> ret = Collections.newSetFromMap(new IdentityHashMap<>(c.size()));\n\t\tret.addAll(c);\n\n\t\treturn ret;//new IdentityHashSet<>(c);\n\t}\n\n\tpublic static <T> Set<T> copySet(Set<T> set) {\n\t\tif (set instanceof HashSet) {\n\t\t\treturn new HashSet<>(set);\n\t\t} else {\n\t\t\treturn newIdentityHashSet(set);\n\t\t}\n\t}\n\n\tpublic static FileSystem iterateJar(Path archive, boolean autoClose, Consumer<Path> handler) {\n\t\tboolean existing = false;\n\t\tFileSystem fs = null;\n\n\t\ttry {\n\t\t\tURI uri = new URI(\"jar:\"+archive.toUri().toString());\n\n\t\t\tsynchronized (Util.class) {\n\t\t\t\ttry {\n\t\t\t\t\tfs = FileSystems.getFileSystem(uri);\n\t\t\t\t\texisting = true;\n\t\t\t\t\tautoClose = false;\n\t\t\t\t} catch (FileSystemNotFoundException e) {\n\t\t\t\t\tfs = FileSystems.newFileSystem(uri, Collections.emptyMap());\n\t\t\t\t\texisting = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tFiles.walkFileTree(fs.getPath(\"/\"), new SimpleFileVisitor<Path>() {\n\t\t\t\t@Override\n\t\t\t\tpublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n\t\t\t\t\tif (file.toString().endsWith(\".class\")) {\n\t\t\t\t\t\thandler.accept(file);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn FileVisitResult.CONTINUE;\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\tcloseSilently(fs);\n\t\t\tthrow new UncheckedIOException(e);\n\t\t} catch (URISyntaxException e) {\n\t\t\tcloseSilently(fs);\n\t\t\tthrow new RuntimeException(e);\n\t\t} catch (Throwable t) {\n\t\t\tcloseSilently(fs);\n\t\t\tthrow t;\n\t\t}\n\n\t\tif (autoClose) closeSilently(fs);\n\n\t\treturn autoClose || existing ? null : fs;\n\t}\n\n\tpublic static boolean clearDir(Path path, Predicate<Path> disallowed) throws IOException {\n\t\ttry (Stream<Path> stream = Files.walk(path, FileVisitOption.FOLLOW_LINKS)) {\n\t\t\tif (stream.anyMatch(disallowed)) return false;\n\t\t}\n\n\t\tAtomicBoolean ret = new AtomicBoolean(true);\n\n\t\tFiles.walkFileTree(path, new SimpleFileVisitor<Path>() {\n\t\t\t@Override\n\t\t\tpublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n\t\t\t\tif (disallowed.test(file)) {\n\t\t\t\t\tret.set(false);\n\n\t\t\t\t\treturn FileVisitResult.TERMINATE;\n\t\t\t\t} else {\n\t\t\t\t\tFiles.delete(file);\n\n\t\t\t\t\treturn FileVisitResult.CONTINUE;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n\t\t\t\tif (exc != null) throw exc;\n\t\t\t\tif (!dir.equals(path)) Files.delete(dir);\n\n\t\t\t\treturn FileVisitResult.CONTINUE;\n\t\t\t}\n\t\t});\n\n\t\treturn ret.get();\n\t}\n\n\tpublic static void closeSilently(Closeable c) {\n\t\tif (c == null) return;\n\n\t\ttry {\n\t\t\tc.close();\n\t\t} catch (IOException e) { }\n\t}\n\n\tpublic static boolean isCallToInterface(MethodInsnNode insn) {\n\t\tassert insn.itf || insn.getOpcode() != Opcodes.INVOKEINTERFACE;\n\n\t\treturn insn.itf;\n\t\t/*return insn.getOpcode() == Opcodes.INVOKEINTERFACE\n\t\t\t\t|| (insn.getOpcode() == Opcodes.INVOKESPECIAL || insn.getOpcode() == Opcodes.INVOKESTATIC) && insn.itf;*/\n\t}\n\n\tpublic static boolean isCallToInterface(Handle handle) {\n\t\tassert handle.isInterface() || handle.getTag() != Opcodes.H_INVOKEINTERFACE;\n\n\t\treturn handle.isInterface();\n\n\t\t/*return handle.getTag() == Opcodes.H_INVOKEINTERFACE\n\t\t\t\t|| (handle.getTag() == Opcodes.H_INVOKESPECIAL || handle.getTag() == Opcodes.H_NEWINVOKESPECIAL || handle.getTag() == Opcodes.H_INVOKESTATIC) && handle.isInterface();*/\n\t}\n\n\tpublic static String formatAccessFlags(int access, AFElementType type) {\n\t\tint assoc = type.assoc;\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tfor (int i = 0; i < accessFlags.length; i++) {\n\t\t\tif ((accessAssoc[i] & assoc) == 0) continue;\n\t\t\tif ((access & accessFlags[i]) == 0) continue;\n\n\t\t\tif (sb.length() != 0) sb.append(' ');\n\t\t\tsb.append(accessNames[i]);\n\n\t\t\taccess &= ~accessFlags[i];\n\t\t}\n\n\t\tif (access != 0) {\n\t\t\tif (sb.length() != 0) sb.append(' ');\n\t\t\tsb.append(\"0x\");\n\t\t\tsb.append(Integer.toHexString(access));\n\t\t}\n\n\t\treturn sb.toString();\n\t}\n\n\tpublic enum AFElementType {\n\t\tClass(1), Method(2), Field(4), Parameter(8), InnerClass(16);\n\n\t\tAFElementType(int assoc) {\n\t\t\tthis.assoc = assoc;\n\t\t}\n\n\t\tfinal int assoc;\n\t}\n\n\tprivate static final int[] accessFlags = new int[] { Opcodes.ACC_PUBLIC, Opcodes.ACC_PRIVATE, Opcodes.ACC_PROTECTED, Opcodes.ACC_STATIC,\n\t\t\tOpcodes.ACC_FINAL, Opcodes.ACC_SUPER, Opcodes.ACC_SYNCHRONIZED, Opcodes.ACC_VOLATILE, Opcodes.ACC_BRIDGE, Opcodes.ACC_VARARGS,\n\t\t\tOpcodes.ACC_TRANSIENT, Opcodes.ACC_NATIVE, Opcodes.ACC_INTERFACE, Opcodes.ACC_ABSTRACT, Opcodes.ACC_STRICT, Opcodes.ACC_SYNTHETIC,\n\t\t\tOpcodes.ACC_ANNOTATION, Opcodes.ACC_ENUM, Opcodes.ACC_MANDATED };\n\tprivate static final String[] accessNames = new String[] { \"public\", \"private\", \"protected\", \"static\",\n\t\t\t\"final\", \"super\", \"synchronized\", \"volatile\", \"bridge\", \"varargs\",\n\t\t\t\"transient\", \"native\", \"interface\", \"abstract\", \"strict\", \"synthetic\",\n\t\t\t\"annotation\", \"enum\", \"mandated\" };\n\tprivate static final byte[] accessAssoc = new byte[] { 7, 7, 7, 6,\n\t\t\t15, 1, 2, 4, 2, 2,\n\t\t\t4, 2, 1, 3, 2, 15,\n\t\t\t1, 21, 8 };\n\n\tpublic static Handle getTargetHandle(Handle bsm, Object[] bsmArgs) {\n\t\tif (isJavaLambdaMetafactory(bsm)) {\n\t\t\treturn (Handle) bsmArgs[1];\n\t\t} else if (isIrrelevantBsm(bsm)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tSystem.out.printf(\"unknown invokedynamic bsm: %s/%s%s (tag=%d iif=%b)%n\", bsm.getOwner(), bsm.getName(), bsm.getDesc(), bsm.getTag(), bsm.isInterface());\n\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static boolean isJavaLambdaMetafactory(Handle bsm) {\n\t\treturn bsm.getTag() == Opcodes.H_INVOKESTATIC\n\t\t\t\t&& bsm.getOwner().equals(\"java/lang/invoke/LambdaMetafactory\")\n\t\t\t\t&& (bsm.getName().equals(\"metafactory\")\n\t\t\t\t\t\t&& bsm.getDesc().equals(\"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;\")\n\t\t\t\t\t\t|| bsm.getName().equals(\"altMetafactory\")\n\t\t\t\t\t\t&& bsm.getDesc().equals(\"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;\"))\n\t\t\t\t&& !bsm.isInterface();\n\t}\n\n\tpublic static boolean isIrrelevantBsm(Handle bsm) {\n\t\treturn bsm.getOwner().equals(\"java/lang/invoke/StringConcatFactory\")\n\t\t\t\t|| bsm.getOwner().equals(\"java/lang/runtime/ObjectMethods\");\n\t}\n\n\tpublic static boolean isValidJavaIdentifier(String s) {\n\t\tif (s.isEmpty()) return false;\n\n\t\tint cp = s.codePointAt(0);\n\t\tif (!Character.isJavaIdentifierStart(cp)) return false;\n\n\t\tfor (int i = Character.charCount(cp), max = s.length(); i < max; i += Character.charCount(cp)) {\n\t\t\tcp = s.codePointAt(i);\n\t\t\tif (!Character.isJavaIdentifierPart(cp)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic static int compareNatural(String a, String b) {\n\t\tfinal int lenA = a.length();\n\t\tfinal int lenB = b.length();\n\t\tint posA = 0;\n\t\tint lastSize = 0;\n\n\t\tfor (int max = Math.min(lenA, lenB); posA < max; ) {\n\t\t\tint cA = Character.codePointAt(a, posA);\n\t\t\tint cB = Character.codePointAt(b, posA);\n\n\t\t\tif (cA != cB) break;\n\n\t\t\tlastSize = Character.charCount(cA);\n\t\t\tposA += lastSize;\n\t\t}\n\n\t\tif (posA == lenA && lenA == lenB) return 0;\n\n\t\tint posB = posA = posA - lastSize;\n\t\tint endA = -1;\n\t\tint endB = -1;\n\n\t\tfor (;;) {\n\t\t\tint startA = posA;\n\t\t\tboolean isNumA = false;\n\n\t\t\twhile (posA < lenA) {\n\t\t\t\tint c = Character.codePointAt(a, posA);\n\n\t\t\t\tif ((c >= '0' && c <= '9') != isNumA) {\n\t\t\t\t\tif (posA == startA) {\n\t\t\t\t\t\tisNumA = !isNumA; // isNum had the wrong initial value\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (endA < posA) {\n\t\t\t\t\t\t\tendA = posA;\n\n\t\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\t\tendA += Character.charCount(c);\n\t\t\t\t\t\t\t} while (endA < lenA && (c = Character.codePointAt(a, endA)) != '.' && c != '/');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (c == '.' || c == '/') {\n\t\t\t\t\tendA = posA; // unconditionally mark end to handle 0-length segments (those won't be re-visited)\n\t\t\t\t\tif (posA == startA) posA++; // consume only if first to avoid polluting comparisons within segments, otherwise trigger revisit\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (c == '$') {\n\t\t\t\t\tif (posA == startA) posA++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tposA += Character.charCount(c);\n\t\t\t}\n\n\t\t\tint startB = posB;\n\t\t\tboolean isNumB = false;\n\n\t\t\twhile (posB < lenB) {\n\t\t\t\tint c = Character.codePointAt(b, posB);\n\n\t\t\t\tif ((c >= '0' && c <= '9') != isNumB) {\n\t\t\t\t\tif (posB == startB) {\n\t\t\t\t\t\tisNumB = !isNumB;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (endB < posB) {\n\t\t\t\t\t\t\tendB = posB;\n\n\t\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\t\tendB += Character.charCount(c);\n\t\t\t\t\t\t\t} while (endB < lenB && (c = Character.codePointAt(b, endB)) != '.' && c != '/');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (c == '.' || c == '/') {\n\t\t\t\t\tendB = posB;\n\t\t\t\t\tif (posB == startB) posB++;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (c == '$') {\n\t\t\t\t\tif (posB == startB) posB++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tposB += Character.charCount(c);\n\t\t\t}\n\n\t\t\tboolean hasEndA = endA >= startA && endA < lenA; // segment separator exists after current region\n\t\t\tboolean hasEndB = endB >= startB && endB < lenB;\n\n\t\t\tif (hasEndA != hasEndB) {\n\t\t\t\treturn hasEndA ? 1 : -1;\n\t\t\t}\n\n\t\t\tif (isNumA && isNumB) {\n\t\t\t\tint segLenA = posA - startA;\n\t\t\t\tint segLenB = posB - startB;\n\n\t\t\t\tif (segLenA != segLenB) {\n\t\t\t\t\treturn segLenA < segLenB ? -1 : 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile (startA < posA) {\n\t\t\t\tif (startB == posB) return 1;\n\n\t\t\t\tint cA = Character.codePointAt(a, startA);\n\t\t\t\tint cB = Character.codePointAt(b, startB);\n\n\t\t\t\tif (cA != cB) {\n\t\t\t\t\treturn cA < cB ? -1 : 1;\n\t\t\t\t}\n\n\t\t\t\tstartA += Character.charCount(cA);\n\t\t\t\tstartB += Character.charCount(cB);\n\t\t\t}\n\n\t\t\tif (startB != posB) return -1;\n\t\t}\n\t}\n\n\tpublic static final Object asmNodeSync = new Object();\n}",
"public class AsmClassRemapper extends ClassRemapper {\n\tpublic static void process(ClassNode source, AsmRemapper remapper, ClassVisitor sink) {\n\t\tsource.accept(new AsmClassRemapper(sink, remapper));\n\t}\n\n\tprivate AsmClassRemapper(ClassVisitor cv, AsmRemapper remapper) {\n\t\tsuper(cv, remapper);\n\n\t\tthis.remapper = remapper;\n\t}\n\n\t@Override\n\tpublic MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {\n\t\tif (methodName != null) throw new IllegalStateException(\"already vising a method\");\n\n\t\tmethodName = name;\n\t\tmethodDesc = desc;\n\n\t\treturn super.visitMethod(access, name, desc, signature, exceptions);\n\t}\n\n\t@Override\n\tprotected MethodVisitor createMethodRemapper(MethodVisitor mv) {\n\t\treturn new AsmMethodRemapper(mv, remapper);\n\t}\n\n\tprivate class AsmMethodRemapper extends MethodRemapper {\n\t\tpublic AsmMethodRemapper(MethodVisitor mv, AsmRemapper remapper) {\n\t\t\tsuper(mv, remapper);\n\n\t\t\tthis.remapper = remapper;\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitParameter(String name, int access) {\n\t\t\tcheckState();\n\t\t\tname = remapper.mapArgName(className, methodName, methodDesc, name, argsVisited);\n\t\t\targsVisited++;\n\t\t\tsuper.visitParameter(name, access);\n\t\t}\n\n\t\tprivate void checkParameters() {\n\t\t\tif (argsVisited > 0 || methodDesc.startsWith(\"()\")) return;\n\n\t\t\tint argCount = Type.getArgumentTypes(methodDesc).length;\n\n\t\t\tfor (int i = 0; i < argCount; i++) {\n\t\t\t\tvisitParameter(null, 0);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic AnnotationVisitor visitAnnotationDefault() {\n\t\t\tcheckParameters();\n\t\t\treturn super.visitAnnotationDefault();\n\t\t}\n\n\t\t@Override\n\t\tpublic AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {\n\t\t\tcheckParameters();\n\t\t\treturn super.visitAnnotation(descriptor, visible);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitAnnotableParameterCount(int parameterCount, boolean visible) {\n\t\t\tcheckParameters();\n\t\t\tsuper.visitAnnotableParameterCount(parameterCount, visible);\n\t\t}\n\n\t\t@Override\n\t\tpublic AnnotationVisitor visitParameterAnnotation(int parameter, String descriptor, boolean visible) {\n\t\t\tcheckParameters();\n\t\t\treturn super.visitParameterAnnotation(parameter, descriptor, visible);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitAttribute(Attribute attribute) {\n\t\t\tcheckParameters();\n\t\t\tsuper.visitAttribute(attribute);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitCode() {\n\t\t\tcheckParameters();\n\t\t\tsuper.visitCode();\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, final boolean itf) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tif (mv != null) {\n\t\t\t\tmv.visitMethodInsn(opcode, remapper.mapType(owner),\n\t\t\t\t\t\tremapper.mapMethodName(owner, name, desc, itf),\n\t\t\t\t\t\tremapper.mapMethodDesc(desc), itf);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tif (mv == null) return;\n\n\t\t\tHandle target = Util.getTargetHandle(bsm, bsmArgs);\n\n\t\t\tif (target != null) {\n\t\t\t\tname = remapper.mapMethodName(target.getOwner(), target.getName(), target.getDesc(), target.isInterface());\n\t\t\t} else {\n\t\t\t\tString owner = Type.getType(desc).getReturnType().getInternalName();\n\n\t\t\t\tname = remapper.mapArbitraryInvokeDynamicMethodName(owner, name);\n\t\t\t}\n\n\t\t\tboolean copied = false;\n\n\t\t\tfor (int i = 0; i < bsmArgs.length; i++) {\n\t\t\t\tObject oldArg = bsmArgs[i];\n\t\t\t\tObject newArg = remapper.mapValue(oldArg);\n\n\t\t\t\tif (newArg != oldArg) {\n\t\t\t\t\tif (!copied) {\n\t\t\t\t\t\tbsmArgs = Arrays.copyOf(bsmArgs, bsmArgs.length);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tbsmArgs[i] = newArg;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmv.visitInvokeDynamicInsn(name, remapper.mapMethodDesc(desc), (Handle) remapper.mapValue(bsm), bsmArgs);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitFrame(type, nLocal, local, nStack, stack);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitInsn(final int opcode) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitInsn(opcode);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitIntInsn(final int opcode, final int operand) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitIntInsn(opcode, operand);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitVarInsn(final int opcode, final int var) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitVarInsn(opcode, var);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitTypeInsn(final int opcode, final String type) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitTypeInsn(opcode, type);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitFieldInsn(opcode, owner, name, desc);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitJumpInsn(final int opcode, final Label label) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\t\t\tsuper.visitJumpInsn(opcode, label);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitLabel(final Label label) {\n\t\t\tcheckState();\n\t\t\tif (insnIndex == 0 && !labels.isEmpty()) throw new IllegalStateException();\n\n\t\t\tlabels.put(label, insnIndex);\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitLabel(label);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitLdcInsn(final Object cst) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitLdcInsn(cst);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitIincInsn(final int var, final int increment) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitIincInsn(var, increment);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitTableSwitchInsn(min, max, dflt, labels);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitLookupSwitchInsn(dflt, keys, labels);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitMultiANewArrayInsn(final String desc, final int dims) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitMultiANewArrayInsn(desc, dims);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitLineNumber(final int line, final Label start) {\n\t\t\tcheckState();\n\t\t\tinsnIndex++;\n\n\t\t\tsuper.visitLineNumber(line, start);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {\n\t\t\tcheckState();\n\n\t\t\tint startInsn = labels.get(start);\n\t\t\tint endInsn = labels.get(end);\n\n\t\t\tname = remapper.mapLocalVariableName(className, methodName, methodDesc, name, desc, index, startInsn, endInsn);\n\n\t\t\tsuper.visitLocalVariable(name, desc, signature, start, end, index);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitEnd() {\n\t\t\tcheckState();\n\t\t\tcheckParameters();\n\n\t\t\tinsnIndex = 0;\n\t\t\tlabels.clear();\n\t\t\targsVisited = 0;\n\t\t\tmethodName = methodDesc = null;\n\n\t\t\tsuper.visitEnd();\n\t\t}\n\n\t\tprivate void checkState() {\n\t\t\tif (methodName == null) throw new IllegalStateException(\"not visiting a method\");\n\t\t}\n\n\t\tprotected final AsmRemapper remapper;\n\n\t\tprotected int insnIndex;\n\t\tprotected Map<Label, Integer> labels = new IdentityHashMap<>();\n\t\tprivate int argsVisited;\n\t}\n\n\tprotected final AsmRemapper remapper;\n\tprotected String methodName;\n\tprotected String methodDesc;\n}",
"public class AsmRemapper extends Remapper {\n\tpublic AsmRemapper(ClassEnv env, NameType nameType) {\n\t\tthis.env = env;\n\t\tthis.nameType = nameType;\n\t}\n\n\t@Override\n\tpublic String map(String typeName) {\n\t\tClassInstance cls = env.getClsByName(typeName);\n\t\tif (cls == null) return typeName;\n\n\t\treturn cls.getName(nameType);\n\t}\n\n\t@Override\n\tpublic String mapFieldName(String owner, String name, String desc) {\n\t\tClassInstance cls = env.getClsByName(owner);\n\t\tif (cls == null) return name;\n\n\t\tFieldInstance field = cls.resolveField(name, desc);\n\t\tif (field == null) return name;\n\n\t\treturn field.getName(nameType);\n\t}\n\n\t@Override\n\tpublic String mapMethodName(String owner, String name, String desc) {\n\t\tif (!desc.startsWith(\"(\")) { // workaround for Remapper.mapValue calling mapMethodName even if the Handle is a field one\n\t\t\treturn mapFieldName(owner, name, desc);\n\t\t}\n\n\t\tClassInstance cls = env.getClsByName(owner);\n\t\tif (cls == null) return name;\n\n\t\tMethodInstance method = cls.getMethod(name, desc);\n\n\t\tif (method == null) {\n\t\t\tassert false : String.format(\"can't find method %s%s in %s\", name, desc, cls);;\n\t\t\treturn name;\n\t\t}\n\n\t\treturn method.getName(nameType);\n\t}\n\n\tpublic String mapMethodName(String owner, String name, String desc, boolean itf) {\n\t\tClassInstance cls = env.getClsByName(owner);\n\t\tif (cls == null) return name;\n\n\t\tMethodInstance method = cls.resolveMethod(name, desc, itf);\n\t\tif (method == null) return name;\n\n\t\treturn method.getName(nameType);\n\t}\n\n\tpublic String mapArbitraryInvokeDynamicMethodName(String owner, String name) {\n\t\tClassInstance cls = env.getClsByName(owner);\n\t\tif (cls == null) return name;\n\n\t\tMethodInstance method = cls.getMethod(name, null);\n\t\tif (method == null) return name;\n\n\t\treturn method.getName(nameType);\n\t}\n\n\tpublic String mapArgName(String className, String methodName, String methodDesc, String name, int asmIndex) {\n\t\tClassInstance cls = env.getClsByName(className);\n\t\tif (cls == null) return name;\n\n\t\tMethodInstance method = cls.getMethod(methodName, methodDesc);\n\t\tif (method == null) return name;\n\n\t\treturn method.getArg(asmIndex).getName(nameType);\n\t}\n\n\tpublic String mapLocalVariableName(String className, String methodName, String methodDesc, String name, String desc, int lvIndex, int startInsn, int endInsn) {\n\t\tClassInstance cls = env.getClsByName(className);\n\t\tif (cls == null) return name;\n\n\t\tMethodInstance method = cls.getMethod(methodName, methodDesc);\n\t\tif (method == null) return name;\n\n\t\tMethodVarInstance var = method.getArgOrVar(lvIndex, startInsn, endInsn);\n\n\t\tif (var != null) {\n\t\t\tassert var.getType().getId().equals(desc);\n\n\t\t\tname = var.getName(nameType);\n\t\t}\n\n\t\treturn name;\n\t}\n\n\tprivate final ClassEnv env;\n\tprivate final NameType nameType;\n}",
"public class ClassifierUtil {\n\tpublic static boolean checkPotentialEquality(ClassInstance a, ClassInstance b) {\n\t\tif (a == b) return true;\n\t\tif (a.getMatch() != null) return a.getMatch() == b;\n\t\tif (b.getMatch() != null) return b.getMatch() == a;\n\t\tif (!a.isMatchable() || !b.isMatchable()) return false;\n\t\tif (a.isArray() != b.isArray()) return false;\n\t\tif (a.isArray() && !checkPotentialEquality(a.getElementClass(), b.getElementClass())) return false;\n\t\tif (!checkNameObfMatch(a, b)) return false;\n\n\t\treturn true;\n\t}\n\n\tprivate static boolean checkNameObfMatch(Matchable<?> a, Matchable<?> b) {\n\t\tboolean nameObfA = a.isNameObfuscated();\n\t\tboolean nameObfB = b.isNameObfuscated();\n\n\t\tif (nameObfA && nameObfB) { // both obf\n\t\t\treturn true;\n\t\t} else if (nameObfA != nameObfB) { // one obf\n\t\t\treturn !a.getEnv().getGlobal().assumeBothOrNoneObfuscated;\n\t\t} else { // neither obf\n\t\t\treturn a.getName().equals(b.getName());\n\t\t}\n\t}\n\n\tpublic static boolean checkPotentialEquality(MethodInstance a, MethodInstance b) {\n\t\tif (a == b) return true;\n\t\tif (a.getMatch() != null) return a.getMatch() == b;\n\t\tif (b.getMatch() != null) return b.getMatch() == a;\n\t\tif (!a.isMatchable() || !b.isMatchable()) return false;\n\t\tif (!checkPotentialEquality(a.getCls(), b.getCls())) return false;\n\t\tif (!checkNameObfMatch(a, b)) return false;\n\t\tif ((a.getId().startsWith(\"<\") || b.getId().startsWith(\"<\")) && !a.getName().equals(b.getName())) return false; // require <clinit> and <init> to match\n\n\t\tMethodInstance hierarchyMatch = a.getHierarchyMatch();\n\t\tif (hierarchyMatch != null && !hierarchyMatch.getAllHierarchyMembers().contains(b)) return false;\n\n\t\tif (a.getType() == MethodType.LAMBDA_IMPL && b.getType() == MethodType.LAMBDA_IMPL) { // require same \"outer method\" for lambdas\n\t\t\tboolean found = false;\n\n\t\t\tmaLoop: for (MethodInstance ma : a.getRefsIn()) {\n\t\t\t\tfor (MethodInstance mb : b.getRefsIn()) {\n\t\t\t\t\tif (checkPotentialEquality(ma, mb)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak maLoop;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!found) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic static boolean checkPotentialEquality(FieldInstance a, FieldInstance b) {\n\t\tif (a == b) return true;\n\t\tif (a.getMatch() != null) return a.getMatch() == b;\n\t\tif (b.getMatch() != null) return b.getMatch() == a;\n\t\tif (!a.isMatchable() || !b.isMatchable()) return false;\n\t\tif (!checkPotentialEquality(a.getCls(), b.getCls())) return false;\n\t\tif (!checkNameObfMatch(a, b)) return false;\n\n\t\treturn true;\n\t}\n\n\tpublic static boolean checkPotentialEquality(MethodVarInstance a, MethodVarInstance b) {\n\t\tif (a == b) return true;\n\t\tif (a.getMatch() != null) return a.getMatch() == b;\n\t\tif (b.getMatch() != null) return b.getMatch() == a;\n\t\tif (!a.isMatchable() || !b.isMatchable()) return false;\n\t\tif (a.isArg() != b.isArg()) return false;\n\t\tif (!checkPotentialEquality(a.getMethod(), b.getMethod())) return false;\n\t\tif (!checkNameObfMatch(a, b)) return false;\n\n\t\treturn true;\n\t}\n\n\tpublic static boolean checkPotentialEqualityNullable(ClassInstance a, ClassInstance b) {\n\t\tif (a == null && b == null) return true;\n\t\tif (a == null || b == null) return false;\n\n\t\treturn checkPotentialEquality(a, b);\n\t}\n\n\tpublic static boolean checkPotentialEqualityNullable(MethodInstance a, MethodInstance b) {\n\t\tif (a == null && b == null) return true;\n\t\tif (a == null || b == null) return false;\n\n\t\treturn checkPotentialEquality(a, b);\n\t}\n\n\tpublic static boolean checkPotentialEqualityNullable(FieldInstance a, FieldInstance b) {\n\t\tif (a == null && b == null) return true;\n\t\tif (a == null || b == null) return false;\n\n\t\treturn checkPotentialEquality(a, b);\n\t}\n\n\tpublic static boolean checkPotentialEqualityNullable(MethodVarInstance a, MethodVarInstance b) {\n\t\tif (a == null && b == null) return true;\n\t\tif (a == null || b == null) return false;\n\n\t\treturn checkPotentialEquality(a, b);\n\t}\n\n\tpublic static double compareCounts(int countA, int countB) {\n\t\tint delta = Math.abs(countA - countB);\n\t\tif (delta == 0) return 1;\n\n\t\treturn 1 - (double) delta / Math.max(countA, countB);\n\t}\n\n\tpublic static <T> double compareSets(Set<T> setA, Set<T> setB, boolean readOnly) {\n\t\tif (readOnly) setB = Util.copySet(setB);\n\n\t\tint oldSize = setB.size();\n\t\tsetB.removeAll(setA);\n\n\t\tint matched = oldSize - setB.size();\n\t\tint total = setA.size() - matched + oldSize;\n\n\t\treturn total == 0 ? 1 : (double) matched / total;\n\t}\n\n\tpublic static double compareClassSets(Set<ClassInstance> setA, Set<ClassInstance> setB, boolean readOnly) {\n\t\treturn compareIdentitySets(setA, setB, readOnly, ClassifierUtil::checkPotentialEquality);\n\t}\n\n\tpublic static double compareMethodSets(Set<MethodInstance> setA, Set<MethodInstance> setB, boolean readOnly) {\n\t\treturn compareIdentitySets(setA, setB, readOnly, ClassifierUtil::checkPotentialEquality);\n\t}\n\n\tpublic static double compareFieldSets(Set<FieldInstance> setA, Set<FieldInstance> setB, boolean readOnly) {\n\t\treturn compareIdentitySets(setA, setB, readOnly, ClassifierUtil::checkPotentialEquality);\n\t}\n\n\tprivate static <T extends Matchable<T>> double compareIdentitySets(Set<T> setA, Set<T> setB, boolean readOnly, BiPredicate<T, T> comparator) {\n\t\tif (setA.isEmpty() || setB.isEmpty()) {\n\t\t\treturn setA.isEmpty() && setB.isEmpty() ? 1 : 0;\n\t\t}\n\n\t\tif (readOnly) {\n\t\t\tsetA = Util.newIdentityHashSet(setA);\n\t\t\tsetB = Util.newIdentityHashSet(setB);\n\t\t}\n\n\t\tfinal int total = setA.size() + setB.size();\n\t\tfinal boolean assumeBothOrNoneObfuscated = setA.iterator().next().getEnv().getGlobal().assumeBothOrNoneObfuscated;\n\t\tint unmatched = 0;\n\n\t\t// precise matches, nameObfuscated a\n\t\tfor (Iterator<T> it = setA.iterator(); it.hasNext(); ) {\n\t\t\tT a = it.next();\n\n\t\t\tif (setB.remove(a)) {\n\t\t\t\tit.remove();\n\t\t\t} else if (a.getMatch() != null) {\n\t\t\t\tif (!setB.remove(a.getMatch())) {\n\t\t\t\t\tunmatched++;\n\t\t\t\t}\n\n\t\t\t\tit.remove();\n\t\t\t} else if (assumeBothOrNoneObfuscated && !a.isNameObfuscated()) {\n\t\t\t\tunmatched++;\n\t\t\t\tit.remove();\n\t\t\t}\n\t\t}\n\n\t\t// nameObfuscated b\n\t\tif (assumeBothOrNoneObfuscated) {\n\t\t\tfor (Iterator<T> it = setB.iterator(); it.hasNext(); ) {\n\t\t\t\tT b = it.next();\n\n\t\t\t\tif (!b.isNameObfuscated()) {\n\t\t\t\t\tunmatched++;\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (Iterator<T> it = setA.iterator(); it.hasNext(); ) {\n\t\t\tT a = it.next();\n\n\t\t\tassert a.getMatch() == null && (!assumeBothOrNoneObfuscated || a.isNameObfuscated());\n\t\t\tboolean found = false;\n\n\t\t\tfor (T b : setB) {\n\t\t\t\tif (comparator.test(a, b)) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!found) {\n\t\t\t\tunmatched++;\n\t\t\t\tit.remove();\n\t\t\t}\n\t\t}\n\n\t\tfor (T b : setB) {\n\t\t\tboolean found = false;\n\n\t\t\tfor (T a : setA) {\n\t\t\t\tif (comparator.test(a, b)) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!found) {\n\t\t\t\tunmatched++;\n\t\t\t}\n\t\t}\n\n\t\tassert unmatched <= total;\n\n\t\treturn (double) (total - unmatched) / total;\n\t}\n\n\tpublic static double compareClassLists(List<ClassInstance> listA, List<ClassInstance> listB) {\n\t\treturn compareLists(listA, listB, List::get, List::size, (a, b) -> ClassifierUtil.checkPotentialEquality(a, b) ? COMPARED_SIMILAR : COMPARED_DISTINCT);\n\t}\n\n\tpublic static double compareInsns(MethodInstance a, MethodInstance b) {\n\t\tif (a.getAsmNode() == null || b.getAsmNode() == null) return 1;\n\n\t\tInsnList ilA = a.getAsmNode().instructions;\n\t\tInsnList ilB = b.getAsmNode().instructions;\n\n\t\treturn compareLists(ilA, ilB, InsnList::get, InsnList::size, (inA, inB) -> compareInsns(inA, inB, ilA, ilB, (list, item) -> list.indexOf(item), a, b, a.getEnv().getGlobal()));\n\t}\n\n\tpublic static double compareInsns(List<AbstractInsnNode> listA, List<AbstractInsnNode> listB, ClassEnvironment env) {\n\t\treturn compareLists(listA, listB, List::get, List::size, (inA, inB) -> compareInsns(inA, inB, listA, listB, (list, item) -> list.indexOf(item), null, null, env));\n\t}\n\n\tprivate static <T> int compareInsns(AbstractInsnNode insnA, AbstractInsnNode insnB, T listA, T listB, ToIntBiFunction<T, AbstractInsnNode> posProvider,\n\t\t\tMethodInstance mthA, MethodInstance mthB, ClassEnvironment env) {\n\t\tif (insnA.getOpcode() != insnB.getOpcode()) return COMPARED_DISTINCT;\n\n\t\tswitch (insnA.getType()) {\n\t\tcase AbstractInsnNode.INT_INSN: {\n\t\t\tIntInsnNode a = (IntInsnNode) insnA;\n\t\t\tIntInsnNode b = (IntInsnNode) insnB;\n\n\t\t\treturn a.operand == b.operand ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.VAR_INSN: {\n\t\t\tVarInsnNode a = (VarInsnNode) insnA;\n\t\t\tVarInsnNode b = (VarInsnNode) insnB;\n\n\t\t\tif (mthA != null && mthB != null) {\n\t\t\t\tMethodVarInstance varA = mthA.getArgOrVar(a.var, posProvider.applyAsInt(listA, insnA));\n\t\t\t\tMethodVarInstance varB = mthB.getArgOrVar(b.var, posProvider.applyAsInt(listB, insnB));\n\n\t\t\t\tif (varA != null && varB != null) {\n\t\t\t\t\tif (!checkPotentialEquality(varA, varB)) {\n\t\t\t\t\t\treturn COMPARED_DISTINCT;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn checkPotentialEquality(varA.getType(), varB.getType()) ? COMPARED_SIMILAR : COMPARED_POSSIBLE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.TYPE_INSN: {\n\t\t\tTypeInsnNode a = (TypeInsnNode) insnA;\n\t\t\tTypeInsnNode b = (TypeInsnNode) insnB;\n\t\t\tClassInstance clsA = env.getClsByNameA(a.desc);\n\t\t\tClassInstance clsB = env.getClsByNameB(b.desc);\n\n\t\t\treturn checkPotentialEqualityNullable(clsA, clsB) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.FIELD_INSN: {\n\t\t\tFieldInsnNode a = (FieldInsnNode) insnA;\n\t\t\tFieldInsnNode b = (FieldInsnNode) insnB;\n\t\t\tClassInstance clsA = env.getClsByNameA(a.owner);\n\t\t\tClassInstance clsB = env.getClsByNameB(b.owner);\n\n\t\t\tif (clsA == null && clsB == null) return COMPARED_SIMILAR;\n\t\t\tif (clsA == null || clsB == null) return COMPARED_DISTINCT;\n\n\t\t\tFieldInstance fieldA = clsA.resolveField(a.name, a.desc);\n\t\t\tFieldInstance fieldB = clsB.resolveField(b.name, b.desc);\n\n\t\t\treturn checkPotentialEqualityNullable(fieldA, fieldB) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.METHOD_INSN: {\n\t\t\tMethodInsnNode a = (MethodInsnNode) insnA;\n\t\t\tMethodInsnNode b = (MethodInsnNode) insnB;\n\n\t\t\treturn compareMethods(a.owner, a.name, a.desc, Util.isCallToInterface(a),\n\t\t\t\t\tb.owner, b.name, b.desc, Util.isCallToInterface(b),\n\t\t\t\t\tenv) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.INVOKE_DYNAMIC_INSN: {\n\t\t\tInvokeDynamicInsnNode a = (InvokeDynamicInsnNode) insnA;\n\t\t\tInvokeDynamicInsnNode b = (InvokeDynamicInsnNode) insnB;\n\n\t\t\tif (!a.bsm.equals(b.bsm)) return COMPARED_DISTINCT;\n\n\t\t\tif (Util.isJavaLambdaMetafactory(a.bsm)) {\n\t\t\t\tHandle implA = (Handle) a.bsmArgs[1];\n\t\t\t\tHandle implB = (Handle) b.bsmArgs[1];\n\n\t\t\t\tif (implA.getTag() != implB.getTag()) return COMPARED_DISTINCT;\n\n\t\t\t\tswitch (implA.getTag()) {\n\t\t\t\tcase Opcodes.H_INVOKEVIRTUAL:\n\t\t\t\tcase Opcodes.H_INVOKESTATIC:\n\t\t\t\tcase Opcodes.H_INVOKESPECIAL:\n\t\t\t\tcase Opcodes.H_NEWINVOKESPECIAL:\n\t\t\t\tcase Opcodes.H_INVOKEINTERFACE:\n\t\t\t\t\treturn compareMethods(implA.getOwner(), implA.getName(), implA.getDesc(), Util.isCallToInterface(implA),\n\t\t\t\t\t\t\timplB.getOwner(), implB.getName(), implB.getDesc(), Util.isCallToInterface(implB),\n\t\t\t\t\t\t\tenv) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t\t\tdefault:\n\t\t\t\t\tSystem.out.println(\"unexpected impl tag: \"+implA.getTag());\n\t\t\t\t}\n\t\t\t} else if (!Util.isIrrelevantBsm(a.bsm)) {\n\t\t\t\tSystem.out.printf(\"unknown invokedynamic bsm: %s/%s%s (tag=%d iif=%b)%n\", a.bsm.getOwner(), a.bsm.getName(), a.bsm.getDesc(), a.bsm.getTag(), a.bsm.isInterface());\n\t\t\t}\n\n\t\t\t// TODO: implement\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.JUMP_INSN: {\n\t\t\tJumpInsnNode a = (JumpInsnNode) insnA;\n\t\t\tJumpInsnNode b = (JumpInsnNode) insnB;\n\n\t\t\t// check if the 2 jumps have the same direction\n\t\t\tint dirA = Integer.signum(posProvider.applyAsInt(listA, a.label) - posProvider.applyAsInt(listA, a));\n\t\t\tint dirB = Integer.signum(posProvider.applyAsInt(listB, b.label) - posProvider.applyAsInt(listB, b));\n\n\t\t\treturn dirA == dirB ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.LABEL: {\n\t\t\t// TODO: implement\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.LDC_INSN: {\n\t\t\tLdcInsnNode a = (LdcInsnNode) insnA;\n\t\t\tLdcInsnNode b = (LdcInsnNode) insnB;\n\t\t\tClass<?> typeClsA = a.cst.getClass();\n\n\t\t\tif (typeClsA != b.cst.getClass()) return COMPARED_DISTINCT;\n\n\t\t\tif (typeClsA == Type.class) {\n\t\t\t\tType typeA = (Type) a.cst;\n\t\t\t\tType typeB = (Type) b.cst;\n\n\t\t\t\tif (typeA.getSort() != typeB.getSort()) return COMPARED_DISTINCT;\n\n\t\t\t\tswitch (typeA.getSort()) {\n\t\t\t\tcase Type.ARRAY:\n\t\t\t\tcase Type.OBJECT:\n\t\t\t\t\treturn checkPotentialEqualityNullable(env.getClsByIdA(typeA.getDescriptor()), env.getClsByIdB(typeB.getDescriptor())) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t\t\tcase Type.METHOD:\n\t\t\t\t\t// TODO: implement\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn a.cst.equals(b.cst) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.IINC_INSN: {\n\t\t\tIincInsnNode a = (IincInsnNode) insnA;\n\t\t\tIincInsnNode b = (IincInsnNode) insnB;\n\n\t\t\tif (a.incr != b.incr) return COMPARED_DISTINCT;\n\n\t\t\tif (mthA != null && mthB != null) {\n\t\t\t\tMethodVarInstance varA = mthA.getArgOrVar(a.var, posProvider.applyAsInt(listA, insnA));\n\t\t\t\tMethodVarInstance varB = mthB.getArgOrVar(b.var, posProvider.applyAsInt(listB, insnB));\n\n\t\t\t\tif (varA != null && varB != null) {\n\t\t\t\t\treturn checkPotentialEquality(varA, varB) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.TABLESWITCH_INSN: {\n\t\t\tTableSwitchInsnNode a = (TableSwitchInsnNode) insnA;\n\t\t\tTableSwitchInsnNode b = (TableSwitchInsnNode) insnB;\n\n\t\t\treturn a.min == b.min && a.max == b.max ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.LOOKUPSWITCH_INSN: {\n\t\t\tLookupSwitchInsnNode a = (LookupSwitchInsnNode) insnA;\n\t\t\tLookupSwitchInsnNode b = (LookupSwitchInsnNode) insnB;\n\n\t\t\treturn a.keys.equals(b.keys) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.MULTIANEWARRAY_INSN: {\n\t\t\tMultiANewArrayInsnNode a = (MultiANewArrayInsnNode) insnA;\n\t\t\tMultiANewArrayInsnNode b = (MultiANewArrayInsnNode) insnB;\n\n\t\t\tif (a.dims != b.dims) return COMPARED_DISTINCT;\n\n\t\t\tClassInstance clsA = env.getClsByNameA(a.desc);\n\t\t\tClassInstance clsB = env.getClsByNameB(b.desc);\n\n\t\t\treturn checkPotentialEqualityNullable(clsA, clsB) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.FRAME: {\n\t\t\t// TODO: implement\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.LINE: {\n\t\t\t// TODO: implement\n\t\t\tbreak;\n\t\t}\n\t\t}\n\n\t\treturn COMPARED_SIMILAR;\n\t}\n\n\tprivate static boolean compareMethods(String ownerA, String nameA, String descA, boolean toIfA, String ownerB, String nameB, String descB, boolean toIfB, ClassEnvironment env) {\n\t\tClassInstance clsA = env.getClsByNameA(ownerA);\n\t\tClassInstance clsB = env.getClsByNameB(ownerB);\n\n\t\tif (clsA == null && clsB == null) return true;\n\t\tif (clsA == null || clsB == null) return false;\n\n\t\treturn compareMethods(clsA, nameA, descA, toIfA, clsB, nameB, descB, toIfB);\n\t}\n\n\tprivate static boolean compareMethods(ClassInstance ownerA, String nameA, String descA, boolean toIfA, ClassInstance ownerB, String nameB, String descB, boolean toIfB) {\n\t\tMethodInstance methodA = ownerA.resolveMethod(nameA, descA, toIfA);\n\t\tMethodInstance methodB = ownerB.resolveMethod(nameB, descB, toIfB);\n\n\t\tif (methodA == null && methodB == null) return true;\n\t\tif (methodA == null || methodB == null) return false;\n\n\t\treturn checkPotentialEquality(methodA, methodB);\n\t}\n\n\tprivate static <T, U> double compareLists(T listA, T listB, ListElementRetriever<T, U> elementRetriever, ListSizeRetriever<T> sizeRetriever, ElementComparator<U> elementComparator) {\n\t\tfinal int sizeA = sizeRetriever.apply(listA);\n\t\tfinal int sizeB = sizeRetriever.apply(listB);\n\n\t\tif (sizeA == 0 && sizeB == 0) return 1;\n\t\tif (sizeA == 0 || sizeB == 0) return 0;\n\n\t\tif (sizeA == sizeB) {\n\t\t\tboolean match = true;\n\n\t\t\tfor (int i = 0; i < sizeA; i++) {\n\t\t\t\tif (elementComparator.compare(elementRetriever.apply(listA, i), elementRetriever.apply(listB, i)) != COMPARED_SIMILAR) {\n\t\t\t\t\tmatch = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (match) return 1;\n\t\t}\n\n\t\t// levenshtein distance as per wp (https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows)\n\t\tint[] v0 = new int[sizeB + 1];\n\t\tint[] v1 = new int[sizeB + 1];\n\n\t\tfor (int i = 1; i < v0.length; i++) {\n\t\t\tv0[i] = i * COMPARED_DISTINCT;\n\t\t}\n\n\t\tfor (int i = 0; i < sizeA; i++) {\n\t\t\tv1[0] = (i + 1) * COMPARED_DISTINCT;\n\n\t\t\tfor (int j = 0; j < sizeB; j++) {\n\t\t\t\tint cost = elementComparator.compare(elementRetriever.apply(listA, i), elementRetriever.apply(listB, j));\n\t\t\t\tv1[j + 1] = Math.min(Math.min(v1[j] + COMPARED_DISTINCT, v0[j + 1] + COMPARED_DISTINCT), v0[j] + cost);\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < v0.length; j++) {\n\t\t\t\tv0[j] = v1[j];\n\t\t\t}\n\t\t}\n\n\t\tint distance = v1[sizeB];\n\t\tint upperBound = Math.max(sizeA, sizeB) * COMPARED_DISTINCT;\n\t\tassert distance >= 0 && distance <= upperBound;\n\n\t\treturn 1 - (double) distance / upperBound;\n\t}\n\n\tpublic static int[] mapInsns(MethodInstance a, MethodInstance b) {\n\t\tif (a.getAsmNode() == null || b.getAsmNode() == null) return null;\n\n\t\tInsnList ilA = a.getAsmNode().instructions;\n\t\tInsnList ilB = b.getAsmNode().instructions;\n\n\t\tif (ilA.size() * ilB.size() < 1000) {\n\t\t\treturn mapInsns(ilA, ilB, a, b, a.getEnv().getGlobal());\n\t\t} else {\n\t\t\treturn a.getEnv().getGlobal().getCache().compute(ilMapCacheToken, a, b, (mA, mB) -> mapInsns(mA.getAsmNode().instructions, mB.getAsmNode().instructions, mA, mB, mA.getEnv().getGlobal()));\n\t\t}\n\t}\n\n\tpublic static int[] mapInsns(InsnList listA, InsnList listB, MethodInstance mthA, MethodInstance mthB, ClassEnvironment env) {\n\t\treturn mapLists(listA, listB, InsnList::get, InsnList::size, (inA, inB) -> compareInsns(inA, inB, listA, listB, (list, item) -> list.indexOf(item), mthA, mthB, env));\n\t}\n\n\tprivate static <T, U> int[] mapLists(T listA, T listB, ListElementRetriever<T, U> elementRetriever, ListSizeRetriever<T> sizeRetriever, ElementComparator<U> elementComparator) {\n\t\tfinal int sizeA = sizeRetriever.apply(listA);\n\t\tfinal int sizeB = sizeRetriever.apply(listB);\n\n\t\tif (sizeA == 0 && sizeB == 0) return new int[0];\n\n\t\tfinal int[] ret = new int[sizeA];\n\n\t\tif (sizeA == 0 || sizeB == 0) {\n\t\t\tArrays.fill(ret, -1);\n\n\t\t\treturn ret;\n\t\t}\n\n\t\tif (sizeA == sizeB) {\n\t\t\tboolean match = true;\n\n\t\t\tfor (int i = 0; i < sizeA; i++) {\n\t\t\t\tif (elementComparator.compare(elementRetriever.apply(listA, i), elementRetriever.apply(listB, i)) != COMPARED_SIMILAR) {\n\t\t\t\t\tmatch = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (match) {\n\t\t\t\tfor (int i = 0; i < ret.length; i++) {\n\t\t\t\t\tret[i] = i;\n\t\t\t\t}\n\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\t// levenshtein distance as per wp (https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows)\n\t\tint size = sizeA + 1;\n\t\tint[] v = new int[size * (sizeB + 1)];\n\n\t\tfor (int i = 1; i <= sizeA; i++) {\n\t\t\tv[i + 0] = i * COMPARED_DISTINCT;\n\t\t}\n\n\t\tfor (int j = 1; j <= sizeB; j++) {\n\t\t\tv[0 + j * size] = j * COMPARED_DISTINCT;\n\t\t}\n\n\t\tfor (int j = 1; j <= sizeB; j++) {\n\t\t\tfor (int i = 1; i <= sizeA; i++) {\n\t\t\t\tint cost = elementComparator.compare(elementRetriever.apply(listA, i - 1), elementRetriever.apply(listB, j - 1));\n\n\t\t\t\tv[i + j * size] = Math.min(Math.min(v[i - 1 + j * size] + COMPARED_DISTINCT,\n\t\t\t\t\t\tv[i + (j - 1) * size] + COMPARED_DISTINCT),\n\t\t\t\t\t\tv[i - 1 + (j - 1) * size] + cost);\n\t\t\t}\n\t\t}\n\n\t\t/*for (int j = 0; j <= sizeB; j++) {\n\t\t\tfor (int i = 0; i <= sizeA; i++) {\n\t\t\t\tSystem.out.printf(\"%2d \", v[i + j * size]);\n\t\t\t}\n\n\t\t\tSystem.out.println();\n\t\t}*/\n\n\t\tint i = sizeA;\n\t\tint j = sizeB;\n\t\t//boolean valid = true;\n\n\t\twhile (i > 0 || j > 0) {\n\t\t\tint c = v[i + j * size];\n\t\t\tint delCost = i > 0 ? v[i - 1 + j * size] : Integer.MAX_VALUE;\n\t\t\tint insCost = j > 0 ? v[i + (j - 1) * size] : Integer.MAX_VALUE;\n\t\t\tint keepCost = j > 0 && i > 0 ? v[i - 1 + (j - 1) * size] : Integer.MAX_VALUE;\n\n\t\t\tif (keepCost <= delCost && keepCost <= insCost) {\n\t\t\t\tif (c - keepCost >= COMPARED_DISTINCT) {\n\t\t\t\t\tassert c - keepCost == COMPARED_DISTINCT;\n\t\t\t\t\t//System.out.printf(\"%d/%d rep %s -> %s%n\", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)), toString(elementRetriever.apply(listB, j - 1)));\n\t\t\t\t\tret[i - 1] = -1;\n\t\t\t\t} else {\n\t\t\t\t\t//System.out.printf(\"%d/%d eq %s - %s%n\", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)), toString(elementRetriever.apply(listB, j - 1)));\n\t\t\t\t\tret[i - 1] = j - 1;\n\n\t\t\t\t\t/*U e = elementRetriever.apply(listA, i - 1);\n\n\t\t\t\t\tif (e instanceof AbstractInsnNode\n\t\t\t\t\t\t\t&& ((AbstractInsnNode) e).getOpcode() != ((AbstractInsnNode) elementRetriever.apply(listB, j - 1)).getOpcode()) {\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t}*/\n\t\t\t\t}\n\n\t\t\t\ti--;\n\t\t\t\tj--;\n\t\t\t} else if (delCost < insCost) {\n\t\t\t\t//System.out.printf(\"%d/%d del %s%n\", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)));\n\t\t\t\tret[i - 1] = -1;\n\t\t\t\ti--;\n\t\t\t} else {\n\t\t\t\t//System.out.printf(\"%d/%d ins %s%n\", i-1, j-1, toString(elementRetriever.apply(listB, j - 1)));\n\t\t\t\tj--;\n\t\t\t}\n\t\t}\n\n\t\t/*if (!valid) {\n\t\t\tassert valid;\n\t\t}*/\n\n\t\treturn ret;\n\t}\n\n\tpublic interface ElementComparator<T> {\n\t\tint compare(T a, T b);\n\t}\n\n\tpublic static final int COMPARED_SIMILAR = 0;\n\tpublic static final int COMPARED_POSSIBLE = 1;\n\tpublic static final int COMPARED_DISTINCT = 2;\n\n\tprivate static String toString(Object node) {\n\t\tif (node instanceof AbstractInsnNode) {\n\t\t\tTextifier textifier = new Textifier();\n\t\t\tMethodVisitor visitor = new TraceMethodVisitor(textifier);\n\n\t\t\t((AbstractInsnNode) node).accept(visitor);\n\n\t\t\treturn textifier.getText().get(0).toString().trim();\n\t\t} else {\n\t\t\treturn Objects.toString(node);\n\t\t}\n\t}\n\n\tprivate interface ListElementRetriever<T, U> {\n\t\tU apply(T list, int pos);\n\t}\n\n\tprivate interface ListSizeRetriever<T> {\n\t\tint apply(T list);\n\t}\n\n\tpublic static <T extends Matchable<T>> List<RankResult<T>> rank(T src, T[] dsts, Collection<IClassifier<T>> classifiers, BiPredicate<T, T> potentialEqualityCheck, ClassEnvironment env, double maxMismatch) {\n\t\tList<RankResult<T>> ret = new ArrayList<>(dsts.length);\n\n\t\tfor (T dst : dsts) {\n\t\t\tRankResult<T> result = rank(src, dst, classifiers, potentialEqualityCheck, env, maxMismatch);\n\t\t\tif (result != null) ret.add(result);\n\t\t}\n\n\t\tret.sort(Comparator.<RankResult<T>, Double>comparing(RankResult::getScore).reversed());\n\n\t\treturn ret;\n\t}\n\n\tpublic static <T extends Matchable<T>> List<RankResult<T>> rankParallel(T src, T[] dsts, Collection<IClassifier<T>> classifiers, BiPredicate<T, T> potentialEqualityCheck, ClassEnvironment env, double maxMismatch) {\n\t\treturn Arrays.stream(dsts)\n\t\t\t\t.parallel()\n\t\t\t\t.map(dst -> rank(src, dst, classifiers, potentialEqualityCheck, env, maxMismatch))\n\t\t\t\t.filter(Objects::nonNull)\n\t\t\t\t.sorted(Comparator.<RankResult<T>, Double>comparing(RankResult::getScore).reversed())\n\t\t\t\t.collect(Collectors.toList());\n\t}\n\n\tprivate static <T extends Matchable<T>> RankResult<T> rank(T src, T dst, Collection<IClassifier<T>> classifiers, BiPredicate<T, T> potentialEqualityCheck, ClassEnvironment env, double maxMismatch) {\n\t\tassert src.getEnv() != dst.getEnv();\n\n\t\tif (!potentialEqualityCheck.test(src, dst)) return null;\n\n\t\tdouble score = 0;\n\t\tdouble mismatch = 0;\n\t\tList<ClassifierResult<T>> results = new ArrayList<>(classifiers.size());\n\n\t\tfor (IClassifier<T> classifier : classifiers) {\n\t\t\tdouble cScore = classifier.getScore(src, dst, env);\n\t\t\tassert cScore > -epsilon && cScore < 1 + epsilon : \"invalid score from \"+classifier.getName()+\": \"+cScore;\n\n\t\t\tdouble weight = classifier.getWeight();\n\t\t\tdouble weightedScore = cScore * weight;\n\n\t\t\tmismatch += weight - weightedScore;\n\t\t\tif (mismatch >= maxMismatch) return null;\n\n\t\t\tscore += weightedScore;\n\t\t\tresults.add(new ClassifierResult<>(classifier, cScore));\n\t\t}\n\n\t\treturn new RankResult<>(dst, score, results);\n\t}\n\n\tpublic static void extractStrings(InsnList il, Set<String> out) {\n\t\textractStrings(il.iterator(), out);\n\t}\n\n\tpublic static void extractStrings(Collection<AbstractInsnNode> il, Set<String> out) {\n\t\textractStrings(il.iterator(), out);\n\t}\n\n\tprivate static void extractStrings(Iterator<AbstractInsnNode> it, Set<String> out) {\n\t\twhile (it.hasNext()) {\n\t\t\tAbstractInsnNode aInsn = it.next();\n\n\t\t\tif (aInsn instanceof LdcInsnNode) {\n\t\t\t\tLdcInsnNode insn = (LdcInsnNode) aInsn;\n\n\t\t\t\tif (insn.cst instanceof String) {\n\t\t\t\t\tout.add((String) insn.cst);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void extractNumbers(MethodNode node, Set<Integer> ints, Set<Long> longs, Set<Float> floats, Set<Double> doubles) {\n\t\tfor (Iterator<AbstractInsnNode> it = node.instructions.iterator(); it.hasNext(); ) {\n\t\t\tAbstractInsnNode aInsn = it.next();\n\n\t\t\tif (aInsn instanceof LdcInsnNode) {\n\t\t\t\tLdcInsnNode insn = (LdcInsnNode) aInsn;\n\n\t\t\t\thandleNumberValue(insn.cst, ints, longs, floats, doubles);\n\t\t\t} else if (aInsn instanceof IntInsnNode) {\n\t\t\t\tIntInsnNode insn = (IntInsnNode) aInsn;\n\n\t\t\t\tints.add(insn.operand);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void handleNumberValue(Object number, Set<Integer> ints, Set<Long> longs, Set<Float> floats, Set<Double> doubles) {\n\t\tif (number == null) return;\n\n\t\tif (number instanceof Integer) {\n\t\t\tints.add((Integer) number);\n\t\t} else if (number instanceof Long) {\n\t\t\tlongs.add((Long) number);\n\t\t} else if (number instanceof Float) {\n\t\t\tfloats.add((Float) number);\n\t\t} else if (number instanceof Double) {\n\t\t\tdoubles.add((Double) number);\n\t\t}\n\t}\n\n\tpublic static <T extends Matchable<T>> double classifyPosition(T a, T b,\n\t\t\tToIntFunction<T> positionSupplier,\n\t\t\tBiFunction<T, Integer, T> siblingSupplier,\n\t\t\tFunction<T, T[]> siblingsSupplier) {\n\t\tint posA = positionSupplier.applyAsInt(a);\n\t\tint posB = positionSupplier.applyAsInt(b);\n\t\tT[] siblingsA = siblingsSupplier.apply(a);\n\t\tT[] siblingsB = siblingsSupplier.apply(b);\n\n\t\tif (posA == posB && siblingsA.length == siblingsB.length) return 1;\n\t\tif (posA == -1 || posB == -1) return posA == posB ? 1 : 0;\n\n\t\t// try to find the index range enclosed by other mapped members and compare relative to it\n\t\tint startPosA = 0;\n\t\tint startPosB = 0;\n\t\tint endPosA = siblingsA.length;\n\t\tint endPosB = siblingsB.length;\n\n\t\tif (posA > 0) {\n\t\t\tfor (int i = posA - 1; i >= 0; i--) {\n\t\t\t\tT c = siblingSupplier.apply(a, i);\n\t\t\t\tT match = c.getMatch();\n\n\t\t\t\tif (match != null) {\n\t\t\t\t\tstartPosA = i + 1;\n\t\t\t\t\tstartPosB = positionSupplier.applyAsInt(match) + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (posA < endPosA - 1) {\n\t\t\tfor (int i = posA + 1; i < endPosA; i++) {\n\t\t\t\tT c = siblingSupplier.apply(a, i);\n\t\t\t\tT match = c.getMatch();\n\n\t\t\t\tif (match != null) {\n\t\t\t\t\tendPosA = i;\n\t\t\t\t\tendPosB = positionSupplier.applyAsInt(match);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (startPosB >= endPosB || startPosB > posB || endPosB <= posB) {\n\t\t\tstartPosA = startPosB = 0;\n\t\t\tendPosA = siblingsA.length;\n\t\t\tendPosB = siblingsB.length;\n\t\t}\n\n\t\tdouble relPosA = getRelativePosition(posA - startPosA, endPosA - startPosA);\n\t\tassert relPosA >= 0 && relPosA <= 1;\n\t\tdouble relPosB = getRelativePosition(posB - startPosB, endPosB - startPosB);\n\t\tassert relPosB >= 0 && relPosB <= 1;\n\n\t\treturn 1 - Math.abs(relPosA - relPosB);\n\t}\n\n\tprivate static double getRelativePosition(int position, int size) {\n\t\tif (size == 1) return 0.5;\n\t\tassert size > 1;\n\n\t\treturn (double) position / (size - 1);\n\t}\n\n\tprivate static final double epsilon = 1e-6;\n\n\tprivate static final CacheToken<int[]> ilMapCacheToken = new CacheToken<>();\n}",
"public static final class ClassSignature implements PotentialComparable<ClassSignature> {\n\tpublic static ClassSignature parse(String sig, ClassEnv env) {\n\t\t// [<TypeParameter+>] ClassTypeSignature ClassTypeSignature*\n\t\tClassSignature ret = new ClassSignature();\n\t\tMutableInt pos = new MutableInt();\n\n\t\tif (sig.startsWith(\"<\")) {\n\t\t\tpos.val++;\n\t\t\tret.typeParameters = new ArrayList<>();\n\n\t\t\tdo {\n\t\t\t\tret.typeParameters.add(TypeParameter.parse(sig, pos, env));\n\t\t\t} while (sig.charAt(pos.val) != '>');\n\n\t\t\tpos.val++;\n\t\t}\n\n\t\tret.superClassSignature = ClassTypeSignature.parse(sig, pos, env);\n\n\t\tif (pos.val < sig.length()) {\n\t\t\tret.superInterfaceSignatures = new ArrayList<>();\n\n\t\t\tdo {\n\t\t\t\tret.superInterfaceSignatures.add(ClassTypeSignature.parse(sig, pos, env));\n\t\t\t} while (pos.val < sig.length());\n\t\t}\n\n\t\tassert ret.toString().equals(sig);\n\n\t\treturn ret;\n\t}\n\n\tpublic String toString(NameType nameType) {\n\t\tStringBuilder ret = new StringBuilder();\n\n\t\tif (typeParameters != null) {\n\t\t\tret.append('<');\n\n\t\t\tfor (TypeParameter tp : typeParameters) {\n\t\t\t\tret.append(tp.toString(nameType));\n\t\t\t}\n\n\t\t\tret.append('>');\n\t\t}\n\n\t\tret.append(superClassSignature.toString(nameType));\n\n\t\tif (superInterfaceSignatures != null) {\n\t\t\tfor (ClassTypeSignature ts : superInterfaceSignatures) {\n\t\t\t\tret.append(ts.toString(nameType));\n\t\t\t}\n\t\t}\n\n\t\treturn ret.toString();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn toString(NameType.PLAIN);\n\t}\n\n\t@Override\n\tpublic boolean isPotentiallyEqual(ClassSignature o) {\n\t\treturn Signature.isPotentiallyEqual(typeParameters, o.typeParameters)\n\t\t\t\t&& superClassSignature.isPotentiallyEqual(o.superClassSignature)\n\t\t\t\t&& Signature.isPotentiallyEqual(superInterfaceSignatures, o.superInterfaceSignatures);\n\t}\n\n\t// [<\n\tList<TypeParameter> typeParameters;\n\t// >]\n\tClassTypeSignature superClassSignature;\n\tList<ClassTypeSignature> superInterfaceSignatures;\n}"
] | import java.net.URI;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import matcher.NameType;
import matcher.SimilarityChecker;
import matcher.Util;
import matcher.bcremap.AsmClassRemapper;
import matcher.bcremap.AsmRemapper;
import matcher.classifier.ClassifierUtil;
import matcher.type.Signature.ClassSignature; | }
ret = sb.toString();
}
return full ? ret : ret.substring(ret.lastIndexOf('.') + 1);
}
public boolean isReal() {
return origin != null;
}
public URI getOrigin() {
return origin;
}
@Override
public Matchable<?> getOwner() {
return null;
}
@Override
public ClassEnv getEnv() {
return env;
}
public ClassNode[] getAsmNodes() {
return asmNodes;
}
public URI getAsmNodeOrigin(int index) {
if (index < 0 || index > 0 && (asmNodeOrigins == null || index >= asmNodeOrigins.length)) throw new IndexOutOfBoundsException(index);
return index == 0 ? origin : asmNodeOrigins[index];
}
public ClassNode getMergedAsmNode() {
if (asmNodes == null) return null;
if (asmNodes.length == 1) return asmNodes[0];
return asmNodes[0]; // TODO: actually merge
}
void addAsmNode(ClassNode node, URI origin) {
if (!input) throw new IllegalStateException("not mergeable");
asmNodes = Arrays.copyOf(asmNodes, asmNodes.length + 1);
asmNodes[asmNodes.length - 1] = node;
if (asmNodeOrigins == null) {
asmNodeOrigins = new URI[2];
asmNodeOrigins[0] = this.origin;
} else {
asmNodeOrigins = Arrays.copyOf(asmNodeOrigins, asmNodeOrigins.length + 1);
}
asmNodeOrigins[asmNodeOrigins.length - 1] = origin;
}
@Override
public boolean hasPotentialMatch() {
if (matchedClass != null) return true;
if (!isMatchable()) return false;
for (ClassInstance o : env.getOther().getClasses()) {
if (o.isReal() && ClassifierUtil.checkPotentialEquality(this, o)) return true;
}
return false;
}
@Override
public boolean isMatchable() {
return matchable;
}
@Override
public boolean setMatchable(boolean matchable) {
if (!matchable && matchedClass != null) return false;
this.matchable = matchable;
return true;
}
@Override
public ClassInstance getMatch() {
return matchedClass;
}
public void setMatch(ClassInstance cls) {
assert cls == null || isMatchable();
assert cls == null || cls.getEnv() != env && !cls.getEnv().isShared();
this.matchedClass = cls;
}
@Override
public boolean isFullyMatched(boolean recursive) {
if (matchedClass == null) return false;
for (MethodInstance m : methods) {
if (m.hasPotentialMatch() && (!m.hasMatch() || recursive && !m.isFullyMatched(true))) {
return false;
}
}
for (FieldInstance m : fields) {
if (m.hasPotentialMatch() && (!m.hasMatch() || recursive && !m.isFullyMatched(true))) {
return false;
}
}
return true;
}
@Override
public float getSimilarity() {
if (matchedClass == null) return 0;
| return SimilarityChecker.compare(this, matchedClass); | 1 |
otto-de/edison-jobtrigger | src/main/java/de/otto/edison/jobtrigger/trigger/TriggerService.java | [
"@Component\n@ConfigurationProperties(prefix = \"edison.jobtrigger\")\npublic class JobTriggerProperties {\n\n @Valid\n private Jobresults jobresults = new Jobresults();\n\n @Valid\n private Scheduler scheduler = new Scheduler();\n\n @Valid\n private Security security = new Security();\n\n\n public Jobresults getJobresults() {\n return jobresults;\n }\n\n public void setJobresults(Jobresults jobresults) {\n this.jobresults = jobresults;\n }\n\n public Security getSecurity() {\n return security;\n }\n\n public void setSecurity(Security security) {\n this.security = security;\n }\n\n public Scheduler getScheduler() {\n return scheduler;\n }\n\n public void setScheduler(Scheduler scheduler) {\n this.scheduler = scheduler;\n }\n\n public static class Jobresults {\n\n @Min(0)\n private int max = 1000;\n\n public int getMax() {\n return max;\n }\n\n public void setMax(int max) {\n this.max = max;\n }\n }\n\n public static class Scheduler {\n\n @Min(1)\n private int poolsize = 10;\n\n public int getPoolsize() {\n return poolsize;\n }\n\n public void setPoolsize(int poolsize) {\n this.poolsize = poolsize;\n }\n }\n\n public static class Security {\n\n private String basicAuthUser;\n\n private String basicAuthPasswd;\n\n public String getBasicAuthUser() {\n return basicAuthUser;\n }\n\n public String getBasicAuthPasswd() {\n return basicAuthPasswd;\n }\n\n public void setBasicAuthUser(String basicAuthUser) {\n this.basicAuthUser = basicAuthUser;\n }\n\n public void setBasicAuthPasswd(String basicAuthPasswd) {\n this.basicAuthPasswd = basicAuthPasswd;\n }\n }\n\n}",
"public class JobDefinition {\n private final String definitionUrl;\n private final String env;\n private final String service;\n private final String triggerUrl;\n private final String jobType;\n private final String description;\n private final Optional<String> cron;\n private Optional<Duration> fixedDelay;\n final int retries;\n final Optional<Duration> retryDelay;\n\n public JobDefinition(final String definitionUrl,\n final String env,\n final String service,\n final String triggerUrl,\n final String jobType,\n final String description,\n final Optional<String> cron,\n final Optional<Duration> fixedDelay,\n final int retries,\n final Optional<Duration> retryDelay) {\n this.definitionUrl = definitionUrl;\n this.env = env;\n this.service = service;\n this.triggerUrl = triggerUrl;\n this.jobType = jobType;\n this.description = description;\n this.cron = cron;\n this.fixedDelay = fixedDelay;\n this.retries = retries;\n this.retryDelay = retryDelay;\n }\n\n public String getDefinitionUrl() {\n return definitionUrl;\n }\n\n public String getJobType() {\n return jobType;\n }\n\n public String getEnv() {\n return env;\n }\n\n public String getService() {\n return service;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Optional<String> getCron() {\n return cron;\n }\n\n public String getTriggerUrl() {\n return triggerUrl;\n }\n\n public Optional<Duration> getFixedDelay() {\n return fixedDelay;\n }\n\n public int getRetries() {\n return retries;\n }\n\n public Optional<Duration> getRetryDelay() {\n return retryDelay;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n JobDefinition that = (JobDefinition) o;\n\n if (retries != that.retries) return false;\n if (cron != null ? !cron.equals(that.cron) : that.cron != null) return false;\n if (definitionUrl != null ? !definitionUrl.equals(that.definitionUrl) : that.definitionUrl != null)\n return false;\n if (description != null ? !description.equals(that.description) : that.description != null) return false;\n if (env != null ? !env.equals(that.env) : that.env != null) return false;\n if (fixedDelay != null ? !fixedDelay.equals(that.fixedDelay) : that.fixedDelay != null) return false;\n if (jobType != null ? !jobType.equals(that.jobType) : that.jobType != null) return false;\n if (retryDelay != null ? !retryDelay.equals(that.retryDelay) : that.retryDelay != null) return false;\n if (service != null ? !service.equals(that.service) : that.service != null) return false;\n if (triggerUrl != null ? !triggerUrl.equals(that.triggerUrl) : that.triggerUrl != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = definitionUrl != null ? definitionUrl.hashCode() : 0;\n result = 31 * result + (env != null ? env.hashCode() : 0);\n result = 31 * result + (service != null ? service.hashCode() : 0);\n result = 31 * result + (triggerUrl != null ? triggerUrl.hashCode() : 0);\n result = 31 * result + (jobType != null ? jobType.hashCode() : 0);\n result = 31 * result + (description != null ? description.hashCode() : 0);\n result = 31 * result + (cron != null ? cron.hashCode() : 0);\n result = 31 * result + (fixedDelay != null ? fixedDelay.hashCode() : 0);\n result = 31 * result + retries;\n result = 31 * result + (retryDelay != null ? retryDelay.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"JobDefinition{\" +\n \"cron=\" + cron +\n \", definitionUrl='\" + definitionUrl + '\\'' +\n \", env='\" + env + '\\'' +\n \", service='\" + service + '\\'' +\n \", triggerUrl='\" + triggerUrl + '\\'' +\n \", jobType='\" + jobType + '\\'' +\n \", description='\" + description + '\\'' +\n \", fixedDelay=\" + fixedDelay +\n \", retries=\" + retries +\n \", retryDelay=\" + retryDelay +\n '}';\n }\n}",
"public interface DiscoveryListener {\n\n void updatedJobDefinitions();\n\n}",
"@Service\npublic class DiscoveryService {\n\n private static final Logger LOG = LoggerFactory.getLogger(DiscoveryService.class);\n public static final String JOB_DEFINITION_LINK_RELATION_TYPE = \"http://github.com/otto-de/edison/link-relations/job/definition\";\n public static final String JOB_TRIGGER_LINK_RELATION_TYPE = \"http://github.com/otto-de/edison/link-relations/job/trigger\";\n\n private AsyncHttpClient httpClient;\n private Registry serviceRegistry;\n private AuthProvider authHeaderProvider;\n\n private volatile DiscoveryListener listener;\n private volatile ImmutableList<JobDefinition> jobDefinitions = ImmutableList.of();\n\n public DiscoveryService(AsyncHttpClient asyncHttpClient, Registry serviceRegistry, AuthProvider authHeaderProvider) {\n httpClient = asyncHttpClient;\n this.serviceRegistry = serviceRegistry;\n this.authHeaderProvider = authHeaderProvider;\n }\n\n @PostConstruct\n public void postConstruct() {\n newSingleThreadScheduledExecutor().scheduleWithFixedDelay(this::rediscover, 0, 1, MINUTES);\n }\n\n public void register(final DiscoveryListener listener) {\n this.listener = listener;\n }\n\n public void rediscover() {\n LOG.info(\"Starting rediscovery of job definitions...\");\n final ImmutableList<JobDefinition> discoveryResult = discover();\n if (discoveryResult.size() != jobDefinitions.size() || !discoveryResult.containsAll(jobDefinitions)) {\n LOG.info(\"Discovered changes in job definitions. Old: \" + jobDefinitions + \" New: \" + discoveryResult);\n LOG.info(\"Discovered changes in job definitions. Diff: \" + symmetricDifference(copyOf(jobDefinitions), copyOf(discoveryResult)));\n jobDefinitions = discoveryResult;\n listener.updatedJobDefinitions();\n } else {\n LOG.info(\"No changes in job definitions\");\n }\n LOG.info(\"...done\");\n }\n\n public List<JobDefinition> allJobDefinitions() {\n return jobDefinitions;\n }\n\n private ImmutableList<JobDefinition> discover() {\n final List<JobDefinition> result = new CopyOnWriteArrayList<>();\n serviceRegistry.findServices()\n .parallelStream()\n .forEach(service -> {\n final String jobDefinitionsUrl = service.getHref() + \"/internal/jobdefinitions\";\n try {\n LOG.info(\"Trying to find job definitions at \" + jobDefinitionsUrl);\n final BoundRequestBuilder boundRequestBuilder = httpClient\n .prepareGet(jobDefinitionsUrl);\n authHeaderProvider.setAuthHeader(boundRequestBuilder);\n final Response response = boundRequestBuilder\n .setHeader(\"Accept\", \"application/json\")\n .execute().get();\n if (response.getStatusCode() < 300) {\n result.addAll(jobDefinitionsFrom(service, response));\n } else {\n LOG.info(\"No definitions found for {}. Status={}\", service.getService(), response.getStatusCode());\n }\n } catch (final Exception e) {\n LOG.warn(\"Did not get a response from {} with Exception message '{}'.\", jobDefinitionsUrl, e.getMessage(), e);\n }\n });\n return ImmutableList.copyOf(result);\n }\n\n @VisibleForTesting\n List<JobDefinition> jobDefinitionsFrom(final RegisteredService service, final Response jobDefinitionsResponse) {\n final LinksRepresentation document = new Gson()\n .fromJson(jobDefinitionsResponse.getResponseBody(), LinksRepresentation.class);\n final List<String> jobDefinitionUrls = document.getLinks().stream()\n .filter(l -> l.rel.equals(JOB_DEFINITION_LINK_RELATION_TYPE))\n .map(l -> l.href)\n .collect(toList());\n if (jobDefinitionUrls.isEmpty()) {\n LOG.warn(\"Did not find any URLs with rel={}\", JOB_DEFINITION_LINK_RELATION_TYPE);\n }\n final List<JobDefinition> jobDefinitions = new CopyOnWriteArrayList<>();\n jobDefinitionUrls\n .stream()\n .forEach(definitionUrl -> {\n try {\n LOG.info(\"Getting job definition from \" + definitionUrl);\n final BoundRequestBuilder boundRequestBuilder = httpClient\n .prepareGet(definitionUrl);\n authHeaderProvider.setAuthHeader(boundRequestBuilder);\n final Response response = boundRequestBuilder\n .setHeader(\"Accept\", \"application/json\")\n .execute().get();\n if (response.getStatusCode() < 300) {\n jobDefinitions.add(jobDefinitionFrom(definitionUrl, service, response));\n } else {\n LOG.info(\"Failed to get job definition with \" + response.getStatusCode());\n }\n } catch (InterruptedException | ExecutionException e) {\n LOG.warn(\"Did not get a job definition from {}: {}\", definitionUrl, e.getMessage());\n }\n });\n LOG.info(\"Found \" + jobDefinitions.size() + \" job definitions.\");\n return jobDefinitions;\n }\n\n @VisibleForTesting\n JobDefinition jobDefinitionFrom(final String definitionUrl, final RegisteredService service, final Response response) {\n final JobDefinitionRepresentation def = new Gson()\n .fromJson(response.getResponseBody(), JobDefinitionRepresentation.class);\n final Optional<Link> triggerLink = def.getLinks().stream()\n .filter(l -> l.rel.equals(JOB_TRIGGER_LINK_RELATION_TYPE))\n .findAny();\n if (triggerLink.isPresent()) {\n return new JobDefinition(\n definitionUrl,\n service.getEnvironment(),\n service.getService(),\n triggerLink.get().href,\n def.getType(),\n def.getName(),\n ofNullable(def.getCron()),\n ofNullable(def.getFixedDelay() != null ? ofSeconds(def.getFixedDelay()) : null),\n def.getRetries(),\n ofNullable(def.getRetryDelay() != null ? ofSeconds(def.getRetryDelay()) : null)\n );\n } else {\n LOG.warn(\"No link to job trigger found: \" + def);\n return null;\n }\n }\n}",
"@Component\n@EnableConfigurationProperties(JobTriggerProperties.class)\npublic class BasicAuthCredentials {\n\n private static final String VAULT_PREFIX = \"VAULT \";\n public static String AUTHORIZATION_HEADER = \"Authorization\";\n\n private static final String BASIC_PREFIX = \"Basic \";\n\n private final String basicAuthUser;\n private final String basicAuthPasswd;\n\n @Autowired\n public BasicAuthCredentials(final JobTriggerProperties jobTriggerProperties, final VaultOperations vaultOperations) {\n basicAuthUser = jobTriggerProperties.getSecurity().getBasicAuthUser();\n String passwd = jobTriggerProperties.getSecurity().getBasicAuthPasswd();\n\n if(passwd != null && passwd.startsWith(VAULT_PREFIX)) {\n String vaultPath = passwd.substring(VAULT_PREFIX.length());\n basicAuthPasswd = vaultOperations.read(vaultPath).getData().get(\"value\").toString();\n } else {\n basicAuthPasswd = passwd;\n }\n }\n\n public Optional<String> base64Encoded() {\n if (basicAuthUser == null || basicAuthPasswd == null) {\n return Optional.empty();\n } else {\n final String credentials = basicAuthUser + \":\" + basicAuthPasswd;\n return Optional.of(BASIC_PREFIX + Base64.getEncoder().encodeToString(credentials.getBytes()));\n }\n }\n}",
"public static TriggerStatus fromHttpStatus(final int statusCode) {\n final String message;\n final State state;\n switch (statusCode) {\n case SC_OK:\n case SC_CREATED:\n case SC_ACCEPTED:\n case SC_NO_CONTENT:\n message = TRIGGERED;\n state = State.OK;\n break;\n case SC_CONFLICT:\n message = BLOCKED;\n state = State.BLOCKED;\n break;\n case SC_NOT_FOUND:\n message = NOT_FOUND;\n state = State.FAILED;\n break;\n default:\n message = FAILED + statusCode;\n state = State.FAILED;\n }\n return new TriggerStatus(state, message);\n}",
"public static TriggerStatus fromMessage(final String message) {\n return new TriggerStatus(State.FAILED, message);\n}",
"public static Trigger periodicTrigger(final Duration delay) {\n return new PeriodicTrigger(delay.getSeconds() * 1000L);\n}"
] | import de.otto.edison.jobtrigger.configuration.JobTriggerProperties;
import de.otto.edison.jobtrigger.definition.JobDefinition;
import de.otto.edison.jobtrigger.discovery.DiscoveryListener;
import de.otto.edison.jobtrigger.discovery.DiscoveryService;
import de.otto.edison.jobtrigger.security.BasicAuthCredentials;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.Response;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.Trigger;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import static de.otto.edison.jobtrigger.trigger.TriggerStatus.fromHttpStatus;
import static de.otto.edison.jobtrigger.trigger.TriggerStatus.fromMessage;
import static de.otto.edison.jobtrigger.trigger.Triggers.periodicTrigger;
import static java.lang.String.valueOf;
import static java.time.Duration.of;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
import static org.slf4j.LoggerFactory.getLogger; | package de.otto.edison.jobtrigger.trigger;
/**
* @author Guido Steinacker
* @since 05.09.15
*/
@Service
@EnableConfigurationProperties(JobTriggerProperties.class)
public class TriggerService implements DiscoveryListener {
private static final Logger LOG = getLogger(TriggerService.class);
private DiscoveryService discoveryService;
private JobScheduler scheduler;
private AsyncHttpClient httpClient;
private final TriggerRunnablesService triggerRunnablesService;
private int maxJobResults = 1000;
private final Deque<TriggerResult> lastResults = new ConcurrentLinkedDeque<>();
private final AtomicBoolean isStarted = new AtomicBoolean(false);
private final AtomicLong currentIndex = new AtomicLong(0);
private BasicAuthCredentials basicAuthCredentials;
@Autowired
public TriggerService(final DiscoveryService discoveryService,
final JobScheduler scheduler,
final AsyncHttpClient httpClient,
final JobTriggerProperties jobTriggerProperties,
final BasicAuthCredentials basicAuthCredentials,
final TriggerRunnablesService triggerRunnablesService) {
this.discoveryService = discoveryService;
this.scheduler = scheduler;
this.httpClient = httpClient;
this.maxJobResults = jobTriggerProperties.getJobresults().getMax();
this.basicAuthCredentials = basicAuthCredentials;
this.triggerRunnablesService = triggerRunnablesService;
}
@PostConstruct
public void postConstruct() {
discoveryService.register(this);
}
public void startTriggering() {
final List<JobDefinition> jobDefinitions = discoveryService.allJobDefinitions();
scheduler.updateTriggers(jobDefinitions
.stream()
.filter(jobDefinition -> jobDefinition.getFixedDelay().isPresent() || jobDefinition.getCron().isPresent())
.map(toJobTrigger())
.collect(toList()));
isStarted.set(true);
}
public void stopTriggering() {
scheduler.stopAllTriggers();
isStarted.set(false);
}
@Override
public void updatedJobDefinitions() {
startTriggering();
}
public boolean isStarted() {
return isStarted.get();
}
public List<TriggerResult> getLastResults() {
return new ArrayList<>(lastResults);
}
private Runnable runnableFor(final JobDefinition jobDefinition) {
return triggerRunnablesService.httpTriggerRunnable(jobDefinition, new DefaultTriggerResponseConsumer(jobDefinition));
}
private Function<JobDefinition, JobTrigger> toJobTrigger() {
return jobDefinition -> {
try {
return new JobTrigger(jobDefinition, triggerFor(jobDefinition), runnableFor(jobDefinition));
} catch (final Exception e) {
final Runnable failingJobRunnable = () -> {
lastResults.addFirst(new TriggerResult(nextId(), fromMessage(e.getMessage()), emptyMessage(), jobDefinition));
}; | return new JobTrigger(jobDefinition, periodicTrigger(of(10, MINUTES)), failingJobRunnable); | 7 |
domenique/tripled-framework | eventstore-core/src/test/java/eu/tripledframework/eventstore/infrastructure/ReflectionObjectConstructorTest.java | [
"public class DomainEvent {\n\n private String id;\n private String aggregateRootIdentifier;\n private int revision;\n private ZonedDateTime timestamp;\n\n public DomainEvent(String aggregateRootIdentifier) {\n this.id = UUID.randomUUID().toString();\n this.aggregateRootIdentifier = aggregateRootIdentifier;\n this.timestamp = ZonedDateTime.now();\n this.revision = 0;\n }\n\n public DomainEvent(String aggregateRootIdentifier, int revision) {\n // TODO: Where should the revision come from ?\n // it should be an incrementing number this should not be in the domainEvent?\n this.id = UUID.randomUUID().toString();\n this.aggregateRootIdentifier = aggregateRootIdentifier;\n this.timestamp = ZonedDateTime.now();\n this.revision = revision;\n }\n\n protected DomainEvent() {\n // for frameworks\n }\n\n public String getId() {\n return id;\n }\n\n public String getAggregateRootIdentifier() {\n return aggregateRootIdentifier;\n }\n\n public int getRevision() {\n return revision;\n }\n\n public ZonedDateTime getTimestamp() {\n return timestamp;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n final DomainEvent other = (DomainEvent) obj;\n return Objects.equals(this.id, other.id);\n }\n}",
"public class MyAggregateRoot implements ConstructionAware {\n\n public String identifier;\n public String name;\n public String address;\n public boolean postReconstructCalled;\n public boolean constructorCalled;\n public boolean updateAddressCalled;\n public boolean updateAddressWhichCannotBeInvokedCalled;\n\n @ConstructionHandler(MyAggregateRootCreatedEvent.class)\n public MyAggregateRoot(@EP(\"aggregateRootIdentifier\") String identifier, @EP(\"name\") String name) {\n this.identifier = identifier;\n this.name = name;\n this.constructorCalled = true;\n }\n\n @ConstructionHandler(AddressUpdatedEvent.class)\n public void updateAddress(@EP(\"address\") String address) {\n this.address = address;\n this.updateAddressCalled = true;\n }\n\n @ConstructionHandler(AddressUpdatedEventWhichCannotBeInvoked.class)\n public void updateAddressWhichCannotBeInvoked() throws InvocationTargetException {\n this.updateAddressWhichCannotBeInvokedCalled = true;\n throw new InvocationTargetException(null, \"oeps\");\n }\n\n @Override\n public void postConstruct() {\n this.postReconstructCalled = true;\n }\n\n public void reset() {\n constructorCalled = false;\n updateAddressCalled = false;\n updateAddressWhichCannotBeInvokedCalled = false;\n }\n}",
"public abstract class NotInstantiatableAggregateRoot implements ConstructionAware {\n\n private final String identifier;\n private final String name;\n\n @ConstructionHandler(MyAggregateRootCreatedEvent.class)\n public NotInstantiatableAggregateRoot(@EP(\"aggregateRootIdentifier\") String identifier, @EP(\"name\") String name) {\n this.identifier = identifier;\n this.name = name;\n }\n\n}",
"public interface ObjectConstructor<T> {\n\n T construct(Collection<DomainEvent> events);\n\n T applyDomainEvents(T instance, Collection<DomainEvent> events);\n}",
"public class AddressUpdatedEvent extends DomainEvent {\n private String address;\n\n public AddressUpdatedEvent(String identifier, String address) {\n super(identifier);\n this.address = address;\n }\n\n public AddressUpdatedEvent(String identifier, int revision, String address) {\n super(identifier, revision);\n this.address = address;\n }\n\n public String getAddress() {\n return address;\n }\n}",
"public class AddressUpdatedEventWhichCannotBeInvoked extends DomainEvent {\n}",
"public class MyAggregateRootCreatedEvent extends DomainEvent {\n private String name;\n\n public MyAggregateRootCreatedEvent(String identifier, String name) {\n super(identifier);\n this.name = name;\n }\n\n public MyAggregateRootCreatedEvent(String identifier, String name, int revision) {\n super(identifier, revision);\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n}",
"public class UnMappedEvent extends DomainEvent {\n}"
] | import eu.tripledframework.eventstore.domain.DomainEvent;
import eu.tripledframework.eventstore.domain.MyAggregateRoot;
import eu.tripledframework.eventstore.domain.NotInstantiatableAggregateRoot;
import eu.tripledframework.eventstore.domain.ObjectConstructor;
import eu.tripledframework.eventstore.event.AddressUpdatedEvent;
import eu.tripledframework.eventstore.event.AddressUpdatedEventWhichCannotBeInvoked;
import eu.tripledframework.eventstore.event.MyAggregateRootCreatedEvent;
import eu.tripledframework.eventstore.event.UnMappedEvent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat; | /*
* Copyright 2015 TripleD framework.
*
* 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.tripledframework.eventstore.infrastructure;
public class ReflectionObjectConstructorTest {
@Test
void whenGivenAnEmptyListOfEvents_ShouldReturnNull() {
// given
ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class);
// when
MyAggregateRoot object = objectConstructor.construct(Collections.emptyList());
// then
assertThat(object, nullValue());
}
@Test
void whenGivenANullEventList_ShouldReturnNull() {
// given
ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class);
// when
MyAggregateRoot object = objectConstructor.construct(null);
// then
assertThat(object, nullValue());
}
@Test
void whenGivenAnEmptyListOfEventsAndAnInstance_ShouldReturnInstance() {
// given
ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class);
// when
MyAggregateRoot instance = new MyAggregateRoot("id", "name");
MyAggregateRoot object = objectConstructor.applyDomainEvents(instance, Collections.emptyList());
// then
assertThat(object, sameInstance(instance));
}
@Test
void whenGivenAnNullListOfEventsAndAnInstance_ShouldReturnInstance() {
// given
ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class);
// when
MyAggregateRoot instance = new MyAggregateRoot("id", "name");
MyAggregateRoot object = objectConstructor.applyDomainEvents(instance, null);
// then
assertThat(object, sameInstance(instance));
}
@Test
void whenGivenOneEvent_ShouldCreateInstance() {
// given
String sourceIdentifier = UUID.randomUUID().toString();
MyAggregateRootCreatedEvent event = new MyAggregateRootCreatedEvent(sourceIdentifier, "Wallstreet");
ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class);
// when
MyAggregateRoot instance = objectConstructor.construct(Arrays.asList(event));
// then
assertThat(instance.identifier, equalTo(sourceIdentifier));
assertThat(instance.name, equalTo(event.getName()));
assertThat(instance.address, nullValue());
assertThat(instance.postReconstructCalled, is(true));
assertThat(event.getId(), notNullValue());
assertThat(event.getAggregateRootIdentifier(), notNullValue());
assertThat(event.getTimestamp(), notNullValue());
}
@Test
void whenGivenTwoEvents_ShouldCreateInstanceWithEventsReplayed() {
// given
String sourceIdentifier = UUID.randomUUID().toString();
MyAggregateRootCreatedEvent event = new MyAggregateRootCreatedEvent(sourceIdentifier, "Wallstreet");
AddressUpdatedEvent secondEvent = new AddressUpdatedEvent(sourceIdentifier, "streetName streetNumber");
ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class);
// when
MyAggregateRoot instance = objectConstructor.construct(Arrays.asList(event, secondEvent));
// then
assertThat(instance.identifier, equalTo(sourceIdentifier));
assertThat(instance.name, equalTo(event.getName()));
assertThat(instance.address, equalTo(secondEvent.getAddress()));
assertThat(instance.postReconstructCalled, is(true));
}
@Test
void whenGivenTwoEventsOutOfOrder_ShouldThrowException() {
// given
String identifier = UUID.randomUUID().toString(); | DomainEvent event = new MyAggregateRootCreatedEvent(identifier, "Wallstreet"); | 0 |
emina/kodkod | src/kodkod/util/nodes/PrettyPrinter.java | [
"public final class Decl extends Decls {\n\t\n private final Variable variable;\n private final Multiplicity mult;\n private final Expression expression;\n \n /** \n * Constructs a new declaration from the specified variable and\n * expression, with the specified order.\n * \n * @ensures this.variable' = variable && this.expression' = expression && this.multiplicity' = mult\n * @throws NullPointerException variable = null || expression = null || mult = null\n * @throws IllegalArgumentException variable.arity != expression.arity \n */\n Decl(Variable variable, Multiplicity mult, Expression expression) {\n \t\tif (mult==Multiplicity.NO)\n \t\t\tthrow new IllegalArgumentException(\"NO is not a valid multiplicity in a declaration.\");\n if (variable.arity() != expression.arity())\n throw new IllegalArgumentException(\"Unmatched arities in a declaration: \" + variable + \" and \" + expression);\n if (mult != Multiplicity.SET && expression.arity()>1) \n \t\tthrow new IllegalArgumentException(\"Cannot use multiplicity \" + mult + \" with an expression of arity > 1.\");\n this.variable = variable;\n this.mult = mult;\n this.expression = expression;\n }\n \n /**\n * Returns the variable in this declaration.\n * @return this.variable\n */\n public Variable variable() { return variable; }\n \n /**\n * Returns the multiplicity in this declaration.\n * @return this.multiplicity\n */\n public Multiplicity multiplicity() { return mult; }\n \n /**\n * Returns the expression in this declaration.\n * @return this.expresssion\n */\n public Expression expression() { return expression; }\n \n /**\n * {@inheritDoc}\n * @see kodkod.ast.Node#accept(kodkod.ast.visitor.ReturnVisitor)\n */\n public <E, F, D, I> D accept(ReturnVisitor<E, F, D, I> visitor) {\n return visitor.visit(this);\n }\n \n /**\n * {@inheritDoc}\n * @see kodkod.ast.Node#accept(kodkod.ast.visitor.VoidVisitor)\n */\n public void accept(VoidVisitor visitor) {\n visitor.visit(this);\n }\n \n /**\n * {@inheritDoc}\n * @see kodkod.ast.Node#toString()\n */\n public String toString() { return variable + \": \" + mult + \" \" + expression; }\n \n}",
"public abstract class Expression extends Node {\n\t\n\t/** The universal relation: contains all atoms in a {@link kodkod.instance.Universe universe of discourse}. */\n\tpublic static final Expression UNIV = new ConstantExpression(\"univ\", 1);\n\t\n\t/** The identity relation: maps all atoms in a {@link kodkod.instance.Universe universe of discourse} to themselves. */\n\tpublic static final Expression IDEN = new ConstantExpression(\"iden\", 2);\n\t\n\t/** The empty relation: contains no atoms. */\n\tpublic static final Expression NONE = new ConstantExpression(\"none\", 1);\n\t\n\t/** The integer relation: contains all atoms {@link kodkod.instance.Bounds bound} to integers */\n\tpublic static final Expression INTS = new ConstantExpression(\"ints\", 1);\n\t\n /**\n * Constructs a leaf expression\n * @ensures no this.children'\n */\n Expression() { }\n\n /**\n * Returns the join of this and the specified expression. The effect\n * of this method is the same as calling this.compose(JOIN, expr).\n * @return this.compose(JOIN, expr)\n */\n public final Expression join(Expression expr) {\n return compose(JOIN,expr);\n }\n \n /**\n * Returns the product of this and the specified expression. The effect\n * of this method is the same as calling this.compose(PRODUCT, expr).\n * @return this.compose(PRODUCT, expr)\n */\n public final Expression product(Expression expr) {\n return compose(PRODUCT,expr);\n }\n \n /**\n * Returns the union of this and the specified expression. The effect\n * of this method is the same as calling this.compose(UNION, expr).\n * @return this.compose(UNION, expr)\n */\n public final Expression union(Expression expr) {\n \treturn compose(UNION,expr);\n }\n \n /**\n * Returns the difference of this and the specified expression. The effect\n * of this method is the same as calling this.compose(DIFFERENCE, expr).\n * @return this.compose(DIFFERENCE, expr)\n */\n public final Expression difference(Expression expr) {\n \treturn compose(DIFFERENCE,expr);\n }\n \n /**\n * Returns the intersection of this and the specified expression. The effect\n * of this method is the same as calling this.compose(INTERSECTION, expr).\n * @return this.compose(INTERSECTION, expr)\n */\n public final Expression intersection(Expression expr) {\n \treturn compose(INTERSECTION,expr);\n }\n \n /**\n * Returns the relational override of this with the specified expression. The effect\n * of this method is the same as calling this.compose(OVERRIDE, expr).\n * @return this.compose(OVERRIDE, expr)\n */\n public final Expression override(Expression expr) {\n \treturn compose(OVERRIDE,expr);\n }\n \n /**\n * Returns the composition of this and the specified expression, using the\n * given binary operator.\n * @requires op in ExprOperator.BINARY\n * @return {e: Expression | e.left = this and e.right = expr and e.op = this }\n */\n public final Expression compose(ExprOperator op, Expression expr) {\n \treturn new BinaryExpression(this, op, expr);\n }\n \n /**\n * Returns the union of the given expressions. The effect of this method is the\n * same as calling compose(UNION, exprs).\n * @return compose(UNION, exprs)\n */\n public static Expression union(Expression...exprs) { \n \treturn compose(UNION, exprs);\n }\n \n /**\n * Returns the union of the given expressions. The effect of this method is the\n * same as calling compose(UNION, exprs).\n * @return compose(UNION, exprs)\n */\n public static Expression union(Collection<? extends Expression> exprs) { \n \treturn compose(UNION, exprs);\n }\n \n /**\n * Returns the intersection of the given expressions. The effect of this method is the\n * same as calling compose(INTERSECTION, exprs).\n * @return compose(INTERSECTION, exprs)\n */\n public static Expression intersection(Expression...exprs) { \n \treturn compose(INTERSECTION, exprs);\n }\n \n /**\n * Returns the intersection of the given expressions. The effect of this method is the\n * same as calling compose(INTERSECTION, exprs).\n * @return compose(INTERSECTION, exprs)\n */\n public static Expression intersection(Collection<? extends Expression> exprs) { \n \treturn compose(INTERSECTION, exprs);\n }\n \n /**\n * Returns the product of the given expressions. The effect of this method is the\n * same as calling compose(PRODUCT, exprs).\n * @return compose(PRODUCT, exprs)\n */\n public static Expression product(Expression...exprs) { \n \treturn compose(PRODUCT, exprs);\n }\n \n /**\n * Returns the product of the given expressions. The effect of this method is the\n * same as calling compose(PRODUCT, exprs).\n * @return compose(PRODUCT, exprs)\n */\n public static Expression product(Collection<? extends Expression> exprs) { \n \treturn compose(PRODUCT, exprs);\n }\n \n /**\n * Returns the override of the given expressions. The effect of this method is the\n * same as calling compose(OVERRIDE, exprs).\n * @return compose(OVERRIDE, exprs)\n */\n public static Expression override(Expression...exprs) { \n \treturn compose(OVERRIDE, exprs);\n }\n \n /**\n * Returns the override of the given expressions. The effect of this method is the\n * same as calling compose(OVERRIDE, exprs).\n * @return compose(OVERRIDE, exprs)\n */\n public static Expression override(Collection<? extends Expression> exprs) { \n \treturn compose(OVERRIDE, exprs);\n }\n \n /**\n * Returns the composition of the given expressions using the given operator. \n * @requires exprs.length = 2 => op.binary(), exprs.length > 2 => op.nary()\n * @return exprs.length=1 => exprs[0] else {e: Expression | e.children = exprs and e.op = this }\n */\n public static Expression compose(ExprOperator op, Expression...exprs) { \n \tswitch(exprs.length) { \n \tcase 0 : \tthrow new IllegalArgumentException(\"Expected at least one argument: \" + Arrays.toString(exprs));\n \tcase 1 : \treturn exprs[0];\n \tcase 2 : \treturn new BinaryExpression(exprs[0], op, exprs[1]);\n \tdefault : \treturn new NaryExpression(op, Containers.copy(exprs, new Expression[exprs.length]));\n \t}\n }\n \n /**\n * Returns the composition of the given expressions using the given operator. \n * @requires exprs.size() = 2 => op.binary(), exprs.size() > 2 => op.nary()\n * @return exprs.size()=1 => exprs.iterator().next() else {e: Expression | e.children = exprs.toArray() and e.op = this }\n */\n public static Expression compose(ExprOperator op, Collection<? extends Expression> exprs) { \n \tswitch(exprs.size()) { \n \tcase 0 : \tthrow new IllegalArgumentException(\"Expected at least one argument: \" + exprs);\n \tcase 1 : \treturn exprs.iterator().next();\n \tcase 2 :\n \t\tfinal Iterator<? extends Expression> itr = exprs.iterator();\n \t\treturn new BinaryExpression(itr.next(), op, itr.next());\n \tdefault : \t\t\t\n \t\treturn new NaryExpression(op, exprs.toArray(new Expression[exprs.size()]));\n \t}\n }\n \n \n \n /**\n * Returns the transpose of this. The effect of this method is the same\n * as calling this.apply(TRANSPOSE).\n * @return this.apply(TRANSPOSE)\n */\n public final Expression transpose() {\n return apply(TRANSPOSE);\n }\n \n /**\n * Returns the transitive closure of this. The effect of this method is the same\n * as calling this.apply(CLOSURE).\n * @return this.apply(CLOSURE)\n */\n public final Expression closure() {\n return apply(CLOSURE);\n }\n \n /**\n * Returns the reflexive transitive closure of this. The effect of this \n * method is the same\n * as calling this.apply(REFLEXIVE_CLOSURE).\n * @return this.apply(REFLEXIVE_CLOSURE)\n */\n public final Expression reflexiveClosure() {\n \treturn apply(REFLEXIVE_CLOSURE);\n }\n \n /**\n * Returns the expression that results from applying the given unary operator\n * to this. \n * @requires op.unary()\n * @return {e: Expression | e.expression = this && e.op = this }\n * @throws IllegalArgumentException this.arity != 2\n */\n public final Expression apply(ExprOperator op) {\n \treturn new UnaryExpression(op, this);\n }\n \n /**\n * Returns the projection of this expression onto the specified columns.\n * @return {e: Expression | e = project(this, columns) }\n * @throws IllegalArgumentException columns.length < 1\n */\n public final Expression project(IntExpression... columns) {\n \treturn new ProjectExpression(this, columns);\n }\n \n /**\n * Returns the cardinality of this expression. The effect of this method is the\n * same as calling this.apply(CARDINALITY). \n * @return this.apply(CARDINALITY)\n */\n public final IntExpression count() {\n \treturn apply(CARDINALITY);\n }\n \n /**\n * Returns the sum of the integer atoms in this expression. The effect of this method is the\n * same as calling this.apply(SUM). \n * @return this.apply(SUM)\n */\n public final IntExpression sum() {\n \treturn apply(SUM);\n }\n \n /**\n * Returns the cast of this expression to an integer expression,\n * that represents either the cardinality of this expression (if op is CARDINALITY)\n * or the sum of the integer atoms it contains (if op is SUM).\n * @return {e: IntExpression | e.op = op && e.expression = this} \n */\n public final IntExpression apply(ExprCastOperator op) { \n \treturn new ExprToIntCast(this, op);\n }\n \n /**\n * Returns the formula 'this = expr'. The effect of this method is the same \n * as calling this.compare(EQUALS, expr).\n * @return this.compare(EQUALS, expr)\n */\n public final Formula eq(Expression expr) {\n \treturn compare(EQUALS, expr);\n }\n \n /**\n * Returns the formula 'this in expr'. The effect of this method is the same \n * as calling this.compare(SUBSET, expr).\n * @return this.compare(SUBSET, expr)\n */\n public final Formula in(Expression expr) {\n \treturn compare(SUBSET, expr);\n }\n \n /**\n * Returns the formula that represents the comparison of this and the\n * given expression using the given comparison operator.\n * @return {f: Formula | f.left = this && f.right = expr && f.op = op}\n */\n public final Formula compare(ExprCompOperator op, Expression expr) {\n \treturn new ComparisonFormula(this, op, expr);\n }\n \n /**\n * Returns the formula 'some this'. The effect of this method is the same as calling\n * this.apply(SOME).\n * @return this.apply(SOME)\n */\n public final Formula some() {\n return apply(SOME);\n }\n \n /**\n * Returns the formula 'no this'. The effect of this method is the same as calling\n * this.apply(NO).\n * @return this.apply(NO)\n */\n public final Formula no() {\n return apply(NO);\n }\n \n /**\n * Returns the formula 'one this'. The effect of this method is the same as calling\n * this.apply(ONE).\n * @return this.apply(ONE)\n */\n public final Formula one() {\n return apply(ONE);\n }\n \n /**\n * Returns the formula 'lone this'. The effect of this method is the same as calling\n * this.apply(LONE).\n * @return this.apply(LONE)\n */\n public final Formula lone() {\n return apply(LONE);\n }\n \n /**\n * Returns the formula that results from applying the specified multiplicity to\n * this expression. The SET multiplicity is not allowed.\n * @return {f: Formula | f.multiplicity = mult && f.expression = this}\n * @throws IllegalArgumentException mult = SET\n */\n public final Formula apply(Multiplicity mult) {\n \treturn new MultiplicityFormula(mult, this);\n }\n \n /**\n * Returns the arity of this expression.\n * @return this.arity\n */\n public abstract int arity();\n \n /**\n * Accepts the given visitor and returns the result.\n * @see kodkod.ast.Node#accept(kodkod.ast.visitor.ReturnVisitor)\n */\n public abstract <E, F, D, I> E accept(ReturnVisitor<E, F, D, I> visitor);\n }",
"public abstract class IntExpression extends Node {\n\n\t/**\n\t * Constructs an IntExpression.\n\t */\n\tIntExpression() {}\n\n\t/**\n\t * Returns a formula stating that the given int expression and \n\t * this have the same value. The effect\n * of this method is the same as calling this.compare(EQ, intExpr).\n\t * @return this.compare(EQ, intExpr)\n\t */\n\tpublic final Formula eq(IntExpression intExpr) {\n\t\treturn this.compare(EQ, intExpr);\n\t}\n\t\n\t/**\n\t * Returns a formula stating that the value of this int expression is less than the \n\t * value of the given int expression The effect\n * of this method is the same as calling this.compare(LT, intExpr).\n\t * @return this.compare(LT, intExpr)\n\t */\n\tpublic final Formula lt(IntExpression intExpr) {\n\t\treturn this.compare(LT, intExpr);\n\t}\n\t\n\t/**\n\t * Returns a formula stating that the value of this int expression is less than\n\t * or equal to the value of the given int expression The effect\n * of this method is the same as calling this.compare(LTE, intExpr).\n\t * @return this.compare(LTE, intExpr)\n\t */\n\tpublic final Formula lte(IntExpression intExpr) {\n\t\treturn this.compare(LTE, intExpr);\n\t}\n\t\n\t/**\n\t * Returns a formula stating that the value of this int expression is greater than the \n\t * value of the given int expression The effect\n * of this method is the same as calling this.compare(GT, intExpr).\n\t * @return this.compare(GT, intExpr)\n\t */\n\tpublic final Formula gt(IntExpression intExpr) {\n\t\treturn this.compare(GT, intExpr);\n\t}\n\t\n\t/**\n\t * Returns a formula stating that the value of this int expression is greater than\n\t * or equal to the value of the given int expression The effect\n * of this method is the same as calling this.compare(GTE, intExpr).\n\t * @return this.compare(GTE, intExpr)\n\t */\n\tpublic final Formula gte(IntExpression intExpr) {\n\t\treturn this.compare(GTE, intExpr);\n\t}\n\t\n\t/**\n\t * Returns a formula comparing this and the given integer expression using the\n\t * specified operator.\n\t * @return {f: Formula | f.left = this and f.right = intExpr and f.op = op }\n\t */\n\tpublic Formula compare(IntCompOperator op, IntExpression intExpr) {\n\t\tif (op==null || intExpr==null)\n\t\t\tthrow new NullPointerException();\n\t\treturn new IntComparisonFormula(this, op, intExpr);\t\n\t}\n\t\n\t/**\n\t * Returns an integer expression that is the sum of all\n\t * values that this integer expression can take given the\n\t * provided declarations.\n\t * @return {e: IntExpression | e.decls = decls and e.intExpr = this }\n\t */\n\tpublic final IntExpression sum(Decls decls) {\n\t\treturn new SumExpression(decls, this);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the sum of this and\n\t * the given int node. The effect of this method is the same as calling\n\t * this.compose(PLUS, intExpr).\n\t * @return this.compose(PLUS, intExpr)\n\t */\n\tpublic final IntExpression plus(IntExpression intExpr) {\n\t\treturn compose(PLUS, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the difference between this and\n\t * the given int node. The effect of this method is the same as calling\n\t * this.compose(MINUS, intExpr).\n\t * @return this.compose(MINUS, intExpr)\n\t */\n\tpublic final IntExpression minus(IntExpression intExpr) {\n\t\treturn compose(MINUS, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the product of this and\n\t * the given int node. The effect of this method is the same as calling\n\t * this.compose(MULTIPLY, intExpr).\n\t * @return this.compose(MULTIPLY, intExpr)\n\t */\n\tpublic final IntExpression multiply(IntExpression intExpr) {\n\t\treturn compose(MULTIPLY, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the quotient of the division\n\t * between this and the given int node. The effect of this method is the same as calling\n\t * this.compose(DIVIDE, intExpr).\n\t * @return this.compose(DIVIDE, intExpr)\n\t */\n\tpublic final IntExpression divide(IntExpression intExpr) {\n\t\treturn compose(DIVIDE, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the remainder of the division\n\t * between this and the given int node. The effect of this method is the same as calling\n\t * this.compose(MODULO, intExpr).\n\t * @return this.compose(MODULO, intExpr)\n\t */\n\tpublic final IntExpression modulo(IntExpression intExpr) {\n\t\treturn compose(MODULO, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the bitwise AND of this and\n\t * the given int node. The effect of this method is the same as calling\n\t * this.compose(AND, intExpr).\n\t * @return this.compose(AND, intExpr)\n\t */\n\tpublic final IntExpression and(IntExpression intExpr) {\n\t\treturn compose(AND, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the bitwise OR of this and\n\t * the given int node. The effect of this method is the same as calling\n\t * this.compose(OR, intExpr).\n\t * @return this.compose(OR, intExpr)\n\t */\n\tpublic final IntExpression or(IntExpression intExpr) {\n\t\treturn compose(OR, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the bitwise XOR of this and\n\t * the given int node. The effect of this method is the same as calling\n\t * this.compose(XOR, intExpr).\n\t * @return this.compose(XOR, intExpr)\n\t */\n\tpublic final IntExpression xor(IntExpression intExpr) {\n\t\treturn compose(XOR, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the left shift of this by\n\t * the given int node. The effect of this method is the same as calling\n\t * this.compose(SHL, intExpr).\n\t * @return this.compose(SHL, intExpr)\n\t */\n\tpublic final IntExpression shl(IntExpression intExpr) {\n\t\treturn compose(SHL, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the right shift of this and\n\t * the given int node, with zero extension. The effect of this method is the same as calling\n\t * this.compose(SHR, intExpr).\n\t * @return this.compose(SHR, intExpr)\n\t */\n\tpublic final IntExpression shr(IntExpression intExpr) {\n\t\treturn compose(SHR, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the right shift of this and\n\t * the given int node, with sign extension. The effect of this method is the same as calling\n\t * this.compose(SHA, intExpr).\n\t * @return this.compose(SHA, intExpr)\n\t */\n\tpublic final IntExpression sha(IntExpression intExpr) {\n\t\treturn compose(SHA, intExpr);\n\t}\n\t\n\t/**\n\t * Returns an expression that combines this and the given integer expression using the\n\t * specified operator.\n\t * @requires op.binary()\n\t * @return {e: IntExpression | e.left = this and e.right = intExpr and e.op = op }\n\t */\n\tpublic final IntExpression compose(IntOperator op, IntExpression intExpr) {\n\t\tif (op==null || intExpr==null)\n\t\t\tthrow new NullPointerException();\n\t\treturn new BinaryIntExpression(this, op, intExpr);\t\n\t}\n\t\n\t/**\n * Returns the sum of the given int expressions. The effect of this method is the\n * same as calling compose(PLUS, intExprs).\n * @return compose(PLUS, intExprs)\n */\n public static IntExpression plus(IntExpression...intExprs) { \n \treturn compose(PLUS, intExprs);\n }\n \n /**\n * Returns the plus of the given int expressions. The effect of this method is the\n * same as calling compose(PLUS, intExprs).\n * @return compose(PLUS, intExprs)\n */\n public static IntExpression plus(Collection<? extends IntExpression> intExprs) { \n \treturn compose(PLUS, intExprs);\n }\n \n\t/**\n * Returns the product of the given int expressions. The effect of this method is the\n * same as calling compose(MULTIPLY, intExprs).\n * @return compose(MULTIPLY, intExprs)\n */\n public static IntExpression multiply(IntExpression...intExprs) { \n \treturn compose(MULTIPLY, intExprs);\n }\n \n /**\n * Returns the product of the given int expressions. The effect of this method is the\n * same as calling compose(MULTIPLY, intExprs).\n * @return compose(MULTIPLY, intExprs)\n */\n public static IntExpression multiply(Collection<? extends IntExpression> intExprs) { \n \treturn compose(MULTIPLY, intExprs);\n }\n \n\t/**\n * Returns the bitwise and of the given int expressions. The effect of this method is the\n * same as calling compose(AND, intExprs).\n * @return compose(AND, intExprs)\n */\n public static IntExpression and(IntExpression...intExprs) { \n \treturn compose(AND, intExprs);\n }\n \n /**\n * Returns the bitwise and of the given int expressions. The effect of this method is the\n * same as calling compose(AND, intExprs).\n * @return compose(AND, intExprs)\n */\n public static IntExpression and(Collection<? extends IntExpression> intExprs) { \n \treturn compose(AND, intExprs);\n }\n \n /**\n * Returns the bitwise or of the given int expressions. The effect of this method is the\n * same as calling compose(OR, intExprs).\n * @return compose(OR, intExprs)\n */\n public static IntExpression or(IntExpression...intExprs) { \n \treturn compose(OR, intExprs);\n }\n \n /**\n * Returns the bitwise or of the given int expressions. The effect of this method is the\n * same as calling compose(OR, intExprs).\n * @return compose(OR, intExprs)\n */\n public static IntExpression or(Collection<? extends IntExpression> intExprs) { \n \treturn compose(OR, intExprs);\n }\n \t\n\t/**\n * Returns the composition of the given int expressions using the given operator. \n * @requires intExprs.length = 2 => op.binary(), intExprs.length > 2 => op.nary()\n * @return intExprs.length=1 => intExprs[0] else {e: IntExpression | e.children = intExprs and e.op = this }\n */\n public static IntExpression compose(IntOperator op, IntExpression...intExprs) { \n \tswitch(intExprs.length) { \n \tcase 0 : \tthrow new IllegalArgumentException(\"Expected at least one argument: \" + Arrays.toString(intExprs));\n \tcase 1 : \treturn intExprs[0];\n \tcase 2 : \treturn new BinaryIntExpression(intExprs[0], op, intExprs[1]);\n \tdefault :\n \t\treturn new NaryIntExpression(op, Containers.copy(intExprs, new IntExpression[intExprs.length]));\n \t}\n }\n \n /**\n * Returns the composition of the given int expressions using the given operator. \n * @requires intExprs.length = 2 => op.binary(), intExprs.length > 2 => op.nary()\n * @return intExprs.size() = 1 => intExprs.iterator().next() else {e: IntExpression | e.children = intExprs.toArray() and e.op = this }\n */\n public static IntExpression compose(IntOperator op, Collection<? extends IntExpression> intExprs) { \n \tswitch(intExprs.size()) { \n \tcase 0 : \tthrow new IllegalArgumentException(\"Expected at least one argument: \" + intExprs);\n \tcase 1 : \treturn intExprs.iterator().next();\n \tcase 2 :\n \t\tfinal Iterator<? extends IntExpression> itr = intExprs.iterator();\n \t\treturn new BinaryIntExpression(itr.next(), op, itr.next());\n \tdefault : \t\t\t\n \t\treturn new NaryIntExpression(op, intExprs.toArray(new IntExpression[intExprs.size()]));\n \t}\n }\n\t\n\t/**\n\t * Returns an IntExpression that represents the negation of this int expression.\n\t * The effect of this method is the same as calling this.apply(NEG).\n\t * @return this.apply(NEG)\n\t */\n\tpublic final IntExpression negate() {\n\t\treturn apply(NEG);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the bitwise negation of this int expression.\n\t * The effect of this method is the same as calling this.apply(NOT).\n\t * @return this.apply(NOT)\n\t */\n\tpublic final IntExpression not() {\n\t\treturn apply(NOT);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the absolute value of this int expression.\n\t * The effect of this method is the same as calling this.apply(ABS).\n\t * @return this.apply(ABS)\n\t */\n\tpublic final IntExpression abs() {\n\t\treturn apply(ABS);\n\t}\n\t\n\t/**\n\t * Returns an IntExpression that represents the sign of this int expression.\n\t * The effect of this method is the same as calling this.apply(SGN).\n\t * @return this.apply(SGN)\n\t */\n\tpublic final IntExpression signum() {\n\t\treturn apply(SGN);\n\t}\n\t\n\t/**\n\t * Returns an expression that represents the application of the given unary\n\t * operator to this integer expression.\n\t * @requires op.unary()\n\t * @return {e: IntExpression | e.op = op and e.intExpr = this }\n\t */\n\tpublic final IntExpression apply(IntOperator op) {\n\t\treturn new UnaryIntExpression(op, this);\n\t}\n\t\n\t/**\n\t * Returns an expression whose meaning is the singleton set containing the atom \n\t * that represents the integer given by this integer expression.\n\t * The effect of this method is the same as calling this.cast(INTCAST).\n\t * @return this.cast(INTCAST)\n\t */\n\tpublic final Expression toExpression() {\n\t\treturn cast(INTCAST);\n\t}\n\t\n\t/**\n\t * Returns an expression whose meaning is the set containing the atoms \n\t * that represent the powers of 2 (bits) present in this integer expression.\n\t * The effect of this method is the same as calling this.cast(BITSETCAST).\n\t * @return this.cast(BITSETCAST)\n\t */\n\tpublic final Expression toBitset() { \n\t\treturn cast(BITSETCAST);\n\t}\n\t\n\t/**\n\t * Returns an expression that is the relational representation of this\n\t * integer expression specified by the given operator.\n\t * @return an expression that is the relational representation of this\n\t * integer expression specified by the given operator.\n\t */\n\tpublic final Expression cast(IntCastOperator op) { \n\t\tif (op==null) throw new NullPointerException();\n\t\treturn new IntToExprCast(this, op);\n\t}\n\t\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.ast.Node#accept(kodkod.ast.visitor.ReturnVisitor)\n\t */\n\tpublic abstract <E, F, D, I> I accept(ReturnVisitor<E, F, D, I> visitor) ;\n\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.ast.Node#accept(kodkod.ast.visitor.VoidVisitor)\n\t */\n\tpublic abstract void accept(VoidVisitor visitor);\n\n}",
"public abstract class LeafExpression extends Expression {\n\n\tprivate final int arity;\n\tprivate final String name;\n\n\t/**\n\t * Constructs a leaf with the specified name and arity\n\t * \n\t * @ensures this.name' = name && this.arity' = arity \n\t * @throws IllegalArgumentException arity < 1\n\t */\n\tLeafExpression(String name, int arity) {\n\t\tif (arity < 1) {\n\t\t\tthrow new IllegalArgumentException(\"Arity must be at least 1: \" + arity);\n\t\t}\n\t\tthis.name = name;\n\t\tthis.arity = arity;\n\t}\n\n\n\t/**\n\t * Returns the arity of this leaf.\n\t * @return this.arity\n\t */\n\tpublic final int arity() {\n\t\treturn arity;\n\t}\n\n\t/**\n\t * Returns the name of this leaf.\n\t * @return this.name\n\t */\n\tpublic final String name() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.ast.Node#toString()\n\t */\n\tpublic String toString() {\n\t\treturn name;\n\t}\n\n}",
"public final class Variable extends LeafExpression {\n\n\t/**\n\t * Constructs a variable with the specified name and arity 1.\n\t * @ensures this.name' = name && this.arity' = 1\n\t */\n\tprivate Variable(String name) {\n\t\tsuper(name, 1);\n\t}\n\n\t/**\n\t * Constructs a variable with the specified name and arity.\n\t * @ensures this.name' = name && this.arity' = arity\n\t */\n\tprivate Variable(String name, int arity) {\n\t\tsuper(name, arity);\n\t}\n\n\t/**\n\t * Returns a new variable with the specified name and arity 1.\n\t * @ensures this.name' = name && this.arity' = 1\n\t */\n\tpublic static Variable unary(String name) {\n\t\treturn new Variable(name);\n\t}\n\n\t/**\n\t * Returns a new variable with the specified name and arity.\n\t * @ensures this.name' = name && this.arity' = arity\n\t * @throws IllegalArgumentException arity < 1\n\t */\n\tpublic static Variable nary(String name, int arity) {\n\t\treturn new Variable(name, arity);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to at most one element of the given expression: 'this: lone expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = LONE && d.expression = expr }\n\t * @throws NullPointerException expr = null\n\t * @throws IllegalArgumentException this.arity != expr.arity || expr.arity != 1\n\t */\n\tpublic Decl loneOf(Expression expr) {\n\t\treturn new Decl(this, Multiplicity.LONE, expr);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to exactly one element of the given expression: 'this: one expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = ONE && d.expression = expr }\n\t * @throws NullPointerException expr = null\n\t * @throws IllegalArgumentException this.arity != expr.arity || expr.arity != 1\n\t */\n\tpublic Decl oneOf(Expression expr) {\n\t\treturn new Decl(this, Multiplicity.ONE, expr);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to at least one element of the given expression: 'this: some expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = SOME && d.expression = expr }\n\t * @throws NullPointerException expr = null\n\t * @throws IllegalArgumentException this.arity != expr.arity || expr.arity != 1\n\t */\n\tpublic Decl someOf(Expression expr) {\n\t\treturn new Decl(this, Multiplicity.SOME, expr);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to a subset of the elements in the given expression: 'this: set expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = SET && d.expression = expr }\n\t * @throws NullPointerException expr = null\n\t * @throws IllegalArgumentException this.arity != expr.arity \n\t */\n\tpublic Decl setOf(Expression expr) {\n\t\treturn new Decl(this, Multiplicity.SET, expr);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to the specified number of the elements in the given expression: 'this: mult expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = mult && d.expression = expr }\n\t * @throws NullPointerException expression = null || mult = null\n\t * @throws IllegalArgumentException mult = NO\n\t * @throws IllegalArgumentException mult in ONE + LONE + SOME && expr.arity != 1\n\t * @throws IllegalArgumentException this.arity != expr.arity\n\t */\n\tpublic Decl declare(Multiplicity mult, Expression expr) {\n\t\treturn new Decl(this, mult, expr);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.ast.Expression#accept(kodkod.ast.visitor.ReturnVisitor)\n\t */\n\tpublic <E, F, D, I> E accept(ReturnVisitor<E, F, D, I> visitor) {\n\t\treturn visitor.visit(this);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.ast.Node#accept(kodkod.ast.visitor.VoidVisitor)\n\t */\n\tpublic void accept(VoidVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n}",
"public interface VoidVisitor {\n\n\t/** \n\t * Visits the given sequence of declarations. \n\t **/\n public void visit(Decls decls);\n /** \n\t * Visits the given declaration.\n\t **/\n public void visit(Decl decl);\n \n /** \n\t * Visits the given relation. \n\t **/\n public void visit(Relation relation);\n /** \n\t * Visits the given variable. \n\t **/\n public void visit(Variable variable);\n /** \n\t * Visits the given constant expression. \n\t **/\n public void visit(ConstantExpression constExpr);\n \n /** \n\t * Visits the given unary expression. \n\t **/\n public void visit(UnaryExpression unaryExpr); \n \n /** \n\t * Visits the given binary expression. \n\t **/\n public void visit(BinaryExpression binExpr);\n \n /** \n\t * Visits the given nary expression.\n\t **/\n public void visit(NaryExpression expr);\n \n \n /** \n\t * Visits the given comprehension. \n\t **/\n public void visit(Comprehension comprehension);\n /** \n\t * Visits the given if-then expression.\n\t **/\n public void visit(IfExpression ifExpr);\n /**\n * Visits the given projection expression.\n */\n public void visit(ProjectExpression project);\n \n \n /**\n * Visits the given integer cast expression.\n */\n public void visit(IntToExprCast castExpr);\n /**\n * Visits the given integer constant.\n */\n public void visit(IntConstant intConst);\n /**\n * Visits the given unary integer expression.\n */\n public void visit(ExprToIntCast intExpr);\n /**\n * Visits the given if-int-expression.\n */\n public void visit(IfIntExpression intExpr);\n /** \n\t * Visits the given nary int expression.\n\t **/\n public void visit(NaryIntExpression intExpr);\n /**\n * Visits the given binary integer expression.\n */\n public void visit(BinaryIntExpression intExpr);\n /**\n * Visits the given unary integer expression.\n */\n public void visit(UnaryIntExpression intExpr);\n /**\n * Visits the given sum expression.\n */\n public void visit(SumExpression intExpr);\n /**\n * Visits the given integer comparison formula.\n */\n public void visit(IntComparisonFormula intComp);\n \n /** \n\t * Visits the given quantified formula. \n\t **/\n public void visit(QuantifiedFormula quantFormula);\n /** \n\t * Visits the given nary formula.\n\t **/\n public void visit(NaryFormula formula);\n /** \n\t * Visits the given binary formula.\n\t **/\n public void visit(BinaryFormula binFormula);\n /** \n\t * Visits the given negation. \n\t **/\n public void visit(NotFormula not);\n /** \n\t * Visits the given constant formula. \n\t **/\n public void visit(ConstantFormula constant);\n \n /** \n\t * Visits the given comparison formula.\n\t **/\n public void visit(ComparisonFormula compFormula);\n /** \n\t * Visits the given multiplicity formula.\n\t **/\n public void visit(MultiplicityFormula multFormula);\n /**\n * Visits the given relation predicate.\n */\n public void visit(RelationPredicate predicate);\n \n}"
] | import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import kodkod.ast.BinaryExpression;
import kodkod.ast.BinaryFormula;
import kodkod.ast.BinaryIntExpression;
import kodkod.ast.ComparisonFormula;
import kodkod.ast.Comprehension;
import kodkod.ast.ConstantExpression;
import kodkod.ast.ConstantFormula;
import kodkod.ast.Decl;
import kodkod.ast.Decls;
import kodkod.ast.ExprToIntCast;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.IfExpression;
import kodkod.ast.IfIntExpression;
import kodkod.ast.IntComparisonFormula;
import kodkod.ast.IntConstant;
import kodkod.ast.IntExpression;
import kodkod.ast.IntToExprCast;
import kodkod.ast.LeafExpression;
import kodkod.ast.MultiplicityFormula;
import kodkod.ast.NaryExpression;
import kodkod.ast.NaryFormula;
import kodkod.ast.NaryIntExpression;
import kodkod.ast.Node;
import kodkod.ast.NotFormula;
import kodkod.ast.ProjectExpression;
import kodkod.ast.QuantifiedFormula;
import kodkod.ast.Relation;
import kodkod.ast.RelationPredicate;
import kodkod.ast.SumExpression;
import kodkod.ast.UnaryExpression;
import kodkod.ast.UnaryIntExpression;
import kodkod.ast.Variable;
import kodkod.ast.operator.ExprOperator;
import kodkod.ast.operator.FormulaOperator;
import kodkod.ast.operator.IntOperator;
import kodkod.ast.operator.Multiplicity;
import kodkod.ast.visitor.VoidVisitor;
| /** @ensures appends the tokenization of the given node to this.tokens */
public void visit(ProjectExpression node) {
append("project");
append("[");
node.expression().accept(this);
comma();
append("<");
final Iterator<IntExpression> cols = node.columns();
cols.next().accept(this);
while(cols.hasNext()) {
comma();
cols.next().accept(this);
}
append(">");
append("]");
}
/** @ensures this.tokens' = concat[ this.tokens, "Int","[",
* tokenize[node.intExpr], "]" ] **/
public void visit(IntToExprCast node) {
append("Int");
append("[");
node.intExpr().accept(this);
append("]");
}
/** @ensures this.tokens' = concat[ this.tokens, "int","[",
* tokenize[node.expression], "]" ] **/
public void visit(ExprToIntCast node) {
switch(node.op()) {
case SUM:
append("int");
append("[");
node.expression().accept(this);
append("]");
break;
case CARDINALITY :
append("#");
append("(");
node.expression().accept(this);
append(")");
break;
default : throw new IllegalArgumentException("unknown operator: " + node.op());
}
}
/** @ensures appends the tokenization of the given node to this.tokens */
public void visit(RelationPredicate node) {
switch(node.name()) {
case ACYCLIC :
append("acyclic");
append("[");
node.relation().accept(this);
append("]");
break;
case FUNCTION :
RelationPredicate.Function func = (RelationPredicate.Function)node;
append("function");
append("[");
func.relation().accept(this);
colon();
func.domain().accept(this);
infix("->");
keyword(func.targetMult());
func.range().accept(this);
append("]");
break;
case TOTAL_ORDERING :
RelationPredicate.TotalOrdering ord = (RelationPredicate.TotalOrdering)node;
append("ord");
append("[");
ord.relation().accept(this);
comma();
ord.ordered().accept(this);
comma();
ord.first().accept(this);
comma();
ord.last().accept(this);
append("]");
break;
default:
throw new AssertionError("unreachable");
}
}
}
private static class Dotifier implements VoidVisitor {
private final StringBuilder graph = new StringBuilder();
private final Map<Node,Integer> ids = new LinkedHashMap<Node, Integer>();
static String apply(Node node) {
final Dotifier dot = new Dotifier();
dot.graph.append("digraph {\n");
node.accept(dot);
dot.graph.append("}");
return dot.graph.toString();
}
private boolean visited(Node n) {
if (ids.containsKey(n)) return true;
ids.put(n, ids.size());
return false;
}
private String id(Node n) { return "N" + ids.get(n); }
private void node(Node n, String label) {
graph.append(id(n));
graph.append("[ label=\"" );
graph.append(ids.get(n));
graph.append("(");
graph.append(label);
graph.append(")\"];\n");
}
private void edge(Node n1, Node n2) {
| if (n2 instanceof LeafExpression || n2 instanceof ConstantFormula || n2 instanceof IntConstant) {
| 3 |
ralscha/wampspring | src/test/java/ch/rasc/wampspring/call/CallTest.java | [
"public class CallErrorMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final String errorURI;\n\n\tprivate final String errorDesc;\n\n\tprivate final Object errorDetails;\n\n\tpublic CallErrorMessage(CallMessage callMessage, String errorURI, String errorDesc) {\n\t\tthis(callMessage, errorURI, errorDesc, null);\n\t}\n\n\tpublic CallErrorMessage(CallMessage callMessage, String errorURI, String errorDesc,\n\t\t\tObject errorDetails) {\n\t\tsuper(WampMessageType.CALLERROR);\n\t\tthis.callID = callMessage.getCallID();\n\t\tthis.errorURI = errorURI;\n\t\tthis.errorDesc = errorDesc;\n\t\tthis.errorDetails = errorDetails;\n\n\t\tsetWebSocketSessionId(callMessage.getWebSocketSessionId());\n\t\tsetPrincipal(callMessage.getPrincipal());\n\t}\n\n\tpublic CallErrorMessage(JsonParser jp) throws IOException {\n\t\tsuper(WampMessageType.CALLERROR);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.callID = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.errorURI = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.errorDesc = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.END_ARRAY) {\n\t\t\tthis.errorDetails = jp.readValueAs(Object.class);\n\t\t}\n\t\telse {\n\t\t\tthis.errorDetails = null;\n\t\t}\n\t}\n\n\tpublic String getCallID() {\n\t\treturn this.callID;\n\t}\n\n\tpublic String getErrorURI() {\n\t\treturn this.errorURI;\n\t}\n\n\tpublic String getErrorDesc() {\n\t\treturn this.errorDesc;\n\t}\n\n\tpublic Object getErrorDetails() {\n\t\treturn this.errorDetails;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(this.callID);\n\t\t\tjg.writeString(this.errorURI);\n\t\t\tjg.writeString(this.errorDesc);\n\t\t\tif (this.errorDetails != null) {\n\t\t\t\tjg.writeObject(this.errorDetails);\n\t\t\t}\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CallErrorMessage [callID=\" + this.callID + \", errorURI=\" + this.errorURI\n\t\t\t\t+ \", errorDesc=\" + this.errorDesc + \", errorDetails=\" + this.errorDetails\n\t\t\t\t+ \"]\";\n\t}\n\n}",
"public class CallMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final String procURI;\n\n\tprivate final List<Object> arguments;\n\n\tpublic CallMessage(String callID, String procURI, Object... arguments) {\n\t\tsuper(WampMessageType.CALL);\n\t\tthis.callID = callID;\n\t\tthis.procURI = procURI;\n\t\tif (arguments != null) {\n\t\t\tthis.arguments = Arrays.asList(arguments);\n\t\t}\n\t\telse {\n\t\t\tthis.arguments = null;\n\t\t}\n\n\t}\n\n\tpublic CallMessage(JsonParser jp) throws IOException {\n\t\tthis(jp, null);\n\t}\n\n\tpublic CallMessage(JsonParser jp, WampSession wampSession) throws IOException {\n\t\tsuper(WampMessageType.CALL);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.callID = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.procURI = replacePrefix(jp.getValueAsString(), wampSession);\n\n\t\tList<Object> args = new ArrayList<>();\n\t\twhile (jp.nextToken() != JsonToken.END_ARRAY) {\n\t\t\targs.add(jp.readValueAs(Object.class));\n\t\t}\n\n\t\tif (!args.isEmpty()) {\n\t\t\tthis.arguments = Collections.unmodifiableList(args);\n\t\t}\n\t\telse {\n\t\t\tthis.arguments = null;\n\t\t}\n\t}\n\n\tpublic String getCallID() {\n\t\treturn this.callID;\n\t}\n\n\tpublic String getProcURI() {\n\t\treturn this.procURI;\n\t}\n\n\tpublic List<Object> getArguments() {\n\t\treturn this.arguments;\n\t}\n\n\t@Override\n\tpublic String getDestination() {\n\t\treturn this.procURI;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(this.callID);\n\t\t\tjg.writeString(this.procURI);\n\t\t\tif (this.arguments != null) {\n\t\t\t\tfor (Object argument : this.arguments) {\n\t\t\t\t\tjg.writeObject(argument);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CallMessage [callID=\" + this.callID + \", procURI=\" + this.procURI\n\t\t\t\t+ \", arguments=\" + this.arguments + \"]\";\n\t}\n\n}",
"public class CallResultMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final Object result;\n\n\tpublic CallResultMessage(CallMessage callMessage, Object result) {\n\t\tsuper(WampMessageType.CALLRESULT);\n\t\tthis.callID = callMessage.getCallID();\n\t\tthis.result = result;\n\n\t\tsetWebSocketSessionId(callMessage.getWebSocketSessionId());\n\t\tsetPrincipal(callMessage.getPrincipal());\n\t}\n\n\tpublic CallResultMessage(JsonParser jp) throws IOException {\n\t\tsuper(WampMessageType.CALLRESULT);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.callID = jp.getValueAsString();\n\n\t\tjp.nextToken();\n\t\tthis.result = jp.readValueAs(Object.class);\n\t}\n\n\tpublic String getCallID() {\n\t\treturn this.callID;\n\t}\n\n\tpublic Object getResult() {\n\t\treturn this.result;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(this.callID);\n\t\t\tjg.writeObject(this.result);\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CallResultMessage [callID=\" + this.callID + \", result=\" + this.result\n\t\t\t\t+ \"]\";\n\t}\n\n}",
"public abstract class WampMessage implements Message<Object> {\n\n\tprotected final static Object EMPTY_OBJECT = new Object();\n\n\tprivate final MutableMessageHeaders messageHeaders = new MutableMessageHeaders();\n\n\tWampMessage(WampMessageType type) {\n\t\tsetHeader(WampMessageHeader.WAMP_MESSAGE_TYPE, type);\n\t}\n\n\tint getTypeId() {\n\t\treturn getType().getTypeId();\n\t}\n\n\tpublic WampMessageType getType() {\n\t\treturn getHeader(WampMessageHeader.WAMP_MESSAGE_TYPE);\n\t}\n\n\tpublic void setHeader(WampMessageHeader header, Object value) {\n\t\tthis.messageHeaders.getRawHeaders().put(header.name(), value);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> T getHeader(WampMessageHeader header) {\n\t\treturn (T) this.messageHeaders.get(header.name());\n\t}\n\n\tpublic void setDestinationTemplateVariables(Map<String, String> vars) {\n\t\tthis.messageHeaders.getRawHeaders().put(\n\t\t\t\tDestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER,\n\t\t\t\tvars);\n\t}\n\n\t/**\n\t * Convenient method to retrieve the WebSocket session id.\n\t */\n\tpublic String getWebSocketSessionId() {\n\t\treturn getHeader(WampMessageHeader.WEBSOCKET_SESSION_ID);\n\t}\n\n\tpublic void setWebSocketSessionId(String webSocketSessionId) {\n\t\tsetHeader(WampMessageHeader.WEBSOCKET_SESSION_ID, webSocketSessionId);\n\t}\n\n\tpublic String getDestination() {\n\t\treturn null;\n\t}\n\n\tpublic Principal getPrincipal() {\n\t\treturn getHeader(WampMessageHeader.PRINCIPAL);\n\t}\n\n\tvoid setPrincipal(Principal principal) {\n\t\tsetHeader(WampMessageHeader.PRINCIPAL, principal);\n\t}\n\n\tpublic WampSession getWampSession() {\n\t\treturn (WampSession) getHeader(WampMessageHeader.WAMP_SESSION);\n\t}\n\n\tvoid setWampSession(WampSession wampSession) {\n\t\tsetHeader(WampMessageHeader.WAMP_SESSION, wampSession);\n\t}\n\n\t@Override\n\tpublic Object getPayload() {\n\t\treturn EMPTY_OBJECT;\n\t}\n\n\t@Override\n\tpublic MessageHeaders getHeaders() {\n\t\treturn this.messageHeaders;\n\t}\n\n\tpublic static <T extends WampMessage> T fromJson(WebSocketSession session,\n\t\t\tJsonFactory jsonFactory, String json) throws IOException {\n\n\t\tWampSession wampSession = new WampSession(session);\n\n\t\tT newWampMessage = fromJson(jsonFactory, json, wampSession);\n\n\t\tnewWampMessage.setWebSocketSessionId(session.getId());\n\t\tnewWampMessage.setPrincipal(session.getPrincipal());\n\t\tnewWampMessage.setWampSession(wampSession);\n\n\t\treturn newWampMessage;\n\t}\n\n\tpublic abstract String toJson(JsonFactory jsonFactory) throws IOException;\n\n\tpublic static <T extends WampMessage> T fromJson(JsonFactory jsonFactory, String json)\n\t\t\tthrows IOException {\n\t\treturn fromJson(jsonFactory, json, null);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static <T extends WampMessage> T fromJson(JsonFactory jsonFactory, String json,\n\t\t\tWampSession wampSession) throws IOException {\n\n\t\ttry (JsonParser jp = jsonFactory.createParser(json)) {\n\t\t\tif (jp.nextToken() != JsonToken.START_ARRAY) {\n\t\t\t\tthrow new IOException(\"Not a JSON array\");\n\t\t\t}\n\t\t\tif (jp.nextToken() != JsonToken.VALUE_NUMBER_INT) {\n\t\t\t\tthrow new IOException(\"Wrong message format\");\n\t\t\t}\n\n\t\t\tWampMessageType messageType = WampMessageType.fromTypeId(jp.getValueAsInt());\n\n\t\t\tswitch (messageType) {\n\t\t\tcase WELCOME:\n\t\t\t\treturn (T) new WelcomeMessage(jp);\n\t\t\tcase PREFIX:\n\t\t\t\treturn (T) new PrefixMessage(jp);\n\t\t\tcase CALL:\n\t\t\t\treturn (T) new CallMessage(jp, wampSession);\n\t\t\tcase CALLRESULT:\n\t\t\t\treturn (T) new CallResultMessage(jp);\n\t\t\tcase CALLERROR:\n\t\t\t\treturn (T) new CallErrorMessage(jp);\n\t\t\tcase SUBSCRIBE:\n\t\t\t\treturn (T) new SubscribeMessage(jp, wampSession);\n\t\t\tcase UNSUBSCRIBE:\n\t\t\t\treturn (T) new UnsubscribeMessage(jp, wampSession);\n\t\t\tcase PUBLISH:\n\t\t\t\treturn (T) new PublishMessage(jp, wampSession);\n\t\t\tcase EVENT:\n\t\t\t\treturn (T) new EventMessage(jp, wampSession);\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"serial\")\n\tprivate static class MutableMessageHeaders extends MessageHeaders {\n\n\t\tpublic MutableMessageHeaders() {\n\t\t\tsuper(null, MessageHeaders.ID_VALUE_NONE, -1L);\n\t\t}\n\n\t\t@Override\n\t\tpublic Map<String, Object> getRawHeaders() {\n\t\t\treturn super.getRawHeaders();\n\t\t}\n\t}\n\n\tprotected String replacePrefix(String uri, WampSession wampSession) {\n\t\tif (uri != null && wampSession != null && wampSession.hasPrefixes()) {\n\t\t\tString[] curie = uri.split(\":\");\n\t\t\tif (curie.length == 2) {\n\t\t\t\tString prefix = wampSession.getPrefix(curie[0]);\n\t\t\t\tif (prefix != null) {\n\t\t\t\t\treturn prefix + curie[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn uri;\n\t}\n\n}",
"@RunWith(SpringRunner.class)\n@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)\n@Ignore\npublic class BaseWampTest {\n\n\tprotected final JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper());\n\n\t@LocalServerPort\n\tpublic int actualPort;\n\n\tprotected WampMessage sendWampMessage(WampMessage msg) throws InterruptedException,\n\t\t\tExecutionException, TimeoutException, IOException {\n\t\tCompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler(\n\t\t\t\tthis.jsonFactory);\n\t\tWebSocketClient webSocketClient = createWebSocketClient();\n\n\t\ttry (WebSocketSession webSocketSession = webSocketClient\n\t\t\t\t.doHandshake(result, wampEndpointUrl()).get()) {\n\n\t\t\tresult.getWelcomeMessage();\n\t\t\twebSocketSession.sendMessage(new TextMessage(msg.toJson(this.jsonFactory)));\n\n\t\t\treturn result.getWampMessage();\n\t\t}\n\t}\n\n\tprotected WebSocketClient createWebSocketClient() {\n\t\treturn new StandardWebSocketClient();\n\t}\n\n\tprotected WebSocketSession startWebSocketSession(AbstractWebSocketHandler result)\n\t\t\tthrows InterruptedException, ExecutionException {\n\t\tWebSocketClient webSocketClient = createWebSocketClient();\n\t\treturn webSocketClient.doHandshake(result, wampEndpointUrl()).get();\n\t}\n\n\tprotected String wampEndpointUrl() {\n\t\treturn \"ws://localhost:\" + this.actualPort + \"/wamp\";\n\t}\n\n\tprotected WampMessage sendAuthenticatedMessage(WampMessage msg) throws Exception {\n\t\tCompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler(\n\t\t\t\tthis.jsonFactory);\n\n\t\tWebSocketClient webSocketClient = createWebSocketClient();\n\t\ttry (WebSocketSession webSocketSession = webSocketClient\n\t\t\t\t.doHandshake(result, wampEndpointUrl()).get()) {\n\n\t\t\tresult.getWelcomeMessage();\n\t\t\tauthenticate(result, webSocketSession);\n\t\t\twebSocketSession.sendMessage(new TextMessage(msg.toJson(this.jsonFactory)));\n\n\t\t\treturn result.getWampMessage();\n\t\t}\n\t}\n\n\tprotected void authenticate(CompletableFutureWebSocketHandler result,\n\t\t\tWebSocketSession webSocketSession)\n\t\t\tthrows IOException, InterruptedException, InvalidKeyException,\n\t\t\tNoSuchAlgorithmException, ExecutionException, TimeoutException {\n\t\tCallMessage authReqCallMessage = new CallMessage(\"1\",\n\t\t\t\t\"http://api.wamp.ws/procedure#authreq\", \"a\", Collections.emptyMap());\n\t\twebSocketSession.sendMessage(\n\t\t\t\tnew TextMessage(authReqCallMessage.toJson(this.jsonFactory)));\n\t\tWampMessage response = result.getWampMessage();\n\n\t\tassertThat(response).isInstanceOf(CallResultMessage.class);\n\t\tCallResultMessage resultMessage = (CallResultMessage) response;\n\t\tassertThat(resultMessage.getCallID()).isEqualTo(\"1\");\n\t\tassertThat(resultMessage.getResult()).isNotNull();\n\n\t\tresult.reset();\n\n\t\tString challengeBase64 = (String) resultMessage.getResult();\n\t\tString signature = DefaultAuthenticationHandler.generateHMacSHA256(\"secretofa\",\n\t\t\t\tchallengeBase64);\n\n\t\tCallMessage authCallMessage = new CallMessage(\"2\",\n\t\t\t\t\"http://api.wamp.ws/procedure#auth\", signature);\n\t\twebSocketSession\n\t\t\t\t.sendMessage(new TextMessage(authCallMessage.toJson(this.jsonFactory)));\n\t\tresponse = result.getWampMessage();\n\n\t\tassertThat(response).isInstanceOf(CallResultMessage.class);\n\t\tresultMessage = (CallResultMessage) response;\n\t\tassertThat(resultMessage.getCallID()).isEqualTo(\"2\");\n\t\tassertThat(resultMessage.getResult()).isNull();\n\n\t\tresult.reset();\n\t}\n\n}"
] | import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ch.rasc.wampspring.config.EnableWamp;
import ch.rasc.wampspring.message.CallErrorMessage;
import ch.rasc.wampspring.message.CallMessage;
import ch.rasc.wampspring.message.CallResultMessage;
import ch.rasc.wampspring.message.WampMessage;
import ch.rasc.wampspring.testsupport.BaseWampTest; | /**
* Copyright 2014-2017 the original author or authors.
*
* 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 ch.rasc.wampspring.call;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
classes = CallTest.Config.class)
public class CallTest extends BaseWampTest {
@Test
public void testCallArguments() throws Exception {
WampMessage receivedMessage = sendWampMessage(
new CallMessage("callID", "callService.simpleTest", "argument", 12));
assertThat(receivedMessage).isInstanceOf(CallResultMessage.class);
CallResultMessage result = (CallResultMessage) receivedMessage;
assertThat(result.getCallID()).isEqualTo("callID");
assertThat(result.getResult()).isNull();
}
@Test
public void testNoParameters() throws Exception {
WampMessage receivedMessage = sendWampMessage(
new CallMessage("callID2", "callService.noParams"));
assertThat(receivedMessage).isInstanceOf(CallResultMessage.class);
CallResultMessage result = (CallResultMessage) receivedMessage;
assertThat(result.getCallID()).isEqualTo("callID2");
assertThat(result.getResult()).isEqualTo("nothing here");
}
@Test
public void testCallOwnProcUri() throws Exception {
WampMessage receivedMessage = sendWampMessage(
new CallMessage("theCallId", "myOwnProcURI", "argument", 13));
assertThat(receivedMessage).isInstanceOf(CallResultMessage.class);
CallResultMessage result = (CallResultMessage) receivedMessage;
assertThat(result.getCallID()).isEqualTo("theCallId");
assertThat(result.getResult()).isNull();
}
@Test
public void testReturnValue() throws Exception {
WampMessage receivedMessage = sendWampMessage(
new CallMessage("12", "callService.sum", 3, 4));
assertThat(receivedMessage).isInstanceOf(CallResultMessage.class);
CallResultMessage result = (CallResultMessage) receivedMessage;
assertThat(result.getCallID()).isEqualTo("12");
assertThat(result.getResult()).isEqualTo(7);
}
@Test
public void testWithError() throws Exception {
WampMessage receivedMessage = sendWampMessage(
new CallMessage("13", "callService.error", "theArgument")); | assertThat(receivedMessage).isInstanceOf(CallErrorMessage.class); | 0 |
aNNiMON/HotaruFX | app/src/main/java/com/annimon/hotarufx/visual/PropertyType.java | [
"public class FontValue extends MapValue {\n\n public static Font toFont(MapValue mapValue) {\n final var map = mapValue.getMap();\n final var family = map.getOrDefault(\"family\", new StringValue(Font.getDefault().getFamily())).asString();\n final var weight = map.getOrDefault(\"weight\", NumberValue.of(FontWeight.NORMAL.getWeight())).asInt();\n final var isItalic = map.getOrDefault(\"italic\", NumberValue.ZERO).asBoolean();\n final var posture = isItalic ? FontPosture.ITALIC : FontPosture.REGULAR;\n final var size = map.getOrDefault(\"size\", NumberValue.MINUS_ONE).asDouble();\n return Font.font(family, FontWeight.findByWeight(weight), posture, size);\n }\n\n private final Font font;\n\n public FontValue(Font font) {\n super(4);\n this.font = font;\n init();\n }\n\n private void init() {\n final var map = super.getMap();\n map.put(\"family\", new StringValue(font.getFamily()));\n map.put(\"isItalic\", NumberValue.fromBoolean(font.getStyle().toLowerCase().contains(\"italic\")));\n final var weight = FontWeight.findByName(font.getStyle());\n map.put(\"weight\", NumberValue.of(weight != null\n ? (weight.getWeight())\n : FontWeight.NORMAL.getWeight()));\n map.put(\"size\", NumberValue.of(font.getSize()));\n }\n\n @Override\n public int type() {\n return Types.MAP;\n }\n\n public Font getFont() {\n return font;\n }\n\n @Override\n public Object raw() {\n return font;\n }\n\n @Override\n public Number asNumber() {\n throw new TypeException(\"Cannot cast font to number\");\n }\n\n @Override\n public String asString() {\n throw new TypeException(\"Cannot cast font to string\");\n }\n\n @Override\n public int compareTo(Value o) {\n return 0;\n }\n}",
"public class MapValue implements Value, Iterable<Map.Entry<String, Value>> {\n\n public static final MapValue EMPTY = new MapValue(1);\n\n public static MapValue merge(MapValue map1, MapValue map2) {\n final MapValue result = new MapValue(map1.size() + map2.size());\n result.map.putAll(map1.map);\n result.map.putAll(map2.map);\n return result;\n }\n\n private final Map<String, Value> map;\n\n public MapValue(int size) {\n this.map = new HashMap<>(size);\n }\n\n public MapValue(Map<String, Value> map) {\n this.map = map;\n }\n\n @Override\n public int type() {\n return Types.MAP;\n }\n\n public int size() {\n return map.size();\n }\n\n public Map<String, Value> getMap() {\n return map;\n }\n\n @Override\n public Object raw() {\n return map;\n }\n\n @Override\n public Number asNumber() {\n throw new TypeException(\"Cannot cast map to number\");\n }\n\n @Override\n public String asString() {\n return map.toString();\n }\n\n @Override\n public Iterator<Map.Entry<String, Value>> iterator() {\n return map.entrySet().iterator();\n }\n\n @Override\n public int hashCode() {\n int hash = 5;\n hash = 37 * hash + Objects.hashCode(this.map);\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null) return false;\n if (getClass() != obj.getClass())\n return false;\n final MapValue other = (MapValue) obj;\n return Objects.equals(this.map, other.map);\n }\n\n @Override\n public int compareTo(Value o) {\n if (o.type() == Types.MAP) {\n final int lengthCompare = Integer.compare(size(), ((MapValue) o).size());\n if (lengthCompare != 0) return lengthCompare;\n }\n return asString().compareTo(o.asString());\n }\n\n @Override\n public String toString() {\n return asString();\n }\n}",
"public class NodeValue implements Value {\n\n private final ObjectNode node;\n private final PropertyBindings bindings;\n\n public NodeValue(ObjectNode node) {\n this.node = node;\n bindings = node.propertyBindings();\n }\n\n @Override\n public int type() {\n return Types.NODE;\n }\n\n public ObjectNode getNode() {\n return node;\n }\n\n @Override\n public Object raw() {\n return node;\n }\n\n public void fill(MapValue map) {\n map.getMap().forEach(this::set);\n }\n\n @SuppressWarnings(\"unchecked\")\n public Value get(String key) {\n if (!bindings.containsKey(key)) {\n throw new HotaruRuntimeException(\"Unable to get property \" + key + \" from node value\");\n }\n final Property property = bindings.get(key);\n final var timeline = property.getProperty().get();\n final var type = property.getType();\n switch (type) {\n case BOOLEAN:\n return type.<Boolean>getToHFX().apply(\n ((PropertyTimeline<Boolean>) timeline).getProperty().getValue());\n case NUMBER:\n return type.<Number>getToHFX().apply(\n ((PropertyTimeline<Number>) timeline).getProperty().getValue());\n case STRING:\n return type.<String>getToHFX().apply(\n ((PropertyTimeline<String>) timeline).getProperty().getValue());\n case NODE:\n case CLIP_NODE:\n return type.<Node>getToHFX().apply(\n ((PropertyTimeline<Node>) timeline).getProperty().getValue());\n case PAINT:\n return type.<Paint>getToHFX().apply(\n ((PropertyTimeline<Paint>) timeline).getProperty().getValue());\n case FONT:\n return type.<Font>getToHFX().apply(\n ((PropertyTimeline<Font>) timeline).getProperty().getValue());\n default:\n throw new TypeException(\"Unknown type of node property\");\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public void set(String key, Value value) {\n if (!bindings.containsKey(key)) return;\n final Property property = bindings.get(key);\n final var timeline = property.getProperty().get();\n final var type = property.getType();\n switch (type) {\n case BOOLEAN:\n ((PropertyTimeline<Boolean>) timeline).getProperty().setValue(\n type.<Boolean>getFromHFX().apply(value));\n break;\n case NUMBER:\n ((PropertyTimeline<Number>) timeline).getProperty().setValue(\n type.<Number>getFromHFX().apply(value));\n break;\n case STRING:\n ((PropertyTimeline<String>) timeline).getProperty().setValue(\n type.<String>getFromHFX().apply(value));\n break;\n case PAINT:\n ((PropertyTimeline<Paint>) timeline).getProperty().setValue(\n type.<Paint>getFromHFX().apply(value));\n break;\n case NODE:\n case CLIP_NODE:\n ((PropertyTimeline<Node>) timeline).getProperty().setValue(\n type.<Node>getFromHFX().apply(value));\n break;\n case FONT:\n ((PropertyTimeline<Font>) timeline).getProperty().setValue(\n type.<Font>getFromHFX().apply(value));\n break;\n }\n }\n\n public Value getProperty(String key) {\n final var property = bindings.get(key);\n if (property == null) {\n throw new HotaruRuntimeException(\"Unable to get property \" + key + \" from node value\");\n }\n return new PropertyValue(property);\n }\n\n @Override\n public Number asNumber() {\n throw new TypeException(\"Cannot cast node to number\");\n }\n\n @Override\n public String asString() {\n throw new TypeException(\"Cannot cast node to string\");\n }\n\n @Override\n public int compareTo(Value o) {\n return 0;\n }\n}",
"public class NumberValue implements Value {\n\n public static final NumberValue MINUS_ONE, ZERO, ONE;\n\n private static final int CACHE_MIN = -128, CACHE_MAX = 127;\n private static final NumberValue[] NUMBER_CACHE;\n static {\n final int length = CACHE_MAX - CACHE_MIN + 1;\n NUMBER_CACHE = new NumberValue[length];\n int value = CACHE_MIN;\n for (int i = 0; i < length; i++) {\n NUMBER_CACHE[i] = new NumberValue(value++);\n }\n\n final int zeroIndex = -CACHE_MIN;\n MINUS_ONE = NUMBER_CACHE[zeroIndex - 1];\n ZERO = NUMBER_CACHE[zeroIndex];\n ONE = NUMBER_CACHE[zeroIndex + 1];\n }\n\n public static NumberValue fromBoolean(boolean b) {\n return b ? ONE : ZERO;\n }\n\n public static NumberValue of(int value) {\n if (CACHE_MIN <= value && value <= CACHE_MAX) {\n return NUMBER_CACHE[-CACHE_MIN + value];\n }\n return new NumberValue(value);\n }\n\n public static NumberValue of(Number value) {\n return new NumberValue(value);\n }\n\n private final Number value;\n\n private NumberValue(Number value) {\n this.value = value;\n }\n\n @Override\n public int type() {\n return Types.NUMBER;\n }\n\n @Override\n public Number raw() {\n return value;\n }\n\n public boolean asBoolean() {\n return value.intValue() != 0;\n }\n\n @Override\n public Number asNumber() {\n return value;\n }\n\n @Override\n public String asString() {\n return value.toString();\n }\n\n @Override\n public int hashCode() {\n int hash = 3;\n hash = 71 * hash + value.hashCode();\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null) return false;\n if (getClass() != obj.getClass())\n return false;\n final Number other = ((NumberValue) obj).value;\n if (value instanceof Double || other instanceof Double) {\n return Double.compare(value.doubleValue(), other.doubleValue()) == 0;\n }\n if (value instanceof Float || other instanceof Float) {\n return Float.compare(value.floatValue(), other.floatValue()) == 0;\n }\n if (value instanceof Long || other instanceof Long) {\n return Long.compare(value.longValue(), other.longValue()) == 0;\n }\n return Integer.compare(value.intValue(), other.intValue()) == 0;\n }\n\n @Override\n public int compareTo(Value o) {\n if (o.type() == Types.NUMBER) {\n final Number other = ((NumberValue) o).value;\n if (value instanceof Double || other instanceof Double) {\n return Double.compare(value.doubleValue(), other.doubleValue());\n }\n if (value instanceof Float || other instanceof Float) {\n return Float.compare(value.floatValue(), other.floatValue());\n }\n if (value instanceof Long || other instanceof Long) {\n return Long.compare(value.longValue(), other.longValue());\n }\n return Integer.compare(value.intValue(), other.intValue());\n }\n return asString().compareTo(o.asString());\n }\n\n @Override\n public String toString() {\n return asString();\n }\n}",
"public class StringValue implements Value {\n\n private final String value;\n\n public StringValue(String value) {\n this.value = value;\n }\n\n public int length() {\n return value.length();\n }\n\n @Override\n public int type() {\n return Types.STRING;\n }\n\n @Override\n public Object raw() {\n return value;\n }\n\n @Override\n public int asInt() {\n try {\n return Integer.parseInt(value);\n } catch (NumberFormatException e) {\n return 0;\n }\n }\n\n @Override\n public double asDouble() {\n try {\n return Double.parseDouble(value);\n } catch (NumberFormatException e) {\n return 0;\n }\n }\n\n @Override\n public Number asNumber() {\n return asDouble();\n }\n\n @Override\n public String asString() {\n return value;\n }\n\n @Override\n public int hashCode() {\n int hash = 3;\n hash = 97 * hash + Objects.hashCode(this.value);\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null) return false;\n if (getClass() != obj.getClass())\n return false;\n final StringValue other = (StringValue) obj;\n return Objects.equals(this.value, other.value);\n }\n\n @Override\n public int compareTo(Value o) {\n if (o.type() == Types.STRING) {\n return value.compareTo(((StringValue) o).value);\n }\n return asString().compareTo(o.asString());\n }\n\n @Override\n public String toString() {\n return asString();\n }\n}",
"public class Types {\n\n public static final int\n OBJECT = 0,\n NUMBER = 1,\n STRING = 2,\n ARRAY = 3,\n MAP = 4,\n NODE = 5,\n PROPERTY = 6,\n INTERPOLATOR = 7,\n FUNCTION = 8;\n}",
"public interface Value extends Comparable<Value> {\n\n Object raw();\n\n default boolean asBoolean() {\n return asInt() != 0;\n }\n\n default int asInt() {\n return asNumber().intValue();\n }\n\n default double asDouble() {\n return asNumber().doubleValue();\n }\n\n Number asNumber();\n\n String asString();\n\n int type();\n}",
"public abstract class ObjectNode {\n\n private final Node node;\n private PropertyTimelineHolder<Boolean> visible;\n private PropertyTimelineHolder<Number> opacity;\n private PropertyTimelineHolder<Node> clip;\n private PropertyTimelineHolder<String> style;\n private PropertyTimelineHolder<Number> rotate;\n private PropertyTimelineHolder<Number> translateX, translateY, translateZ;\n private PropertyTimelineHolder<Number> scaleX, scaleY, scaleZ;\n private PropertyTimelineHolder<Number> layoutX, layoutY;\n private PropertyTimelineHolder<String> blendMode;\n private boolean isRenderable;\n\n public ObjectNode(Node node) {\n this.node = node;\n visible = PropertyTimelineHolder.empty();\n opacity = PropertyTimelineHolder.empty();\n clip = PropertyTimelineHolder.empty();\n style = PropertyTimelineHolder.empty();\n rotate = PropertyTimelineHolder.empty();\n translateX = PropertyTimelineHolder.empty();\n translateY = PropertyTimelineHolder.empty();\n translateZ = PropertyTimelineHolder.empty();\n scaleX = PropertyTimelineHolder.empty();\n scaleY = PropertyTimelineHolder.empty();\n scaleZ = PropertyTimelineHolder.empty();\n layoutX = PropertyTimelineHolder.empty();\n layoutY = PropertyTimelineHolder.empty();\n blendMode = PropertyTimelineHolder.empty();\n isRenderable = true;\n }\n\n public Node getFxNode() {\n return node;\n }\n\n public boolean isRenderable() {\n return isRenderable;\n }\n\n public void setRenderable(boolean renderable) {\n isRenderable = renderable;\n }\n\n public PropertyTimeline<Boolean> visibleProperty() {\n return visible.setIfEmptyThenGet(node::visibleProperty);\n }\n\n public PropertyTimeline<Number> opacityProperty() {\n return opacity.setIfEmptyThenGet(node::opacityProperty);\n }\n\n public PropertyTimeline<Node> clipProperty() {\n return clip.setIfEmptyThenGet(node::clipProperty);\n }\n\n public PropertyTimeline<String> styleProperty() {\n return style.setIfEmptyThenGet(node::styleProperty);\n }\n\n public PropertyTimeline<Number> rotateProperty() {\n return rotate.setIfEmptyThenGet(node::rotateProperty);\n }\n\n public PropertyTimeline<Number> translateXProperty() {\n return translateX.setIfEmptyThenGet(node::translateXProperty);\n }\n\n public PropertyTimeline<Number> translateYProperty() {\n return translateY.setIfEmptyThenGet(node::translateYProperty);\n }\n\n public PropertyTimeline<Number> translateZProperty() {\n return translateZ.setIfEmptyThenGet(node::translateZProperty);\n }\n\n public PropertyTimeline<Number> scaleXProperty() {\n return scaleX.setIfEmptyThenGet(node::scaleXProperty);\n }\n\n public PropertyTimeline<Number> scaleYProperty() {\n return scaleY.setIfEmptyThenGet(node::scaleYProperty);\n }\n\n public PropertyTimeline<Number> scaleZProperty() {\n return scaleZ.setIfEmptyThenGet(node::scaleZProperty);\n }\n\n public PropertyTimeline<Number> layoutXProperty() {\n return layoutX.setIfEmptyThenGet(node::layoutXProperty);\n }\n\n public PropertyTimeline<Number> layoutYProperty() {\n return layoutY.setIfEmptyThenGet(node::layoutYProperty);\n }\n\n public PropertyTimeline<String> blendModeProperty() {\n return blendMode.setIfEmptyThenGet(enumToString(BlendMode.class, node.blendModeProperty()));\n }\n\n public void buildTimeline(TimeLine timeline) {\n visible.applyIfPresent(timeline);\n opacity.applyIfPresent(timeline);\n clip.applyIfPresent(timeline);\n style.applyIfPresent(timeline);\n rotate.applyIfPresent(timeline);\n translateX.applyIfPresent(timeline);\n translateY.applyIfPresent(timeline);\n translateZ.applyIfPresent(timeline);\n scaleX.applyIfPresent(timeline);\n scaleY.applyIfPresent(timeline);\n scaleZ.applyIfPresent(timeline);\n layoutX.applyIfPresent(timeline);\n layoutY.applyIfPresent(timeline);\n blendMode.applyIfPresent(timeline);\n }\n\n public final PropertyBindings propertyBindings() {\n return propertyBindings(new PropertyBindings());\n }\n\n protected PropertyBindings propertyBindings(PropertyBindings bindings) {\n return bindings\n .add(\"visible\", BOOLEAN, this::visibleProperty)\n .add(\"opacity\", NUMBER, this::opacityProperty)\n .add(\"clip\", CLIP_NODE, this::clipProperty)\n .add(\"css\", STRING, this::styleProperty)\n .add(\"style\", STRING, this::styleProperty)\n .add(\"rotate\", NUMBER, this::rotateProperty)\n .add(\"translateX\", NUMBER, this::translateXProperty)\n .add(\"translateY\", NUMBER, this::translateYProperty)\n .add(\"translateZ\", NUMBER, this::translateZProperty)\n .add(\"scaleX\", NUMBER, this::scaleXProperty)\n .add(\"scaleY\", NUMBER, this::scaleYProperty)\n .add(\"scaleZ\", NUMBER, this::scaleZProperty)\n .add(\"layoutX\", NUMBER, this::layoutXProperty)\n .add(\"layoutY\", NUMBER, this::layoutYProperty)\n .add(\"blendMode\", STRING, this::blendModeProperty);\n }\n\n protected <T extends Enum<T>> Supplier<WritableValue<String>> enumToString(Class<T> enumClass, ObjectProperty<T> property) {\n return () -> {\n final var stringProperty = new SimpleStringProperty();\n stringProperty.bindBidirectional(property, new StringConverter<T>() {\n @Override\n public String toString(T object) {\n if (object == null) {\n return \"null\";\n }\n return object.name();\n }\n\n @Override\n public T fromString(String string) {\n if (\"null\".equals(string)) {\n return null;\n }\n try {\n return Enum.valueOf(enumClass, string);\n } catch (IllegalArgumentException e) {\n try {\n final var number = (int) Double.parseDouble(string);\n return enumClass.cast(EnumSet.allOf(enumClass).toArray()[number]);\n } catch (Exception ex) {\n throw new HotaruRuntimeException(\"No constant \" + string\n + \" for type \" + enumClass.getSimpleName());\n }\n }\n }\n });\n return stringProperty;\n };\n }\n\n public abstract <R, T> R accept(NodeVisitor<R, T> visitor, T input);\n}",
"public interface NodeVisitor<R, T> {\n\n R visit(ArcNode node, T input);\n R visit(CircleNode node, T input);\n R visit(EllipseNode node, T input);\n R visit(GroupNode node, T input);\n R visit(ImageNode node, T input);\n R visit(LineNode node, T input);\n R visit(PolygonNode node, T input);\n R visit(PolylineNode node, T input);\n R visit(RectangleNode node, T input);\n R visit(SVGPathNode node, T input);\n R visit(TextNode node, T input);\n}"
] | import com.annimon.hotarufx.lib.FontValue;
import com.annimon.hotarufx.lib.MapValue;
import com.annimon.hotarufx.lib.NodeValue;
import com.annimon.hotarufx.lib.NumberValue;
import com.annimon.hotarufx.lib.StringValue;
import com.annimon.hotarufx.lib.Types;
import com.annimon.hotarufx.lib.Value;
import com.annimon.hotarufx.visual.objects.ObjectNode;
import com.annimon.hotarufx.visual.visitors.NodeVisitor;
import java.util.function.Function;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.text.Font; | package com.annimon.hotarufx.visual;
public enum PropertyType {
BOOLEAN(Value::asBoolean, o -> NumberValue.fromBoolean(Boolean.TRUE.equals(o))),
NUMBER(toNumber(), o -> NumberValue.of((Number) o)),
STRING(Value::asString, o -> new StringValue(String.valueOf(o))),
NODE(toNode(), fromNode()),
CLIP_NODE(toClipNode(), fromNode()),
PAINT(v -> Color.valueOf(v.asString()), o -> new StringValue(o.toString())),
FONT(toFont(), object -> new FontValue((Font) object));
PropertyType(Function<Value, Object> fromHFX, Function<Object, Value> toHFX) {
this.fromHFX = fromHFX;
this.toHFX = toHFX;
}
private final Function<Value, Object> fromHFX;
private final Function<Object, Value> toHFX;
@SuppressWarnings("unchecked")
public <T> Function<Value, T> getFromHFX() {
return (Function<Value, T>) fromHFX;
}
@SuppressWarnings("unchecked")
public <T> Function<T, Value> getToHFX() {
return (Function<T, Value>) toHFX;
}
private static Function<Value, Object> toNumber() {
return value -> {
if (value.type() == Types.NUMBER) {
return ((NumberValue) value).raw();
}
return value.asDouble();
};
}
private static Function<Value, Object> toNode() {
return v -> ((NodeValue)v).getNode().getFxNode();
}
private static Function<Value, Object> toClipNode() {
return v -> { | ObjectNode node = ((NodeValue) v).getNode(); | 7 |
utapyngo/owl2vcs | src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java | [
"public class AddPrefixData extends PrefixChangeData {\r\n\r\n private static final long serialVersionUID = 2801228470061214801L;\r\n\r\n public AddPrefixData(String prefixName, String prefix) {\r\n super(prefixName, prefix);\r\n }\r\n\r\n @Override\r\n public <R, E extends Exception> R accept(\r\n CustomOntologyChangeDataVisitor<R, E> visitor) throws E {\r\n return visitor.visit(this);\r\n }\r\n\r\n @Override\r\n public AddPrefix createOntologyChange(OWLOntology ontology) {\r\n if (ontology == null) {\r\n throw new NullPointerException(\"ontology must not be null\");\r\n }\r\n return new AddPrefix(ontology, getPrefixName(), getPrefix());\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return \"AddPrefixData\".hashCode()\r\n + getPrefixName().hashCode()\r\n + getPrefix().hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof AddPrefixData)) {\r\n return false;\r\n }\r\n AddPrefixData other = (AddPrefixData) obj;\r\n return getPrefixName().equals(other.getPrefixName())\r\n && getPrefix().equals(other.getPrefix());\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"AddPrefixData\");\r\n sb.append(\"(\");\r\n sb.append(getPrefixName().toString());\r\n sb.append(\"=\");\r\n sb.append(getPrefix().toString());\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n}\r",
"public class ModifyPrefixData extends PrefixChangeData {\r\n\r\n private static final long serialVersionUID = -4830654067341708579L;\r\n\r\n private final String oldPrefix;\r\n\r\n public ModifyPrefixData(String prefixName, String oldPrefix, String newPrefix) {\r\n super(prefixName, newPrefix);\r\n this.oldPrefix = oldPrefix;\r\n }\r\n\r\n @Override\r\n public <R, E extends Exception> R accept(\r\n CustomOntologyChangeDataVisitor<R, E> visitor) throws E {\r\n return visitor.visit(this);\r\n }\r\n\r\n @Override\r\n public ModifyPrefix createOntologyChange(OWLOntology ontology) {\r\n if (ontology == null) {\r\n throw new NullPointerException(\"ontology must not be null\");\r\n }\r\n return new ModifyPrefix(ontology, getPrefixName(), getOldPrefix(), getPrefix());\r\n }\r\n\r\n /**\r\n * @return the newPrefix\r\n */\r\n public String getOldPrefix() {\r\n return oldPrefix;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return \"ModifyPrefixData\".hashCode()\r\n + getPrefixName().hashCode()\r\n + getOldPrefix().hashCode()\r\n + getPrefix().hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ModifyPrefixData)) {\r\n return false;\r\n }\r\n ModifyPrefixData other = (ModifyPrefixData) obj;\r\n return getPrefixName().equals(other.getPrefixName())\r\n && getOldPrefix().equals(other.getOldPrefix())\r\n && getPrefix().equals(other.getPrefix());\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"ModifyPrefixData\");\r\n sb.append(\"(\");\r\n sb.append(getPrefixName().toString());\r\n sb.append(\"=\");\r\n sb.append(getOldPrefix().toString());\r\n sb.append(\" \");\r\n sb.append(getPrefix().toString());\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n @Override\r\n public Collection<String> getPrefixSignature() {\r\n final Collection<String> sig = super.getPrefixSignature();\r\n sig.add(getOldPrefix());\r\n return sig;\r\n }\r\n}\r",
"public class RemovePrefixData extends PrefixChangeData {\r\n\r\n private static final long serialVersionUID = 938006048114096186L;\r\n\r\n public RemovePrefixData(String prefixName, String prefix) {\r\n super(prefixName, prefix);\r\n }\r\n\r\n @Override\r\n public <R, E extends Exception> R accept(\r\n CustomOntologyChangeDataVisitor<R, E> visitor) throws E {\r\n return visitor.visit(this);\r\n }\r\n\r\n @Override\r\n public RemovePrefix createOntologyChange(OWLOntology ontology) {\r\n if (ontology == null) {\r\n throw new NullPointerException(\"ontology must not be null\");\r\n }\r\n return new RemovePrefix(ontology, getPrefixName(), getPrefix());\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return \"RemovePrefixData\".hashCode()\r\n + getPrefixName().hashCode()\r\n + getPrefix().hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof RemovePrefixData)) {\r\n return false;\r\n }\r\n RemovePrefixData other = (RemovePrefixData) obj;\r\n return getPrefixName().equals(other.getPrefixName())\r\n && getPrefix().equals(other.getPrefix());\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"RemovePrefixData\");\r\n sb.append(\"(\");\r\n sb.append(getPrefixName().toString());\r\n sb.append(\"=\");\r\n sb.append(getPrefix().toString());\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n}\r",
"public class RenamePrefixData extends PrefixChangeData {\r\n\r\n private static final long serialVersionUID = -3363060595690396626L;\r\n private final String oldPrefixName;\r\n\r\n public RenamePrefixData(String oldPrefixName, String prefix, String newPrefixName) {\r\n super(newPrefixName, prefix);\r\n this.oldPrefixName = oldPrefixName;\r\n }\r\n\r\n @Override\r\n public <R, E extends Exception> R accept(\r\n CustomOntologyChangeDataVisitor<R, E> visitor) throws E {\r\n return visitor.visit(this);\r\n }\r\n\r\n @Override\r\n public RenamePrefix createOntologyChange(OWLOntology ontology) {\r\n if (ontology == null) {\r\n throw new NullPointerException(\"ontology must not be null\");\r\n }\r\n return new RenamePrefix(ontology, getOldPrefixName(), getPrefix(), getPrefixName());\r\n }\r\n\r\n /**\r\n * @return the newPrefixName\r\n */\r\n public String getOldPrefixName() {\r\n return oldPrefixName;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return \"RenamePrefixData\".hashCode()\r\n + getPrefixName().hashCode()\r\n + getPrefix().hashCode()\r\n + getOldPrefixName().hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof RenamePrefixData)) {\r\n return false;\r\n }\r\n RenamePrefixData other = (RenamePrefixData) obj;\r\n return getPrefixName().equals(other.getPrefixName())\r\n && getPrefix().equals(other.getPrefix())\r\n && getOldPrefixName().equals(other.getOldPrefixName());\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"RenamePrefixData\");\r\n sb.append(\"(\");\r\n sb.append(getOldPrefixName().toString());\r\n sb.append(\" \");\r\n sb.append(getPrefixName().toString());\r\n sb.append(\"=\");\r\n sb.append(getPrefix().toString());\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n @Override\r\n public Collection<String> getPrefixSignature() {\r\n final Collection<String> sig = super.getPrefixSignature();\r\n sig.add(getOldPrefixName());\r\n return sig;\r\n }\r\n}\r",
"public class SetOntologyFormatData extends CustomOntologyChangeData {\r\n\r\n private static final long serialVersionUID = 4000984588491273026L;\r\n\r\n private final OWLOntologyFormat newFormat;\r\n\r\n public SetOntologyFormatData(OWLOntologyFormat newFormat) {\r\n if (newFormat == null) {\r\n throw new NullPointerException(\"newFormat must not be null\");\r\n }\r\n this.newFormat = newFormat;\r\n }\r\n\r\n /**\r\n * Creates a set ontology format change, which will set the format of the\r\n * ontology to the specified new format specified as a string.\r\n *\r\n * @param ont\r\n * The ontology whose format is to be changed\r\n * @param newOntologyFormat\r\n * A string representing the new ontology format\r\n * @throws UnknownOntologyFormatException\r\n */\r\n public SetOntologyFormatData(final String newFormatString)\r\n throws UnknownOntologyFormatException {\r\n super();\r\n OWLOntologyFormat newOntologyFormat;\r\n if (newFormatString.equals(\"RDF/XML\"))\r\n newOntologyFormat = new RDFXMLOntologyFormat();\r\n else if (newFormatString.equals(\"OWL/XML\"))\r\n newOntologyFormat = new OWLXMLOntologyFormat();\r\n else if (newFormatString.equals(\"Turtle\"))\r\n newOntologyFormat = new TurtleOntologyFormat();\r\n else if (newFormatString.equals(\"OWL Functional Syntax\"))\r\n newOntologyFormat = new OWLFunctionalSyntaxOntologyFormat();\r\n else if (newFormatString.equals(\"Manchester OWL Syntax\"))\r\n newOntologyFormat = new ManchesterOWLSyntaxOntologyFormat();\r\n else\r\n throw new UnknownOntologyFormatException(\"Unknown format: \" + newFormatString);\r\n this.newFormat = newOntologyFormat;\r\n }\r\n\r\n @Override\r\n public SetOntologyFormat createOntologyChange(OWLOntology ontology) {\r\n if (ontology == null) {\r\n throw new NullPointerException(\"ontology must not be null\");\r\n }\r\n return new SetOntologyFormat(ontology, newFormat);\r\n }\r\n\r\n public OWLOntologyFormat getNewFormat() {\r\n return newFormat;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return \"SetOntologyFormatData\".hashCode() + newFormat.hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof SetOntologyFormatData)) {\r\n return false;\r\n }\r\n SetOntologyFormatData other = (SetOntologyFormatData) obj;\r\n return newFormat.equals(other.newFormat);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"SetOntologyFormatData\");\r\n sb.append(\"(OntologyFormat(\");\r\n sb.append(newFormat);\r\n sb.append(\"))\");\r\n return sb.toString();\r\n }\r\n\r\n @Override\r\n public <R, E extends Exception> R accept(\r\n CustomOntologyChangeDataVisitor<R, E> visitor) throws E {\r\n return visitor.visit(this);\r\n }\r\n\r\n}\r"
] | import org.semanticweb.owlapi.change.OWLOntologyChangeDataVisitor;
import owl2vcs.changes.AddPrefixData;
import owl2vcs.changes.ModifyPrefixData;
import owl2vcs.changes.RemovePrefixData;
import owl2vcs.changes.RenamePrefixData;
import owl2vcs.changes.SetOntologyFormatData;
| package owl2vcs.changeset;
public interface CustomOntologyChangeDataVisitor<R, E extends Exception>
extends OWLOntologyChangeDataVisitor<R, E> {
| R visit(SetOntologyFormatData data) throws E;
| 4 |
GoogleCloudPlatform/opentelemetry-operations-java | exporters/metrics/src/test/java/com/google/cloud/opentelemetry/metric/MetricTranslatorTest.java | [
"static final DoublePointData aDoublePoint =\n DoublePointData.create(\n 1599030114 * NANO_PER_SECOND,\n 1599031814 * NANO_PER_SECOND,\n Attributes.of(stringKey(\"label1\"), \"value1\", booleanKey(\"label2\"), false),\n 32d);",
"static final DoubleSummaryPointData aDoubleSummaryPoint =\n DoubleSummaryPointData.create(\n 1599030114 * NANO_PER_SECOND,\n 1599031814 * NANO_PER_SECOND,\n Attributes.of(stringKey(\"label1\"), \"value1\", booleanKey(\"label2\"), false),\n 1,\n 32d,\n Collections.emptyList());",
"static final Resource aGceResource = Resource.create(someGceAttributes);",
"static final DoubleHistogramPointData aHistogramPoint =\n DoubleHistogramPointData.create(\n 0,\n 1,\n Attributes.builder().put(\"test\", \"one\").build(),\n 3d,\n Arrays.asList(1.0),\n Arrays.asList(1L, 2L),\n Arrays.asList(\n DoubleExemplarData.create(\n Attributes.builder().put(\"test2\", \"two\").build(), 2, \"spanId\", \"traceId\", 3.0)));",
"static final LongPointData aLongPoint =\n LongPointData.create(\n 1599030114 * NANO_PER_SECOND,\n 1599031814 * NANO_PER_SECOND,\n Attributes.of(stringKey(\"label1\"), \"value1\", booleanKey(\"label2\"), false),\n 32L);",
"static final MetricData aMetricData =\n MetricData.createLongSum(\n aGceResource,\n anInstrumentationLibraryInfo,\n \"opentelemetry/name\",\n \"description\",\n \"ns\",\n LongSumData.create(\n true, AggregationTemporality.CUMULATIVE, ImmutableList.of(aLongPoint)));",
"static final InstrumentationLibraryInfo anInstrumentationLibraryInfo =\n InstrumentationLibraryInfo.create(\"instrumentName\", \"0\");",
"static final String DESCRIPTOR_TYPE_URL = \"custom.googleapis.com/OpenTelemetry/\";",
"static final String METRIC_DESCRIPTOR_TIME_UNIT = \"ns\";"
] | import static com.google.cloud.opentelemetry.metric.FakeData.aDoublePoint;
import static com.google.cloud.opentelemetry.metric.FakeData.aDoubleSummaryPoint;
import static com.google.cloud.opentelemetry.metric.FakeData.aGceResource;
import static com.google.cloud.opentelemetry.metric.FakeData.aHistogramPoint;
import static com.google.cloud.opentelemetry.metric.FakeData.aLongPoint;
import static com.google.cloud.opentelemetry.metric.FakeData.aMetricData;
import static com.google.cloud.opentelemetry.metric.FakeData.anInstrumentationLibraryInfo;
import static com.google.cloud.opentelemetry.metric.MetricTranslator.DESCRIPTOR_TYPE_URL;
import static com.google.cloud.opentelemetry.metric.MetricTranslator.METRIC_DESCRIPTOR_TIME_UNIT;
import static io.opentelemetry.api.common.AttributeKey.booleanKey;
import static io.opentelemetry.api.common.AttributeKey.longKey;
import static io.opentelemetry.api.common.AttributeKey.stringKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import com.google.api.Distribution;
import com.google.api.LabelDescriptor;
import com.google.api.LabelDescriptor.ValueType;
import com.google.api.Metric;
import com.google.api.Metric.Builder;
import com.google.api.MetricDescriptor;
import com.google.api.MetricDescriptor.MetricKind;
import com.google.common.collect.ImmutableList;
import com.google.monitoring.v3.DroppedLabels;
import com.google.monitoring.v3.SpanContext;
import com.google.protobuf.InvalidProtocolBufferException;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.sdk.metrics.data.AggregationTemporality;
import io.opentelemetry.sdk.metrics.data.DoubleHistogramData;
import io.opentelemetry.sdk.metrics.data.DoubleSumData;
import io.opentelemetry.sdk.metrics.data.DoubleSummaryData;
import io.opentelemetry.sdk.metrics.data.LongSumData;
import io.opentelemetry.sdk.metrics.data.MetricData;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; | /*
* Copyright 2022 Google
*
* 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.google.cloud.opentelemetry.metric;
@RunWith(JUnit4.class)
public class MetricTranslatorTest {
@Test
public void testMapMetricSucceeds() {
String type = "custom.googleapis.com/OpenTelemetry/" + anInstrumentationLibraryInfo.getName();
Builder expectedMetricBuilder = Metric.newBuilder().setType(type);
aLongPoint
.getAttributes()
.forEach((k, v) -> expectedMetricBuilder.putLabels(k.getKey(), v.toString()));
Metric actualMetric = MetricTranslator.mapMetric(aLongPoint.getAttributes(), type);
assertEquals(expectedMetricBuilder.build(), actualMetric);
}
@Test
public void testMapMetricWithWierdAttributeNameSucceeds() {
String type = "custom.googleapis.com/OpenTelemetry/" + anInstrumentationLibraryInfo.getName();
Attributes attributes =
io.opentelemetry.api.common.Attributes.of(stringKey("test.bad"), "value");
Metric expectedMetric =
Metric.newBuilder().setType(type).putLabels("test_bad", "value").build();
Metric actualMetric = MetricTranslator.mapMetric(attributes, type);
assertEquals(expectedMetric, actualMetric);
}
@Test
public void testMapMetricDescriptorSucceeds() {
MetricDescriptor.Builder expectedDescriptor =
MetricDescriptor.newBuilder()
.setDisplayName(aMetricData.getName())
.setType(DESCRIPTOR_TYPE_URL + aMetricData.getName())
.addLabels(LabelDescriptor.newBuilder().setKey("label1").setValueType(ValueType.STRING))
.addLabels(LabelDescriptor.newBuilder().setKey("label2").setValueType(ValueType.BOOL)) | .setUnit(METRIC_DESCRIPTOR_TIME_UNIT) | 8 |
kennylbj/concurrent-java | src/main/java/producerconsumer/Main.java | [
"public class BlockingQueueConsumer implements Consumer<Item>, Runnable {\n private final BlockingQueue<Item> buffer;\n private final Random random = new Random(System.nanoTime());\n\n public BlockingQueueConsumer(BlockingQueue<Item> buffer) {\n this.buffer = buffer;\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n Item item = buffer.take();\n consume(item);\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void consume(Item item) {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n System.out.println(\"[BlockingQueue] Consumer consumes item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n }\n}",
"public class BlockingQueueProducer implements Producer<Item>, Runnable {\n private final BlockingQueue<Item> buffer;\n private final Random random = new Random(System.nanoTime());\n\n public BlockingQueueProducer(BlockingQueue<Item> buffer) {\n this.buffer = buffer;\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n Item item = produce();\n buffer.put(item);\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public Item produce() {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n Item item = Item.generate();\n System.out.println(\"[BlockingQueue] Producer produces item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n return item;\n }\n}",
"public class ConditionConsumer implements Consumer<Item>, Runnable {\n @GuardedBy(\"lock\")\n private final Buffer<Item> buffer;\n private final Lock lock;\n private final Condition full;\n private final Condition empty;\n private final Random random = new Random(System.nanoTime());\n\n public ConditionConsumer(Buffer<Item> buffer, Lock lock, Condition full, Condition empty) {\n this.buffer = buffer;\n this.lock = lock;\n this.full = full;\n this.empty = empty;\n }\n\n @Override\n public void consume(Item item) {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n System.out.println(\"[Condition] Consumer consumes item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n Item item;\n lock.lock();\n try {\n //buffer empty, so wait until no empty\n while (buffer.getSize() == 0) {\n empty.await();\n }\n item = buffer.popItem();\n\n if (buffer.getSize() == buffer.getCapacity() - 1) {\n full.signal();\n }\n } finally {\n lock.unlock();\n }\n //outside critical section\n consume(item);\n }\n } catch (InterruptedException e) {\n System.out.println(\"failed to consume items\");\n Thread.currentThread().interrupt();\n }\n }\n\n}",
"public class ConditionProducer implements Producer<Item>, Runnable {\n @GuardedBy(\"lock\")\n private final Buffer<Item> buffer;\n private final Lock lock;\n private final Condition full;\n private final Condition empty;\n private final Random random = new Random(System.nanoTime());\n\n public ConditionProducer(Buffer<Item> buffer, Lock lock, Condition full, Condition empty) {\n this.buffer = buffer;\n this.lock = lock;\n this.full = full;\n this.empty = empty;\n }\n\n @Override\n public Item produce() {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n Item item = Item.generate();\n System.out.println(\"[Condition] Producer produces item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n return item;\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n //outside critical section\n Item item = produce();\n\n lock.lock();\n try {\n //buffer is full, so wait until no full\n while (buffer.getSize() == buffer.getCapacity()) {\n full.await();\n }\n buffer.putItem(item);\n //signal consumers when buffer size is one\n //to avoid herd effect\n if (buffer.getSize() == 1) {\n empty.signal();\n }\n } finally {\n lock.unlock();\n }\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n}",
"public class SemaphoreConsumer implements Consumer<Item>, Runnable {\n @GuardedBy(\"buffer\")\n private final Buffer<Item> buffer;\n private final Semaphore fullCount;\n private final Semaphore emptyCount;\n private final Random random = new Random(System.nanoTime());\n\n public SemaphoreConsumer(Buffer<Item> buffer, Semaphore fullCount, Semaphore emptyCount) {\n this.buffer = buffer;\n this.fullCount = fullCount;\n this.emptyCount = emptyCount;\n }\n\n @Override\n public void consume(Item item) {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n System.out.println(\"[Semaphore] Consumer consumes item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n fullCount.acquire();\n Item item;\n synchronized (buffer) {\n item = buffer.popItem();\n }\n emptyCount.release();\n consume(item);\n }\n } catch (InterruptedException e) {\n System.out.println(\"failed to consume\");\n Thread.currentThread().interrupt();\n }\n }\n}",
"public class SemaphoreProducer implements Producer<Item>, Runnable {\n @GuardedBy(\"buffer\")\n private final Buffer<Item> buffer;\n private final Semaphore fullCount;\n private final Semaphore emptyCount;\n private final Random random = new Random(System.nanoTime());\n\n public SemaphoreProducer(Buffer<Item> buffer, Semaphore fullCount, Semaphore emptyCount) {\n this.buffer = buffer;\n this.fullCount = fullCount;\n this.emptyCount = emptyCount;\n }\n\n //produce operation may be time-consuming\n @Override\n public Item produce() {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n Item item = Item.generate();\n System.out.println(\"[Semaphore] Producer produces item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n return item;\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n Item item = produce();\n emptyCount.acquire();\n synchronized (buffer) {\n buffer.putItem(item);\n }\n fullCount.release();\n\n }\n } catch (InterruptedException e) {\n System.out.println(\"failed to produce\");\n Thread.currentThread().interrupt();\n }\n\n }\n}"
] | import producerconsumer.blockingqueue.BlockingQueueConsumer;
import producerconsumer.blockingqueue.BlockingQueueProducer;
import producerconsumer.condition.ConditionConsumer;
import producerconsumer.condition.ConditionProducer;
import producerconsumer.semaphore.SemaphoreConsumer;
import producerconsumer.semaphore.SemaphoreProducer;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; | package producerconsumer;
/**
* Created by kennylbj on 16/9/10.
* Implement 3 versions of P/C
* 1) use Semaphore
* 2) use Condition
* 3) use BlockingQueue
* All versions support multiple producers and consumers
*/
public class Main {
private static final int BUFFER_SIZE = 100;
private static final int PRODUCER_NUM = 3;
private static final int CONSUMER_NUM = 2;
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newCachedThreadPool();
// Buffers of all P/C
Buffer<Item> semaphoreBuffer = new LinkListBuffer(BUFFER_SIZE);
Buffer<Item> conditionBuffer = new LinkListBuffer(BUFFER_SIZE);
BlockingQueue<Item> blockingQueueBuffer = new LinkedBlockingQueue<>(BUFFER_SIZE);
// Semaphores for Semaphore version of P/C
Semaphore fullCount = new Semaphore(0);
Semaphore emptyCount = new Semaphore(BUFFER_SIZE);
// Lock and conditions for Condition version of P/C
Lock lock = new ReentrantLock();
Condition full = lock.newCondition();
Condition empty = lock.newCondition();
for (int i = 0; i < PRODUCER_NUM; i++) { | pool.execute(new SemaphoreProducer(semaphoreBuffer, fullCount, emptyCount)); | 5 |
mvescovo/item-reaper | app/src/testMock/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenterTest.java | [
"public interface DataSource {\n\n void getItems(@NonNull String userId, @NonNull String sortBy, @NonNull String caller,\n @NonNull GetItemsCallback callback);\n\n void getItem(@NonNull String itemId, @NonNull String userId, @NonNull String caller,\n @NonNull GetItemCallback callback);\n\n void getNewItemId(@NonNull String userId, @NonNull GetNewItemIdCallback callback);\n\n void saveItem(@NonNull String userId, @NonNull Item item);\n\n void deleteItem(@NonNull String userId, @NonNull Item item);\n\n void deleteAllItems(@NonNull String userId);\n\n interface GetItemsCallback {\n void onItemsLoaded(@Nullable List<Item> items);\n }\n\n interface GetItemCallback {\n void onItemLoaded(@Nullable Item item);\n }\n\n interface GetNewItemIdCallback {\n void onNewItemIdLoaded(@Nullable String newItemId);\n }\n}",
"public class Item implements Serializable, Comparable {\n\n @NonNull\n private String mId = \"-1\";\n private long mPurchaseDate;\n private int mPricePaid;\n private int mDiscount;\n private long mExpiry;\n @Nullable\n private String mCategory;\n @Nullable\n private String mSubCategory;\n @Nullable\n private String mType;\n @Nullable\n private String mSubType;\n @Nullable\n private String mSubType2;\n @Nullable\n private String mSubType3;\n @Nullable\n private String mMainColour;\n @Nullable\n private String mMainColourShade;\n @Nullable\n private String mAccentColour;\n @Nullable\n private String mSize;\n @Nullable\n private String mBrand;\n @Nullable\n private String mShop;\n @Nullable\n private String mDescription;\n @Nullable\n private String mNote;\n @Nullable\n private String mImageUrl;\n private boolean mDeceased;\n\n public Item() {\n // Firebase required no arg constructor.\n }\n\n public Item(@NonNull String id) {\n mId = id;\n mDeceased = false;\n }\n\n public Item(@NonNull String id, long purchaseDate, int pricePaid, int discount,\n long expiry, @Nullable String category, @Nullable String subCategory,\n @NonNull String type, @Nullable String subType, @Nullable String subType2,\n @Nullable String subType3, @Nullable String mainColour,\n @Nullable String mainColourShade, @Nullable String accentColour,\n @Nullable String size, @Nullable String brand, @Nullable String shop,\n @Nullable String description, @Nullable String note,\n @Nullable String imageUrl, boolean deceased) {\n mId = id;\n mPurchaseDate = purchaseDate;\n mPricePaid = pricePaid;\n mDiscount = discount;\n mExpiry = expiry;\n mCategory = category;\n mSubCategory = subCategory;\n mType = type;\n mSubType = subType;\n mSubType2 = subType2;\n mSubType3 = subType3;\n mMainColour = mainColour;\n mMainColourShade = mainColourShade;\n mAccentColour = accentColour;\n mSize = size;\n mBrand = brand;\n mShop = shop;\n mDescription = description;\n mNote = note;\n mImageUrl = imageUrl;\n mDeceased = deceased;\n }\n\n @NonNull\n public String getId() {\n return mId;\n }\n\n public void setId(@NonNull String id) {\n mId = id;\n }\n\n public long getPurchaseDate() {\n return mPurchaseDate;\n }\n\n public void setPurchaseDate(long purchaseDate) {\n mPurchaseDate = purchaseDate;\n }\n\n public int getPricePaid() {\n return mPricePaid;\n }\n\n public void setPricePaid(int pricePaid) {\n mPricePaid = pricePaid;\n }\n\n public int getDiscount() {\n return mDiscount;\n }\n\n public void setDiscount(int discount) {\n mDiscount = discount;\n }\n\n public long getExpiry() {\n return mExpiry;\n }\n\n public void setExpiry(long expiry) {\n mExpiry = expiry;\n }\n\n @Nullable\n public String getCategory() {\n return mCategory;\n }\n\n public void setCategory(@Nullable String category) {\n mCategory = category;\n }\n\n @Nullable\n public String getSubCategory() {\n return mSubCategory;\n }\n\n public void setSubCategory(@Nullable String subCategory) {\n mSubCategory = subCategory;\n }\n\n @Nullable\n public String getType() {\n return mType;\n }\n\n public void setType(@Nullable String type) {\n mType = type;\n }\n\n @Nullable\n public String getSubType() {\n return mSubType;\n }\n\n public void setSubType(@Nullable String subType) {\n mSubType = subType;\n }\n\n @Nullable\n public String getSubType2() {\n return mSubType2;\n }\n\n public void setSubType2(@Nullable String subType2) {\n mSubType2 = subType2;\n }\n\n @Nullable\n public String getSubType3() {\n return mSubType3;\n }\n\n public void setSubType3(@Nullable String subType3) {\n mSubType3 = subType3;\n }\n\n @Nullable\n public String getMainColour() {\n return mMainColour;\n }\n\n public void setMainColour(@Nullable String mainColour) {\n mMainColour = mainColour;\n }\n\n @Nullable\n public String getMainColourShade() {\n return mMainColourShade;\n }\n\n public void setMainColourShade(@Nullable String mainColourShade) {\n mMainColourShade = mainColourShade;\n }\n\n @Nullable\n public String getAccentColour() {\n return mAccentColour;\n }\n\n public void setAccentColour(@Nullable String accentColour) {\n mAccentColour = accentColour;\n }\n\n @Nullable\n public String getSize() {\n return mSize;\n }\n\n public void setSize(@Nullable String size) {\n mSize = size;\n }\n\n @Nullable\n public String getBrand() {\n return mBrand;\n }\n\n public void setBrand(@Nullable String brand) {\n mBrand = brand;\n }\n\n @Nullable\n public String getShop() {\n return mShop;\n }\n\n public void setShop(@Nullable String shop) {\n mShop = shop;\n }\n\n @Nullable\n public String getDescription() {\n return mDescription;\n }\n\n public void setDescription(@Nullable String description) {\n mDescription = description;\n }\n\n @Nullable\n public String getNote() {\n return mNote;\n }\n\n public void setNote(@Nullable String note) {\n mNote = note;\n }\n\n @Nullable\n public String getImageUrl() {\n return mImageUrl;\n }\n\n public void setImageUrl(@Nullable String imageUrl) {\n mImageUrl = imageUrl;\n }\n\n public boolean getDeceased() {\n return mDeceased;\n }\n\n public void setDeceased(boolean deceased) {\n mDeceased = deceased;\n }\n\n // For Firebase map\n public Map<String, Object> toMap() {\n Map<String, Object> result = new HashMap<>();\n result.put(\"id\", mId);\n result.put(\"purchaseDate\", mPurchaseDate);\n result.put(\"pricePaid\", mPricePaid);\n result.put(\"discount\", mDiscount);\n result.put(\"expiry\", mExpiry);\n result.put(\"category\", mCategory);\n result.put(\"subCategory\", mSubCategory);\n result.put(\"type\", mType);\n result.put(\"subType\", mSubType);\n result.put(\"subType2\", mSubType2);\n result.put(\"subType3\", mSubType3);\n result.put(\"mainColour\", mMainColour);\n result.put(\"mainColourShade\", mMainColourShade);\n result.put(\"accentColour\", mAccentColour);\n result.put(\"size\", mSize);\n result.put(\"brand\", mBrand);\n result.put(\"shop\", mShop);\n result.put(\"description\", mDescription);\n result.put(\"note\", mNote);\n result.put(\"imageUrl\", mImageUrl);\n result.put(\"deceased\", mDeceased);\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof Item && ((Item) obj).getId().equals(mId);\n }\n\n @Override\n public int hashCode() {\n return mId.hashCode();\n }\n\n public boolean equalsAllFields(Object obj) {\n boolean result = false;\n if (obj instanceof Item) {\n Item item = (Item) obj;\n result = mId.equals(item.mId) && mPurchaseDate == item.mPurchaseDate\n && mPricePaid == item.mPricePaid && mDiscount == item.mDiscount\n && mExpiry == item.mExpiry\n && (mCategory != null && mCategory.equals(item.mCategory))\n && (mSubCategory != null && mSubCategory.equals(item.mSubCategory))\n && (mType != null && mType.equals(item.mType))\n && (mSubType != null && mSubType.equals(item.mSubType))\n && (mSubType2 != null && mSubType2.equals(item.mSubType2))\n && (mSubType3 != null && mSubType3.equals(item.mSubType3))\n && (mMainColour != null && mMainColour.equals(item.mMainColour))\n && (mMainColourShade != null && mMainColourShade.equals(item.mMainColourShade))\n && (mAccentColour != null && mAccentColour.equals(item.mAccentColour))\n && (mSize != null && mSize.equals(item.mSize))\n && (mBrand != null && mBrand.equals(item.mBrand))\n && (mShop != null && mShop.equals(item.mShop))\n && (mDescription != null && mDescription.equals(item.mDescription))\n && (mNote != null && mNote.equals(item.mNote))\n && (mImageUrl != null && mImageUrl.equals(item.mImageUrl))\n && mDeceased == item.mDeceased;\n }\n return result;\n }\n\n @Override\n public int compareTo(@NonNull Object item2) {\n if (mExpiry > ((Item) item2).getExpiry()) {\n return 1;\n } else if (mExpiry == ((Item) item2).getExpiry()) {\n return 0;\n } else {\n return -1;\n }\n }\n}",
"public class Repository implements DataSource {\n\n private final DataSource mRemoteDataSource;\n List<Item> mCachedItems;\n private String mCurrentSort;\n List<String> mItemCallers;\n\n @Inject\n Repository(DataSource remoteDataSource) {\n mRemoteDataSource = remoteDataSource;\n mCachedItems = new ArrayList<>();\n mItemCallers = new ArrayList<>();\n }\n\n @Override\n public void getItems(@NonNull String userId, @NonNull String sortBy, @NonNull String caller,\n @NonNull final GetItemsCallback callback) {\n if (mCurrentSort == null || !mCurrentSort.equals(sortBy)) {\n mCurrentSort = sortBy;\n mRemoteDataSource.getItems(userId, sortBy, caller, new GetItemsCallback() {\n @Override\n public void onItemsLoaded(@Nullable List<Item> items) {\n if (items != null) {\n mCachedItems = ImmutableList.copyOf(items);\n } else {\n mCachedItems = new ArrayList<>();\n }\n callback.onItemsLoaded(mCachedItems);\n }\n });\n } else {\n callback.onItemsLoaded(mCachedItems);\n }\n }\n\n @Override\n public void getItem(@NonNull final String itemId, @NonNull String userId,\n @NonNull String caller, @NonNull final GetItemCallback callback) {\n // Use cache if possible\n for (Item item : mCachedItems) {\n if (item.getId().equals(itemId)) {\n callback.onItemLoaded(item);\n break;\n }\n }\n\n // Need to make sure a callback is established with the remote data source, even if the\n // item was cached. Item may have been cached from a call to getItems.\n if (!mItemCallers.contains(caller)) {\n mRemoteDataSource.getItem(itemId, userId, caller, new GetItemCallback() {\n @Override\n public void onItemLoaded(@Nullable Item item) {\n if (!mCachedItems.contains(item)) {\n mCachedItems.add(item);\n callback.onItemLoaded(item);\n } else {\n int index = mCachedItems.indexOf(item);\n // If the item has changed since it was cached, replace the cached version.\n if (!mCachedItems.get(index).equalsAllFields(item)) {\n mCachedItems.set(index, item);\n callback.onItemLoaded(item);\n }\n }\n }\n });\n mItemCallers.add(caller);\n }\n }\n\n @Override\n public void getNewItemId(@NonNull String userId, @NonNull final GetNewItemIdCallback callback) {\n mRemoteDataSource.getNewItemId(userId, new GetNewItemIdCallback() {\n @Override\n public void onNewItemIdLoaded(@Nullable String newItemId) {\n if (newItemId != null) {\n callback.onNewItemIdLoaded(newItemId);\n }\n }\n });\n }\n\n @Override\n public void saveItem(@NonNull String userId, @NonNull Item item) {\n mRemoteDataSource.saveItem(userId, item);\n }\n\n @Override\n public void deleteItem(@NonNull String userId, @NonNull Item item) {\n mRemoteDataSource.deleteItem(userId, item);\n }\n\n @Override\n public void deleteAllItems(@NonNull String userId) {\n mRemoteDataSource.deleteAllItems(userId);\n }\n}",
"public final static Item ITEM_1 = new Item(\"1\",\n 1453554000000L, // purchase: 24/01/2016\n 2000,\n 0,\n 1485176400000L, // expiry: 24/01/2017\n \"Clothing\", \"Casual\", \"T-shirt\",\n \"Short sleeve\", \"V-neck\", \"Plain\", \"Black\", \"Dark\", \"Some secondary colour\",\n \"Some Size\", \"Some Brand\", \"Some Shop\", \"Standard plain T-shirt\", \"Some note\",\n \"file:///android_asset/black-t-shirt.jpg\", false);",
"public final static Item ITEM_2 = new Item(\"2\",\n -1, // purchase: unknown\n 3000,\n -1,\n 1514206800000L, // expiry: 26/12/2017\n \"Bathroom\", null,\n \"Towel\", null, null, null, \"White\", null, null, null, null, null, null, null, null,\n false);",
"public final static String USER_ID = \"testUID\";"
] | import com.google.firebase.auth.FirebaseAuth;
import com.michaelvescovo.android.itemreaper.data.DataSource;
import com.michaelvescovo.android.itemreaper.data.Item;
import com.michaelvescovo.android.itemreaper.data.Repository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Arrays;
import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1;
import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2;
import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify; | package com.michaelvescovo.android.itemreaper.item_details;
/**
* @author Michael Vescovo
*/
@RunWith(Parameterized.class)
public class ItemDetailsPresenterTest {
private ItemDetailsPresenter mPresenter;
@Mock
private ItemDetailsContract.View mView;
@Mock
private Repository mRepository;
@Mock
private FirebaseAuth mFirebaseAuth;
@Captor
private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor;
private Item mItem;
public ItemDetailsPresenterTest(Item item) {
mItem = item;
}
@Parameterized.Parameters
public static Iterable<?> data() {
return Arrays.asList(
ITEM_1,
ITEM_2
);
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this); | mPresenter = new ItemDetailsPresenter(mView, mRepository, USER_ID); | 5 |
ceylon/ceylon-model | src/com/redhat/ceylon/model/loader/model/LazyModule.java | [
"public interface ArtifactResult {\n /**\n * Get name.\n *\n * @return the artifact name.\n */\n String name();\n\n /**\n * Get version.\n *\n * @return the version.\n */\n String version();\n\n /**\n * Get import type.\n *\n * @return the import type\n */\n ImportType importType();\n\n /**\n * The result type.\n *\n * @return the type\n */\n ArtifactResultType type();\n\n /**\n * Get visibility type.\n *\n * @return visibility type\n */\n VisibilityType visibilityType();\n\n /**\n * The requested artifact.\n *\n * @return the requested artifact\n * @throws RepositoryException for any I/O error\n */\n File artifact() throws RepositoryException;\n\n /**\n * The resources filter.\n *\n * @return the path filter or null if there is none\n */\n PathFilter filter();\n\n /**\n * Dependencies.\n * <p/>\n * They could be lazily recursively fetched\n * or they could be fetched in one go.\n *\n * @return dependencies, empty list if none\n * @throws RepositoryException for any I/O error\n */\n List<ArtifactResult> dependencies() throws RepositoryException;\n\n /**\n * Get the display string of the repository this\n * result comes from\n *\n * @return the repository display string.\n */\n String repositoryDisplayString();\n \n /**\n * Get the repository this result was resolved from.\n *\n * @return the repository this result was resolved from.\n */\n Repository repository();\n}",
"public class JDKUtils {\n \n public enum JDK {\n JDK7(\"package-list.jdk7\", \"package-list.oracle.jdk7\", \"7\"),\n JDK8(\"package-list.jdk8\", \"package-list.oracle.jdk8\", \"8\");\n \n public final String packageList;\n public final String packageListOracle;\n public final String version;\n \n private JDK(String packageList, String packageListOracle, String version) {\n this.packageList = packageList;\n this.packageListOracle = packageListOracle;\n this.version = version;\n }\n \n public boolean providesVersion(String version){\n if(this.version.equals(version))\n return true;\n // also provides every smaller version\n EnumSet<JDK> smaller = EnumSet.range(JDK7, this);\n // we want strictly smaller\n smaller.remove(this);\n for(JDK smallerJDK : smaller){\n if(smallerJDK.version.equals(version))\n return true;\n }\n return false;\n }\n\n public boolean isLowerVersion(String version) {\n EnumSet<JDK> smaller = EnumSet.range(JDK7, this);\n // we want strictly smaller\n smaller.remove(this);\n for(JDK smallerJDK : smaller){\n if(smallerJDK.version.equals(version))\n return true;\n }\n return false;\n }\n }\n \n public final static JDK jdk;\n \n static {\n String version = System.getProperty(\"java.version\");\n if(version != null && version.startsWith(\"1.8\")){\n jdk = JDK.JDK8;\n }else{\n jdk = JDK.JDK7;\n }\n }\n\n private static Map<String, Tuple> jdkModules;\n private static Map<String, Tuple> jdkOracleModules;\n private static HashMap<String, String> jdkPackageToModule;\n\n private static class Tuple {\n private Set<String> packages;\n private Set<String> paths;\n\n private Tuple() {\n packages = new HashSet<String>();\n paths = new HashSet<String>();\n }\n\n boolean isEmpty() {\n return packages.isEmpty();\n }\n\n Tuple finish() {\n packages = Collections.unmodifiableSet(packages);\n paths = Collections.unmodifiableSet(paths);\n return this;\n }\n }\n\n private static synchronized void loadPackageList() {\n if (jdkModules != null)\n return;\n jdkModules = loadModularPackageList(jdk.packageList);\n jdkOracleModules = loadModularPackageList(jdk.packageListOracle);\n jdkPackageToModule = new HashMap<String,String>();\n for(Entry<String, Tuple> entry : jdkModules.entrySet()){\n for(String pkg : entry.getValue().packages)\n jdkPackageToModule.put(pkg, entry.getKey());\n }\n for(Entry<String, Tuple> entry : jdkOracleModules.entrySet()){\n for(String pkg : entry.getValue().packages)\n jdkPackageToModule.put(pkg, entry.getKey());\n }\n }\n\n private static Map<String, Tuple> loadModularPackageList(String file) {\n try {\n // not thread-safe, but that's OK because the caller is thread-safe\n Map<String, Tuple> jdkPackages = new HashMap<String, Tuple>();\n InputStream inputStream = JDKUtils.class.getResourceAsStream(file);\n if (inputStream == null) {\n throw new RuntimeException(\"Failed to read JDK package list file from \" + file + \": your Ceylon installation is broken.\");\n }\n BufferedReader bis = new BufferedReader(new InputStreamReader(inputStream, \"ASCII\"));\n Tuple tuple = null;\n String moduleName = null;\n String pkg;\n while ((pkg = bis.readLine()) != null) {\n // strip comments\n int commentStart = pkg.indexOf('#');\n if (commentStart > -1)\n pkg = pkg.substring(0, commentStart);\n // strip whitespace\n pkg = pkg.trim();\n // ignore empty lines\n if (pkg.isEmpty())\n continue;\n // see if we start a new module\n if (pkg.startsWith(\"=\")) {\n String name = pkg.substring(1).trim();\n if (name.isEmpty())\n throw new RuntimeException(\"Failed to read JDK module list file from \" + file + \": module has empty name\");\n // close previous module\n if (tuple != null) {\n if (tuple.isEmpty())\n throw new RuntimeException(\"Failed to read JDK module list file from \" + file + \": module \" + moduleName + \" is empty\");\n // save previous module\n jdkPackages.put(moduleName, tuple.finish());\n }\n // start the new module\n moduleName = name;\n tuple = new Tuple();\n continue;\n }\n // add a package to the current module\n if (tuple == null)\n throw new RuntimeException(\"Failed to read JDK module list file from \" + file + \": adding package to undefined module\");\n\n tuple.packages.add(pkg);\n tuple.paths.add(pkg.replace('.', '/'));\n }\n bis.close();\n // close previous module\n if (tuple != null) {\n if (tuple.isEmpty())\n throw new RuntimeException(\"Failed to read JDK module list file from \" + file + \": module \" + moduleName + \" is empty\");\n // save previous module\n jdkPackages.put(moduleName, tuple.finish());\n }\n // sanity check\n if (jdkPackages.size() == 0)\n throw new RuntimeException(\"Failed to read JDK package list file from \" + file + \"(empty package set): your Ceylon installation is broken.\");\n return Collections.unmodifiableMap(jdkPackages);\n } catch (IOException x) {\n throw new RuntimeException(\"Failed to read JDK package list file from \" + file + \": your Ceylon installation is broken.\", x);\n }\n }\n\n public static boolean isJDKModule(String mod) {\n loadPackageList();\n return jdkModules.containsKey(mod);\n }\n\n public static boolean isJDKPackage(String mod, String pkg) {\n loadPackageList();\n Tuple tuple = jdkModules.get(mod);\n return tuple != null && tuple.packages.contains(pkg);\n }\n\n public static boolean isJDKAnyPackage(String pkg) {\n loadPackageList();\n for (Tuple tuple : jdkModules.values()) {\n if (tuple.packages.contains(pkg))\n return true;\n }\n return false;\n }\n\n public static Set<String> getJDKModuleNames() {\n loadPackageList();\n return jdkModules.keySet();\n }\n\n public static Set<String> getJDKPackagesByModule(String module) {\n loadPackageList();\n Tuple tuple = jdkModules.get(module);\n return tuple != null ? tuple.packages : null;\n }\n\n public static Set<String> getJDKPathsByModule(String module) {\n loadPackageList();\n Tuple tuple = jdkModules.get(module);\n return tuple != null ? tuple.paths : null;\n }\n\n public static boolean isOracleJDKModule(String pkg) {\n loadPackageList();\n return jdkOracleModules.containsKey(pkg);\n }\n\n public static boolean isOracleJDKPackage(String mod, String pkg) {\n loadPackageList();\n Tuple tuple = jdkOracleModules.get(mod);\n return tuple != null && tuple.packages.contains(pkg);\n }\n\n public static boolean isOracleJDKAnyPackage(String pkg) {\n loadPackageList();\n for (Tuple tuple : jdkOracleModules.values()) {\n if (tuple.packages.contains(pkg))\n return true;\n }\n return false;\n }\n\n public static Set<String> getOracleJDKModuleNames() {\n loadPackageList();\n return jdkOracleModules.keySet();\n }\n\n public static Set<String> getOracleJDKPackagesByModule(String module) {\n loadPackageList();\n Tuple tuple = jdkOracleModules.get(module);\n return tuple != null ? tuple.packages : null;\n }\n\n public static Set<String> getOracleJDKPathsByModule(String module) {\n loadPackageList();\n Tuple tuple = jdkOracleModules.get(module);\n return tuple != null ? tuple.paths : null;\n }\n\n public static String getJDKModuleNameForPackage(String pkgName) {\n loadPackageList();\n return jdkPackageToModule.get(pkgName);\n }\n}",
"public abstract class AbstractModelLoader implements ModelCompleter, ModelLoader, DeclarationCompleter {\n\n public static final String JAVA_BASE_MODULE_NAME = \"java.base\";\n public static final String CEYLON_LANGUAGE = \"ceylon.language\";\n public static final String CEYLON_LANGUAGE_MODEL = \"ceylon.language.meta.model\";\n public static final String CEYLON_LANGUAGE_MODEL_DECLARATION = \"ceylon.language.meta.declaration\";\n public static final String CEYLON_LANGUAGE_SERIALIZATION = \"ceylon.language.serialization\";\n \n private static final String TIMER_MODEL_LOADER_CATEGORY = \"model loader\";\n \n public static final String CEYLON_CEYLON_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Ceylon\";\n private static final String CEYLON_MODULE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Module\";\n private static final String CEYLON_PACKAGE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Package\";\n public static final String CEYLON_IGNORE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Ignore\";\n private static final String CEYLON_CLASS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Class\";\n private static final String CEYLON_JPA_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Jpa\";\n private static final String CEYLON_ENUMERATED_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Enumerated\";\n //private static final String CEYLON_CONSTRUCTOR_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Constructor\";\n //private static final String CEYLON_PARAMETERLIST_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.ParameterList\";\n public static final String CEYLON_NAME_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Name\";\n private static final String CEYLON_SEQUENCED_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Sequenced\";\n private static final String CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.FunctionalParameter\";\n private static final String CEYLON_DEFAULTED_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Defaulted\";\n private static final String CEYLON_SATISFIED_TYPES_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes\";\n private static final String CEYLON_CASE_TYPES_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.CaseTypes\";\n private static final String CEYLON_TYPE_PARAMETERS = \"com.redhat.ceylon.compiler.java.metadata.TypeParameters\";\n private static final String CEYLON_TYPE_INFO_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.TypeInfo\";\n public static final String CEYLON_ATTRIBUTE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Attribute\";\n public static final String CEYLON_SETTER_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Setter\";\n public static final String CEYLON_OBJECT_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Object\";\n public static final String CEYLON_METHOD_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Method\";\n public static final String CEYLON_CONTAINER_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Container\";\n public static final String CEYLON_LOCAL_CONTAINER_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.LocalContainer\";\n public static final String CEYLON_LOCAL_DECLARATION_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.LocalDeclaration\";\n public static final String CEYLON_LOCAL_DECLARATIONS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.LocalDeclarations\";\n private static final String CEYLON_MEMBERS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Members\";\n private static final String CEYLON_ANNOTATIONS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Annotations\";\n public static final String CEYLON_VALUETYPE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.ValueType\";\n public static final String CEYLON_ALIAS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Alias\";\n public static final String CEYLON_TYPE_ALIAS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.TypeAlias\";\n public static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiation\";\n public static final String CEYLON_ANNOTATION_INSTANTIATION_ARGUMENTS_MEMBER = \"arguments\";\n public static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION_MEMBER = \"primary\";\n \n public static final String CEYLON_ANNOTATION_INSTANTIATION_TREE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiationTree\";\n public static final String CEYLON_STRING_VALUE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.StringValue\";\n public static final String CEYLON_STRING_EXPRS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.StringExprs\";\n public static final String CEYLON_BOOLEAN_VALUE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.BooleanValue\";\n public static final String CEYLON_BOOLEAN_EXPRS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.BooleanExprs\";\n public static final String CEYLON_INTEGER_VALUE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.IntegerValue\";\n public static final String CEYLON_INTEGER_EXPRS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.IntegerExprs\";\n public static final String CEYLON_CHARACTER_VALUE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.CharacterValue\";\n public static final String CEYLON_CHARACTER_EXPRS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.CharacterExprs\";\n public static final String CEYLON_FLOAT_VALUE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.FloatValue\";\n public static final String CEYLON_FLOAT_EXPRS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.FloatExprs\";\n public static final String CEYLON_OBJECT_VALUE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.ObjectValue\";\n public static final String CEYLON_OBJECT_EXPRS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.ObjectExprs\";\n public static final String CEYLON_DECLARATION_VALUE_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.DeclarationValue\";\n public static final String CEYLON_DECLARATION_EXPRS_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.DeclarationExprs\";\n private static final String CEYLON_TRANSIENT_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Transient\";\n private static final String CEYLON_DYNAMIC_ANNOTATION = \"com.redhat.ceylon.compiler.java.metadata.Dynamic\";\n private static final String JAVA_DEPRECATED_ANNOTATION = \"java.lang.Deprecated\";\n \n static final String CEYLON_LANGUAGE_ABSTRACT_ANNOTATION = \"ceylon.language.AbstractAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_ACTUAL_ANNOTATION = \"ceylon.language.ActualAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_ANNOTATION_ANNOTATION = \"ceylon.language.AnnotationAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_DEFAULT_ANNOTATION = \"ceylon.language.DefaultAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_FORMAL_ANNOTATION = \"ceylon.language.FormalAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_SHARED_ANNOTATION = \"ceylon.language.SharedAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_LATE_ANNOTATION = \"ceylon.language.LateAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_SEALED_ANNOTATION = \"ceylon.language.SealedAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_VARIABLE_ANNOTATION = \"ceylon.language.VariableAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_FINAL_ANNOTATION = \"ceylon.language.FinalAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_NATIVE_ANNOTATION = \"ceylon.language.NativeAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_OPTIONAL_ANNOTATION = \"ceylon.language.OptionalAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_SERIALIZABLE_ANNOTATION = \"ceylon.language.SerializableAnnotation$annotation$\";\n \n static final String CEYLON_LANGUAGE_DOC_ANNOTATION = \"ceylon.language.DocAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_THROWS_ANNOTATIONS = \"ceylon.language.ThrownExceptionAnnotation$annotations$\";\n static final String CEYLON_LANGUAGE_THROWS_ANNOTATION = \"ceylon.language.ThrownExceptionAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_AUTHORS_ANNOTATION = \"ceylon.language.AuthorsAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_SEE_ANNOTATIONS = \"ceylon.language.SeeAnnotation$annotations$\";\n static final String CEYLON_LANGUAGE_SEE_ANNOTATION = \"ceylon.language.SeeAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_DEPRECATED_ANNOTATION = \"ceylon.language.DeprecationAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_SUPPRESS_WARNINGS_ANNOTATION = \"ceylon.language.SuppressWarningsAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_LICENSE_ANNOTATION = \"ceylon.language.LicenseAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_TAGS_ANNOTATION = \"ceylon.language.TagsAnnotation$annotation$\";\n static final String CEYLON_LANGUAGE_ALIASES_ANNOTATION = \"ceylon.language.AliasesAnnotation$annotation$\";\n\n // important that these are with ::\n private static final String CEYLON_LANGUAGE_CALLABLE_TYPE_NAME = \"ceylon.language::Callable\";\n private static final String CEYLON_LANGUAGE_TUPLE_TYPE_NAME = \"ceylon.language::Tuple\";\n private static final String CEYLON_LANGUAGE_SEQUENTIAL_TYPE_NAME = \"ceylon.language::Sequential\";\n private static final String CEYLON_LANGUAGE_SEQUENCE_TYPE_NAME = \"ceylon.language::Sequence\";\n private static final String CEYLON_LANGUAGE_EMPTY_TYPE_NAME = \"ceylon.language::Empty\";\n \n private static final TypeMirror OBJECT_TYPE = simpleCeylonObjectType(\"java.lang.Object\");\n private static final TypeMirror ANNOTATION_TYPE = simpleCeylonObjectType(\"java.lang.annotation.Annotation\");\n private static final TypeMirror CEYLON_OBJECT_TYPE = simpleCeylonObjectType(\"ceylon.language.Object\");\n private static final TypeMirror CEYLON_ANNOTATION_TYPE = simpleCeylonObjectType(\"ceylon.language.Annotation\");\n private static final TypeMirror CEYLON_CONSTRAINED_ANNOTATION_TYPE = simpleCeylonObjectType(\"ceylon.language.ConstrainedAnnotation\");\n// private static final TypeMirror CEYLON_FUNCTION_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.FunctionDeclaration\");\n private static final TypeMirror CEYLON_FUNCTION_OR_VALUE_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.FunctionOrValueDeclaration\");\n private static final TypeMirror CEYLON_VALUE_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.ValueDeclaration\");\n private static final TypeMirror CEYLON_ALIAS_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.AliasDeclaration\");\n private static final TypeMirror CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.ClassOrInterfaceDeclaration\");\n private static final TypeMirror CEYLON_CLASS_WITH_INIT_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.ClassWithInitializerDeclaration\");\n private static final TypeMirror CEYLON_CLASS_WITH_CTORS_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.ClassWithConstructorsDeclaration\");\n private static final TypeMirror CEYLON_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.ConstructorDeclaration\");\n private static final TypeMirror CEYLON_CALLABLE_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.CallableConstructorDeclaration\");\n private static final TypeMirror CEYLON_VALUE_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType(\"ceylon.language.meta.declaration.ValueConstructorDeclaration\");\n private static final TypeMirror CEYLON_ANNOTATED_TYPE = simpleCeylonObjectType(\"ceylon.language.Annotated\");\n private static final TypeMirror CEYLON_BASIC_TYPE = simpleCeylonObjectType(\"ceylon.language.Basic\");\n private static final TypeMirror CEYLON_REIFIED_TYPE_TYPE = simpleCeylonObjectType(\"com.redhat.ceylon.compiler.java.runtime.model.ReifiedType\");\n private static final TypeMirror CEYLON_SERIALIZABLE_TYPE = simpleCeylonObjectType(\"com.redhat.ceylon.compiler.java.runtime.serialization.Serializable\");\n private static final TypeMirror CEYLON_TYPE_DESCRIPTOR_TYPE = simpleCeylonObjectType(\"com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor\");\n \n private static final TypeMirror THROWABLE_TYPE = simpleCeylonObjectType(\"java.lang.Throwable\");\n// private static final TypeMirror ERROR_TYPE = simpleCeylonObjectType(\"java.lang.Error\");\n private static final TypeMirror EXCEPTION_TYPE = simpleCeylonObjectType(\"java.lang.Exception\");\n private static final TypeMirror CEYLON_THROWABLE_TYPE = simpleCeylonObjectType(\"java.lang.Throwable\");\n private static final TypeMirror CEYLON_EXCEPTION_TYPE = simpleCeylonObjectType(\"ceylon.language.Exception\");\n \n private static final TypeMirror STRING_TYPE = simpleJDKObjectType(\"java.lang.String\");\n private static final TypeMirror CEYLON_STRING_TYPE = simpleCeylonObjectType(\"ceylon.language.String\");\n \n private static final TypeMirror PRIM_BOOLEAN_TYPE = simpleJDKObjectType(\"boolean\");\n private static final TypeMirror CEYLON_BOOLEAN_TYPE = simpleCeylonObjectType(\"ceylon.language.Boolean\");\n \n private static final TypeMirror PRIM_BYTE_TYPE = simpleJDKObjectType(\"byte\");\n private static final TypeMirror CEYLON_BYTE_TYPE = simpleCeylonObjectType(\"ceylon.language.Byte\");\n \n private static final TypeMirror PRIM_SHORT_TYPE = simpleJDKObjectType(\"short\");\n\n private static final TypeMirror PRIM_INT_TYPE = simpleJDKObjectType(\"int\");\n private static final TypeMirror PRIM_LONG_TYPE = simpleJDKObjectType(\"long\");\n private static final TypeMirror CEYLON_INTEGER_TYPE = simpleCeylonObjectType(\"ceylon.language.Integer\");\n \n private static final TypeMirror PRIM_FLOAT_TYPE = simpleJDKObjectType(\"float\");\n private static final TypeMirror PRIM_DOUBLE_TYPE = simpleJDKObjectType(\"double\");\n private static final TypeMirror CEYLON_FLOAT_TYPE = simpleCeylonObjectType(\"ceylon.language.Float\");\n\n private static final TypeMirror PRIM_CHAR_TYPE = simpleJDKObjectType(\"char\");\n private static final TypeMirror CEYLON_CHARACTER_TYPE = simpleCeylonObjectType(\"ceylon.language.Character\");\n \n // this one has no \"_\" postfix because that's how we look it up\n protected static final String JAVA_LANG_BYTE_ARRAY = \"java.lang.ByteArray\";\n protected static final String JAVA_LANG_SHORT_ARRAY = \"java.lang.ShortArray\";\n protected static final String JAVA_LANG_INT_ARRAY = \"java.lang.IntArray\";\n protected static final String JAVA_LANG_LONG_ARRAY = \"java.lang.LongArray\";\n protected static final String JAVA_LANG_FLOAT_ARRAY = \"java.lang.FloatArray\";\n protected static final String JAVA_LANG_DOUBLE_ARRAY = \"java.lang.DoubleArray\";\n protected static final String JAVA_LANG_CHAR_ARRAY = \"java.lang.CharArray\";\n protected static final String JAVA_LANG_BOOLEAN_ARRAY = \"java.lang.BooleanArray\";\n protected static final String JAVA_LANG_OBJECT_ARRAY = \"java.lang.ObjectArray\";\n\n // this one has the \"_\" postfix because that's what we translate it to\n private static final String CEYLON_BYTE_ARRAY = \"com.redhat.ceylon.compiler.java.language.ByteArray\";\n private static final String CEYLON_SHORT_ARRAY = \"com.redhat.ceylon.compiler.java.language.ShortArray\";\n private static final String CEYLON_INT_ARRAY = \"com.redhat.ceylon.compiler.java.language.IntArray\";\n private static final String CEYLON_LONG_ARRAY = \"com.redhat.ceylon.compiler.java.language.LongArray\";\n private static final String CEYLON_FLOAT_ARRAY = \"com.redhat.ceylon.compiler.java.language.FloatArray\";\n private static final String CEYLON_DOUBLE_ARRAY = \"com.redhat.ceylon.compiler.java.language.DoubleArray\";\n private static final String CEYLON_CHAR_ARRAY = \"com.redhat.ceylon.compiler.java.language.CharArray\";\n private static final String CEYLON_BOOLEAN_ARRAY = \"com.redhat.ceylon.compiler.java.language.BooleanArray\";\n private static final String CEYLON_OBJECT_ARRAY = \"com.redhat.ceylon.compiler.java.language.ObjectArray\";\n\n private static final TypeMirror JAVA_BYTE_ARRAY_TYPE = simpleJDKObjectType(\"java.lang.ByteArray\");\n private static final TypeMirror JAVA_SHORT_ARRAY_TYPE = simpleJDKObjectType(\"java.lang.ShortArray\");\n private static final TypeMirror JAVA_INT_ARRAY_TYPE = simpleJDKObjectType(\"java.lang.IntArray\");\n private static final TypeMirror JAVA_LONG_ARRAY_TYPE = simpleJDKObjectType(\"java.lang.LongArray\");\n private static final TypeMirror JAVA_FLOAT_ARRAY_TYPE = simpleJDKObjectType(\"java.lang.FloatArray\");\n private static final TypeMirror JAVA_DOUBLE_ARRAY_TYPE = simpleJDKObjectType(\"java.lang.DoubleArray\");\n private static final TypeMirror JAVA_CHAR_ARRAY_TYPE = simpleJDKObjectType(\"java.lang.CharArray\");\n private static final TypeMirror JAVA_BOOLEAN_ARRAY_TYPE = simpleJDKObjectType(\"java.lang.BooleanArray\");\n private static final TypeMirror JAVA_IO_SERIALIZABLE_TYPE_TYPE = simpleJDKObjectType(\"java.io.Serializable\");\n \n private static TypeMirror simpleJDKObjectType(String name) {\n return new SimpleReflType(name, SimpleReflType.Module.JDK, TypeKind.DECLARED);\n }\n private static TypeMirror simpleCeylonObjectType(String name) {\n return new SimpleReflType(name, SimpleReflType.Module.CEYLON, TypeKind.DECLARED);\n }\n\n protected Map<String, Declaration> valueDeclarationsByName = new HashMap<String, Declaration>();\n protected Map<String, Declaration> typeDeclarationsByName = new HashMap<String, Declaration>();\n protected Map<Package, Unit> unitsByPackage = new HashMap<Package, Unit>();\n protected TypeParser typeParser;\n /** \n * The type factory \n * (<strong>should not be used while completing a declaration</strong>)\n */\n protected Unit typeFactory;\n protected final Set<String> loadedPackages = new HashSet<String>();\n protected final Map<String,LazyPackage> packagesByName = new HashMap<String,LazyPackage>();\n protected boolean packageDescriptorsNeedLoading = false;\n protected boolean isBootstrap;\n protected ModuleManager moduleManager;\n protected Modules modules;\n protected Map<String, ClassMirror> classMirrorCache = new HashMap<String, ClassMirror>();\n protected boolean binaryCompatibilityErrorRaised = false;\n protected Timer timer;\n private Map<String,LazyPackage> modulelessPackages = new HashMap<String,LazyPackage>();\n private ParameterNameParser parameterNameParser = new ParameterNameParser(this);\n \n /**\n * Loads a given package, if required. This is mostly useful for the javac reflection impl.\n * \n * @param the module to load the package from\n * @param packageName the package name to load\n * @param loadDeclarations true to load all the declarations in this package.\n * @return \n */\n public abstract boolean loadPackage(Module module, String packageName, boolean loadDeclarations);\n\n public final Object getLock(){\n return this;\n }\n\n /**\n * To be redefined by subclasses if they don't need local declarations.\n */\n protected boolean needsLocalDeclarations(){\n return true;\n }\n\n /**\n * For subclassers to skip private members. Defaults to false.\n */\n protected boolean needsPrivateMembers() {\n return true;\n }\n\n public boolean searchAgain(ClassMirror cachedMirror, Module module, String name) {\n return false;\n }\n \n public boolean searchAgain(Declaration cachedDeclaration, LazyPackage lazyPackage, String name) {\n return false;\n }\n \n /**\n * Looks up a ClassMirror by name. Uses cached results, and caches the result of calling lookupNewClassMirror\n * on cache misses.\n * \n * @param module the module in which we should find the class\n * @param name the name of the Class to load\n * @return a ClassMirror for the specified class, or null if not found.\n */\n public final ClassMirror lookupClassMirror(Module module, String name) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n try{\n // Java array classes are not where we expect them\n if (JAVA_LANG_OBJECT_ARRAY.equals(name)\n || JAVA_LANG_BOOLEAN_ARRAY.equals(name)\n || JAVA_LANG_BYTE_ARRAY.equals(name)\n || JAVA_LANG_SHORT_ARRAY.equals(name)\n || JAVA_LANG_INT_ARRAY.equals(name)\n || JAVA_LANG_LONG_ARRAY.equals(name)\n || JAVA_LANG_FLOAT_ARRAY.equals(name)\n || JAVA_LANG_DOUBLE_ARRAY.equals(name)\n || JAVA_LANG_CHAR_ARRAY.equals(name)) {\n // turn them into their real class location (get rid of the \"java.lang\" prefix)\n name = \"com.redhat.ceylon.compiler.java.language\" + name.substring(9);\n module = getLanguageModule();\n }\n String cacheKey = cacheKeyByModule(module, name);\n // we use containsKey to be able to cache null results\n if(classMirrorCache.containsKey(cacheKey)) {\n ClassMirror cachedMirror = classMirrorCache.get(cacheKey);\n if (! searchAgain(cachedMirror, module, name)) {\n return cachedMirror;\n }\n }\n ClassMirror mirror = lookupNewClassMirror(module, name);\n // we even cache null results\n classMirrorCache.put(cacheKey, mirror);\n return mirror;\n }finally{\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n }\n\n protected String cacheKeyByModule(Module module, String name) {\n return getCacheKeyByModule(module, name);\n }\n\n public static String getCacheKeyByModule(Module module, String name){\n String moduleSignature = module.getSignature();\n StringBuilder buf = new StringBuilder(moduleSignature.length()+1+name.length());\n // '/' is allowed in module version but not in module or class name, so we're good\n return buf.append(moduleSignature).append('/').append(name).toString();\n }\n\n protected boolean lastPartHasLowerInitial(String name) {\n int index = name.lastIndexOf('.');\n if (index != -1){\n name = name.substring(index+1);\n }\n // remove any possibly quoting char\n name = NamingBase.stripLeadingDollar(name);\n if(!name.isEmpty()){\n int codepoint = name.codePointAt(0);\n return JvmBackendUtil.isLowerCase(codepoint);\n }\n return false;\n }\n \n /**\n * Looks up a ClassMirror by name. Called by lookupClassMirror on cache misses.\n * \n * @param module the module in which we should find the given class\n * @param name the name of the Class to load\n * @return a ClassMirror for the specified class, or null if not found.\n */\n protected abstract ClassMirror lookupNewClassMirror(Module module, String name);\n\n /**\n * Adds the given module to the set of modules from which we can load classes.\n * \n * @param module the module\n * @param artifact the module's artifact, if any. Can be null. \n */\n public abstract void addModuleToClassPath(Module module, ArtifactResult artifact);\n\n /**\n * Returns true if the given module has been added to this model loader's classpath.\n * Defaults to true.\n */\n public boolean isModuleInClassPath(Module module){\n return true;\n }\n \n /**\n * Returns true if the given method is overriding an inherited method (from super class or interfaces).\n */\n protected abstract boolean isOverridingMethod(MethodMirror methodMirror);\n\n /**\n * Returns true if the given method is overloading an inherited method (from super class or interfaces).\n */\n protected abstract boolean isOverloadingMethod(MethodMirror methodMirror);\n\n /**\n * Logs a warning.\n */\n protected abstract void logWarning(String message);\n\n /**\n * Logs a debug message.\n */\n protected abstract void logVerbose(String message);\n \n /**\n * Logs an error\n */\n protected abstract void logError(String message);\n \n public void loadStandardModules(){\n // set up the type factory\n Timer nested = timer.nestedTimer();\n nested.startTask(\"load ceylon.language\");\n Module languageModule = loadLanguageModuleAndPackage();\n \n nested.endTask();\n \n nested.startTask(\"load JDK\");\n // make sure the jdk modules are loaded\n loadJDKModules();\n Module jdkModule = findOrCreateModule(JAVA_BASE_MODULE_NAME, JDKUtils.jdk.version);\n nested.endTask();\n \n /*\n * We start by loading java.lang and ceylon.language because we will need them no matter what.\n */\n nested.startTask(\"load standard packages\");\n loadPackage(jdkModule, \"java.lang\", false);\n loadPackage(languageModule, \"com.redhat.ceylon.compiler.java.metadata\", false);\n loadPackage(languageModule, \"com.redhat.ceylon.compiler.java.language\", false);\n nested.endTask();\n }\n protected Module loadLanguageModuleAndPackage() {\n Module languageModule = findOrCreateModule(CEYLON_LANGUAGE, null);\n addModuleToClassPath(languageModule, null);\n Package languagePackage = findOrCreatePackage(languageModule, CEYLON_LANGUAGE);\n typeFactory.setPackage(languagePackage);\n \n // make sure the language module has its real dependencies added, because we need them in the classpath\n // otherwise we will get errors on the Util and Metamodel calls we insert\n // WARNING! Make sure this list is always the same as the one in /ceylon-runtime/dist/repo/ceylon/language/_version_/module.xml\n languageModule.addImport(new ModuleImport(findOrCreateModule(\"com.redhat.ceylon.compiler.java\", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java));\n languageModule.addImport(new ModuleImport(findOrCreateModule(\"com.redhat.ceylon.compiler.js\", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java));\n languageModule.addImport(new ModuleImport(findOrCreateModule(\"com.redhat.ceylon.common\", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java));\n languageModule.addImport(new ModuleImport(findOrCreateModule(\"com.redhat.ceylon.model\", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java));\n languageModule.addImport(new ModuleImport(findOrCreateModule(\"com.redhat.ceylon.module-resolver\", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java));\n languageModule.addImport(new ModuleImport(findOrCreateModule(\"com.redhat.ceylon.typechecker\", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java));\n languageModule.addImport(new ModuleImport(findOrCreateModule(\"org.jboss.modules\", Versions.DEPENDENCY_JBOSS_MODULES_VERSION), false, false, Backend.Java));\n languageModule.addImport(new ModuleImport(findOrCreateModule(\"org.jboss.jandex\", Versions.DEPENDENCY_JANDEX_VERSION), false, false, Backend.Java));\n \n return languageModule;\n }\n protected void loadJDKModules() {\n for(String jdkModule : JDKUtils.getJDKModuleNames())\n findOrCreateModule(jdkModule, JDKUtils.jdk.version);\n for(String jdkOracleModule : JDKUtils.getOracleJDKModuleNames())\n findOrCreateModule(jdkOracleModule, JDKUtils.jdk.version);\n }\n\n /**\n * This is meant to be called if your subclass doesn't call loadStandardModules for whatever reason\n */\n public void setupWithNoStandardModules() {\n Module languageModule = modules.getLanguageModule();\n if(languageModule == null)\n throw new RuntimeException(\"Assertion failed: language module is null\");\n Package languagePackage = languageModule.getPackage(CEYLON_LANGUAGE);\n if(languagePackage == null)\n throw new RuntimeException(\"Assertion failed: language package is null\");\n typeFactory.setPackage(languagePackage);\n }\n\n enum ClassType {\n ATTRIBUTE, METHOD, OBJECT, CLASS, INTERFACE;\n }\n \n private ClassMirror loadClass(Module module, String pkgName, String className) {\n ClassMirror moduleClass = null;\n try{\n loadPackage(module, pkgName, false);\n moduleClass = lookupClassMirror(module, className);\n }catch(Exception x){\n logVerbose(\"[Failed to complete class \"+className+\"]\");\n }\n return moduleClass;\n }\n\n private Declaration convertNonPrimitiveTypeToDeclaration(Module moduleScope, TypeMirror type, Scope scope, DeclarationType declarationType) {\n switch(type.getKind()){\n case VOID:\n return typeFactory.getAnythingDeclaration();\n case ARRAY:\n return ((Class)convertToDeclaration(getLanguageModule(), JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE));\n case DECLARED:\n return convertDeclaredTypeToDeclaration(moduleScope, type, declarationType);\n case TYPEVAR:\n return safeLookupTypeParameter(scope, type.getQualifiedName());\n case WILDCARD:\n return typeFactory.getNothingDeclaration();\n // those can't happen\n case BOOLEAN:\n case BYTE:\n case CHAR:\n case SHORT:\n case INT:\n case LONG:\n case FLOAT:\n case DOUBLE:\n // all the autoboxing should already have been done\n throw new RuntimeException(\"Expected non-primitive type: \"+type);\n case ERROR:\n return null;\n default:\n throw new RuntimeException(\"Failed to handle type \"+type);\n }\n }\n\n private Declaration convertDeclaredTypeToDeclaration(Module moduleScope, TypeMirror type, DeclarationType declarationType) {\n // SimpleReflType does not do declared class so we make an exception for it\n String typeName = type.getQualifiedName();\n if(type instanceof SimpleReflType){\n Module module = null;\n switch(((SimpleReflType) type).getModule()){\n case CEYLON: module = getLanguageModule(); break;\n case JDK : module = getJDKBaseModule(); break;\n }\n return convertToDeclaration(module, typeName, declarationType);\n }\n ClassMirror classMirror = type.getDeclaredClass();\n Module module = findModuleForClassMirror(classMirror);\n if(isImported(moduleScope, module)){\n return convertToDeclaration(module, typeName, declarationType);\n }else{\n if(module != null && isFlatClasspath() && isMavenModule(moduleScope))\n return convertToDeclaration(module, typeName, declarationType);\n String error = \"Declaration '\" + typeName + \"' could not be found in module '\" + moduleScope.getNameAsString() \n + \"' or its imported modules\";\n if(module != null && !module.isDefault())\n error += \" but was found in the non-imported module '\"+module.getNameAsString()+\"'\";\n return logModelResolutionException(null, moduleScope, error).getDeclaration();\n }\n }\n \n public Declaration convertToDeclaration(Module module, ClassMirror classMirror, DeclarationType declarationType) {\n return convertToDeclaration(module, null, classMirror, declarationType);\n }\n \n private Declaration convertToDeclaration(Module module, Declaration container, ClassMirror classMirror, DeclarationType declarationType) {\n // find its package\n String pkgName = getPackageNameForQualifiedClassName(classMirror);\n if (pkgName.equals(\"java.lang\")) {\n module = getJDKBaseModule();\n }\n \n Declaration decl = findCachedDeclaration(module, container, classMirror, declarationType);\n if (decl != null) {\n return decl;\n }\n \n // avoid ignored classes\n if(classMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)\n return null;\n // avoid local interfaces that were pulled to the toplevel if required\n if(classMirror.getAnnotation(CEYLON_LOCAL_CONTAINER_ANNOTATION) != null\n && !needsLocalDeclarations())\n return null;\n // avoid Ceylon annotations\n if(classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null\n && classMirror.isAnnotationType())\n return null;\n // avoid module and package descriptors too\n if(classMirror.getAnnotation(CEYLON_MODULE_ANNOTATION) != null\n || classMirror.getAnnotation(CEYLON_PACKAGE_ANNOTATION) != null)\n return null;\n \n List<Declaration> decls = new ArrayList<Declaration>();\n \n LazyPackage pkg = findOrCreatePackage(module, pkgName);\n\n decl = createDeclaration(module, container, classMirror, declarationType, decls);\n cacheDeclaration(module, container, classMirror, declarationType, decl, decls);\n\n // find/make its Unit\n Unit unit = getCompiledUnit(pkg, classMirror);\n\n // set all the containers\n for(Declaration d : decls){\n \n // add it to its Unit\n d.setUnit(unit);\n unit.addDeclaration(d);\n\n setContainer(classMirror, d, pkg);\n }\n\n return decl;\n }\n\n public String getPackageNameForQualifiedClassName(String pkg, String qualifiedName){\n // Java array classes we pretend come from java.lang\n if(qualifiedName.startsWith(CEYLON_OBJECT_ARRAY)\n || qualifiedName.startsWith(CEYLON_BOOLEAN_ARRAY)\n || qualifiedName.startsWith(CEYLON_BYTE_ARRAY)\n || qualifiedName.startsWith(CEYLON_SHORT_ARRAY)\n || qualifiedName.startsWith(CEYLON_INT_ARRAY)\n || qualifiedName.startsWith(CEYLON_LONG_ARRAY)\n || qualifiedName.startsWith(CEYLON_FLOAT_ARRAY)\n || qualifiedName.startsWith(CEYLON_DOUBLE_ARRAY)\n || qualifiedName.startsWith(CEYLON_CHAR_ARRAY))\n return \"java.lang\";\n else\n return unquotePackageName(pkg);\n \n }\n \n protected String getPackageNameForQualifiedClassName(ClassMirror classMirror) {\n return getPackageNameForQualifiedClassName(classMirror.getPackage().getQualifiedName(), classMirror.getQualifiedName());\n }\n \n private String unquotePackageName(PackageMirror pkg) {\n return unquotePackageName(pkg.getQualifiedName());\n }\n\n private String unquotePackageName(String pkg) {\n return JvmBackendUtil.removeChar('$', pkg);\n }\n\n private void setContainer(ClassMirror classMirror, Declaration d, LazyPackage pkg) {\n // add it to its package if it's not an inner class\n if(!classMirror.isInnerClass() && !classMirror.isLocalClass()){\n d.setContainer(pkg);\n d.setScope(pkg);\n pkg.addCompiledMember(d);\n if(d instanceof LazyInterface && ((LazyInterface) d).isCeylon()){\n setInterfaceCompanionClass(d, null, pkg);\n }\n ModelUtil.setVisibleScope(d);\n }else if(classMirror.isLocalClass() && !classMirror.isInnerClass()){\n // set its container to the package for now, but don't add it to the package as a member because it's not\n Scope localContainer = getLocalContainer(pkg, classMirror, d);\n if(localContainer != null){\n d.setContainer(localContainer);\n d.setScope(localContainer);\n // do not add it as member, it has already been registered by getLocalContainer\n }else{\n d.setContainer(pkg);\n d.setScope(pkg);\n }\n ((LazyElement)d).setLocal(true);\n }else if(d instanceof ClassOrInterface || d instanceof TypeAlias){\n // do overloads later, since their container is their abstract superclass's container and\n // we have to set that one first\n if(d instanceof Class == false || !((Class)d).isOverloaded()){\n ClassOrInterface container = getContainer(pkg.getModule(), classMirror);\n if (d.isNativeHeader() && container.isNative()) {\n container = (ClassOrInterface)ModelUtil.getNativeHeader(container);\n }\n d.setContainer(container);\n d.setScope(container);\n if(d instanceof LazyInterface && ((LazyInterface) d).isCeylon()){\n setInterfaceCompanionClass(d, container, pkg);\n }\n // let's not trigger lazy-loading\n ((LazyContainer)container).addMember(d);\n ModelUtil.setVisibleScope(d);\n // now we can do overloads\n if(d instanceof Class && ((Class)d).getOverloads() != null){\n for(Declaration overload : ((Class)d).getOverloads()){\n overload.setContainer(container);\n overload.setScope(container);\n // let's not trigger lazy-loading\n ((LazyContainer)container).addMember(overload);\n ModelUtil.setVisibleScope(overload);\n }\n }\n }\n }\n }\n\n protected void setInterfaceCompanionClass(Declaration d, ClassOrInterface container, LazyPackage pkg) {\n // find its companion class in its real container\n ClassMirror containerMirror = null;\n if(container instanceof LazyClass){\n containerMirror = ((LazyClass) container).classMirror;\n }else if(container instanceof LazyInterface){\n // container must be a LazyInterface, as TypeAlias doesn't contain anything\n containerMirror = ((LazyInterface)container).companionClass;\n if(containerMirror == null){\n throw new ModelResolutionException(\"Interface companion class for \"+container.getQualifiedNameString()+\" not set up\");\n }\n }\n String companionName;\n if(containerMirror != null)\n companionName = containerMirror.getFlatName() + \"$\" + NamingBase.suffixName(NamingBase.Suffix.$impl, d.getName());\n else{\n // toplevel\n String p = pkg.getNameAsString();\n companionName = \"\";\n if(!p.isEmpty())\n companionName = p + \".\";\n companionName += NamingBase.suffixName(NamingBase.Suffix.$impl, d.getName());\n }\n ClassMirror companionClass = lookupClassMirror(pkg.getModule(), companionName);\n if(companionClass == null){\n ((Interface)d).setCompanionClassNeeded(false);\n }\n ((LazyInterface)d).companionClass = companionClass;\n }\n \n private Scope getLocalContainer(Package pkg, ClassMirror classMirror, Declaration declaration) {\n AnnotationMirror localContainerAnnotation = classMirror.getAnnotation(CEYLON_LOCAL_CONTAINER_ANNOTATION);\n String qualifier = getAnnotationStringValue(classMirror, CEYLON_LOCAL_DECLARATION_ANNOTATION, \"qualifier\");\n \n // deal with types local to functions in the body of toplevel non-lazy attributes, whose container is ultimately the package\n Boolean isPackageLocal = getAnnotationBooleanValue(classMirror, CEYLON_LOCAL_DECLARATION_ANNOTATION, \"isPackageLocal\");\n if(BooleanUtil.isTrue(isPackageLocal)){\n // make sure it still knows it's a local\n declaration.setQualifier(qualifier);\n return null;\n }\n\n LocalDeclarationContainer methodDecl = null;\n // we get a @LocalContainer annotation for local interfaces\n if(localContainerAnnotation != null){\n methodDecl = (LocalDeclarationContainer) findLocalContainerFromAnnotationAndSetCompanionClass(pkg, (Interface) declaration, localContainerAnnotation);\n }else{\n // all the other cases stay where they belong\n MethodMirror method = classMirror.getEnclosingMethod();\n if(method == null)\n return null;\n \n // see where that method belongs\n ClassMirror enclosingClass = method.getEnclosingClass();\n while(enclosingClass.isAnonymous()){\n // this gives us the method in which the anonymous class is, which should be the one we're looking for\n method = enclosingClass.getEnclosingMethod();\n if(method == null)\n return null;\n // and the method's containing class\n enclosingClass = method.getEnclosingClass();\n }\n \n // if we are in a setter class, the attribute is declared in the getter class, so look for its declaration there\n TypeMirror getterClass = (TypeMirror) getAnnotationValue(enclosingClass, CEYLON_SETTER_ANNOTATION, \"getterClass\");\n boolean isSetter = false;\n // we use void.class as default value\n if(getterClass != null && !getterClass.isPrimitive()){\n enclosingClass = getterClass.getDeclaredClass();\n isSetter = true;\n }\n \n String javaClassName = enclosingClass.getQualifiedName();\n \n // make sure we don't go looking in companion classes\n if(javaClassName.endsWith(NamingBase.Suffix.$impl.name()))\n javaClassName = javaClassName.substring(0, javaClassName.length() - 5);\n \n // find the enclosing declaration\n Declaration enclosingClassDeclaration = convertToDeclaration(pkg.getModule(), javaClassName, DeclarationType.TYPE);\n if(enclosingClassDeclaration instanceof ClassOrInterface){\n ClassOrInterface containerDecl = (ClassOrInterface) enclosingClassDeclaration;\n // now find the method's declaration \n // FIXME: find the proper overload if any\n String name = method.getName();\n if(method.isConstructor() || name.startsWith(NamingBase.Prefix.$default$.toString())){\n methodDecl = (LocalDeclarationContainer) containerDecl;\n }else{\n // this is only for error messages\n String type;\n // lots of special cases\n if(isStringAttribute(method)){\n name = \"string\";\n type = \"attribute\";\n }else if(isHashAttribute(method)){\n name = \"hash\";\n type = \"attribute\";\n }else if(isGetter(method)) {\n // simple attribute\n name = getJavaAttributeName(method);\n type = \"attribute\";\n }else if(isSetter(method)) {\n // simple attribute\n name = getJavaAttributeName(method);\n type = \"attribute setter\";\n isSetter = true;\n }else{\n type = \"method\";\n }\n // strip any escaping or private suffix\n // it can be foo$priv$canonical so get rid of that one first\n if (name.endsWith(NamingBase.Suffix.$canonical$.toString())) {\n name = name.substring(0, name.length()-11);\n }\n name = JvmBackendUtil.strip(name, true, method.isPublic() || method.isProtected() || method.isDefaultAccess());\n if(name.indexOf('$') > 0){\n // may be a default parameter expression? get the method name which is first\n name = name.substring(0, name.indexOf('$'));\n }\n\n methodDecl = (LocalDeclarationContainer) containerDecl.getDirectMember(name, null, false);\n\n if(methodDecl == null)\n throw new ModelResolutionException(\"Failed to load outer \"+type+\" \" + name \n + \" for local type \" + classMirror.getQualifiedName().toString());\n\n // if it's a setter we wanted, let's get it\n if(isSetter){\n LocalDeclarationContainer setter = (LocalDeclarationContainer) ((Value)methodDecl).getSetter();\n if(setter == null)\n throw new ModelResolutionException(\"Failed to load outer \"+type+\" \" + name \n + \" for local type \" + classMirror.getQualifiedName().toString());\n methodDecl = setter;\n }\n }\n }else if(enclosingClassDeclaration instanceof LazyFunction){\n // local and toplevel methods\n methodDecl = (LazyFunction)enclosingClassDeclaration;\n }else if(enclosingClassDeclaration instanceof LazyValue){\n // local and toplevel attributes\n if(enclosingClassDeclaration.isToplevel() && method.getName().equals(NamingBase.Unfix.set_.name()))\n isSetter = true;\n if(isSetter){\n LocalDeclarationContainer setter = (LocalDeclarationContainer) ((LazyValue)enclosingClassDeclaration).getSetter();\n if(setter == null)\n throw new ModelResolutionException(\"Failed to toplevel attribute setter \" + enclosingClassDeclaration.getName() \n + \" for local type \" + classMirror.getQualifiedName().toString());\n methodDecl = setter;\n }else\n methodDecl = (LazyValue)enclosingClassDeclaration;\n }else{\n throw new ModelResolutionException(\"Unknown container type \" + enclosingClassDeclaration \n + \" for local type \" + classMirror.getQualifiedName().toString());\n }\n }\n\n // we have the method, now find the proper local qualifier if any\n if(qualifier == null)\n return null;\n declaration.setQualifier(qualifier);\n methodDecl.addLocalDeclaration(declaration);\n return methodDecl;\n }\n \n private Scope findLocalContainerFromAnnotationAndSetCompanionClass(Package pkg, Interface declaration, AnnotationMirror localContainerAnnotation) {\n @SuppressWarnings(\"unchecked\")\n List<String> path = (List<String>) localContainerAnnotation.getValue(\"path\");\n // we start at the package\n Scope scope = pkg;\n for(String name : path){\n scope = (Scope) getDirectMember(scope, name);\n }\n String companionClassName = (String) localContainerAnnotation.getValue(\"companionClassName\");\n if(companionClassName == null || companionClassName.isEmpty()){\n declaration.setCompanionClassNeeded(false);\n return scope;\n }\n ClassMirror container;\n Scope javaClassScope;\n if(scope instanceof TypedDeclaration && ((TypedDeclaration) scope).isMember())\n javaClassScope = scope.getContainer();\n else\n javaClassScope = scope;\n \n if(javaClassScope instanceof LazyInterface){\n container = ((LazyInterface)javaClassScope).companionClass;\n }else if(javaClassScope instanceof LazyClass){\n container = ((LazyClass) javaClassScope).classMirror;\n }else if(javaClassScope instanceof LazyValue){\n container = ((LazyValue) javaClassScope).classMirror;\n }else if(javaClassScope instanceof LazyFunction){\n container = ((LazyFunction) javaClassScope).classMirror;\n }else if(javaClassScope instanceof SetterWithLocalDeclarations){\n container = ((SetterWithLocalDeclarations) javaClassScope).classMirror;\n }else{\n throw new ModelResolutionException(\"Unknown scope class: \"+javaClassScope);\n }\n String qualifiedCompanionClassName = container.getQualifiedName() + \"$\" + companionClassName;\n ClassMirror companionClassMirror = lookupClassMirror(pkg.getModule(), qualifiedCompanionClassName);\n if(companionClassMirror == null)\n throw new ModelResolutionException(\"Could not find companion class mirror: \"+qualifiedCompanionClassName);\n ((LazyInterface)declaration).companionClass = companionClassMirror;\n return scope;\n }\n \n /**\n * Looks for a direct member of type ClassOrInterface. We're not using Class.getDirectMember()\n * because it skips object types and we want them.\n */\n public static Declaration getDirectMember(Scope container, String name) {\n if(name.isEmpty())\n return null;\n boolean wantsSetter = false;\n if(name.startsWith(NamingBase.Suffix.$setter$.name())){\n wantsSetter = true;\n name = name.substring(8);\n }\n \n if(Character.isDigit(name.charAt(0))){\n // this is a local type we have a different accessor for it\n return ((LocalDeclarationContainer)container).getLocalDeclaration(name);\n }\n // don't even try using getDirectMember except on Package,\n // because it will fail miserably during completion, since we\n // will for instance have only anonymous types first, before we load their anonymous values, and\n // when we go looking for them we won't be able to find them until we add their anonymous values,\n // which is too late\n if(container instanceof Package){\n // don't use Package.getMembers() as it loads the whole package\n Declaration result = container.getDirectMember(name, null, false);\n return selectTypeOrSetter(result, wantsSetter);\n }else{\n // must be a Declaration\n for(Declaration member : container.getMembers()){\n // avoid constructors with no name\n if(member.getName() == null)\n continue;\n if(!member.getName().equals(name))\n continue;\n Declaration result = selectTypeOrSetter(member, wantsSetter);\n if(result != null)\n return result;\n }\n }\n // not found\n return null;\n }\n \n private static Declaration selectTypeOrSetter(Declaration member, boolean wantsSetter) {\n // if we found a type or a method/value we're good to go\n if (member instanceof ClassOrInterface\n || member instanceof Constructor\n || member instanceof Function) {\n return member;\n }\n // if it's a Value return its object type by preference, the member otherwise\n if (member instanceof Value){\n TypeDeclaration typeDeclaration = ((Value) member).getTypeDeclaration();\n if(typeDeclaration instanceof Class && typeDeclaration.isAnonymous())\n return typeDeclaration;\n // did we want the setter?\n if(wantsSetter)\n return ((Value)member).getSetter();\n // must be a non-object value\n return member;\n }\n return null;\n }\n \n private ClassOrInterface getContainer(Module module, ClassMirror classMirror) {\n AnnotationMirror containerAnnotation = classMirror.getAnnotation(CEYLON_CONTAINER_ANNOTATION);\n if(containerAnnotation != null){\n TypeMirror javaClassMirror = (TypeMirror)containerAnnotation.getValue(\"klass\");\n String javaClassName = javaClassMirror.getQualifiedName();\n ClassOrInterface containerDecl = (ClassOrInterface) convertToDeclaration(module, javaClassName, DeclarationType.TYPE);\n if(containerDecl == null)\n throw new ModelResolutionException(\"Failed to load outer type \" + javaClassName \n + \" for inner type \" + classMirror.getQualifiedName().toString());\n return containerDecl;\n }else{\n return (ClassOrInterface) convertToDeclaration(module, classMirror.getEnclosingClass(), DeclarationType.TYPE);\n }\n }\n\n private Declaration findCachedDeclaration(Module module, Declaration container,\n ClassMirror classMirror, DeclarationType declarationType) {\n ClassType type = getClassType(classMirror);\n String key = classMirror.getCacheKey(module);\n boolean isNativeHeaderMember = container != null && container.isNativeHeader();\n if (isNativeHeaderMember) {\n key = key + \"$header\";\n }\n // see if we already have it\n Map<String, Declaration> declarationCache = getCacheByType(type, declarationType);\n return declarationCache.get(key);\n }\n \n private void cacheDeclaration(Module module, Declaration container, ClassMirror classMirror,\n DeclarationType declarationType, Declaration decl, List<Declaration> decls) {\n ClassType type = getClassType(classMirror);\n String key = classMirror.getCacheKey(module);\n boolean isNativeHeaderMember = container != null && container.isNativeHeader();\n if (isNativeHeaderMember) {\n key = key + \"$header\";\n }\n if(type == ClassType.OBJECT){\n typeDeclarationsByName.put(key, getByType(decls, Class.class));\n valueDeclarationsByName.put(key, getByType(decls, Value.class));\n }else {\n Map<String, Declaration> declarationCache = getCacheByType(type, declarationType);\n declarationCache.put(key, decl);\n }\n }\n \n private Map<String, Declaration> getCacheByType(ClassType type, DeclarationType declarationType) {\n Map<String, Declaration> declarationCache = null;\n switch(type){\n case OBJECT:\n if(declarationType == DeclarationType.TYPE){\n declarationCache = typeDeclarationsByName;\n break;\n }\n // else fall-through to value\n case ATTRIBUTE:\n case METHOD:\n declarationCache = valueDeclarationsByName;\n break;\n case CLASS:\n case INTERFACE:\n declarationCache = typeDeclarationsByName;\n }\n return declarationCache;\n }\n \n private Declaration getByType(List<Declaration> decls, java.lang.Class<?> klass) {\n for (Declaration decl : decls) {\n if (klass.isAssignableFrom(decl.getClass())) {\n return decl;\n }\n }\n return null;\n }\n\n private Declaration createDeclaration(Module module, Declaration container, ClassMirror classMirror,\n DeclarationType declarationType, List<Declaration> decls) {\n Declaration decl = null;\n Declaration hdr = null;\n \n checkBinaryCompatibility(classMirror);\n \n ClassType type = getClassType(classMirror);\n boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null;\n boolean isNativeHeaderMember = container != null && container.isNativeHeader();\n \n try{\n // make it\n switch(type){\n case ATTRIBUTE:\n decl = makeToplevelAttribute(classMirror, isNativeHeaderMember);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true);\n if (isCeylon && shouldCreateNativeHeader(decl, container)) {\n hdr = makeToplevelAttribute(classMirror, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n }\n break;\n case METHOD:\n decl = makeToplevelMethod(classMirror, isNativeHeaderMember);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true);\n if (isCeylon && shouldCreateNativeHeader(decl, container)) {\n hdr = makeToplevelMethod(classMirror, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n }\n break;\n case OBJECT:\n // we first make a class\n Declaration objectClassDecl = makeLazyClass(classMirror, null, null, isNativeHeaderMember);\n setNonLazyDeclarationProperties(objectClassDecl, classMirror, classMirror, classMirror, true);\n decls.add(objectClassDecl);\n if (isCeylon && shouldCreateNativeHeader(objectClassDecl, container)) {\n Declaration hdrobj = makeLazyClass(classMirror, null, null, true);\n setNonLazyDeclarationProperties(hdrobj, classMirror, classMirror, classMirror, true);\n decls.add(initNativeHeader(hdrobj, objectClassDecl));\n }\n // then we make a value for it, if it's not an inline object expr\n if(objectClassDecl.isNamed()){\n Declaration objectDecl = makeToplevelAttribute(classMirror, isNativeHeaderMember);\n setNonLazyDeclarationProperties(objectDecl, classMirror, classMirror, classMirror, true);\n decls.add(objectDecl);\n if (isCeylon && shouldCreateNativeHeader(objectDecl, container)) {\n Declaration hdrobj = makeToplevelAttribute(classMirror, true);\n setNonLazyDeclarationProperties(hdrobj, classMirror, classMirror, classMirror, true);\n decls.add(initNativeHeader(hdrobj, objectDecl));\n }\n // which one did we want?\n decl = declarationType == DeclarationType.TYPE ? objectClassDecl : objectDecl;\n }else{\n decl = objectClassDecl;\n }\n break;\n case CLASS:\n if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){\n decl = makeClassAlias(classMirror);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true);\n }else if(classMirror.getAnnotation(CEYLON_TYPE_ALIAS_ANNOTATION) != null){\n decl = makeTypeAlias(classMirror);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true);\n }else{\n final List<MethodMirror> constructors = getClassConstructors(classMirror, constructorOnly);\n if (!constructors.isEmpty()) {\n Boolean hasConstructors = hasConstructors(classMirror);\n if (constructors.size() > 1) {\n if (hasConstructors == null || !hasConstructors) {\n decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon);\n } else {\n decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon);\n if (isCeylon && shouldCreateNativeHeader(decl, container)) {\n hdr = makeLazyClass(classMirror, null, null, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n }\n }\n } else {\n if (hasConstructors == null || !hasConstructors) {\n // single constructor\n MethodMirror constructor = constructors.get(0);\n // if the class and constructor have different visibility, we pretend there's an overload of one\n // if it's a ceylon class we don't care that they don't match sometimes, like for inner classes\n // where the constructor is protected because we want to use an accessor, in this case the class\n // visibility is to be used\n if(isCeylon || getJavaVisibility(classMirror) == getJavaVisibility(constructor)){\n decl = makeLazyClass(classMirror, null, constructor, isNativeHeaderMember);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon);\n if (isCeylon && shouldCreateNativeHeader(decl, container)) {\n hdr = makeLazyClass(classMirror, null, constructor, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n }\n }else{\n decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon);\n }\n } else {\n decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon);\n if (isCeylon && shouldCreateNativeHeader(decl, container)) {\n hdr = makeLazyClass(classMirror, null, null, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n }\n }\n }\n } else if(isCeylon && classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION) != null) {\n // objects don't need overloading stuff\n decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon);\n if (isCeylon && shouldCreateNativeHeader(decl, container)) {\n hdr = makeLazyClass(classMirror, null, null, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n }\n } else {\n // no visible constructors\n decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember);\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon);\n if (isCeylon && shouldCreateNativeHeader(decl, container)) {\n hdr = makeLazyClass(classMirror, null, null, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n }\n }\n if (!isCeylon) {\n setSealedFromConstructorMods(decl, constructors);\n }\n }\n break;\n case INTERFACE:\n boolean isAlias = classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null;\n if(isAlias){\n decl = makeInterfaceAlias(classMirror);\n }else{\n decl = makeLazyInterface(classMirror, isNativeHeaderMember);\n }\n setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon);\n if (!isAlias && isCeylon && shouldCreateNativeHeader(decl, container)) {\n hdr = makeLazyInterface(classMirror, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n }\n break;\n }\n }catch(ModelResolutionException x){\n // FIXME: this may not be the best thing to do, perhaps we should have an erroneous Class,Interface,Function\n // etc, like javac's model does?\n decl = logModelResolutionException(x, null, \"Failed to load declaration \"+classMirror).getDeclaration();\n }\n\n // objects have special handling above\n if(type != ClassType.OBJECT){\n decls.add(decl);\n if (hdr != null) {\n decls.add(initNativeHeader(hdr, decl));\n }\n }\n \n return decl;\n }\n \n private ClassType getClassType(ClassMirror classMirror) {\n ClassType type;\n if(classMirror.isCeylonToplevelAttribute()){\n type = ClassType.ATTRIBUTE;\n }else if(classMirror.isCeylonToplevelMethod()){\n type = ClassType.METHOD;\n }else if(classMirror.isCeylonToplevelObject()){\n type = ClassType.OBJECT;\n }else if(classMirror.isInterface()){\n type = ClassType.INTERFACE;\n }else{\n type = ClassType.CLASS;\n }\n return type;\n }\n \n private boolean shouldCreateNativeHeader(Declaration decl, Declaration container) {\n // TODO instead of checking for \"shared\" we should add an annotation\n // to all declarations that have a native header and check that here\n if (decl.isNativeImplementation() && decl.isShared()) {\n if (container != null) {\n if (!decl.isOverloaded()) {\n return !container.isNative();\n }\n } else {\n return true;\n }\n }\n return false;\n }\n \n private boolean shouldLinkNatives(Declaration decl) {\n // TODO instead of checking for \"shared\" we should add an annotation\n // to all declarations that have a native header and check that here\n if (decl.isNative() && decl.isShared()) {\n Declaration container = (Declaration)decl.getContainer();\n return container.isNativeHeader();\n }\n return false;\n }\n \n private Declaration initNativeHeader(Declaration hdr, Declaration impl) {\n List<Declaration> al = getOverloads(hdr);\n if (al == null) {\n al = new ArrayList<Declaration>(1);\n }\n al.add(impl);\n setOverloads(hdr, al);\n return hdr;\n }\n \n private void initNativeHeaderMember(Declaration hdr) {\n Declaration impl = ModelUtil.getNativeDeclaration(hdr.getContainer(), hdr.getName(), Backends.JAVA);\n initNativeHeader(hdr, impl);\n }\n \n /** Returns:\n * <ul>\n * <li>true if the class has named constructors ({@code @Class(...constructors=true)}).</li>\n * <li>false if the class has an initializer constructor.</li>\n * <li>null if the class lacks {@code @Class} (i.e. is not a Ceylon class).</li>\n * </ul>\n * @param classMirror\n * @return\n */\n private Boolean hasConstructors(ClassMirror classMirror) {\n AnnotationMirror a = classMirror.getAnnotation(CEYLON_CLASS_ANNOTATION);\n Boolean hasConstructors;\n if (a != null) {\n hasConstructors = (Boolean)a.getValue(\"constructors\");\n if (hasConstructors == null) {\n hasConstructors = false;\n }\n } else {\n hasConstructors = null;\n }\n return hasConstructors;\n }\n \n private boolean isDefaultNamedCtor(ClassMirror classMirror,\n MethodMirror ctor) {\n return classMirror.getName().equals(getCtorName(ctor));\n }\n \n private String getCtorName(MethodMirror ctor) {\n AnnotationMirror nameAnno = ctor.getAnnotation(CEYLON_NAME_ANNOTATION);\n if (nameAnno != null) {\n return (String)nameAnno.getValue();\n } else {\n return null;\n }\n }\n \n private void setSealedFromConstructorMods(Declaration decl,\n final List<MethodMirror> constructors) {\n boolean effectivelySealed = true;\n for (MethodMirror ctor : constructors) {\n if (ctor.isPublic() || ctor.isProtected()) {\n effectivelySealed = false;\n break;\n }\n }\n if (effectivelySealed && decl instanceof Class) {\n Class type = (Class)decl;\n type.setSealed(effectivelySealed);\n if (type.getOverloads() != null) {\n for (Declaration oload : type.getOverloads()) {\n ((Class)oload).setSealed(effectivelySealed);\n }\n }\n }\n }\n\n private Declaration makeOverloadedConstructor(List<MethodMirror> constructors, ClassMirror classMirror, List<Declaration> decls, boolean isCeylon) {\n // If the class has multiple constructors we make a copy of the class\n // for each one (each with it's own single constructor) and make them\n // a subclass of the original\n Class supercls = makeLazyClass(classMirror, null, null, false);\n // the abstraction class gets the class modifiers\n setNonLazyDeclarationProperties(supercls, classMirror, classMirror, classMirror, isCeylon);\n supercls.setAbstraction(true);\n List<Declaration> overloads = new ArrayList<Declaration>(constructors.size());\n // all filtering is done in getClassConstructors\n for (MethodMirror constructor : constructors) {\n LazyClass subdecl = makeLazyClass(classMirror, supercls, constructor, false);\n // the subclasses class get the constructor modifiers\n setNonLazyDeclarationProperties(subdecl, constructor, constructor, classMirror, isCeylon);\n subdecl.setOverloaded(true);\n overloads.add(subdecl);\n decls.add(subdecl);\n }\n supercls.setOverloads(overloads);\n return supercls;\n }\n\n private void setNonLazyDeclarationProperties(Declaration decl, AccessibleMirror mirror, AnnotatedMirror annotatedMirror, ClassMirror classMirror, boolean isCeylon) {\n if(isCeylon){\n // when we're in a local type somewhere we must turn public declarations into package or protected ones, so\n // we have to check the shared annotation\n decl.setShared(mirror.isPublic() || annotatedMirror.getAnnotation(CEYLON_LANGUAGE_SHARED_ANNOTATION) != null);\n setDeclarationAliases(decl, annotatedMirror);\n }else{\n decl.setShared(mirror.isPublic() || (mirror.isDefaultAccess() && classMirror.isInnerClass()) || mirror.isProtected());\n decl.setPackageVisibility(mirror.isDefaultAccess());\n decl.setProtectedVisibility(mirror.isProtected());\n }\n decl.setDeprecated(isDeprecated(annotatedMirror));\n }\n\n private enum JavaVisibility {\n PRIVATE, PACKAGE, PROTECTED, PUBLIC;\n }\n \n private JavaVisibility getJavaVisibility(AccessibleMirror mirror) {\n if(mirror.isPublic())\n return JavaVisibility.PUBLIC;\n if(mirror.isProtected())\n return JavaVisibility.PROTECTED;\n if(mirror.isDefaultAccess())\n return JavaVisibility.PACKAGE;\n return JavaVisibility.PRIVATE;\n }\n\n protected Declaration makeClassAlias(ClassMirror classMirror) {\n return new LazyClassAlias(classMirror, this);\n }\n\n protected Declaration makeTypeAlias(ClassMirror classMirror) {\n return new LazyTypeAlias(classMirror, this);\n }\n\n protected Declaration makeInterfaceAlias(ClassMirror classMirror) {\n return new LazyInterfaceAlias(classMirror, this);\n }\n\n private void checkBinaryCompatibility(ClassMirror classMirror) {\n // let's not report it twice\n if(binaryCompatibilityErrorRaised)\n return;\n AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION);\n if(annotation == null)\n return; // Java class, no check\n Integer major = (Integer) annotation.getValue(\"major\");\n if(major == null)\n major = 0;\n Integer minor = (Integer) annotation.getValue(\"minor\");\n if(minor == null)\n minor = 0;\n if(!Versions.isJvmBinaryVersionSupported(major.intValue(), minor.intValue())){\n logError(\"Ceylon class \" + classMirror.getQualifiedName() + \" was compiled by an incompatible version of the Ceylon compiler\"\n +\"\\nThe class was compiled using \"+major+\".\"+minor+\".\"\n +\"\\nThis compiler supports \"+Versions.JVM_BINARY_MAJOR_VERSION+\".\"+Versions.JVM_BINARY_MINOR_VERSION+\".\"\n +\"\\nPlease try to recompile your module using a compatible compiler.\"\n +\"\\nBinary compatibility will only be supported after Ceylon 1.2.\");\n binaryCompatibilityErrorRaised = true;\n }\n }\n\n interface MethodMirrorFilter {\n boolean accept(MethodMirror methodMirror);\n }\n \n MethodMirrorFilter constructorOnly = new MethodMirrorFilter() {\n @Override\n public boolean accept(MethodMirror methodMirror) {\n return methodMirror.isConstructor();\n }\n };\n \n class ValueConstructorGetter implements MethodMirrorFilter{\n private ClassMirror classMirror;\n\n ValueConstructorGetter(ClassMirror classMirror) {\n this.classMirror = classMirror;\n }\n @Override\n public boolean accept(MethodMirror methodMirror) {\n return (!methodMirror.isConstructor() \n && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) != null\n && methodMirror.getReturnType().getDeclaredClass().toString().equals(classMirror.toString()));\n }\n };\n \n private void setHasJpaConstructor(LazyClass c, ClassMirror classMirror) {\n for(MethodMirror methodMirror : classMirror.getDirectMethods()){\n if (methodMirror.isConstructor()\n && methodMirror.getAnnotation(CEYLON_JPA_ANNOTATION) != null) {\n c.setHasJpaConstructor(true);\n break;\n }\n }\n }\n \n private List<MethodMirror> getClassConstructors(ClassMirror classMirror, MethodMirrorFilter p) {\n LinkedList<MethodMirror> constructors = new LinkedList<MethodMirror>();\n boolean isFromJDK = isFromJDK(classMirror);\n for(MethodMirror methodMirror : classMirror.getDirectMethods()){\n // We skip members marked with @Ignore, unless they value constructor getters\n if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null\n &&methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null)\n continue;\n if (!p.accept(methodMirror))\n continue;\n // FIXME: tmp hack to skip constructors that have type params as we don't handle them yet\n if(!methodMirror.getTypeParameters().isEmpty())\n continue;\n // FIXME: temporary, because some private classes from the jdk are\n // referenced in private methods but not available\n if(isFromJDK \n && !methodMirror.isPublic()\n // allow protected because we can subclass them, but not package-private because we can't define\n // classes in the jdk packages\n && !methodMirror.isProtected())\n continue;\n\n // if we are expecting Ceylon code, check that we have enough reified type parameters\n if(classMirror.getAnnotation(AbstractModelLoader.CEYLON_CEYLON_ANNOTATION) != null){\n List<AnnotationMirror> tpAnnotations = getTypeParametersFromAnnotations(classMirror);\n int tpCount = tpAnnotations != null ? tpAnnotations.size() : classMirror.getTypeParameters().size();\n if(!checkReifiedTypeDescriptors(tpCount, classMirror.getQualifiedName(), methodMirror, true))\n continue;\n }\n \n constructors.add(methodMirror);\n }\n return constructors;\n }\n\n private boolean checkReifiedTypeDescriptors(int tpCount, String containerName, MethodMirror methodMirror, boolean isConstructor) {\n List<VariableMirror> params = methodMirror.getParameters();\n int actualTypeDescriptorParameters = 0;\n for(VariableMirror param : params){\n if(param.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null && sameType(CEYLON_TYPE_DESCRIPTOR_TYPE, param.getType())){\n actualTypeDescriptorParameters++;\n }else\n break;\n }\n if(tpCount != actualTypeDescriptorParameters){\n if(isConstructor)\n logError(\"Constructor for '\"+containerName+\"' should take \"+tpCount\n +\" reified type arguments (TypeDescriptor) but has '\"+actualTypeDescriptorParameters+\"': skipping constructor.\");\n else\n logError(\"Function '\"+containerName+\".\"+methodMirror.getName()+\"' should take \"+tpCount\n +\" reified type arguments (TypeDescriptor) but has '\"+actualTypeDescriptorParameters+\"': method is invalid.\");\n return false;\n }\n return true;\n }\n\n protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) {\n Unit unit = unitsByPackage.get(pkg);\n if(unit == null){\n unit = new Unit();\n unit.setPackage(pkg);\n unitsByPackage.put(pkg, unit);\n }\n return unit;\n }\n\n protected LazyValue makeToplevelAttribute(ClassMirror classMirror, boolean isNativeHeader) {\n LazyValue value = new LazyValue(classMirror, this);\n\n AnnotationMirror objectAnnotation = classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION);\n if(objectAnnotation == null) {\n manageNativeBackend(value, classMirror, isNativeHeader);\n } else {\n manageNativeBackend(value, getGetterMethodMirror(value, value.classMirror, true), isNativeHeader);\n }\n\n return value;\n }\n\n protected LazyFunction makeToplevelMethod(ClassMirror classMirror, boolean isNativeHeader) {\n LazyFunction method = new LazyFunction(classMirror, this);\n\n manageNativeBackend(method, getFunctionMethodMirror(method), isNativeHeader);\n\n return method;\n }\n \n protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror initOrDefaultConstructor, boolean isNativeHeader) {\n LazyClass klass = new LazyClass(classMirror, this, superClass, initOrDefaultConstructor);\n AnnotationMirror objectAnnotation = classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION);\n if(objectAnnotation != null){\n klass.setAnonymous(true);\n // isFalse will only consider non-null arguments, and we default to true if null\n if(BooleanUtil.isFalse((Boolean) objectAnnotation.getValue(\"named\")))\n klass.setNamed(false);\n }\n klass.setAnnotation(classMirror.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null);\n if(klass.isCeylon())\n klass.setAbstract(classMirror.getAnnotation(CEYLON_LANGUAGE_ABSTRACT_ANNOTATION) != null\n // for toplevel classes if the annotation is missing we respect the java abstract modifier\n // for member classes that would be ambiguous between formal and abstract so we don't and require\n // the model annotation\n || (!classMirror.isInnerClass() && !classMirror.isLocalClass() && classMirror.isAbstract()));\n \n else\n klass.setAbstract(classMirror.isAbstract());\n klass.setFormal(classMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null);\n klass.setDefault(classMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null);\n klass.setSerializable(classMirror.getAnnotation(CEYLON_LANGUAGE_SERIALIZABLE_ANNOTATION) != null\n || classMirror.getQualifiedName().equals(\"ceylon.language.Array\")\n || classMirror.getQualifiedName().equals(\"ceylon.language.Tuple\"));\n // hack to make Throwable sealed until ceylon/ceylon.language#408 is fixed\n klass.setSealed(classMirror.getAnnotation(CEYLON_LANGUAGE_SEALED_ANNOTATION) != null\n || CEYLON_LANGUAGE.equals(classMirror.getPackage().getQualifiedName()) && \"Throwable\".equals(classMirror.getName()));\n boolean actual = classMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null;\n klass.setActual(actual);\n klass.setActualCompleter(this);\n klass.setFinal(classMirror.isFinal());\n klass.setStaticallyImportable(!klass.isCeylon() && classMirror.isStatic());\n \n if(objectAnnotation == null) {\n manageNativeBackend(klass, classMirror, isNativeHeader);\n } else {\n manageNativeBackend(klass, getGetterMethodMirror(klass, klass.classMirror, true), isNativeHeader);\n }\n \n return klass;\n }\n\n protected LazyInterface makeLazyInterface(ClassMirror classMirror, boolean isNativeHeader) {\n LazyInterface iface = new LazyInterface(classMirror, this);\n iface.setSealed(classMirror.getAnnotation(CEYLON_LANGUAGE_SEALED_ANNOTATION) != null);\n iface.setDynamic(classMirror.getAnnotation(CEYLON_DYNAMIC_ANNOTATION) != null);\n iface.setStaticallyImportable(!iface.isCeylon());\n \n manageNativeBackend(iface, classMirror, isNativeHeader);\n \n return iface;\n }\n\n public Declaration convertToDeclaration(Module module, String typeName, DeclarationType declarationType) {\n return convertToDeclaration(module, null, typeName, declarationType);\n }\n\n private Declaration convertToDeclaration(Module module, Declaration container, String typeName, DeclarationType declarationType) {\n synchronized(getLock()){\n // FIXME: this needs to move to the type parser and report warnings\n //This should be done where the TypeInfo annotation is parsed\n //to avoid retarded errors because of a space after a comma\n typeName = typeName.trim();\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n try{\n if (\"ceylon.language.Nothing\".equals(typeName)) {\n return typeFactory.getNothingDeclaration();\n } else if (\"java.lang.Throwable\".equals(typeName)) {\n // FIXME: this being here is highly dubious\n return convertToDeclaration(modules.getLanguageModule(), \"ceylon.language.Throwable\", declarationType);\n } else if (\"java.lang.Exception\".equals(typeName)) {\n // FIXME: this being here is highly dubious\n return convertToDeclaration(modules.getLanguageModule(), \"ceylon.language.Exception\", declarationType);\n } else if (\"java.lang.Annotation\".equals(typeName)) {\n // FIXME: this being here is highly dubious\n // here we prefer Annotation over ConstrainedAnnotation but that's fine\n return convertToDeclaration(modules.getLanguageModule(), \"ceylon.language.Annotation\", declarationType);\n }\n ClassMirror classMirror;\n try{\n classMirror = lookupClassMirror(module, typeName);\n }catch(NoClassDefFoundError x){\n // FIXME: this may not be the best thing to do. If the class is not there we don't know what type of declaration\n // to return, but perhaps if we use annotation scanner rather than reflection we can figure it out, at least\n // in cases where the supertype is missing, which throws in reflection at class load.\n return logModelResolutionException(x.getMessage(), module, \"Unable to load type \"+typeName).getDeclaration();\n }\n if (classMirror == null) {\n // special case when bootstrapping because we may need to pull the decl from the typechecked model\n if(isBootstrap && typeName.startsWith(CEYLON_LANGUAGE+\".\")){\n Declaration languageDeclaration = findLanguageModuleDeclarationForBootstrap(typeName);\n if(languageDeclaration != null)\n return languageDeclaration;\n }\n\n throw new ModelResolutionException(\"Failed to resolve \"+typeName);\n }\n // we only allow source loading when it's java code we're compiling in the same go\n // (well, technically before the ceylon code)\n if(classMirror.isLoadedFromSource() && !classMirror.isJavaSource())\n return null;\n return convertToDeclaration(module, container, classMirror, declarationType);\n }finally{\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n }\n\n private Type newUnknownType() {\n return new UnknownType(typeFactory).getType();\n }\n\n protected TypeParameter safeLookupTypeParameter(Scope scope, String name) {\n TypeParameter param = lookupTypeParameter(scope, name);\n if(param == null)\n throw new ModelResolutionException(\"Type param \"+name+\" not found in \"+scope);\n return param;\n }\n \n private TypeParameter lookupTypeParameter(Scope scope, String name) {\n if(scope instanceof Function){\n Function m = (Function) scope;\n for(TypeParameter param : m.getTypeParameters()){\n if(param.getName().equals(name))\n return param;\n }\n if (!m.isToplevel()) {\n // look it up in its container\n return lookupTypeParameter(scope.getContainer(), name);\n } else {\n // not found\n return null;\n }\n }else if(scope instanceof ClassOrInterface\n || scope instanceof TypeAlias){\n TypeDeclaration decl = (TypeDeclaration) scope;\n for(TypeParameter param : decl.getTypeParameters()){\n if(param.getName().equals(name))\n return param;\n }\n if (!decl.isToplevel()) {\n // look it up in its container\n return lookupTypeParameter(scope.getContainer(), name);\n } else {\n // not found\n return null;\n }\n }else if (scope instanceof Constructor) {\n return lookupTypeParameter(scope.getContainer(), name);\n }else if(scope instanceof Value\n || scope instanceof Setter){\n Declaration decl = (Declaration) scope;\n if (!decl.isToplevel()) {\n // look it up in its container\n return lookupTypeParameter(scope.getContainer(), name);\n } else {\n // not found\n return null;\n }\n }else\n throw new ModelResolutionException(\"Type param \"+name+\" lookup not supported for scope \"+scope);\n }\n \n //\n // Packages\n \n public LazyPackage findExistingPackage(Module module, String pkgName) {\n synchronized(getLock()){\n String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkgName);\n LazyPackage pkg = findCachedPackage(module, quotedPkgName);\n if(pkg != null)\n return pkg;\n // special case for the jdk module\n String moduleName = module.getNameAsString();\n if(AbstractModelLoader.isJDKModule(moduleName)){\n if(JDKUtils.isJDKPackage(moduleName, pkgName) || JDKUtils.isOracleJDKPackage(moduleName, pkgName)){\n return findOrCreatePackage(module, pkgName);\n }\n return null;\n }\n // only create it if it exists\n if(((LazyModule)module).containsPackage(pkgName) && loadPackage(module, pkgName, false)){\n return findOrCreatePackage(module, pkgName);\n }\n return null;\n }\n }\n \n private LazyPackage findCachedPackage(Module module, String quotedPkgName) {\n LazyPackage pkg = packagesByName.get(cacheKeyByModule(module, quotedPkgName));\n if(pkg != null){\n // only return it if it matches the module we're looking for, because if it doesn't we have an issue already logged\n // for a direct dependency on same module different versions logged, so no need to confuse this further\n if(module != null && pkg.getModule() != null && !module.equals(pkg.getModule()))\n return null;\n return pkg;\n }\n return null;\n }\n\n public LazyPackage findOrCreatePackage(Module module, final String pkgName) {\n synchronized(getLock()){\n String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkgName);\n LazyPackage pkg = findCachedPackage(module, quotedPkgName);\n if(pkg != null)\n return pkg;\n // try to find it from the module, perhaps it already got created and we didn't catch it\n if(module instanceof LazyModule){\n pkg = (LazyPackage) ((LazyModule) module).findPackageNoLazyLoading(pkgName);\n }else if(module != null){\n pkg = (LazyPackage) module.getDirectPackage(pkgName);\n }\n boolean isNew = pkg == null;\n if(pkg == null){\n pkg = new LazyPackage(this);\n // FIXME: some refactoring needed\n pkg.setName(Arrays.asList(pkgName.split(\"\\\\.\")));\n }\n packagesByName.put(cacheKeyByModule(module, quotedPkgName), pkg);\n\n // only bind it if we already have a module\n if(isNew && module != null){\n pkg.setModule(module);\n if(module instanceof LazyModule)\n ((LazyModule) module).addPackage(pkg);\n else\n module.getPackages().add(pkg);\n }\n\n // only load package descriptors for new packages after a certain phase\n if(packageDescriptorsNeedLoading)\n loadPackageDescriptor(pkg);\n\n return pkg;\n }\n }\n\n public void loadPackageDescriptors() {\n synchronized(getLock()){\n for(Package pkg : packagesByName.values()){\n loadPackageDescriptor(pkg);\n }\n packageDescriptorsNeedLoading = true;\n }\n }\n\n private void loadPackageDescriptor(Package pkg) {\n // Don't try to load a package descriptor for ceylon.language \n // if we're bootstrapping\n if (isBootstrap \n && pkg.getQualifiedNameString().startsWith(CEYLON_LANGUAGE)) {\n return;\n }\n \n // let's not load package descriptors for Java modules\n if(pkg.getModule() != null \n && ((LazyModule)pkg.getModule()).isJava()){\n pkg.setShared(true);\n return;\n }\n String quotedQualifiedName = JVMModuleUtil.quoteJavaKeywords(pkg.getQualifiedNameString());\n // FIXME: not sure the toplevel package can have a package declaration\n String className = quotedQualifiedName.isEmpty() \n ? NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME \n : quotedQualifiedName + \".\" + NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME;\n logVerbose(\"[Trying to look up package from \"+className+\"]\");\n Module module = pkg.getModule();\n if(module == null)\n throw new RuntimeException(\"Assertion failed: module is null for package \"+pkg.getNameAsString());\n ClassMirror packageClass = loadClass(module, quotedQualifiedName, className);\n if(packageClass == null){\n logVerbose(\"[Failed to complete \"+className+\"]\");\n // missing: leave it private\n return;\n }\n // did we compile it from source or class?\n if(packageClass.isLoadedFromSource()){\n // must have come from source, in which case we walked it and\n // loaded its values already\n logVerbose(\"[We are compiling the package \"+className+\"]\");\n return;\n }\n loadCompiledPackage(packageClass, pkg);\n }\n\n private void loadCompiledPackage(ClassMirror packageClass, Package pkg) {\n String name = getAnnotationStringValue(packageClass, CEYLON_PACKAGE_ANNOTATION, \"name\");\n Boolean shared = getAnnotationBooleanValue(packageClass, CEYLON_PACKAGE_ANNOTATION, \"shared\");\n // FIXME: validate the name?\n if(name == null || name.isEmpty()){\n logWarning(\"Package class \"+pkg.getQualifiedNameString()+\" contains no name, ignoring it\");\n return;\n }\n if(shared == null){\n logWarning(\"Package class \"+pkg.getQualifiedNameString()+\" contains no shared, ignoring it\");\n return;\n }\n pkg.setShared(shared);\n }\n\n public Module lookupModuleByPackageName(String packageName) {\n for(Module module : modules.getListOfModules()){\n // don't try the default module because it will always say yes\n if(module.isDefault())\n continue;\n // skip modules we're not loading things from\n if(!ModelUtil.equalModules(module,getLanguageModule())\n && !isModuleInClassPath(module))\n continue;\n if(module instanceof LazyModule){\n if(((LazyModule)module).containsPackage(packageName))\n return module;\n }else if(isSubPackage(module.getNameAsString(), packageName)){\n return module;\n }\n }\n if(JDKUtils.isJDKAnyPackage(packageName)\n || JDKUtils.isOracleJDKAnyPackage(packageName)){\n String moduleName = JDKUtils.getJDKModuleNameForPackage(packageName);\n return findModule(moduleName, JDKUtils.jdk.version);\n }\n if(packageName.startsWith(\"com.redhat.ceylon.compiler.java.runtime\")\n || packageName.startsWith(\"com.redhat.ceylon.compiler.java.language\")\n || packageName.startsWith(\"com.redhat.ceylon.compiler.java.metadata\")){\n return getLanguageModule();\n }\n return modules.getDefaultModule();\n }\n\n private boolean isSubPackage(String moduleName, String pkgName) {\n return pkgName.equals(moduleName)\n || pkgName.startsWith(moduleName+\".\");\n }\n\n //\n // Modules\n \n /**\n * Finds or creates a new module. This is mostly useful to force creation of modules such as jdk\n * or ceylon.language modules.\n */\n protected Module findOrCreateModule(String moduleName, String version) {\n synchronized(getLock()){\n boolean isJdk = false;\n boolean defaultModule = false;\n\n // make sure it isn't loaded\n Module module = getLoadedModule(moduleName, version);\n if(module != null)\n return module;\n\n if(JDKUtils.isJDKModule(moduleName) || JDKUtils.isOracleJDKModule(moduleName)){\n isJdk = true;\n }\n\n java.util.List<String> moduleNameList = Arrays.asList(moduleName.split(\"\\\\.\"));\n module = moduleManager.getOrCreateModule(moduleNameList, version);\n // make sure that when we load the ceylon language module we set it to where\n // the typechecker will look for it\n if(moduleName.equals(CEYLON_LANGUAGE)\n && modules.getLanguageModule() == null){\n modules.setLanguageModule(module);\n }\n\n // TRICKY We do this only when isJava is true to prevent resetting\n // the value to false by mistake. LazyModule get's created with\n // this attribute to false by default, so it should work\n if (isJdk && module instanceof LazyModule) {\n ((LazyModule)module).setJava(true);\n module.setNativeBackends(Backend.Java.asSet());\n }\n\n // FIXME: this can't be that easy.\n if(isJdk)\n module.setAvailable(true);\n module.setDefault(defaultModule);\n return module;\n }\n }\n\n public boolean loadCompiledModule(Module module) {\n synchronized(getLock()){\n if(module.isDefault())\n return false;\n String pkgName = module.getNameAsString();\n if(pkgName.isEmpty())\n return false;\n String moduleClassName = pkgName + \".\" + NamingBase.MODULE_DESCRIPTOR_CLASS_NAME;\n logVerbose(\"[Trying to look up module from \"+moduleClassName+\"]\");\n ClassMirror moduleClass = loadClass(module, pkgName, moduleClassName);\n if(moduleClass == null){\n // perhaps we have an old module?\n String oldModuleClassName = pkgName + \".\" + NamingBase.OLD_MODULE_DESCRIPTOR_CLASS_NAME;\n logVerbose(\"[Trying to look up older module descriptor from \"+oldModuleClassName+\"]\");\n ClassMirror oldModuleClass = loadClass(module, pkgName, oldModuleClassName);\n // keep it only if it has a module annotation, otherwise it could be a normal value\n if(oldModuleClass != null && oldModuleClass.getAnnotation(CEYLON_MODULE_ANNOTATION) != null)\n moduleClass = oldModuleClass;\n }\n if(moduleClass != null){\n // load its module annotation\n return loadCompiledModule(module, moduleClass, moduleClassName);\n }\n // give up\n return false;\n }\n }\n\n private boolean loadCompiledModule(Module module, ClassMirror moduleClass, String moduleClassName) {\n String name = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, \"name\");\n String version = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, \"version\");\n if(name == null || name.isEmpty()){\n logWarning(\"Module class \"+moduleClassName+\" contains no name, ignoring it\");\n return false;\n }\n if(!name.equals(module.getNameAsString())){\n logWarning(\"Module class \"+moduleClassName+\" declares an invalid name: \"+name+\". It should be: \"+module.getNameAsString());\n return false;\n }\n if(version == null || version.isEmpty()){\n logWarning(\"Module class \"+moduleClassName+\" contains no version, ignoring it\");\n return false;\n }\n if(!version.equals(module.getVersion())){\n logWarning(\"Module class \"+moduleClassName+\" declares an invalid version: \"+version+\". It should be: \"+module.getVersion());\n return false;\n }\n int major = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, \"major\", 0);\n int minor = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, \"minor\", 0);\n module.setMajor(major);\n module.setMinor(minor);\n\n // no need to load the \"nativeBackends\" annotation value, it's loaded from annotations\n setAnnotations(module, moduleClass, false);\n \n List<AnnotationMirror> imports = getAnnotationArrayValue(moduleClass, CEYLON_MODULE_ANNOTATION, \"dependencies\");\n if(imports != null){\n for (AnnotationMirror importAttribute : imports) {\n String dependencyName = (String) importAttribute.getValue(\"name\");\n if (dependencyName != null) {\n String dependencyVersion = (String) importAttribute.getValue(\"version\");\n\n Module dependency = moduleManager.getOrCreateModule(ModuleManager.splitModuleName(dependencyName), dependencyVersion);\n\n Boolean optionalVal = (Boolean) importAttribute.getValue(\"optional\");\n\n Boolean exportVal = (Boolean) importAttribute.getValue(\"export\");\n\n List<String> nativeBackends = (List<String>) importAttribute.getValue(\"nativeBackends\");\n Backends backends = nativeBackends == null ? Backends.ANY : Backends.fromAnnotations(nativeBackends);\n\n ModuleImport moduleImport = moduleManager.findImport(module, dependency);\n if (moduleImport == null) {\n boolean optional = optionalVal != null && optionalVal;\n boolean export = exportVal != null && exportVal;\n moduleImport = new ModuleImport(dependency, optional, export, backends);\n module.addImport(moduleImport);\n }\n }\n }\n }\n \n module.setAvailable(true);\n \n modules.getListOfModules().add(module);\n Module languageModule = modules.getLanguageModule();\n module.setLanguageModule(languageModule);\n if(!ModelUtil.equalModules(module, languageModule)){\n ModuleImport moduleImport = moduleManager.findImport(module, languageModule);\n if (moduleImport == null) {\n moduleImport = new ModuleImport(languageModule, false, false);\n module.addImport(moduleImport);\n }\n }\n \n return true;\n } \n \n //\n // Utils for loading type info from the model\n \n @SuppressWarnings(\"unchecked\")\n private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type, String field) {\n return (List<T>) getAnnotationValue(mirror, type, field);\n }\n\n @SuppressWarnings(\"unchecked\")\n private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type) {\n return (List<T>) getAnnotationValue(mirror, type);\n }\n\n private String getAnnotationStringValue(AnnotatedMirror mirror, String type) {\n return getAnnotationStringValue(mirror, type, \"value\");\n }\n \n private String getAnnotationStringValue(AnnotatedMirror mirror, String type, String field) {\n return (String) getAnnotationValue(mirror, type, field);\n }\n \n private Boolean getAnnotationBooleanValue(AnnotatedMirror mirror, String type, String field) {\n return (Boolean) getAnnotationValue(mirror, type, field);\n }\n\n private int getAnnotationIntegerValue(AnnotatedMirror mirror, String type, String field, int defaultValue) {\n Integer val = (Integer) getAnnotationValue(mirror, type, field);\n return val != null ? val : defaultValue;\n }\n \n @SuppressWarnings(\"unchecked\")\n private List<String> getAnnotationStringValues(AnnotationMirror annotation, String field) {\n return (List<String>)annotation.getValue(field);\n }\n \n private Object getAnnotationValue(AnnotatedMirror mirror, String type) {\n return getAnnotationValue(mirror, type, \"value\");\n }\n \n private Object getAnnotationValue(AnnotatedMirror mirror, String type, String fieldName) {\n AnnotationMirror annotation = mirror.getAnnotation(type);\n if(annotation != null){\n return annotation.getValue(fieldName);\n }\n return null;\n }\n\n //\n // ModelCompleter\n \n @Override\n public void complete(LazyInterface iface) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n complete(iface, iface.classMirror);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n\n @Override\n public void completeTypeParameters(LazyInterface iface) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n completeTypeParameters(iface, iface.classMirror);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n\n @Override\n public void complete(LazyClass klass) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n complete(klass, klass.classMirror);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n\n @Override\n public void completeTypeParameters(LazyClass klass) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n completeTypeParameters(klass, klass.classMirror);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n\n @Override\n public void completeTypeParameters(LazyClassAlias lazyClassAlias) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n completeLazyAliasTypeParameters(lazyClassAlias, lazyClassAlias.classMirror);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n \n @Override\n public void completeTypeParameters(LazyInterfaceAlias lazyInterfaceAlias) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n completeLazyAliasTypeParameters(lazyInterfaceAlias, lazyInterfaceAlias.classMirror);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n\n @Override\n public void completeTypeParameters(LazyTypeAlias lazyTypeAlias) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n completeLazyAliasTypeParameters(lazyTypeAlias, lazyTypeAlias.classMirror);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n\n @Override\n public void complete(LazyInterfaceAlias alias) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n \n @Override\n public void complete(LazyClassAlias alias) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION);\n\n String constructorName = (String)alias.classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION).getValue(\"constructor\");\n if (constructorName != null \n && !constructorName.isEmpty()) {\n Declaration constructor = alias.getExtendedType().getDeclaration().getMember(constructorName, null, false);\n if (constructor instanceof FunctionOrValue\n && ((FunctionOrValue)constructor).getTypeDeclaration() instanceof Constructor) {\n alias.setConstructor(((FunctionOrValue)constructor).getTypeDeclaration());\n } else {\n logError(\"class aliased constructor \" + constructorName + \" which is no longer a constructor of \" + alias.getExtendedType().getDeclaration().getQualifiedNameString());\n }\n }\n \n // Find the instantiator method\n MethodMirror instantiator = null;\n ClassMirror instantiatorClass = alias.isToplevel() ? alias.classMirror : alias.classMirror.getEnclosingClass();\n String aliasName = NamingBase.getAliasInstantiatorMethodName(alias);\n for (MethodMirror method : instantiatorClass.getDirectMethods()) {\n if (method.getName().equals(aliasName)) {\n instantiator = method;\n break;\n }\n }\n // Read the parameters from the instantiator, rather than the aliased class\n if (instantiator != null) {\n setParameters(alias, alias.classMirror, instantiator, true, alias);\n }\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n\n @Override\n public void complete(LazyTypeAlias alias) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n completeLazyAlias(alias, alias.classMirror, CEYLON_TYPE_ALIAS_ANNOTATION);\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n\n private void completeLazyAliasTypeParameters(TypeDeclaration alias, ClassMirror mirror) {\n // type parameters\n setTypeParameters(alias, mirror, true);\n }\n\n private void completeLazyAlias(TypeDeclaration alias, ClassMirror mirror, String aliasAnnotationName) {\n // now resolve the extended type\n AnnotationMirror aliasAnnotation = mirror.getAnnotation(aliasAnnotationName);\n String extendedTypeString = (String) aliasAnnotation.getValue();\n \n Type extendedType = decodeType(extendedTypeString, alias, ModelUtil.getModuleContainer(alias), \"alias target\");\n alias.setExtendedType(extendedType);\n }\n\n private void completeTypeParameters(ClassOrInterface klass, ClassMirror classMirror) {\n boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null;\n setTypeParameters(klass, classMirror, isCeylon);\n }\n\n private void complete(ClassOrInterface klass, ClassMirror classMirror) {\n boolean isFromJDK = isFromJDK(classMirror);\n boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null);\n boolean isNativeHeaderMember = klass.isNativeHeader();\n \n // now that everything has containers, do the inner classes\n if(klass instanceof Class == false || !((Class)klass).isOverloaded()){\n // this will not load inner classes of overloads, but that's fine since we want them in the\n // abstracted super class (the real one)\n addInnerClasses(klass, classMirror);\n }\n\n // Java classes with multiple constructors get turned into multiple Ceylon classes\n // Here we get the specific constructor that was assigned to us (if any)\n MethodMirror constructor = null;\n if (klass instanceof LazyClass) {\n constructor = ((LazyClass)klass).getConstructor();\n setHasJpaConstructor((LazyClass)klass, classMirror);\n }\n \n // Set up enumerated constructors before looking at getters,\n // because the type of the getter is the constructor's type\n Boolean hasConstructors = hasConstructors(classMirror);\n if (hasConstructors != null && hasConstructors) {\n HashMap<String, MethodMirror> m = new HashMap<>();\n // Get all the java constructors...\n for (MethodMirror ctorMirror : getClassConstructors(classMirror, constructorOnly)) {\n m.put(getCtorName(ctorMirror), ctorMirror);\n }\n for (MethodMirror ctor : getClassConstructors(classMirror.getEnclosingClass() != null ? classMirror.getEnclosingClass() : classMirror, new ValueConstructorGetter(classMirror))) {\n Object name = getAnnotationValue(ctor, CEYLON_NAME_ANNOTATION);\n MethodMirror ctorMirror = m.remove(name);\n Constructor c;\n // When for each value constructor getter we can add a Value+Constructor\n if (ctorMirror == null) {\n // Only add a Constructor using the getter if we couldn't find a matching java constructor\n c = addConstructor((Class)klass, classMirror, ctor, isNativeHeaderMember);\n } else {\n c = addConstructor((Class)klass, classMirror, ctorMirror, isNativeHeaderMember);\n }\n addConstructorMethorOrValue((Class)klass, classMirror, ctor, c, isNativeHeaderMember);\n if (isCeylon && shouldCreateNativeHeader(c, klass)) {\n Constructor hdr;\n if (ctorMirror == null) {\n hdr = addConstructor((Class)klass, classMirror, ctor, true);\n } else {\n hdr = addConstructor((Class)klass, classMirror, ctorMirror, true);\n }\n addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, hdr, true);\n initNativeHeader(hdr, c);\n } else if (isCeylon && shouldLinkNatives(c)) {\n initNativeHeaderMember(c);\n }\n }\n // Everything left must be a callable constructor, so add Function+Constructor\n for (MethodMirror ctorMirror : m.values()) {\n Constructor c = addConstructor((Class)klass, classMirror, ctorMirror, isNativeHeaderMember);\n addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, c, isNativeHeaderMember);\n if (isCeylon && shouldCreateNativeHeader(c, klass)) {\n Constructor hdr = addConstructor((Class)klass, classMirror, ctorMirror, true);\n addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, hdr, true);\n initNativeHeader(hdr, c);\n } else if (isCeylon && shouldLinkNatives(c)) {\n initNativeHeaderMember(c);\n }\n }\n }\n \n // Turn a list of possibly overloaded methods into a map\n // of lists that contain methods with the same name\n Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>();\n collectMethods(classMirror.getDirectMethods(), methods, isCeylon, isFromJDK);\n\n if(isCeylon && klass instanceof LazyInterface && JvmBackendUtil.isCompanionClassNeeded(klass)){\n ClassMirror companionClass = ((LazyInterface)klass).companionClass;\n if(companionClass != null)\n collectMethods(companionClass.getDirectMethods(), methods, isCeylon, isFromJDK);\n else\n logWarning(\"CompanionClass missing for \"+klass);\n }\n\n boolean seenStringAttribute = false;\n boolean seenHashAttribute = false;\n boolean seenStringGetter = false;\n boolean seenHashGetter = false;\n MethodMirror stringSetter = null;\n MethodMirror hashSetter = null;\n Map<String, List<MethodMirror>> getters = new HashMap<>();\n Map<String, List<MethodMirror>> setters = new HashMap<>();\n \n // Collect attributes\n for(List<MethodMirror> methodMirrors : methods.values()){\n \n for (MethodMirror methodMirror : methodMirrors) {\n // same tests as in isMethodOverloaded()\n if(methodMirror.isConstructor() || isInstantiator(methodMirror)) {\n break;\n } else if(isGetter(methodMirror)) {\n String name = getJavaAttributeName(methodMirror);\n putMultiMap(getters, name, methodMirror);\n } else if(isSetter(methodMirror)) {\n String name = getJavaAttributeName(methodMirror);\n putMultiMap(setters, name, methodMirror);\n } else if(isHashAttribute(methodMirror)) {\n putMultiMap(getters, \"hash\", methodMirror);\n seenHashAttribute = true;\n } else if(isStringAttribute(methodMirror)) {\n putMultiMap(getters, \"string\", methodMirror);\n seenStringAttribute = true;\n } else {\n // we never map getString to a property, or generate one\n if(isStringGetter(methodMirror))\n seenStringGetter = true;\n // same for getHash\n else if(isHashGetter(methodMirror))\n seenHashGetter = true;\n else if(isStringSetter(methodMirror)){\n stringSetter = methodMirror;\n // we will perhaps add it later\n continue;\n }else if(isHashSetter(methodMirror)){\n hashSetter = methodMirror;\n // we will perhaps add it later\n continue;\n }\n }\n }\n }\n \n // now figure out which properties to add\n NEXT_PROPERTY:\n for(Map.Entry<String, List<MethodMirror>> getterEntry : getters.entrySet()){\n String propertyName = getterEntry.getKey();\n List<MethodMirror> getterList = getterEntry.getValue();\n for(MethodMirror getterMethod : getterList){\n // if it's hashCode() or toString() they win\n if(isHashAttribute(getterMethod)) {\n // ERASURE\n // Un-erasing 'hash' attribute from 'hashCode' method\n Declaration decl = addValue(klass, getterMethod, \"hash\", isCeylon, isNativeHeaderMember);\n if (isCeylon && shouldCreateNativeHeader(decl, klass)) {\n Declaration hdr = addValue(klass, getterMethod, \"hash\", true, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n initNativeHeader(hdr, decl);\n } else if (isCeylon && shouldLinkNatives(decl)) {\n initNativeHeaderMember(decl);\n }\n // remove it as a method and add all other getters with the same name\n // as methods\n removeMultiMap(methods, getterMethod.getName(), getterMethod);\n // next property\n continue NEXT_PROPERTY;\n }\n if(isStringAttribute(getterMethod)) {\n // ERASURE\n // Un-erasing 'string' attribute from 'toString' method\n Declaration decl = addValue(klass, getterMethod, \"string\", isCeylon, isNativeHeaderMember);\n if (isCeylon && shouldCreateNativeHeader(decl, klass)) {\n Declaration hdr = addValue(klass, getterMethod, \"string\", true, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n initNativeHeader(hdr, decl);\n } else if (isCeylon && shouldLinkNatives(decl)) {\n initNativeHeaderMember(decl);\n }\n // remove it as a method and add all other getters with the same name\n // as methods\n removeMultiMap(methods, getterMethod.getName(), getterMethod);\n // next property\n continue NEXT_PROPERTY;\n }\n }\n // we've weeded out toString/hashCode, now if we have a single property it's easy we just add it\n if(getterList.size() == 1){\n // FTW!\n MethodMirror getterMethod = getterList.get(0);\n // simple attribute\n Declaration decl = addValue(klass, getterMethod, propertyName, isCeylon, isNativeHeaderMember);\n if (isCeylon && shouldCreateNativeHeader(decl, klass)) {\n Declaration hdr = addValue(klass, getterMethod, propertyName, true, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n initNativeHeader(hdr, decl);\n } else if (isCeylon && shouldLinkNatives(decl)) {\n initNativeHeaderMember(decl);\n }\n // remove it as a method\n removeMultiMap(methods, getterMethod.getName(), getterMethod);\n // next property\n continue NEXT_PROPERTY;\n }\n // we have more than one\n // if we have a setter let's favour the one that matches the setter\n List<MethodMirror> matchingSetters = setters.get(propertyName);\n if(matchingSetters != null){\n if(matchingSetters.size() == 1){\n // single setter will tell us what we need\n MethodMirror matchingSetter = matchingSetters.get(0);\n MethodMirror bestGetter = null;\n boolean booleanSetter = matchingSetter.getParameters().get(0).getType().getKind() == TypeKind.BOOLEAN;\n /*\n * Getters do not support overloading since they have no parameters, so they can only differ based on\n * name. For boolean properties we favour \"is\" getters, otherwise \"get\" getters.\n */\n for(MethodMirror getterMethod : getterList){\n if(propertiesMatch(klass, getterMethod, matchingSetter)){\n if(bestGetter == null)\n bestGetter = getterMethod;\n else{\n // we have two getters, find the best one\n if(booleanSetter){\n // favour the \"is\" getter\n if(getterMethod.getName().startsWith(\"is\"))\n bestGetter = getterMethod;\n // else keep the current best, it must be an \"is\" getter\n }else{\n // favour the \"get\" getter\n if(getterMethod.getName().startsWith(\"get\"))\n bestGetter = getterMethod;\n // else keep the current best, it must be a \"get\" getter\n }\n break;\n }\n }\n }\n if(bestGetter != null){\n // got it!\n // simple attribute\n Declaration decl = addValue(klass, bestGetter, propertyName, isCeylon, isNativeHeaderMember);\n if (isCeylon && shouldCreateNativeHeader(decl, klass)) {\n Declaration hdr = addValue(klass, bestGetter, propertyName, true, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n initNativeHeader(hdr, decl);\n } else if (isCeylon && shouldLinkNatives(decl)) {\n initNativeHeaderMember(decl);\n }\n // remove it as a method and add all other getters with the same name\n // as methods\n removeMultiMap(methods, bestGetter.getName(), bestGetter);\n // next property\n continue NEXT_PROPERTY;\n }// else we cannot find the right getter thanks to the setter, keep looking\n }\n }\n // setters did not help us, we have more than one getter, one must be \"is\"/boolean, the other \"get\"\n if(getterList.size() == 2){\n // if the \"get\" is also a boolean, prefer the \"is\"\n MethodMirror isMethod = null;\n MethodMirror getMethod = null;\n for(MethodMirror getterMethod : getterList){\n if(getterMethod.getName().startsWith(\"is\"))\n isMethod = getterMethod;\n else if(getterMethod.getName().startsWith(\"get\"))\n getMethod = getterMethod;\n }\n if(isMethod != null && getMethod != null){\n MethodMirror bestGetter;\n if(getMethod.getReturnType().getKind() == TypeKind.BOOLEAN){\n // pick the is method\n bestGetter = isMethod;\n }else{\n // just take the getter\n bestGetter = getMethod;\n }\n // simple attribute\n Declaration decl = addValue(klass, bestGetter, propertyName, isCeylon, isNativeHeaderMember);\n if (isCeylon && shouldCreateNativeHeader(decl, klass)) {\n Declaration hdr = addValue(klass, bestGetter, propertyName, true, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n initNativeHeader(hdr, decl);\n } else if (isCeylon && shouldLinkNatives(decl)) {\n initNativeHeaderMember(decl);\n }\n // remove it as a method and add all other getters with the same name\n // as methods\n removeMultiMap(methods, bestGetter.getName(), bestGetter);\n // next property\n continue NEXT_PROPERTY;\n }\n }\n }\n\n // now handle fields\n for(FieldMirror fieldMirror : classMirror.getDirectFields()){\n // We skip members marked with @Ignore\n if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)\n continue;\n if(skipPrivateMember(fieldMirror))\n continue;\n if(isCeylon && fieldMirror.isStatic())\n continue;\n // FIXME: temporary, because some private classes from the jdk are\n // referenced in private methods but not available\n if(isFromJDK && !fieldMirror.isPublic() && !fieldMirror.isProtected())\n continue;\n String name = fieldMirror.getName();\n // skip the field if \"we've already got one\"\n boolean conflicts = klass.getDirectMember(name, null, false) != null\n || \"equals\".equals(name)\n || \"string\".equals(name)\n || \"hash\".equals(name);\n if (!conflicts) {\n Declaration decl = addValue(klass, fieldMirror.getName(), fieldMirror, isCeylon, isNativeHeaderMember);\n if (isCeylon && shouldCreateNativeHeader(decl, klass)) {\n Declaration hdr = addValue(klass, fieldMirror.getName(), fieldMirror, true, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n initNativeHeader(hdr, decl);\n } else if (isCeylon && shouldLinkNatives(decl)) {\n initNativeHeaderMember(decl);\n }\n }\n }\n\n // Now mark all Values for which Setters exist as variable\n for(List<MethodMirror> variables : setters.values()){\n for(MethodMirror setter : variables){\n String name = getJavaAttributeName(setter);\n // make sure we handle private postfixes\n name = JvmBackendUtil.strip(name, isCeylon, setter.isPublic());\n Declaration decl = klass.getMember(name, null, false);\n // skip Java fields, which we only get if there is no getter method, in that case just add the setter method\n if (decl instanceof JavaBeanValue) {\n JavaBeanValue value = (JavaBeanValue)decl;\n // only add the setter if it has the same visibility as the getter\n if (setter.isPublic() && value.mirror.isPublic()\n || setter.isProtected() && value.mirror.isProtected()\n || setter.isDefaultAccess() && value.mirror.isDefaultAccess()\n || (!setter.isPublic() && !value.mirror.isPublic()\n && !setter.isProtected() && !value.mirror.isProtected()\n && !setter.isDefaultAccess() && !value.mirror.isDefaultAccess())) {\n VariableMirror setterParam = setter.getParameters().get(0);\n Type paramType = obtainType(setterParam.getType(), setterParam, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT,\n \"setter '\"+setter.getName()+\"'\", klass);\n // only add the setter if it has exactly the same type as the getter\n if(paramType.isExactly(value.getType())){\n value.setVariable(true);\n value.setSetterName(setter.getName());\n if(value.isTransient()){\n // must be a real setter\n makeSetter(value, null);\n }\n // remove it as a method\n removeMultiMap(methods, setter.getName(), setter);\n }else\n logVerbose(\"Setter parameter type for \"+name+\" does not match corresponding getter type, adding setter as a method\");\n } else {\n logVerbose(\"Setter visibility for \"+name+\" does not match corresponding getter visibility, adding setter as a method\");\n }\n }\n }\n }\n\n // special cases if we have hashCode() setHash() and no getHash()\n if(hashSetter != null){\n if(seenHashAttribute && !seenHashGetter){\n Declaration attr = klass.getDirectMember(\"hash\", null, false);\n if(attr instanceof JavaBeanValue){\n ((JavaBeanValue) attr).setVariable(true);\n ((JavaBeanValue) attr).setSetterName(hashSetter.getName());\n // remove it as a method\n removeMultiMap(methods, hashSetter.getName(), hashSetter);\n }\n }\n }\n // special cases if we have toString() setString() and no getString()\n if(stringSetter != null){\n if(seenStringAttribute && !seenStringGetter){\n Declaration attr = klass.getDirectMember(\"string\", null, false);\n if(attr instanceof JavaBeanValue){\n ((JavaBeanValue) attr).setVariable(true);\n ((JavaBeanValue) attr).setSetterName(stringSetter.getName());\n // remove it as a method\n removeMultiMap(methods, stringSetter.getName(), stringSetter);\n }\n }\n }\n\n // Add the methods, treat remaining getters/setters as methods\n for(List<MethodMirror> methodMirrors : methods.values()){\n boolean isOverloaded = isMethodOverloaded(methodMirrors);\n \n List<Declaration> overloads = null;\n for (MethodMirror methodMirror : methodMirrors) {\n // normal method\n Function m = addMethod(klass, methodMirror, classMirror, isCeylon, isOverloaded, isNativeHeaderMember);\n if (!isOverloaded && isCeylon && shouldCreateNativeHeader(m, klass)) {\n Declaration hdr = addMethod(klass, methodMirror, classMirror, true, isOverloaded, true);\n setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true);\n initNativeHeader(hdr, m);\n } else if (isCeylon && shouldLinkNatives(m)) {\n initNativeHeaderMember(m);\n }\n if (m.isOverloaded()) {\n overloads = overloads == null ? new ArrayList<Declaration>(methodMirrors.size()) : overloads;\n overloads.add(m);\n }\n }\n \n if (overloads != null && !overloads.isEmpty()) {\n // We create an extra \"abstraction\" method for overloaded methods\n Function abstractionMethod = addMethod(klass, methodMirrors.get(0), classMirror, isCeylon, false, false);\n abstractionMethod.setAbstraction(true);\n abstractionMethod.setOverloads(overloads);\n abstractionMethod.setType(newUnknownType());\n }\n }\n\n // Having loaded methods and values, we can now set the constructor parameters\n if(constructor != null\n && !isDefaultNamedCtor(classMirror, constructor)\n && (!(klass instanceof LazyClass) || !((LazyClass)klass).isAnonymous()))\n setParameters((Class)klass, classMirror, constructor, isCeylon, klass);\n\n // Now marry-up attributes and parameters)\n if (klass instanceof Class) {\n for (Declaration m : klass.getMembers()) {\n if (JvmBackendUtil.isValue(m)) {\n Value v = (Value)m;\n Parameter p = ((Class)klass).getParameter(v.getName());\n if (p != null) {\n p.setHidden(true);\n }\n }\n }\n }\n \n setExtendedType(klass, classMirror);\n setSatisfiedTypes(klass, classMirror);\n setCaseTypes(klass, classMirror);\n setAnnotations(klass, classMirror, isNativeHeaderMember);\n \n // local declarations come last, because they need all members to be completed first\n if(!klass.isAlias()){\n ClassMirror containerMirror = classMirror;\n if(klass instanceof LazyInterface){\n ClassMirror companionClass = ((LazyInterface) klass).companionClass;\n if(companionClass != null)\n containerMirror = companionClass;\n }\n addLocalDeclarations((LazyContainer) klass, containerMirror, classMirror);\n }\n \n if (!isCeylon) {\n // In java, a class can inherit a public member from a non-public supertype\n for (Declaration d : klass.getMembers()) {\n if (d.isShared()) {\n d.setVisibleScope(null);\n }\n }\n }\n }\n\n private boolean propertiesMatch(ClassOrInterface klass, MethodMirror getter, MethodMirror setter) {\n // only add the setter if it has the same visibility as the getter\n if (setter.isPublic() && getter.isPublic()\n || setter.isProtected() && getter.isProtected()\n || setter.isDefaultAccess() && getter.isDefaultAccess()\n || (!setter.isPublic() && !getter.isPublic()\n && !setter.isProtected() && !getter.isProtected()\n && !setter.isDefaultAccess() && !getter.isDefaultAccess())) {\n Module module = ModelUtil.getModuleContainer(klass);\n VariableMirror setterParam = setter.getParameters().get(0);\n Type paramType = obtainType(setterParam.getType(), setterParam, klass, module, VarianceLocation.INVARIANT,\n \"setter '\"+setter.getName()+\"'\", klass);\n\n Type returnType = obtainType(getter.getReturnType(), getter, klass, module, VarianceLocation.INVARIANT,\n \"getter '\"+getter.getName()+\"'\", klass);\n // only add the setter if it has exactly the same type as the getter\n if(paramType.isExactly(returnType)){\n return true;\n }\n }\n return false;\n }\n\n private <Key,Val> void removeMultiMap(Map<Key, List<Val>> map, Key key, Val val) {\n List<Val> list = map.get(key);\n if(list != null){\n list.remove(val);\n if(list.isEmpty())\n map.remove(key);\n }\n }\n \n private <Key,Val> void putMultiMap(Map<Key, List<Val>> map, Key key, Val value) {\n List<Val> list = map.get(key);\n if(list == null){\n list = new LinkedList<>();\n map.put(key, list);\n }\n list.add(value);\n }\n \n private Constructor addConstructor(Class klass, ClassMirror classMirror, MethodMirror ctor, boolean isNativeHeader) {\n boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null;\n Constructor constructor = new Constructor();\n constructor.setName(getCtorName(ctor));\n constructor.setContainer(klass);\n constructor.setScope(klass);\n constructor.setUnit(klass.getUnit());\n constructor.setAbstract(ctor.getAnnotation(CEYLON_LANGUAGE_ABSTRACT_ANNOTATION) != null);\n constructor.setExtendedType(klass.getType());\n setNonLazyDeclarationProperties(constructor, ctor, ctor, classMirror, isCeylon);\n setAnnotations(constructor, ctor, isNativeHeader);\n klass.addMember(constructor);\n return constructor;\n }\n \n protected void addConstructorMethorOrValue(Class klass, ClassMirror classMirror, MethodMirror ctor, Constructor constructor, boolean isNativeHeader) {\n boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null;\n if (ctor.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) != null) {\n klass.setEnumerated(true);\n Value v = new Value();\n v.setName(constructor.getName());\n v.setType(constructor.getType());\n v.setContainer(klass);\n v.setScope(klass);\n v.setUnit(klass.getUnit());\n v.setVisibleScope(constructor.getVisibleScope());\n // read annotations from the getter method\n setNonLazyDeclarationProperties(v, ctor, ctor, classMirror, isCeylon);\n setAnnotations(v, ctor, isNativeHeader);\n klass.addMember(v);\n }\n else {\n setParameters(constructor, classMirror, ctor, true, klass);\n klass.setConstructors(true);\n Function f = new Function();\n f.setName(constructor.getName());\n f.setType(constructor.getType());\n f.addParameterList(constructor.getParameterList());\n f.setContainer(klass);\n f.setScope(klass);\n f.setUnit(klass.getUnit());\n f.setVisibleScope(constructor.getVisibleScope());\n // read annotations from the constructor\n setNonLazyDeclarationProperties(f, ctor, ctor, classMirror, isCeylon);\n setAnnotations(f, ctor, isNativeHeader);\n klass.addMember(f);\n }\n }\n \n private boolean isMethodOverloaded(List<MethodMirror> methodMirrors) {\n // it's overloaded if we have more than one method (non constructor/value)\n boolean one = false;\n for (MethodMirror methodMirror : methodMirrors) {\n // same tests as in complete(ClassOrInterface klass, ClassMirror classMirror)\n if(methodMirror.isConstructor() \n || isInstantiator(methodMirror)\n || isGetter(methodMirror)\n || isSetter(methodMirror)\n || isHashAttribute(methodMirror)\n || isStringAttribute(methodMirror)\n || methodMirror.getName().equals(\"hash\")\n || methodMirror.getName().equals(\"string\")){\n break;\n }\n if(one)\n return true;\n one = true;\n }\n return false;\n }\n\n private void collectMethods(List<MethodMirror> methodMirrors, Map<String,List<MethodMirror>> methods,\n boolean isCeylon, boolean isFromJDK) {\n for(MethodMirror methodMirror : methodMirrors){\n // We skip members marked with @Ignore\n if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)\n continue;\n if(skipPrivateMember(methodMirror))\n continue;\n if(methodMirror.isStaticInit())\n continue;\n if(isCeylon && methodMirror.isStatic()\n && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null)\n continue;\n // these are not relevant for our caller\n if(methodMirror.isConstructor() || isInstantiator(methodMirror)) {\n continue;\n } \n // FIXME: temporary, because some private classes from the jdk are\n // referenced in private methods but not available\n if(isFromJDK && !methodMirror.isPublic() && !methodMirror.isProtected())\n continue;\n String methodName = methodMirror.getName();\n List<MethodMirror> homonyms = methods.get(methodName);\n if (homonyms == null) {\n homonyms = new LinkedList<MethodMirror>();\n methods.put(methodName, homonyms);\n }\n homonyms.add(methodMirror);\n }\n }\n \n private boolean skipPrivateMember(AccessibleMirror mirror) {\n return !mirror.isPublic() \n && !mirror.isProtected() \n && !mirror.isDefaultAccess()\n && !needsPrivateMembers();\n }\n\n private void addLocalDeclarations(LocalDeclarationContainer container, ClassMirror classContainerMirror, AnnotatedMirror annotatedMirror) {\n if(!needsLocalDeclarations())\n return;\n AnnotationMirror annotation = annotatedMirror.getAnnotation(CEYLON_LOCAL_DECLARATIONS_ANNOTATION);\n if(annotation == null)\n return;\n List<String> values = getAnnotationStringValues(annotation, \"value\");\n String parentClassName = classContainerMirror.getQualifiedName();\n Package pkg = ModelUtil.getPackageContainer(container);\n Module module = pkg.getModule();\n for(String scope : values){\n // assemble the name with the parent\n String name;\n if(scope.startsWith(\"::\")){\n // interface pulled to toplevel\n name = pkg.getNameAsString() + \".\" + scope.substring(2);\n }else{\n name = parentClassName;\n name += \"$\" + scope;\n }\n Declaration innerDecl = convertToDeclaration(module, (Declaration)container, name, DeclarationType.TYPE);\n if(innerDecl == null)\n throw new ModelResolutionException(\"Failed to load local type \" + name\n + \" for outer type \" + container.getQualifiedNameString());\n }\n }\n\n private boolean isInstantiator(MethodMirror methodMirror) {\n return methodMirror.getName().endsWith(\"$aliased$\");\n }\n \n private boolean isFromJDK(ClassMirror classMirror) {\n String pkgName = unquotePackageName(classMirror.getPackage());\n return JDKUtils.isJDKAnyPackage(pkgName) || JDKUtils.isOracleJDKAnyPackage(pkgName);\n }\n\n private void setAnnotations(Annotated annotated, AnnotatedMirror classMirror, boolean isNativeHeader) {\n if (classMirror.getAnnotation(CEYLON_ANNOTATIONS_ANNOTATION) != null) {\n // If the class has @Annotations then use it (in >=1.2 only ceylon.language does)\n Long mods = (Long)getAnnotationValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION, \"modifiers\");\n if (mods != null) {\n // If there is a modifiers value then use it to load the modifiers\n for (LanguageAnnotation mod : LanguageAnnotation.values()) {\n if (mod.isModifier()) {\n if ((mod.mask & mods) != 0) {\n annotated.getAnnotations().addAll(mod.makeFromCeylonAnnotation(null));\n }\n }\n }\n \n }\n // Load anything else the long way, reading the @Annotation(name=...)\n List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION);\n if(annotations != null) {\n for(AnnotationMirror annotation : annotations){\n annotated.getAnnotations().add(readModelAnnotation(annotation));\n }\n }\n } else {\n // If the class lacks @Annotations then set the modifier annotations\n // according to the presence of @Shared$annotation etc\n for (LanguageAnnotation mod : LanguageAnnotation.values()) {\n if (classMirror.getAnnotation(mod.annotationType) != null) {\n annotated.getAnnotations().addAll(mod.makeFromCeylonAnnotation(classMirror.getAnnotation(mod.annotationType)));\n }\n }\n // Hack for anonymous classes where the getter method has the annotations, \n // but the typechecker wants them on the Class model. \n if ((annotated instanceof Class)\n && ((Class)annotated).isAnonymous()) {\n Class clazz = (Class)annotated;\n Declaration objectValue = clazz.getContainer().getDirectMember(clazz.getName(), null, false);\n if (objectValue != null) {\n annotated.getAnnotations().addAll(objectValue.getAnnotations());\n }\n \n }\n }\n\n boolean hasCeylonDeprecated = false;\n for(Annotation a : annotated.getAnnotations()) {\n if (a.getName().equals(\"deprecated\")) {\n hasCeylonDeprecated = true;\n break;\n }\n }\n\n // Add a ceylon deprecated(\"\") if it's annotated with java.lang.Deprecated\n // and doesn't already have the ceylon annotation\n if (classMirror.getAnnotation(JAVA_DEPRECATED_ANNOTATION) != null) {\n if (!hasCeylonDeprecated) {\n Annotation modelAnnotation = new Annotation();\n modelAnnotation.setName(\"deprecated\");\n modelAnnotation.getPositionalArguments().add(\"\");\n annotated.getAnnotations().add(modelAnnotation);\n hasCeylonDeprecated = true;\n }\n }\n\n if (annotated instanceof Declaration\n && !((Declaration)annotated).getNativeBackends().none()) {\n // Do nothing : \n // it has already been managed when in the makeLazyXXX() function\n } else {\n manageNativeBackend(annotated, classMirror, isNativeHeader);\n }\n }\n \n private void manageNativeBackend(Annotated annotated, AnnotatedMirror mirror, boolean isNativeHeader) {\n if (mirror == null)\n return;\n // Set \"native\" annotation\n @SuppressWarnings(\"unchecked\")\n List<String> nativeBackends = (List<String>)getAnnotationValue(mirror, CEYLON_LANGUAGE_NATIVE_ANNOTATION, \"backends\");\n if (nativeBackends != null) {\n Backends backends = Backends.fromAnnotations(nativeBackends);\n if (isNativeHeader) {\n backends = Backends.HEADER;\n } else if (backends.header()) {\n // Elements in the class file marked `native(\"\")` are actually\n // default implementations taken from the header that were\n // copied to the output, so here we reset them to `native(\"jvm\")`\n backends = Backends.JAVA;\n }\n if (annotated instanceof Declaration) {\n Declaration decl = (Declaration)annotated;\n decl.setNativeBackends(backends);\n if (isNativeHeader) {\n List<Declaration> al = new ArrayList<Declaration>(1);\n setOverloads(decl, al);\n }\n } else if (annotated instanceof Module) {\n ((Module)annotated).setNativeBackends(backends);\n }\n } else {\n // Mark native Classes and Interfaces as well, but don't deal with overloads and such\n if (annotated instanceof LazyClass && !((LazyClass)annotated).isCeylon()\n || annotated instanceof LazyInterface && !((LazyInterface)annotated).isCeylon()) {\n ((Declaration)annotated).setNativeBackends(Backend.Java.asSet());\n }\n }\n }\n\n protected boolean isDeprecated(AnnotatedMirror classMirror){\n if (classMirror.getAnnotation(JAVA_DEPRECATED_ANNOTATION) != null)\n return true;\n if (classMirror.getAnnotation(CEYLON_ANNOTATIONS_ANNOTATION) != null) {\n // Load anything else the long way, reading the @Annotation(name=...)\n List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION);\n if(annotations != null) {\n for(AnnotationMirror annotation : annotations){\n String name = (String) annotation.getValue();\n if(name != null && name.equals(\"deprecated\"))\n return true;\n }\n }\n return false;\n } else {\n // If the class lacks @Annotations then set the modifier annotations\n // according to the presence of @Shared$annotation etc\n return classMirror.getAnnotation(LanguageAnnotation.DEPRECATED.annotationType) != null;\n }\n }\n \n public static List<Declaration> getOverloads(Declaration decl) {\n if (decl instanceof Function) {\n return ((Function)decl).getOverloads();\n }\n else if (decl instanceof Value) {\n return ((Value)decl).getOverloads();\n }\n else if (decl instanceof Class) {\n return ((Class)decl).getOverloads();\n }\n return Collections.emptyList();\n }\n \n public static void setOverloads(Declaration decl, List<Declaration> overloads) {\n if (decl instanceof Function) {\n ((Function)decl).setOverloads(overloads);\n }\n else if (decl instanceof Value) {\n ((Value)decl).setOverloads(overloads);\n }\n else if (decl instanceof Class) {\n ((Class)decl).setOverloads(overloads);\n }\n }\n\n\n private Annotation readModelAnnotation(AnnotationMirror annotation) {\n Annotation modelAnnotation = new Annotation();\n modelAnnotation.setName((String) annotation.getValue());\n @SuppressWarnings(\"unchecked\")\n List<String> arguments = (List<String>) annotation.getValue(\"arguments\");\n if(arguments != null){\n modelAnnotation.getPositionalArguments().addAll(arguments);\n }else{\n @SuppressWarnings(\"unchecked\")\n List<AnnotationMirror> namedArguments = (List<AnnotationMirror>) annotation.getValue(\"namedArguments\");\n if(namedArguments != null){\n for(AnnotationMirror namedArgument : namedArguments){\n String argName = (String) namedArgument.getValue(\"name\");\n String argValue = (String) namedArgument.getValue(\"value\");\n modelAnnotation.getNamedArguments().put(argName, argValue);\n }\n }\n }\n return modelAnnotation;\n }\n\n private void addInnerClasses(ClassOrInterface klass, ClassMirror classMirror) {\n AnnotationMirror membersAnnotation = classMirror.getAnnotation(CEYLON_MEMBERS_ANNOTATION);\n if(membersAnnotation == null)\n addInnerClassesFromMirror(klass, classMirror);\n else\n addInnerClassesFromAnnotation(klass, membersAnnotation);\n }\n\n private void addInnerClassesFromAnnotation(ClassOrInterface klass, AnnotationMirror membersAnnotation) {\n @SuppressWarnings(\"unchecked\")\n List<AnnotationMirror> members = (List<AnnotationMirror>) membersAnnotation.getValue();\n for(AnnotationMirror member : members){\n TypeMirror javaClassMirror = (TypeMirror)member.getValue(\"klass\");\n String javaClassName;\n // void.class is the default value, I guess it's a primitive?\n if(javaClassMirror != null && !javaClassMirror.isPrimitive()){\n javaClassName = javaClassMirror.getQualifiedName();\n }else{\n // we get the class name as a string\n String name = (String)member.getValue(\"javaClassName\");\n ClassMirror container = null;\n if(klass instanceof LazyClass){\n container = ((LazyClass) klass).classMirror;\n }else if(klass instanceof LazyInterface){\n if(((LazyInterface) klass).isCeylon())\n container = ((LazyInterface) klass).companionClass;\n else\n container = ((LazyInterface) klass).classMirror;\n }\n if(container == null)\n throw new ModelResolutionException(\"Unknown container type: \" + klass \n + \" when trying to load inner class \" + name);\n javaClassName = container.getQualifiedName()+\"$\"+name;\n }\n Declaration innerDecl = convertToDeclaration(ModelUtil.getModuleContainer(klass), klass, javaClassName, DeclarationType.TYPE);\n if(innerDecl == null)\n throw new ModelResolutionException(\"Failed to load inner type \" + javaClassName \n + \" for outer type \" + klass.getQualifiedNameString());\n if(shouldLinkNatives(innerDecl)) {\n initNativeHeaderMember(innerDecl);\n }\n }\n }\n\n /**\n * Allows subclasses to do something to the class name\n */\n protected String assembleJavaClass(String javaClass, String packageName) {\n return javaClass;\n }\n\n private void addInnerClassesFromMirror(ClassOrInterface klass, ClassMirror classMirror) {\n boolean isJDK = isFromJDK(classMirror);\n Module module = ModelUtil.getModule(klass);\n for(ClassMirror innerClass : classMirror.getDirectInnerClasses()){\n // We skip members marked with @Ignore\n if(innerClass.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)\n continue;\n // We skip anonymous inner classes\n if(innerClass.isAnonymous())\n continue;\n // We skip private classes, otherwise the JDK has a ton of unresolved things\n if(isJDK && !innerClass.isPublic())\n continue;\n // convert it\n convertToDeclaration(module, klass, innerClass, DeclarationType.TYPE);\n // no need to set its container as that's now handled by convertToDeclaration\n }\n }\n\n private Function addMethod(ClassOrInterface klass, MethodMirror methodMirror, ClassMirror classMirror, \n boolean isCeylon, boolean isOverloaded, boolean isNativeHeader) {\n \n JavaMethod method = new JavaMethod(methodMirror);\n String methodName = methodMirror.getName();\n \n method.setContainer(klass);\n method.setScope(klass);\n method.setRealName(methodName);\n method.setUnit(klass.getUnit());\n method.setOverloaded(isOverloaded || isOverloadingMethod(methodMirror));\n Type type = null;\n try{\n setMethodOrValueFlags(klass, methodMirror, method, isCeylon);\n }catch(ModelResolutionException x){\n // collect an error in its type\n type = logModelResolutionException(x, klass, \"method '\"+methodMirror.getName()+\"' (checking if it is an overriding method)\");\n }\n if(methodName.equals(\"hash\")\n || methodName.equals(\"string\"))\n method.setName(methodName+\"_method\");\n else\n method.setName(JvmBackendUtil.strip(methodName, isCeylon, method.isShared()));\n method.setDefaultedAnnotation(methodMirror.isDefault());\n\n // type params first\n try{\n setTypeParameters(method, methodMirror, isCeylon);\n }catch(ModelResolutionException x){\n if(type == null){\n type = logModelResolutionException(x, klass, \"method '\"+methodMirror.getName()+\"' (loading type parameters)\");\n }\n }\n\n // and its return type\n // do not log an additional error if we had one from checking if it was overriding\n if(type == null)\n type = obtainType(methodMirror.getReturnType(), methodMirror, method, ModelUtil.getModuleContainer(method), VarianceLocation.COVARIANT,\n \"method '\"+methodMirror.getName()+\"'\", klass);\n method.setType(type);\n \n // now its parameters\n if(isEqualsMethod(methodMirror))\n setEqualsParameters(method, methodMirror);\n else\n setParameters(method, classMirror, methodMirror, isCeylon, klass);\n \n method.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror));\n type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), methodMirror.getReturnType()));\n markDeclaredVoid(method, methodMirror);\n markUnboxed(method, methodMirror, methodMirror.getReturnType());\n markTypeErased(method, methodMirror, methodMirror.getReturnType());\n markUntrustedType(method, methodMirror, methodMirror.getReturnType());\n method.setDeprecated(isDeprecated(methodMirror));\n setAnnotations(method, methodMirror, isNativeHeader);\n \n klass.addMember(method);\n ModelUtil.setVisibleScope(method);\n \n addLocalDeclarations(method, classMirror, methodMirror);\n\n return method;\n }\n\n private List<Type> getSignature(Declaration decl) {\n List<Type> result = null;\n if (decl instanceof Functional) {\n Functional func = (Functional)decl;\n if (func.getParameterLists().size() > 0) {\n List<Parameter> params = func.getFirstParameterList().getParameters();\n result = new ArrayList<Type>(params.size());\n for (Parameter p : params) {\n result.add(p.getType());\n }\n }\n }\n return result;\n }\n \n private boolean isStartOfJavaBeanPropertyName(int codepoint){\n return (codepoint == Character.toUpperCase(codepoint)) || codepoint == '_'; \n }\n\n private boolean isNonGenericMethod(MethodMirror methodMirror){\n return !methodMirror.isConstructor() \n && methodMirror.getTypeParameters().isEmpty();\n }\n \n private boolean isGetter(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror))\n return false;\n String name = methodMirror.getName();\n boolean matchesGet = name.length() > 3 && name.startsWith(\"get\") \n && isStartOfJavaBeanPropertyName(name.codePointAt(3)) \n && !\"getString\".equals(name) && !\"getHash\".equals(name) && !\"getEquals\".equals(name);\n boolean matchesIs = name.length() > 2 && name.startsWith(\"is\") \n && isStartOfJavaBeanPropertyName(name.codePointAt(2)) \n && !\"isString\".equals(name) && !\"isHash\".equals(name) && !\"isEquals\".equals(name);\n boolean hasNoParams = methodMirror.getParameters().size() == 0;\n boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID);\n boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN);\n return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams;\n }\n\n private boolean isStringGetter(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror))\n return false;\n String name = methodMirror.getName();\n boolean matchesGet = \"getString\".equals(name);\n boolean matchesIs = \"isString\".equals(name);\n boolean hasNoParams = methodMirror.getParameters().size() == 0;\n boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID);\n boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN);\n return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams;\n }\n\n private boolean isHashGetter(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror))\n return false;\n String name = methodMirror.getName();\n boolean matchesGet = \"getHash\".equals(name);\n boolean matchesIs = \"isHash\".equals(name);\n boolean hasNoParams = methodMirror.getParameters().size() == 0;\n boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID);\n boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN);\n return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams;\n }\n\n private boolean isSetter(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror))\n return false;\n String name = methodMirror.getName();\n boolean matchesSet = name.length() > 3 && name.startsWith(\"set\") \n && isStartOfJavaBeanPropertyName(name.codePointAt(3))\n && !\"setString\".equals(name) && !\"setHash\".equals(name) && !\"setEquals\".equals(name);\n boolean hasOneParam = methodMirror.getParameters().size() == 1;\n boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID);\n return matchesSet && hasOneParam && hasVoidReturn;\n }\n\n private boolean isStringSetter(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror))\n return false;\n String name = methodMirror.getName();\n boolean matchesSet = name.equals(\"setString\");\n boolean hasOneParam = methodMirror.getParameters().size() == 1;\n boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID);\n return matchesSet && hasOneParam && hasVoidReturn;\n }\n\n private boolean isHashSetter(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror))\n return false;\n String name = methodMirror.getName();\n boolean matchesSet = name.equals(\"setHash\");\n boolean hasOneParam = methodMirror.getParameters().size() == 1;\n boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID);\n return matchesSet && hasOneParam && hasVoidReturn;\n }\n\n private boolean isHashAttribute(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror)\n || methodMirror.isStatic())\n return false;\n String name = methodMirror.getName();\n boolean matchesName = \"hashCode\".equals(name);\n boolean hasNoParams = methodMirror.getParameters().size() == 0;\n return matchesName && hasNoParams;\n }\n \n private boolean isStringAttribute(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror)\n || methodMirror.isStatic())\n return false;\n String name = methodMirror.getName();\n boolean matchesName = \"toString\".equals(name);\n boolean hasNoParams = methodMirror.getParameters().size() == 0;\n return matchesName && hasNoParams;\n }\n\n private boolean isEqualsMethod(MethodMirror methodMirror) {\n if(!isNonGenericMethod(methodMirror)\n || methodMirror.isStatic())\n return false;\n String name = methodMirror.getName();\n if(!\"equals\".equals(name)\n || methodMirror.getParameters().size() != 1)\n return false;\n VariableMirror param = methodMirror.getParameters().get(0);\n return sameType(param.getType(), OBJECT_TYPE);\n }\n\n private void setEqualsParameters(Function decl, MethodMirror methodMirror) {\n ParameterList parameters = new ParameterList();\n decl.addParameterList(parameters);\n Parameter parameter = new Parameter();\n Value value = new Value();\n parameter.setModel(value);\n value.setInitializerParameter(parameter);\n value.setUnit(decl.getUnit());\n value.setContainer((Scope) decl);\n value.setScope((Scope) decl);\n parameter.setName(\"that\");\n value.setName(\"that\");\n value.setType(getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, decl, VarianceLocation.INVARIANT));\n parameter.setDeclaration((Declaration) decl);\n parameters.getParameters().add(parameter);\n decl.addMember(value);\n }\n\n private String getJavaAttributeName(MethodMirror methodMirror) {\n String name = getAnnotationStringValue(methodMirror, CEYLON_NAME_ANNOTATION);\n if(name != null)\n return name;\n return getJavaAttributeName(methodMirror.getName());\n }\n \n private String getJavaAttributeName(String getterName) {\n if (getterName.startsWith(\"get\") || getterName.startsWith(\"set\")) {\n return NamingBase.getJavaBeanName(getterName.substring(3));\n } else if (getterName.startsWith(\"is\")) {\n // Starts with \"is\"\n return NamingBase.getJavaBeanName(getterName.substring(2));\n } else {\n throw new RuntimeException(\"Illegal java getter/setter name\");\n }\n }\n\n private Value addValue(ClassOrInterface klass, String ceylonName, FieldMirror fieldMirror, boolean isCeylon, boolean isNativeHeader) {\n // make sure it's a FieldValue so we can figure it out in the backend\n Value value = new FieldValue(fieldMirror.getName());\n value.setContainer(klass);\n value.setScope(klass);\n // use the name annotation if present (used by Java arrays)\n String nameAnnotation = getAnnotationStringValue(fieldMirror, CEYLON_NAME_ANNOTATION);\n value.setName(nameAnnotation != null ? nameAnnotation : ceylonName);\n value.setUnit(klass.getUnit());\n value.setShared(fieldMirror.isPublic() || fieldMirror.isProtected() || fieldMirror.isDefaultAccess());\n value.setProtectedVisibility(fieldMirror.isProtected());\n value.setPackageVisibility(fieldMirror.isDefaultAccess());\n value.setStaticallyImportable(fieldMirror.isStatic());\n setDeclarationAliases(value, fieldMirror);\n // field can't be abstract or interface, so not formal\n // can we override fields? good question. Not really, but from an external point of view?\n // FIXME: figure this out: (default)\n // FIXME: for the same reason, can it be an overriding field? (actual)\n value.setVariable(!fieldMirror.isFinal());\n // figure out if it's an enum subtype in a final static field\n if(fieldMirror.getType().getKind() == TypeKind.DECLARED\n && fieldMirror.getType().getDeclaredClass() != null\n && fieldMirror.getType().getDeclaredClass().isEnum()\n && fieldMirror.isFinal()\n && fieldMirror.isStatic())\n value.setEnumValue(true);\n \n Type type = obtainType(fieldMirror.getType(), fieldMirror, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT,\n \"field '\"+value.getName()+\"'\", klass);\n if (value.isEnumValue()) {\n Class enumValueType = new Class();\n enumValueType.setValueConstructor(true);\n enumValueType.setJavaEnum(true);\n enumValueType.setAnonymous(true);\n enumValueType.setExtendedType(type);\n enumValueType.setContainer(value.getContainer());\n enumValueType.setScope(value.getContainer());\n enumValueType.setDeprecated(value.isDeprecated());\n enumValueType.setName(value.getName());\n enumValueType.setFinal(true);\n enumValueType.setUnit(value.getUnit());\n enumValueType.setStaticallyImportable(value.isStaticallyImportable());\n value.setType(enumValueType.getType());\n value.setUncheckedNullType(false);\n } else {\n value.setType(type);\n value.setUncheckedNullType((!isCeylon && !fieldMirror.getType().isPrimitive()) || isUncheckedNull(fieldMirror));\n }\n type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), fieldMirror.getType()));\n\n markUnboxed(value, null, fieldMirror.getType());\n markTypeErased(value, fieldMirror, fieldMirror.getType());\n markUntrustedType(value, fieldMirror, fieldMirror.getType());\n value.setDeprecated(isDeprecated(fieldMirror));\n setAnnotations(value, fieldMirror, isNativeHeader);\n klass.addMember(value);\n ModelUtil.setVisibleScope(value);\n return value;\n }\n \n private boolean isRaw(Module module, TypeMirror type) {\n // dirty hack to get rid of bug where calling type.isRaw() on a ceylon type we are going to compile would complete() it, which\n // would try to parse its file. For ceylon types we don't need the class file info we can query it\n // See https://github.com/ceylon/ceylon-compiler/issues/1085\n switch(type.getKind()){\n case ARRAY: // arrays are never raw\n case BOOLEAN:\n case BYTE: \n case CHAR:\n case DOUBLE:\n case ERROR:\n case FLOAT:\n case INT:\n case LONG:\n case NULL:\n case SHORT:\n case TYPEVAR:\n case VOID:\n case WILDCARD:\n return false;\n case DECLARED:\n ClassMirror klass = type.getDeclaredClass();\n if(klass.isJavaSource()){\n // I suppose this should work\n return type.isRaw();\n }\n List<String> path = new LinkedList<String>();\n String pkgName = klass.getPackage().getQualifiedName();\n String unquotedPkgName = unquotePackageName(klass.getPackage());\n String qualifiedName = klass.getQualifiedName();\n String relativeName = pkgName.isEmpty() ? qualifiedName : qualifiedName.substring(pkgName.length()+1);\n for(String name : relativeName.split(\"[\\\\$\\\\.]\")){\n if(!name.isEmpty()){\n path.add(name);\n }\n }\n if(path.size() > 1){\n // find the proper class mirror for the container\n klass = loadClass(module, \n pkgName, \n new StringBuilder(pkgName)\n .append('.')\n .append(path.get(0)).toString());\n if(klass == null)\n return false;\n }\n if(!path.isEmpty() && klass.isLoadedFromSource()){\n // we need to find its model\n Scope scope = packagesByName.get(cacheKeyByModule(module, unquotedPkgName));\n if(scope == null)\n return false;\n for(String name : path){\n Declaration decl = scope.getDirectMember(name, null, false);\n if(decl == null)\n return false;\n // if we get a value, we want its type\n if(JvmBackendUtil.isValue(decl)\n && ((Value)decl).getTypeDeclaration().getName().equals(name))\n decl = ((Value)decl).getTypeDeclaration();\n if(decl instanceof TypeDeclaration == false)\n return false;\n scope = (TypeDeclaration)decl;\n }\n TypeDeclaration typeDecl = (TypeDeclaration) scope;\n return !typeDecl.getTypeParameters().isEmpty() && type.getTypeArguments().isEmpty();\n }\n try{\n return type.isRaw();\n }catch(Exception x){\n // ignore this exception, it's likely to be due to missing module imports and an unknown type and\n // it will be logged somewhere else\n return false;\n }\n default:\n return false;\n }\n }\n\n private JavaBeanValue addValue(ClassOrInterface klass, MethodMirror methodMirror, String methodName, boolean isCeylon, boolean isNativeHeader) {\n JavaBeanValue value = new JavaBeanValue(methodMirror);\n value.setGetterName(methodMirror.getName());\n value.setContainer(klass);\n value.setScope(klass);\n value.setUnit(klass.getUnit());\n Type type = null;\n try{\n setMethodOrValueFlags(klass, methodMirror, value, isCeylon);\n }catch(ModelResolutionException x){\n // collect an error in its type\n type = logModelResolutionException(x, klass, \"getter '\"+methodName+\"' (checking if it is an overriding method\");\n }\n value.setName(JvmBackendUtil.strip(methodName, isCeylon, value.isShared()));\n\n // do not log an additional error if we had one from checking if it was overriding\n if(type == null)\n type = obtainType(methodMirror.getReturnType(), methodMirror, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT,\n \"getter '\"+methodName+\"'\", klass);\n value.setType(type);\n // special case for hash attributes which we want to pretend are of type long internally\n if(value.isShared() && methodName.equals(\"hash\"))\n type.setUnderlyingType(\"long\");\n value.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror));\n type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), methodMirror.getReturnType()));\n\n markUnboxed(value, methodMirror, methodMirror.getReturnType());\n markTypeErased(value, methodMirror, methodMirror.getReturnType());\n markUntrustedType(value, methodMirror, methodMirror.getReturnType());\n value.setDeprecated(isDeprecated(methodMirror));\n setAnnotations(value, methodMirror, isNativeHeader);\n klass.addMember(value);\n ModelUtil.setVisibleScope(value);\n return value;\n }\n\n private boolean isUncheckedNull(AnnotatedMirror methodMirror) {\n Boolean unchecked = getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, \"uncheckedNull\");\n return unchecked != null && unchecked.booleanValue();\n }\n\n private void setMethodOrValueFlags(final ClassOrInterface klass, final MethodMirror methodMirror, final FunctionOrValue decl, boolean isCeylon) {\n decl.setShared(methodMirror.isPublic() || methodMirror.isProtected() || methodMirror.isDefaultAccess());\n decl.setProtectedVisibility(methodMirror.isProtected());\n decl.setPackageVisibility(methodMirror.isDefaultAccess());\n setDeclarationAliases(decl, methodMirror);\n if(decl instanceof Value){\n setValueTransientLateFlags((Value)decl, methodMirror, isCeylon);\n }\n if(// for class members we rely on abstract bit\n (klass instanceof Class \n && methodMirror.isAbstract())\n // Trust the abstract bit for Java interfaces, but not for Ceylon ones\n || (klass instanceof Interface\n && !((LazyInterface)klass).isCeylon()\n && methodMirror.isAbstract())\n // For Ceylon interfaces we rely on annotation\n || methodMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null) {\n decl.setFormal(true);\n } else {\n if (// for class members we rely on final/static bits\n (klass instanceof Class\n && !klass.isFinal() // a final class necessarily has final members\n && !methodMirror.isFinal() \n && !methodMirror.isStatic())\n // Java interfaces are never final\n || (klass instanceof Interface\n && !((LazyInterface)klass).isCeylon())\n // For Ceylon interfaces we rely on annotation\n || methodMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null){\n decl.setDefault(true);\n }\n }\n decl.setStaticallyImportable(methodMirror.isStatic() && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null);\n\n decl.setActualCompleter(this);\n }\n \n @Override\n public void completeActual(Declaration decl){\n Scope container = decl.getContainer();\n\n if(container instanceof ClassOrInterface){\n ClassOrInterface klass = (ClassOrInterface) container;\n \n decl.setRefinedDeclaration(decl);\n // we never consider Interface and other stuff, since we never register the actualCompleter for them\n if(decl instanceof Class){\n // Java member classes are never actual \n if(!JvmBackendUtil.isCeylon((Class)decl))\n return;\n // we already set the actual bit for member classes, we just need the refined decl\n if(decl.isActual()){\n Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false);\n decl.setRefinedDeclaration(refined);\n }\n }else{ // Function or Value\n MethodMirror methodMirror;\n if(decl instanceof JavaBeanValue)\n methodMirror = ((JavaBeanValue) decl).mirror;\n else if(decl instanceof JavaMethod)\n methodMirror = ((JavaMethod) decl).mirror;\n else\n throw new ModelResolutionException(\"Unknown type of declaration: \"+decl+\": \"+decl.getClass().getName());\n \n decl.setRefinedDeclaration(decl);\n // For Ceylon interfaces we rely on annotation\n if(klass instanceof LazyInterface\n && ((LazyInterface)klass).isCeylon()){\n boolean actual = methodMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null;\n decl.setActual(actual);\n if(actual){\n Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false);\n decl.setRefinedDeclaration(refined);\n }\n }else{\n if(isOverridingMethod(methodMirror)){\n decl.setActual(true);\n Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false);\n decl.setRefinedDeclaration(refined);\n }\n }\n \n // now that we know the refined declaration, we can check for reified type param support\n // for Ceylon methods\n if(decl instanceof JavaMethod && JvmBackendUtil.isCeylon(klass)){\n if(!methodMirror.getTypeParameters().isEmpty()\n // because this requires the refined decl, we defer this check until we've set it, to not trigger\n // lazy loading just to check.\n && JvmBackendUtil.supportsReified(decl)){\n checkReifiedTypeDescriptors(methodMirror.getTypeParameters().size(), \n container.getQualifiedNameString(), methodMirror, false);\n }\n }\n }\n }\n }\n \n private void setValueTransientLateFlags(Value decl, MethodMirror methodMirror, boolean isCeylon) {\n if(isCeylon)\n decl.setTransient(methodMirror.getAnnotation(CEYLON_TRANSIENT_ANNOTATION) != null);\n else\n // all Java getters are transient, fields are not\n decl.setTransient(decl instanceof FieldValue == false);\n decl.setLate(methodMirror.getAnnotation(CEYLON_LANGUAGE_LATE_ANNOTATION) != null);\n }\n\n private void setExtendedType(ClassOrInterface klass, ClassMirror classMirror) {\n // look at its super type\n TypeMirror superClass = classMirror.getSuperclass();\n Type extendedType;\n \n if(klass instanceof Interface){\n // interfaces need to have their superclass set to Object\n if(superClass == null || superClass.getKind() == TypeKind.NONE)\n extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, klass, VarianceLocation.INVARIANT);\n else\n extendedType = getNonPrimitiveType(ModelUtil.getModule(klass), superClass, klass, VarianceLocation.INVARIANT);\n }else if(klass instanceof Class && ((Class) klass).isOverloaded()){\n // if the class is overloaded we already have it stored\n extendedType = klass.getExtendedType();\n }else{\n String className = classMirror.getQualifiedName();\n String superClassName = superClass == null ? null : superClass.getQualifiedName();\n if(className.equals(\"ceylon.language.Anything\")){\n // ceylon.language.Anything has no super type\n extendedType = null;\n }else if(className.equals(\"java.lang.Object\")){\n // we pretend its superclass is something else, but note that in theory we shouldn't \n // be seeing j.l.Object at all due to unerasure\n extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT);\n }else{\n // read it from annotation first\n String annotationSuperClassName = getAnnotationStringValue(classMirror, CEYLON_CLASS_ANNOTATION, \"extendsType\");\n if(annotationSuperClassName != null && !annotationSuperClassName.isEmpty()){\n extendedType = decodeType(annotationSuperClassName, klass, ModelUtil.getModuleContainer(klass),\n \"extended type\");\n }else{\n // read it from the Java super type\n // now deal with type erasure, avoid having Object as superclass\n if(\"java.lang.Object\".equals(superClassName)){\n extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT);\n } else if(superClass != null){\n try{\n extendedType = getNonPrimitiveType(ModelUtil.getModule(klass), superClass, klass, VarianceLocation.INVARIANT);\n }catch(ModelResolutionException x){\n extendedType = logModelResolutionException(x, klass, \"Error while resolving extended type of \"+klass.getQualifiedNameString());\n }\n }else{\n // FIXME: should this be UnknownType?\n extendedType = null;\n }\n }\n }\n }\n if(extendedType != null)\n klass.setExtendedType(extendedType);\n }\n\n private Type getJavaAnnotationExtendedType(ClassOrInterface klass, ClassMirror classMirror) {\n TypeDeclaration constrainedAnnotation = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CONSTRAINED_ANNOTATION_TYPE, klass, DeclarationType.TYPE);\n AnnotationMirror target = classMirror.getAnnotation(\"java.lang.annotation.Target\");\n Set<Type> types = new HashSet<Type>();\n if(target != null){\n @SuppressWarnings(\"unchecked\")\n List<String> values = (List<String>) target.getValue();\n for(String value : values){\n switch(value){\n case \"TYPE\":\n TypeDeclaration decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE, klass, DeclarationType.TYPE);\n types.add(decl.getType());\n decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_ALIAS_DECLARATION_TYPE, klass, DeclarationType.TYPE);\n types.add(decl.getType());\n break;\n case \"ANNOTATION_TYPE\":\n decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE, klass, DeclarationType.TYPE);\n types.add(decl.getType());\n break;\n case \"CONSTRUCTOR\":\n decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CONSTRUCTOR_DECLARATION_TYPE, klass, DeclarationType.TYPE);\n types.add(decl.getType());\n if (!values.contains(\"TYPE\")) {\n decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_WITH_INIT_DECLARATION_TYPE, klass, DeclarationType.TYPE);\n types.add(decl.getType());\n }\n break;\n case \"METHOD\":\n // method annotations may be applied to shared members which are turned into getter methods\n case \"PARAMETER\":\n decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_FUNCTION_OR_VALUE_DECLARATION_TYPE, klass, DeclarationType.TYPE);\n types.add(decl.getType());\n break;\n case \"FIELD\":\n case \"LOCAL_VARIABLE\":\n decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_VALUE_DECLARATION_TYPE, klass, DeclarationType.TYPE);\n types.add(decl.getType());\n break;\n default:\n // all other values are ambiguous or have no mapping\n }\n }\n }\n Module module = ModelUtil.getModuleContainer(klass);\n Type annotatedType;\n if(types.size() == 1)\n annotatedType = types.iterator().next();\n else if(types.isEmpty()){\n TypeDeclaration decl;\n if(target == null){\n // default is anything\n decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_ANNOTATED_TYPE, klass, DeclarationType.TYPE);\n }else{\n // we either had an empty set which means cannot be used as annotation in Java (only as annotation member)\n // or that we only had unmappable targets\n decl = typeFactory.getNothingDeclaration();\n }\n annotatedType = decl.getType();\n }else{\n List<Type> list = new ArrayList<Type>(types.size());\n list.addAll(types);\n annotatedType = union(list, getUnitForModule(module));\n }\n Type constrainedType = constrainedAnnotation.appliedType(null, Arrays.asList(klass.getType(), getOptionalType(klass.getType(), module), annotatedType));\n return constrainedType;\n }\n \n private void setParameters(Functional decl, ClassMirror classMirror, MethodMirror methodMirror, boolean isCeylon, Scope container) {\n ParameterList parameters = new ParameterList();\n parameters.setNamedParametersSupported(isCeylon);\n decl.addParameterList(parameters);\n int parameterCount = methodMirror.getParameters().size();\n int parameterIndex = 0;\n \n for(VariableMirror paramMirror : methodMirror.getParameters()){\n // ignore some parameters\n if(paramMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)\n continue;\n \n boolean isLastParameter = parameterIndex == parameterCount - 1;\n boolean isVariadic = isLastParameter && methodMirror.isVariadic();\n \n String paramName = getAnnotationStringValue(paramMirror, CEYLON_NAME_ANNOTATION);\n // use whatever param name we find as default\n if(paramName == null)\n paramName = paramMirror.getName();\n \n Parameter parameter = new Parameter();\n parameter.setName(paramName);\n \n TypeMirror typeMirror = paramMirror.getType();\n Module module = ModelUtil.getModuleContainer((Scope) decl);\n\n Type type;\n if(isVariadic){\n // possibly make it optional\n TypeMirror variadicType = typeMirror.getComponentType();\n // we pretend it's toplevel because we want to get magic string conversion for variadic methods\n type = obtainType(ModelUtil.getModuleContainer((Scope)decl), variadicType, (Scope)decl, TypeLocation.TOPLEVEL, VarianceLocation.CONTRAVARIANT);\n if(!isCeylon && !variadicType.isPrimitive()){\n // Java parameters are all optional unless primitives\n Type optionalType = getOptionalType(type, module);\n optionalType.setUnderlyingType(type.getUnderlyingType());\n type = optionalType;\n }\n // turn it into a Sequential<T>\n type = typeFactory.getSequentialType(type);\n }else{\n type = obtainType(typeMirror, paramMirror, (Scope) decl, module, VarianceLocation.CONTRAVARIANT,\n \"parameter '\"+paramName+\"' of method '\"+methodMirror.getName()+\"'\", (Declaration)decl);\n // variadic params may technically be null in Java, but it Ceylon sequenced params may not\n // so it breaks the typechecker logic for handling them, and it will always be a case of bugs\n // in the java side so let's not allow this\n if(!isCeylon && !typeMirror.isPrimitive()){\n // Java parameters are all optional unless primitives\n Type optionalType = getOptionalType(type, module);\n optionalType.setUnderlyingType(type.getUnderlyingType());\n type = optionalType;\n }\n }\n type.setRaw(isRaw(ModelUtil.getModuleContainer(container), typeMirror));\n \n FunctionOrValue value = null;\n boolean lookedup = false;\n if (isCeylon && decl instanceof Class){\n // For a functional parameter to a class, we can just lookup the member\n value = (FunctionOrValue)((Class)decl).getDirectMember(paramName, null, false);\n lookedup = value != null;\n } \n if (value == null) {\n // So either decl is not a Class, \n // or the method or value member of decl is not shared\n AnnotationMirror functionalParameterAnnotation = paramMirror.getAnnotation(CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION);\n if (functionalParameterAnnotation != null) {\n // A functional parameter to a method\n Function method = loadFunctionalParameter((Declaration)decl, paramName, type, (String)functionalParameterAnnotation.getValue());\n value = method;\n parameter.setDeclaredAnything(method.isDeclaredVoid());\n } else {\n // A value parameter to a method\n value = new Value();\n value.setType(type);\n }\n \n value.setContainer((Scope) decl);\n value.setScope((Scope) decl);\n ModelUtil.setVisibleScope(value);\n value.setUnit(((Element)decl).getUnit());\n value.setName(paramName);\n }else{\n // Ceylon 1.1 had a bug where TypeInfo for functional parameters included the full CallableType on the method\n // rather than just the method return type, so we try to detect this and fix it\n if(value instanceof Function \n && isCeylon1Dot1(classMirror)){\n Type newType = getSimpleCallableReturnType(value.getType());\n if(!newType.isUnknown())\n value.setType(newType);\n }\n }\n value.setInitializerParameter(parameter);\n parameter.setModel(value);\n\n if(paramMirror.getAnnotation(CEYLON_SEQUENCED_ANNOTATION) != null\n || isVariadic)\n parameter.setSequenced(true);\n if(paramMirror.getAnnotation(CEYLON_DEFAULTED_ANNOTATION) != null)\n parameter.setDefaulted(true);\n if (parameter.isSequenced() &&\n // FIXME: store info in Sequenced\n typeFactory.isNonemptyIterableType(parameter.getType())) {\n parameter.setAtLeastOne(true);\n }\n // unboxed is already set if it's a real method\n if(!lookedup){\n // if it's variadic, consider the array element type (T[] == T...) for boxing rules\n markUnboxed(value, null, isVariadic ? \n paramMirror.getType().getComponentType()\n : paramMirror.getType());\n }\n parameter.setDeclaration((Declaration) decl);\n value.setDeprecated(value.isDeprecated() || isDeprecated(paramMirror));\n setAnnotations(value, paramMirror, false);\n parameters.getParameters().add(parameter);\n if (!lookedup) {\n parameter.getDeclaration().getMembers().add(parameter.getModel());\n }\n \n parameterIndex++;\n }\n if (decl instanceof Function) {\n // Multiple parameter lists\n AnnotationMirror functionalParameterAnnotation = methodMirror.getAnnotation(CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION);\n if (functionalParameterAnnotation != null) {\n parameterNameParser.parseMpl((String)functionalParameterAnnotation.getValue(), ((Function)decl).getType().getFullType(), (Function)decl);\n }\n }\n }\n\n private boolean isCeylon1Dot1(ClassMirror classMirror) {\n AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION);\n if(annotation == null)\n return false;\n Integer major = (Integer) annotation.getValue(\"major\");\n if(major == null)\n major = 0;\n Integer minor = (Integer) annotation.getValue(\"minor\");\n if(minor == null)\n minor = 0;\n return major == Versions.V1_1_BINARY_MAJOR_VERSION && minor == Versions.V1_1_BINARY_MINOR_VERSION;\n }\n \n private Function loadFunctionalParameter(Declaration decl, String paramName, Type type, String parameterNames) {\n Function method = new Function();\n method.setName(paramName);\n method.setUnit(decl.getUnit());\n if (parameterNames == null || parameterNames.isEmpty()) {\n // This branch is broken, but it deals with old code which lacked\n // the encoding of parameter names of functional parameters, so we'll keep it until 1.2\n method.setType(getSimpleCallableReturnType(type));\n ParameterList pl = new ParameterList();\n int count = 0;\n for (Type pt : getSimpleCallableArgumentTypes(type)) {\n Parameter p = new Parameter();\n Value v = new Value();\n String name = \"arg\" + count++;\n p.setName(name);\n v.setName(name);\n v.setType(pt);\n v.setContainer(method);\n v.setScope(method);\n p.setModel(v);\n v.setInitializerParameter(p);\n pl.getParameters().add(p);\n method.addMember(v);\n }\n method.addParameterList(pl);\n } else {\n try {\n parameterNameParser.parse(parameterNames, type, method);\n } catch(Exception x){\n logError(x.getClass().getSimpleName() + \" while parsing parameter names of \"+decl+\": \" + x.getMessage());\n return method;\n }\n }\n return method;\n }\n\n List<Type> getSimpleCallableArgumentTypes(Type type) {\n if(type != null\n && type.isClassOrInterface()\n && type.getDeclaration().getQualifiedNameString().equals(CEYLON_LANGUAGE_CALLABLE_TYPE_NAME)\n && type.getTypeArgumentList().size() >= 2)\n return flattenCallableTupleType(type.getTypeArgumentList().get(1));\n return Collections.emptyList();\n }\n\n List<Type> flattenCallableTupleType(Type tupleType) {\n if(tupleType != null\n && tupleType.isClassOrInterface()){\n String declName = tupleType.getDeclaration().getQualifiedNameString();\n if(declName.equals(CEYLON_LANGUAGE_TUPLE_TYPE_NAME)){\n List<Type> tal = tupleType.getTypeArgumentList();\n if(tal.size() >= 3){\n List<Type> ret = flattenCallableTupleType(tal.get(2));\n ret.add(0, tal.get(1));\n return ret;\n }\n }else if(declName.equals(CEYLON_LANGUAGE_EMPTY_TYPE_NAME)){\n return new LinkedList<Type>();\n }else if(declName.equals(CEYLON_LANGUAGE_SEQUENTIAL_TYPE_NAME)){\n LinkedList<Type> ret = new LinkedList<Type>();\n ret.add(tupleType);\n return ret;\n }else if(declName.equals(CEYLON_LANGUAGE_SEQUENCE_TYPE_NAME)){\n LinkedList<Type> ret = new LinkedList<Type>();\n ret.add(tupleType);\n return ret;\n }\n }\n return Collections.emptyList();\n }\n \n Type getSimpleCallableReturnType(Type type) {\n if(type != null\n && type.isClassOrInterface()\n && type.getDeclaration().getQualifiedNameString().equals(CEYLON_LANGUAGE_CALLABLE_TYPE_NAME)\n && !type.getTypeArgumentList().isEmpty())\n return type.getTypeArgumentList().get(0);\n return newUnknownType();\n }\n \n private Type getOptionalType(Type type, Module moduleScope) {\n if(type.isUnknown())\n return type;\n // we do not use Unit.getOptionalType because it causes lots of lazy loading that ultimately triggers the typechecker's\n // infinite recursion loop\n List<Type> list = new ArrayList<Type>(2);\n list.add(typeFactory.getNullType());\n list.add(type);\n return union(list, getUnitForModule(moduleScope));\n }\n \n private Type logModelResolutionError(Scope container, String message) {\n return logModelResolutionException((String)null, container, message);\n }\n\n private Type logModelResolutionException(ModelResolutionException x, Scope container, String message) {\n return logModelResolutionException(x.getMessage(), container, message);\n }\n \n private Type logModelResolutionException(final String exceptionMessage, Scope container, final String message) {\n final Module module = ModelUtil.getModuleContainer(container);\n return logModelResolutionException(exceptionMessage, module, message);\n }\n \n private Type logModelResolutionException(final String exceptionMessage, Module module, final String message) {\n UnknownType.ErrorReporter errorReporter;\n if(module != null && !module.isDefault()){\n final StringBuilder sb = new StringBuilder();\n sb.append(\"Error while loading the \").append(module.getNameAsString()).append(\"/\").append(module.getVersion());\n sb.append(\" module:\\n \");\n sb.append(message);\n \n if(exceptionMessage != null)\n sb.append(\":\\n \").append(exceptionMessage);\n errorReporter = makeModelErrorReporter(module, sb.toString());\n }else if(exceptionMessage == null){\n errorReporter = makeModelErrorReporter(message);\n }else{\n errorReporter = makeModelErrorReporter(message+\": \"+exceptionMessage);\n }\n UnknownType ret = new UnknownType(typeFactory);\n ret.setErrorReporter(errorReporter);\n return ret.getType();\n }\n\n /**\n * To be overridden by subclasses\n */\n protected UnknownType.ErrorReporter makeModelErrorReporter(String message) {\n return new LogErrorRunnable(this, message);\n }\n \n /**\n * To be overridden by subclasses\n */\n protected abstract UnknownType.ErrorReporter makeModelErrorReporter(Module module, String message);\n\n private static class LogErrorRunnable extends UnknownType.ErrorReporter {\n\n private AbstractModelLoader modelLoader;\n\n public LogErrorRunnable(AbstractModelLoader modelLoader, String message) {\n super(message);\n this.modelLoader = modelLoader;\n }\n\n @Override\n public void reportError() {\n modelLoader.logError(getMessage());\n }\n }\n\n private void markTypeErased(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) {\n if (BooleanUtil.isTrue(getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, \"erased\"))) {\n decl.setTypeErased(true);\n } else {\n decl.setTypeErased(sameType(type, OBJECT_TYPE));\n }\n }\n \n private void markUntrustedType(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) {\n if (BooleanUtil.isTrue(getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, \"untrusted\"))) {\n decl.setUntrustedType(true);\n }\n }\n \n private void markDeclaredVoid(Function decl, MethodMirror methodMirror) {\n if (methodMirror.isDeclaredVoid() || \n BooleanUtil.isTrue(getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, \"declaredVoid\"))) {\n decl.setDeclaredVoid(true);\n }\n }\n\n /*private boolean hasTypeParameterWithConstraints(TypeMirror type) {\n switch(type.getKind()){\n case BOOLEAN:\n case BYTE:\n case CHAR:\n case DOUBLE:\n case FLOAT:\n case INT:\n case LONG:\n case SHORT:\n case VOID:\n case WILDCARD:\n return false;\n case ARRAY:\n return hasTypeParameterWithConstraints(type.getComponentType());\n case DECLARED:\n for(TypeMirror ta : type.getTypeArguments()){\n if(hasTypeParameterWithConstraints(ta))\n return true;\n }\n return false;\n case TYPEVAR:\n TypeParameterMirror typeParameter = type.getTypeParameter();\n return typeParameter != null && hasNonErasedBounds(typeParameter);\n default:\n return false;\n }\n }*/\n \n private void markUnboxed(TypedDeclaration decl, MethodMirror methodMirror, TypeMirror type) {\n boolean unboxed = false;\n if(type.isPrimitive() \n || type.getKind() == TypeKind.ARRAY\n || sameType(type, STRING_TYPE)\n || (methodMirror != null && methodMirror.isDeclaredVoid())) {\n unboxed = true;\n }\n decl.setUnboxed(unboxed);\n }\n\n @Override\n public void complete(LazyValue value) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n try{\n MethodMirror meth = getGetterMethodMirror(value, value.classMirror, value.isToplevel());\n if(meth == null || meth.getReturnType() == null){\n value.setType(logModelResolutionError(value.getContainer(), \"Error while resolving toplevel attribute \"+value.getQualifiedNameString()+\": getter method missing\"));\n return;\n }\n value.setDeprecated(value.isDeprecated() | isDeprecated(meth));\n value.setType(obtainType(meth.getReturnType(), meth, null, ModelUtil.getModuleContainer(value.getContainer()), VarianceLocation.INVARIANT,\n \"toplevel attribute\", value));\n\n markVariable(value);\n setValueTransientLateFlags(value, meth, true);\n setAnnotations(value, meth, value.isNativeHeader());\n markUnboxed(value, meth, meth.getReturnType());\n markTypeErased(value, meth, meth.getReturnType());\n\n TypeMirror setterClass = (TypeMirror) getAnnotationValue(value.classMirror, CEYLON_ATTRIBUTE_ANNOTATION, \"setterClass\");\n // void.class is the default value, I guess it's a primitive?\n if(setterClass != null && !setterClass.isPrimitive()){\n ClassMirror setterClassMirror = setterClass.getDeclaredClass();\n value.setVariable(true);\n SetterWithLocalDeclarations setter = makeSetter(value, setterClassMirror);\n // adding local scopes should be done last, when we have the setter, because it may be needed by container chain\n addLocalDeclarations(value, value.classMirror, value.classMirror);\n addLocalDeclarations(setter, setterClassMirror, setterClassMirror);\n }else if(value.isToplevel() && value.isTransient() && value.isVariable()){\n makeSetter(value, value.classMirror);\n // all local scopes for getter/setter are declared in the same class\n // adding local scopes should be done last, when we have the setter, because it may be needed by container chain\n addLocalDeclarations(value, value.classMirror, value.classMirror);\n }else{\n // adding local scopes should be done last, when we have the setter, because it may be needed by container chain\n addLocalDeclarations(value, value.classMirror, value.classMirror);\n }\n }finally{\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n }\n \n private MethodMirror getGetterMethodMirror(Declaration value, ClassMirror classMirror, boolean toplevel) {\n MethodMirror meth = null;\n String getterName;\n if (toplevel) {\n // We do this to prevent calling complete() unnecessarily\n getterName = NamingBase.Unfix.get_.name();\n } else {\n getterName = NamingBase.getGetterName(value);\n }\n for (MethodMirror m : classMirror.getDirectMethods()) {\n // Do not skip members marked with @Ignore, because the getter is supposed to be ignored\n if (m.getName().equals(getterName)\n && (!toplevel || m.isStatic()) \n && m.getParameters().size() == 0) {\n meth = m;\n break;\n }\n }\n return meth;\n }\n\n private void markVariable(LazyValue value) {\n String setterName = NamingBase.getSetterName(value);\n boolean toplevel = value.isToplevel();\n for (MethodMirror m : value.classMirror.getDirectMethods()) {\n // Do not skip members marked with @Ignore, because the getter is supposed to be ignored\n if (m.getName().equals(setterName)\n && (!toplevel || m.isStatic()) \n && m.getParameters().size() == 1) {\n value.setVariable(true);\n }\n }\n }\n\n private SetterWithLocalDeclarations makeSetter(Value value, ClassMirror classMirror) {\n SetterWithLocalDeclarations setter = new SetterWithLocalDeclarations(classMirror);\n setter.setContainer(value.getContainer());\n setter.setScope(value.getContainer());\n setter.setType(value.getType());\n setter.setName(value.getName());\n Parameter p = new Parameter();\n p.setHidden(true);\n Value v = new Value();\n v.setType(value.getType());\n v.setUnboxed(value.getUnboxed());\n v.setInitializerParameter(p);\n v.setContainer(setter);\n p.setModel(v);\n v.setName(setter.getName());\n p.setName(setter.getName());\n p.setDeclaration(setter);\n setter.setParameter(p);\n value.setSetter(setter);\n setter.setGetter(value);\n return setter;\n }\n\n @Override\n public void complete(LazyFunction method) {\n synchronized(getLock()){\n timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);\n try{\n MethodMirror meth = getFunctionMethodMirror(method);\n if(meth == null || meth.getReturnType() == null){\n method.setType(logModelResolutionError(method.getContainer(), \"Error while resolving toplevel method \"+method.getQualifiedNameString()+\": static method missing\"));\n return;\n }\n // only check the static mod for toplevel classes\n if(!method.classMirror.isLocalClass() && !meth.isStatic()){\n method.setType(logModelResolutionError(method.getContainer(), \"Error while resolving toplevel method \"+method.getQualifiedNameString()+\": method is not static\"));\n return;\n }\n\n method.setDeprecated(method.isDeprecated() | isDeprecated(meth));\n // save the method name\n method.setRealMethodName(meth.getName());\n\n // save the method\n method.setMethodMirror(meth);\n\n // type params first\n setTypeParameters(method, meth, true);\n\n method.setType(obtainType(meth.getReturnType(), meth, method, ModelUtil.getModuleContainer(method), VarianceLocation.COVARIANT,\n \"toplevel method\", method));\n method.setDeclaredVoid(meth.isDeclaredVoid());\n markDeclaredVoid(method, meth);\n markUnboxed(method, meth, meth.getReturnType());\n markTypeErased(method, meth, meth.getReturnType());\n markUntrustedType(method, meth, meth.getReturnType());\n\n // now its parameters\n setParameters(method, method.classMirror, meth, true /* toplevel methods are always Ceylon */, method);\n \n method.setAnnotation(meth.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null);\n setAnnotations(method, meth, method.isNativeHeader());\n\n setAnnotationConstructor(method, meth);\n\n addLocalDeclarations(method, method.classMirror, method.classMirror);\n }finally{\n timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);\n }\n }\n }\n\n private MethodMirror getFunctionMethodMirror(LazyFunction method) {\n MethodMirror meth = null;\n String lookupName = method.getName();\n for(MethodMirror m : method.classMirror.getDirectMethods()){\n // We skip members marked with @Ignore\n if(m.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)\n continue;\n\n if(NamingBase.stripLeadingDollar(m.getName()).equals(lookupName)){\n meth = m;\n break;\n }\n }\n return meth;\n }\n \n // for subclasses\n protected abstract void setAnnotationConstructor(LazyFunction method, MethodMirror meth);\n\n public AnnotationProxyMethod makeInteropAnnotationConstructor(LazyInterface iface,\n AnnotationProxyClass klass, OutputElement oe, Package pkg){\n String ctorName = oe == null ? NamingBase.getJavaBeanName(iface.getName()) : NamingBase.getDisambigAnnoCtorName(iface, oe);\n AnnotationProxyMethod ctor = new AnnotationProxyMethod();\n ctor.setAnnotationTarget(oe);\n ctor.setProxyClass(klass);\n ctor.setContainer(pkg);\n ctor.setAnnotation(true);\n ctor.setName(ctorName);\n ctor.setShared(iface.isShared());\n Annotation annotationAnnotation2 = new Annotation();\n annotationAnnotation2.setName(\"annotation\");\n ctor.getAnnotations().add(annotationAnnotation2);\n ctor.setType(((TypeDeclaration)iface).getType());\n ctor.setUnit(iface.getUnit());\n \n ParameterList ctorpl = new ParameterList();\n ctorpl.setPositionalParametersSupported(false);\n ctor.addParameterList(ctorpl);\n \n List<Parameter> ctorParams = new ArrayList<Parameter>();\n for (Declaration member : iface.getMembers()) {\n boolean isValue = member.getName().equals(\"value\");\n if (member instanceof JavaMethod) {\n JavaMethod m = (JavaMethod)member;\n \n \n Parameter ctorParam = new Parameter();\n ctorParams.add(ctorParam);\n Value value = new Value();\n ctorParam.setModel(value);\n value.setInitializerParameter(ctorParam);\n ctorParam.setDeclaration(ctor);\n value.setContainer(klass);\n value.setScope(klass);\n ctorParam.setDefaulted(m.isDefaultedAnnotation());\n value.setName(member.getName());\n ctorParam.setName(member.getName());\n value.setType(annotationParameterType(iface.getUnit(), m));\n value.setUnboxed(true);\n value.setUnit(iface.getUnit());\n if(isValue)\n ctorpl.getParameters().add(0, ctorParam);\n else\n ctorpl.getParameters().add(ctorParam);\n ctor.addMember(value);\n }\n }\n makeInteropAnnotationConstructorInvocation(ctor, klass, ctorParams);\n return ctor;\n }\n\n /**\n * For subclasses that provide compilation to Java annotations.\n */\n protected abstract void makeInteropAnnotationConstructorInvocation(AnnotationProxyMethod ctor, AnnotationProxyClass klass, List<Parameter> ctorParams);\n \n /**\n * <pre>\n * annotation class Annotation$Proxy(...) satisfies Annotation {\n * // a `shared` class parameter for each method of Annotation\n * }\n * </pre>\n * @param iface The model of the annotation @interface\n * @return The annotation class for the given interface\n */\n public AnnotationProxyClass makeInteropAnnotationClass(\n LazyInterface iface, Package pkg) {\n AnnotationProxyClass klass = new AnnotationProxyClass(iface);\n klass.setContainer(pkg);\n klass.setScope(pkg);\n klass.setName(iface.getName()+\"$Proxy\");\n klass.setShared(iface.isShared());\n klass.setAnnotation(true);\n Annotation annotationAnnotation = new Annotation();\n annotationAnnotation.setName(\"annotation\");\n klass.getAnnotations().add(annotationAnnotation);\n klass.getSatisfiedTypes().add(iface.getType());\n klass.setUnit(iface.getUnit());\n ParameterList classpl = new ParameterList();\n klass.addParameterList(classpl);\n klass.setScope(pkg);\n \n for (Declaration member : iface.getMembers()) {\n boolean isValue = member.getName().equals(\"value\");\n if (member instanceof JavaMethod) {\n JavaMethod m = (JavaMethod)member;\n Parameter klassParam = new Parameter();\n Value value = new Value();\n klassParam.setModel(value);\n value.setInitializerParameter(klassParam);\n klassParam.setDeclaration(klass);\n value.setContainer(klass);\n value.setScope(klass);\n value.setName(member.getName());\n klassParam.setName(member.getName());\n value.setType(annotationParameterType(iface.getUnit(), m));\n value.setUnboxed(true);\n value.setUnit(iface.getUnit());\n if(isValue)\n classpl.getParameters().add(0, klassParam);\n else\n classpl.getParameters().add(klassParam);\n klass.addMember(value);\n }\n }\n return klass;\n }\n\n private Type annotationParameterType(Unit unit, JavaMethod m) {\n Type type = m.getType();\n if (JvmBackendUtil.isJavaArray(type.getDeclaration())) {\n String name = type.getDeclaration().getQualifiedNameString();\n final Type elementType;\n String underlyingType = null;\n if(name.equals(\"java.lang::ObjectArray\")){\n Type eType = type.getTypeArgumentList().get(0);\n String elementTypeName = eType.getDeclaration().getQualifiedNameString();\n if (\"java.lang::String\".equals(elementTypeName)) {\n elementType = unit.getStringType();\n } else if (\"java.lang::Class\".equals(elementTypeName)\n || \"java.lang.Class\".equals(eType.getUnderlyingType())) {\n // Two cases because the types \n // Class[] and Class<?>[] are treated differently by \n // AbstractModelLoader.obtainType()\n \n // TODO Replace with metamodel ClassOrInterface type\n // once we have support for metamodel references\n elementType = unit.getAnythingType();\n underlyingType = \"java.lang.Class\";\n } else {\n elementType = eType; \n }\n // TODO Enum elements\n } else if(name.equals(\"java.lang::LongArray\")) {\n elementType = unit.getIntegerType();\n } else if (name.equals(\"java.lang::ByteArray\")) {\n elementType = unit.getByteType();\n } else if (name.equals(\"java.lang::ShortArray\")) {\n elementType = unit.getIntegerType();\n underlyingType = \"short\";\n } else if (name.equals(\"java.lang::IntArray\")){\n elementType = unit.getIntegerType();\n underlyingType = \"int\";\n } else if(name.equals(\"java.lang::BooleanArray\")){\n elementType = unit.getBooleanType();\n } else if(name.equals(\"java.lang::CharArray\")){\n elementType = unit.getCharacterType();\n underlyingType = \"char\";\n } else if(name.equals(\"java.lang::DoubleArray\")) {\n elementType = unit.getFloatType();\n } else if (name.equals(\"java.lang::FloatArray\")){\n elementType = unit.getFloatType();\n underlyingType = \"float\";\n } else {\n throw new RuntimeException();\n }\n elementType.setUnderlyingType(underlyingType);\n Type iterableType = unit.getIterableType(elementType);\n return iterableType;\n } else if (\"java.lang::Class\".equals(type.getDeclaration().getQualifiedNameString())) {\n // TODO Replace with metamodel ClassOrInterface type\n // once we have support for metamodel references\n return unit.getAnythingType();\n } else {\n return type;\n }\n }\n\n //\n // Satisfied Types\n \n private List<String> getSatisfiedTypesFromAnnotations(AnnotatedMirror symbol) {\n return getAnnotationArrayValue(symbol, CEYLON_SATISFIED_TYPES_ANNOTATION);\n }\n \n private void setSatisfiedTypes(ClassOrInterface klass, ClassMirror classMirror) {\n List<String> satisfiedTypes = getSatisfiedTypesFromAnnotations(classMirror);\n if(satisfiedTypes != null){\n klass.getSatisfiedTypes().addAll(getTypesList(satisfiedTypes, klass, ModelUtil.getModuleContainer(klass), \"satisfied types\", klass.getQualifiedNameString()));\n }else{\n if(classMirror.isAnnotationType())\n // this only happens for Java annotations since Ceylon annotations are ignored\n // turn @Target into a subtype of ConstrainedAnnotation\n klass.getSatisfiedTypes().add(getJavaAnnotationExtendedType(klass, classMirror));\n\n for(TypeMirror iface : classMirror.getInterfaces()){\n // ignore generated interfaces\n if(sameType(iface, CEYLON_REIFIED_TYPE_TYPE) \n || sameType(iface, CEYLON_SERIALIZABLE_TYPE)\n || (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null && sameType(iface, JAVA_IO_SERIALIZABLE_TYPE_TYPE)))\n continue;\n try{\n klass.getSatisfiedTypes().add(getNonPrimitiveType(ModelUtil.getModule(klass), iface, klass, VarianceLocation.INVARIANT));\n }catch(ModelResolutionException x){\n String classPackageName = unquotePackageName(classMirror.getPackage());\n if(JDKUtils.isJDKAnyPackage(classPackageName)){\n if(iface.getKind() == TypeKind.DECLARED){\n // check if it's a JDK thing\n ClassMirror ifaceClass = iface.getDeclaredClass();\n String ifacePackageName = unquotePackageName(ifaceClass.getPackage());\n if(JDKUtils.isOracleJDKAnyPackage(ifacePackageName)){\n // just log and ignore it\n logMissingOracleType(iface.getQualifiedName());\n continue;\n }\n }\n }\n }\n }\n }\n }\n\n //\n // Case Types\n \n private List<String> getCaseTypesFromAnnotations(AnnotatedMirror symbol) {\n return getAnnotationArrayValue(symbol, CEYLON_CASE_TYPES_ANNOTATION);\n }\n \n private String getSelfTypeFromAnnotations(AnnotatedMirror symbol) {\n return getAnnotationStringValue(symbol, CEYLON_CASE_TYPES_ANNOTATION, \"of\");\n }\n\n private void setCaseTypes(ClassOrInterface klass, ClassMirror classMirror) {\n if (classMirror.isEnum()) {\n ArrayList<Type> caseTypes = new ArrayList<Type>();\n for (Declaration member : klass.getMembers()) {\n if (member instanceof FieldValue\n && ((FieldValue) member).isEnumValue()) {\n caseTypes.add(((FieldValue)member).getType());\n }\n }\n klass.setCaseTypes(caseTypes);\n } else {\n String selfType = getSelfTypeFromAnnotations(classMirror);\n Module moduleScope = ModelUtil.getModuleContainer(klass);\n if(selfType != null && !selfType.isEmpty()){\n Type type = decodeType(selfType, klass, moduleScope, \"self type\");\n if(!type.isTypeParameter()){\n logError(\"Invalid type signature for self type of \"+klass.getQualifiedNameString()+\": \"+selfType+\" is not a type parameter\");\n }else{\n klass.setSelfType(type);\n List<Type> caseTypes = new LinkedList<Type>();\n caseTypes.add(type);\n klass.setCaseTypes(caseTypes);\n }\n } else {\n List<String> caseTypes = getCaseTypesFromAnnotations(classMirror);\n if(caseTypes != null && !caseTypes.isEmpty()){\n klass.setCaseTypes(getTypesList(caseTypes, klass, moduleScope, \"case types\", klass.getQualifiedNameString()));\n }\n }\n }\n }\n\n private List<Type> getTypesList(List<String> caseTypes, Scope scope, Module moduleScope, String targetType, String targetName) {\n List<Type> producedTypes = new LinkedList<Type>();\n for(String type : caseTypes){\n producedTypes.add(decodeType(type, scope, moduleScope, targetType));\n }\n return producedTypes;\n }\n\n //\n // Type parameters loading\n\n @SuppressWarnings(\"unchecked\")\n private List<AnnotationMirror> getTypeParametersFromAnnotations(AnnotatedMirror symbol) {\n return (List<AnnotationMirror>) getAnnotationValue(symbol, CEYLON_TYPE_PARAMETERS);\n }\n\n // from our annotation\n private void setTypeParametersFromAnnotations(Scope scope, List<TypeParameter> params, AnnotatedMirror mirror, \n List<AnnotationMirror> typeParameterAnnotations, List<TypeParameterMirror> typeParameterMirrors) {\n // We must first add every type param, before we resolve the bounds, which can\n // refer to type params.\n String selfTypeName = getSelfTypeFromAnnotations(mirror);\n int i=0;\n for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){\n TypeParameter param = new TypeParameter();\n param.setUnit(((Element)scope).getUnit());\n param.setContainer(scope);\n param.setScope(scope);\n ModelUtil.setVisibleScope(param);\n param.setDeclaration((Declaration) scope);\n // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface\n if(scope instanceof LazyContainer)\n ((LazyContainer)scope).addMember(param);\n else // must be a method\n scope.addMember(param);\n param.setName((String)typeParamAnnotation.getValue(\"value\"));\n param.setExtendedType(typeFactory.getAnythingType());\n if(i < typeParameterMirrors.size()){\n TypeParameterMirror typeParameterMirror = typeParameterMirrors.get(i);\n param.setNonErasedBounds(hasNonErasedBounds(typeParameterMirror));\n }\n \n String varianceName = (String) typeParamAnnotation.getValue(\"variance\");\n if(varianceName != null){\n if(varianceName.equals(\"IN\")){\n param.setContravariant(true);\n }else if(varianceName.equals(\"OUT\"))\n param.setCovariant(true);\n }\n \n // If this is a self type param then link it to its type's declaration\n if (param.getName().equals(selfTypeName)) {\n param.setSelfTypedDeclaration((TypeDeclaration)scope);\n }\n \n params.add(param);\n i++;\n }\n\n Module moduleScope = ModelUtil.getModuleContainer(scope);\n // Now all type params have been set, we can resolve the references parts\n Iterator<TypeParameter> paramsIterator = params.iterator();\n for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){\n TypeParameter param = paramsIterator.next();\n \n @SuppressWarnings(\"unchecked\")\n List<String> satisfiesAttribute = (List<String>)typeParamAnnotation.getValue(\"satisfies\");\n setListOfTypes(param.getSatisfiedTypes(), satisfiesAttribute, scope, moduleScope, \n \"type parameter '\"+param.getName()+\"' satisfied types\");\n\n @SuppressWarnings(\"unchecked\")\n List<String> caseTypesAttribute = (List<String>)typeParamAnnotation.getValue(\"caseTypes\");\n if(caseTypesAttribute != null && !caseTypesAttribute.isEmpty())\n param.setCaseTypes(new LinkedList<Type>());\n setListOfTypes(param.getCaseTypes(), caseTypesAttribute, scope, moduleScope,\n \"type parameter '\"+param.getName()+\"' case types\");\n\n String defaultValueAttribute = (String)typeParamAnnotation.getValue(\"defaultValue\");\n if(defaultValueAttribute != null && !defaultValueAttribute.isEmpty()){\n Type decodedType = decodeType(defaultValueAttribute, scope, moduleScope, \n \"type parameter '\"+param.getName()+\"' defaultValue\");\n param.setDefaultTypeArgument(decodedType);\n param.setDefaulted(true);\n }\n }\n }\n\n private boolean hasNonErasedBounds(TypeParameterMirror typeParameterMirror) {\n List<TypeMirror> bounds = typeParameterMirror.getBounds();\n // if we have at least one bound and not a single Object one\n return bounds.size() > 0\n && (bounds.size() != 1\n || !sameType(bounds.get(0), OBJECT_TYPE));\n }\n\n private void setListOfTypes(List<Type> destinationTypeList, List<String> serialisedTypes, Scope scope, Module moduleScope, \n String targetType) {\n if(serialisedTypes != null){\n for (String serialisedType : serialisedTypes) {\n Type decodedType = decodeType(serialisedType, scope, moduleScope, targetType);\n destinationTypeList.add(decodedType);\n }\n }\n }\n\n // from java type info\n private void setTypeParameters(Scope scope, List<TypeParameter> params, List<TypeParameterMirror> typeParameters, boolean isCeylon) {\n // We must first add every type param, before we resolve the bounds, which can\n // refer to type params.\n for(TypeParameterMirror typeParam : typeParameters){\n TypeParameter param = new TypeParameter();\n param.setUnit(((Element)scope).getUnit());\n param.setContainer(scope);\n param.setScope(scope);\n ModelUtil.setVisibleScope(param);\n param.setDeclaration((Declaration) scope);\n // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface\n if(scope instanceof LazyContainer)\n ((LazyContainer)scope).addMember(param);\n else // must be a method\n scope.addMember(param);\n param.setName(typeParam.getName());\n param.setExtendedType(typeFactory.getAnythingType());\n params.add(param);\n }\n boolean needsObjectBounds = !isCeylon && scope instanceof Function;\n // Now all type params have been set, we can resolve the references parts\n Iterator<TypeParameter> paramsIterator = params.iterator();\n for(TypeParameterMirror typeParam : typeParameters){\n TypeParameter param = paramsIterator.next();\n List<TypeMirror> bounds = typeParam.getBounds();\n for(TypeMirror bound : bounds){\n Type boundType;\n // we turn java's default upper bound java.lang.Object into ceylon.language.Object\n if(sameType(bound, OBJECT_TYPE)){\n // avoid adding java's default upper bound if it's just there with no meaning,\n // especially since we do not want it for types\n if(bounds.size() == 1)\n break;\n boundType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT);\n }else\n boundType = getNonPrimitiveType(ModelUtil.getModuleContainer(scope), bound, scope, VarianceLocation.INVARIANT);\n param.getSatisfiedTypes().add(boundType);\n }\n if(needsObjectBounds && param.getSatisfiedTypes().isEmpty()){\n Type boundType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT);\n param.getSatisfiedTypes().add(boundType);\n }\n }\n }\n\n // method\n private void setTypeParameters(Function method, MethodMirror methodMirror, boolean isCeylon) {\n List<TypeParameter> params = new LinkedList<TypeParameter>();\n method.setTypeParameters(params);\n List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(methodMirror);\n if(typeParameters != null) {\n setTypeParametersFromAnnotations(method, params, methodMirror, typeParameters, methodMirror.getTypeParameters());\n } else {\n setTypeParameters(method, params, methodMirror.getTypeParameters(), isCeylon);\n }\n }\n\n // class\n private void setTypeParameters(TypeDeclaration klass, ClassMirror classMirror, boolean isCeylon) {\n List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(classMirror);\n List<TypeParameterMirror> mirrorTypeParameters = classMirror.getTypeParameters();\n if(typeParameters != null) {\n if(typeParameters.isEmpty())\n return;\n List<TypeParameter> params = new ArrayList<TypeParameter>(typeParameters.size());\n klass.setTypeParameters(params);\n setTypeParametersFromAnnotations(klass, params, classMirror, typeParameters, mirrorTypeParameters);\n } else {\n if(mirrorTypeParameters.isEmpty())\n return;\n List<TypeParameter> params = new ArrayList<TypeParameter>(mirrorTypeParameters.size());\n klass.setTypeParameters(params);\n setTypeParameters(klass, params, mirrorTypeParameters, isCeylon);\n }\n } \n\n //\n // TypeParsing and ModelLoader\n\n private Type decodeType(String value, Scope scope, Module moduleScope, String targetType) {\n return decodeType(value, scope, moduleScope, targetType, null);\n }\n \n private Type decodeType(String value, Scope scope, Module moduleScope, String targetType, Declaration target) {\n try{\n return typeParser.decodeType(value, scope, moduleScope, getUnitForModule(moduleScope));\n }catch(TypeParserException x){\n String text = formatTypeErrorMessage(\"Error while parsing type of\", targetType, target, scope);\n return logModelResolutionException(x.getMessage(), scope, text);\n }catch(ModelResolutionException x){\n String text = formatTypeErrorMessage(\"Error while resolving type of\", targetType, target, scope);\n return logModelResolutionException(x, scope, text);\n }\n }\n \n private Unit getUnitForModule(Module module) {\n List<Package> packages = module.getPackages();\n if(packages.isEmpty()){\n System.err.println(\"No package for module \"+module.getNameAsString());\n return null;\n }\n Package pkg = packages.get(0);\n if(pkg instanceof LazyPackage == false){\n System.err.println(\"No lazy package for module \"+module.getNameAsString());\n return null;\n }\n Unit unit = getCompiledUnit((LazyPackage) pkg, null);\n if(unit == null){\n System.err.println(\"No unit for module \"+module.getNameAsString());\n return null;\n }\n return unit;\n }\n \n private String formatTypeErrorMessage(String prefix, String targetType, Declaration target, Scope scope) {\n String forTarget;\n if(target != null)\n forTarget = \" for \"+target.getQualifiedNameString();\n else if(scope != null)\n forTarget = \" for \"+scope.getQualifiedNameString();\n else\n forTarget = \"\";\n return prefix+\" \"+targetType+forTarget;\n }\n\n /** Warning: only valid for toplevel types, not for type parameters */\n private Type obtainType(TypeMirror type, AnnotatedMirror symbol, Scope scope, Module moduleScope, VarianceLocation variance, \n String targetType, Declaration target) {\n String typeName = getAnnotationStringValue(symbol, CEYLON_TYPE_INFO_ANNOTATION);\n if (typeName != null) {\n Type ret = decodeType(typeName, scope, moduleScope, targetType, target);\n // even decoded types need to fit with the reality of the underlying type\n ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TOPLEVEL));\n return ret;\n } else {\n try{\n return obtainType(moduleScope, type, scope, TypeLocation.TOPLEVEL, variance);\n }catch(ModelResolutionException x){\n String text = formatTypeErrorMessage(\"Error while resolving type of\", targetType, target, scope);\n return logModelResolutionException(x, scope, text);\n }\n }\n }\n \n private enum TypeLocation {\n TOPLEVEL, TYPE_PARAM;\n }\n \n private enum VarianceLocation {\n /**\n * Used in parameter\n */\n CONTRAVARIANT,\n /**\n * Used in method return value\n */\n COVARIANT,\n /**\n * For field\n */\n INVARIANT;\n }\n\n private String getUnderlyingType(TypeMirror type, TypeLocation location){\n // don't erase to c.l.String if in a type param location\n if ((sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM)\n || sameType(type, PRIM_BYTE_TYPE)\n || sameType(type, PRIM_SHORT_TYPE)\n || sameType(type, PRIM_INT_TYPE)\n || sameType(type, PRIM_FLOAT_TYPE)\n || sameType(type, PRIM_CHAR_TYPE)) {\n return type.getQualifiedName();\n }\n return null;\n }\n \n public Type obtainType(Module moduleScope, TypeMirror type, Scope scope, TypeLocation location, VarianceLocation variance) {\n TypeMirror originalType = type;\n // ERASURE\n type = applyTypeMapping(type, location);\n \n Type ret = getNonPrimitiveType(moduleScope, type, scope, variance);\n if (ret.getUnderlyingType() == null) {\n ret.setUnderlyingType(getUnderlyingType(originalType, location));\n }\n return ret;\n }\n \n private TypeMirror applyTypeMapping(TypeMirror type, TypeLocation location) {\n // don't erase to c.l.String if in a type param location\n if (sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) {\n return CEYLON_STRING_TYPE;\n \n } else if (sameType(type, PRIM_BOOLEAN_TYPE)) {\n return CEYLON_BOOLEAN_TYPE;\n \n } else if (sameType(type, PRIM_BYTE_TYPE)) {\n return CEYLON_BYTE_TYPE;\n \n } else if (sameType(type, PRIM_SHORT_TYPE)) {\n return CEYLON_INTEGER_TYPE;\n \n } else if (sameType(type, PRIM_INT_TYPE)) {\n return CEYLON_INTEGER_TYPE;\n \n } else if (sameType(type, PRIM_LONG_TYPE)) {\n return CEYLON_INTEGER_TYPE;\n \n } else if (sameType(type, PRIM_FLOAT_TYPE)) {\n return CEYLON_FLOAT_TYPE;\n \n } else if (sameType(type, PRIM_DOUBLE_TYPE)) {\n return CEYLON_FLOAT_TYPE;\n \n } else if (sameType(type, PRIM_CHAR_TYPE)) {\n return CEYLON_CHARACTER_TYPE;\n \n } else if (sameType(type, OBJECT_TYPE)) {\n return CEYLON_OBJECT_TYPE;\n \n } else if (sameType(type, THROWABLE_TYPE)) {\n return CEYLON_THROWABLE_TYPE;\n \n } else if (sameType(type, EXCEPTION_TYPE)) {\n return CEYLON_EXCEPTION_TYPE;\n \n } else if (sameType(type, ANNOTATION_TYPE)) {\n // here we prefer Annotation over ConstrainedAnnotation but that's fine\n return CEYLON_ANNOTATION_TYPE;\n \n } else if (type.getKind() == TypeKind.ARRAY) {\n\n TypeMirror ct = type.getComponentType();\n \n if (sameType(ct, PRIM_BOOLEAN_TYPE)) {\n return JAVA_BOOLEAN_ARRAY_TYPE;\n } else if (sameType(ct, PRIM_BYTE_TYPE)) {\n return JAVA_BYTE_ARRAY_TYPE;\n } else if (sameType(ct, PRIM_SHORT_TYPE)) {\n return JAVA_SHORT_ARRAY_TYPE;\n } else if (sameType(ct, PRIM_INT_TYPE)) { \n return JAVA_INT_ARRAY_TYPE;\n } else if (sameType(ct, PRIM_LONG_TYPE)) { \n return JAVA_LONG_ARRAY_TYPE;\n } else if (sameType(ct, PRIM_FLOAT_TYPE)) {\n return JAVA_FLOAT_ARRAY_TYPE;\n } else if (sameType(ct, PRIM_DOUBLE_TYPE)) {\n return JAVA_DOUBLE_ARRAY_TYPE;\n } else if (sameType(ct, PRIM_CHAR_TYPE)) {\n return JAVA_CHAR_ARRAY_TYPE;\n } else {\n // object array\n return new SimpleReflType(JAVA_LANG_OBJECT_ARRAY, SimpleReflType.Module.JDK, TypeKind.DECLARED, ct);\n }\n }\n return type;\n }\n \n private boolean sameType(TypeMirror t1, TypeMirror t2) {\n // make sure we deal with arrays which can't have a qualified name\n if(t1.getKind() == TypeKind.ARRAY){\n if(t2.getKind() != TypeKind.ARRAY)\n return false;\n return sameType(t1.getComponentType(), t2.getComponentType());\n }\n if(t2.getKind() == TypeKind.ARRAY)\n return false;\n // the rest should be OK\n return t1.getQualifiedName().equals(t2.getQualifiedName());\n }\n \n @Override\n public Declaration getDeclaration(Module module, String typeName, DeclarationType declarationType) {\n return convertToDeclaration(module, typeName, declarationType);\n }\n\n private Type getNonPrimitiveType(Module moduleScope, TypeMirror type, Scope scope, VarianceLocation variance) {\n TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(moduleScope, type, scope, DeclarationType.TYPE);\n if(declaration == null){\n throw new ModelResolutionException(\"Failed to find declaration for \"+type.getQualifiedName());\n }\n return applyTypeArguments(moduleScope, declaration, type, scope, variance, TypeMappingMode.NORMAL, null);\n }\n\n private enum TypeMappingMode {\n NORMAL, GENERATOR\n }\n \n @SuppressWarnings(\"serial\")\n private static class RecursiveTypeParameterBoundException extends RuntimeException {}\n \n private Type applyTypeArguments(Module moduleScope, TypeDeclaration declaration,\n TypeMirror type, Scope scope, VarianceLocation variance,\n TypeMappingMode mode, Set<TypeDeclaration> rawDeclarationsSeen) {\n List<TypeMirror> javacTypeArguments = type.getTypeArguments();\n boolean hasTypeParameters = !declaration.getTypeParameters().isEmpty();\n boolean hasTypeArguments = !javacTypeArguments.isEmpty();\n boolean isRaw = !hasTypeArguments && hasTypeParameters;\n // if we have type arguments or type parameters (raw)\n if(hasTypeArguments || isRaw){\n // if it's raw we will need the map anyways\n if(rawDeclarationsSeen == null)\n rawDeclarationsSeen = new HashSet<TypeDeclaration>();\n // detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>>\n if(rawDeclarationsSeen != null && !rawDeclarationsSeen.add(declaration))\n throw new RecursiveTypeParameterBoundException();\n try{\n List<Type> typeArguments = new ArrayList<Type>(javacTypeArguments.size());\n List<TypeParameter> typeParameters = declaration.getTypeParameters();\n List<TypeParameterMirror> typeParameterMirrors = null;\n // SimpleReflType for Object and friends don't have a type, but don't need one\n if(type.getDeclaredClass() != null)\n typeParameterMirrors = type.getDeclaredClass().getTypeParameters();\n Map<TypeParameter,SiteVariance> siteVarianceMap = null;\n int len = hasTypeArguments ? javacTypeArguments.size() : typeParameters.size();\n for(int i=0 ; i<len ; i++){\n TypeParameter typeParameter = null;\n if(i < typeParameters.size())\n typeParameter = typeParameters.get(i);\n Type producedTypeArgument = null;\n // do we have a type argument?\n TypeMirror typeArgument = null;\n SiteVariance siteVariance = null;\n if(hasTypeArguments){\n typeArgument = javacTypeArguments.get(i);\n // if a single type argument is a wildcard and we are in a covariant location, we erase to Object\n if(typeArgument.getKind() == TypeKind.WILDCARD){\n \n TypeMirror bound = typeArgument.getUpperBound();\n if(bound != null){\n siteVariance = SiteVariance.OUT;\n } else {\n bound = typeArgument.getLowerBound();\n if(bound != null){\n // it has a lower bound\n siteVariance = SiteVariance.IN;\n }\n }\n // use the bound in any case\n typeArgument = bound;\n }\n }\n // if we have no type argument, or if it's a wildcard with no bound, use the type parameter bounds if we can\n if(typeArgument == null && typeParameterMirrors != null && i < typeParameterMirrors.size()){\n TypeParameterMirror typeParameterMirror = typeParameterMirrors.get(i);\n // FIXME: multiple bounds?\n if(typeParameterMirror.getBounds().size() == 1){\n // make sure we don't go overboard\n if(rawDeclarationsSeen == null){\n rawDeclarationsSeen = new HashSet<TypeDeclaration>();\n // detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>>\n if(!rawDeclarationsSeen.add(declaration))\n throw new RecursiveTypeParameterBoundException();\n }\n TypeMirror bound = typeParameterMirror.getBounds().get(0);\n try{\n producedTypeArgument = obtainTypeParameterBound(moduleScope, bound, declaration, rawDeclarationsSeen);\n siteVariance = SiteVariance.OUT;\n }catch(RecursiveTypeParameterBoundException x){\n // damnit, go for Object later\n }\n } \n }\n\n // if we have no type argument, or it was a wildcard with no bounds and we could not use the type parameter bounds,\n // let's fall back to \"out Object\"\n if(typeArgument == null && producedTypeArgument == null){\n producedTypeArgument = typeFactory.getObjectType();\n siteVariance = SiteVariance.OUT;\n }\n\n // record use-site variance if required\n if(!JvmBackendUtil.isCeylon(declaration) && siteVariance != null){\n // lazy alloc\n if(siteVarianceMap == null)\n siteVarianceMap = new HashMap<TypeParameter,SiteVariance>();\n siteVarianceMap.put(typeParameter, siteVariance);\n }\n \n // in some cases we may already have a produced type argument we can use. if not let's fetch it\n if(producedTypeArgument == null){\n if(mode == TypeMappingMode.NORMAL)\n producedTypeArgument = obtainType(moduleScope, typeArgument, scope, TypeLocation.TYPE_PARAM, variance);\n else\n producedTypeArgument = obtainTypeParameterBound(moduleScope, typeArgument, scope, rawDeclarationsSeen);\n }\n typeArguments.add(producedTypeArgument);\n }\n Type qualifyingType = null;\n if(type.getQualifyingType() != null){\n qualifyingType = getNonPrimitiveType(moduleScope, type.getQualifyingType(), scope, variance);\n }\n Type ret = declaration.appliedType(qualifyingType, typeArguments);\n if(siteVarianceMap != null){\n ret.setVarianceOverrides(siteVarianceMap);\n }\n ret.setUnderlyingType(type.getQualifiedName());\n ret.setRaw(isRaw);\n\n return ret;\n }finally{\n if(rawDeclarationsSeen != null)\n rawDeclarationsSeen.remove(declaration);\n }\n }\n // we have no type args, but perhaps we have a qualifying type which has some?\n if(type.getQualifyingType() != null){\n // that one may have type arguments\n Type qualifyingType = getNonPrimitiveType(moduleScope, type.getQualifyingType(), scope, variance);\n Type ret = declaration.appliedType(qualifyingType, Collections.<Type>emptyList());\n ret.setUnderlyingType(type.getQualifiedName());\n ret.setRaw(isRaw);\n return ret;\n }\n // no type arg and no qualifying type\n return declaration.getType();\n }\n\n private Type obtainTypeParameterBound(Module moduleScope, TypeMirror type, Scope scope, Set<TypeDeclaration> rawDeclarationsSeen) {\n // type variables are never mapped\n if(type.getKind() == TypeKind.TYPEVAR){\n TypeParameterMirror typeParameter = type.getTypeParameter();\n if(!typeParameter.getBounds().isEmpty()){\n List<Type> bounds = new ArrayList<Type>(typeParameter.getBounds().size());\n for(TypeMirror bound : typeParameter.getBounds()){\n Type boundModel = obtainTypeParameterBound(moduleScope, bound, scope, rawDeclarationsSeen);\n bounds.add(boundModel);\n }\n return intersection(bounds, getUnitForModule(moduleScope));\n }else\n // no bound is Object\n return typeFactory.getObjectType();\n }else{\n TypeMirror mappedType = applyTypeMapping(type, TypeLocation.TYPE_PARAM);\n\n TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(moduleScope, mappedType, scope, DeclarationType.TYPE);\n if(declaration == null){\n throw new RuntimeException(\"Failed to find declaration for \"+type);\n }\n if(declaration instanceof UnknownType)\n return declaration.getType();\n\n Type ret = applyTypeArguments(moduleScope, declaration, type, scope, VarianceLocation.CONTRAVARIANT, TypeMappingMode.GENERATOR, rawDeclarationsSeen);\n \n if (ret.getUnderlyingType() == null) {\n ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TYPE_PARAM));\n }\n return ret;\n }\n }\n \n /*private Type getQualifyingType(TypeDeclaration declaration) {\n // As taken from Type.getType():\n if (declaration.isMember()) {\n return((ClassOrInterface) declaration.getContainer()).getType();\n }\n return null;\n }*/\n\n @Override\n public Type getType(Module module, String pkgName, String name, Scope scope) {\n Declaration decl = getDeclaration(module, pkgName, name, scope);\n if(decl == null)\n return null;\n if(decl instanceof TypeDeclaration)\n return ((TypeDeclaration) decl).getType();\n // it's a method or non-object value, but it's not a type\n return null;\n }\n\n @Override\n public Declaration getDeclaration(Module module, String pkgName, String name, Scope scope) {\n synchronized(getLock()){\n if(scope != null){\n TypeParameter typeParameter = lookupTypeParameter(scope, name);\n if(typeParameter != null)\n return typeParameter;\n }\n if(!isBootstrap || !name.startsWith(CEYLON_LANGUAGE)) {\n if(scope != null && pkgName != null){\n Package containingPackage = ModelUtil.getPackageContainer(scope);\n Package pkg = containingPackage.getModule().getPackage(pkgName);\n String relativeName = null;\n String unquotedName = name.replace(\"$\", \"\");\n if(!pkgName.isEmpty()){\n if(unquotedName.startsWith(pkgName+\".\"))\n relativeName = unquotedName.substring(pkgName.length()+1);\n // else we don't try it's not in this package\n }else\n relativeName = unquotedName;\n if(relativeName != null && pkg != null){\n Declaration declaration = pkg.getDirectMember(relativeName, null, false);\n // if we get a value, we want its type\n if(JvmBackendUtil.isValue(declaration)\n && ((Value)declaration).getTypeDeclaration().getName().equals(relativeName))\n declaration = ((Value)declaration).getTypeDeclaration();\n if(declaration != null)\n return declaration;\n }\n }\n return convertToDeclaration(module, name, DeclarationType.TYPE);\n }\n\n return findLanguageModuleDeclarationForBootstrap(name);\n }\n }\n\n private Declaration findLanguageModuleDeclarationForBootstrap(String name) {\n // make sure we don't return anything for ceylon.language\n if(name.equals(CEYLON_LANGUAGE))\n return null;\n \n // we're bootstrapping ceylon.language so we need to return the ProducedTypes straight from the model we're compiling\n Module languageModule = modules.getLanguageModule();\n \n int lastDot = name.lastIndexOf(\".\");\n if(lastDot == -1)\n return null;\n String pkgName = name.substring(0, lastDot);\n String simpleName = name.substring(lastDot+1);\n // Nothing is a special case with no real decl\n if(name.equals(\"ceylon.language.Nothing\"))\n return typeFactory.getNothingDeclaration();\n\n // find the right package\n Package pkg = languageModule.getDirectPackage(pkgName);\n if(pkg != null){\n Declaration member = pkg.getDirectMember(simpleName, null, false);\n // if we get a value, we want its type\n if(JvmBackendUtil.isValue(member)\n && ((Value)member).getTypeDeclaration().getName().equals(simpleName)){\n member = ((Value)member).getTypeDeclaration();\n }\n if(member != null)\n return member;\n }\n throw new ModelResolutionException(\"Failed to look up given type in language module while bootstrapping: \"+name);\n }\n\n public ClassMirror[] getClassMirrorsToRemove(com.redhat.ceylon.model.typechecker.model.Declaration declaration) {\n if(declaration instanceof LazyClass){\n return new ClassMirror[] { ((LazyClass) declaration).classMirror };\n }\n if(declaration instanceof LazyInterface){\n LazyInterface lazyInterface = (LazyInterface) declaration;\n if (lazyInterface.companionClass != null) {\n return new ClassMirror[] { lazyInterface.classMirror, lazyInterface.companionClass };\n } else {\n return new ClassMirror[] { lazyInterface.classMirror };\n }\n }\n if(declaration instanceof LazyFunction){\n return new ClassMirror[] { ((LazyFunction) declaration).classMirror };\n }\n if(declaration instanceof LazyValue){\n return new ClassMirror[] { ((LazyValue) declaration).classMirror };\n }\n if (declaration instanceof LazyClassAlias) {\n return new ClassMirror[] { ((LazyClassAlias) declaration).classMirror };\n }\n if (declaration instanceof LazyInterfaceAlias) {\n return new ClassMirror[] { ((LazyInterfaceAlias) declaration).classMirror };\n }\n if (declaration instanceof LazyTypeAlias) {\n return new ClassMirror[] { ((LazyTypeAlias) declaration).classMirror };\n }\n return new ClassMirror[0];\n }\n \n public void removeDeclarations(List<Declaration> declarations) {\n synchronized(getLock()){\n Set<String> qualifiedNames = new HashSet<>(declarations.size() * 2);\n \n // keep in sync with getOrCreateDeclaration\n for (Declaration decl : declarations) {\n try {\n ClassMirror[] classMirrors = getClassMirrorsToRemove(decl);\n if (classMirrors == null || classMirrors.length == 0) {\n continue;\n }\n \n Scope container = decl.getContainer();\n boolean isNativeHeaderMember = container instanceof Declaration \n && ((Declaration) container).isNativeHeader();\n \n Map<String, Declaration> firstCache = null;\n Map<String, Declaration> secondCache = null;\n if(decl.isToplevel()){\n if(JvmBackendUtil.isValue(decl)){\n firstCache = valueDeclarationsByName;\n TypeDeclaration typeDeclaration = ((Value)decl).getTypeDeclaration();\n if (typeDeclaration != null) {\n if(typeDeclaration.isAnonymous()) {\n secondCache = typeDeclarationsByName;\n }\n } else {\n // The value declaration has probably not been fully loaded yet.\n // => still try to clean the second cache also, just in case it is an anonymous object\n secondCache = typeDeclarationsByName;\n }\n }else if(JvmBackendUtil.isMethod(decl)) {\n firstCache = valueDeclarationsByName;\n }\n }\n if(decl instanceof ClassOrInterface){\n firstCache = typeDeclarationsByName;\n }\n\n Module module = ModelUtil.getModuleContainer(decl.getContainer());\n // ignore declarations which we do not cache, like member method/attributes\n\n for (ClassMirror classMirror : classMirrors) {\n qualifiedNames.add(classMirror.getQualifiedName());\n String key = classMirror.getCacheKey(module);\n key = isNativeHeaderMember ? key + \"$header\" : key;\n\n if(firstCache != null) {\n if (firstCache.remove(key) == null) {\n System.out.println(\"No non-null declaration removed from the first cache for key : \" + key);\n }\n\n if(secondCache != null) {\n if (secondCache.remove(key) == null) {\n System.out.println(\"No non-null declaration removed from the second cache for key : \" + key);\n }\n }\n }\n }\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n \n List<String> keysToRemove = new ArrayList<>(qualifiedNames.size());\n for (Map.Entry<String, ClassMirror> entry : classMirrorCache.entrySet()) {\n ClassMirror mirror = entry.getValue();\n if (mirror == null \n || qualifiedNames.contains(mirror.getQualifiedName())) {\n keysToRemove.add(entry.getKey());\n }\n }\n\n for (String keyToRemove : keysToRemove) {\n classMirrorCache.remove(keyToRemove);\n }\n }\n }\n\n private static class Stats{\n int loaded, total;\n }\n\n private int inspectForStats(Map<String,Declaration> cache, Map<Package, Stats> loadedByPackage){\n int loaded = 0;\n for(Declaration decl : cache.values()){\n if(decl instanceof LazyElement){\n Package pkg = getPackage(decl);\n if(pkg == null){\n logVerbose(\"[Model loader stats: declaration \"+decl.getName()+\" has no package. Skipping.]\");\n continue;\n }\n Stats stats = loadedByPackage.get(pkg);\n if(stats == null){\n stats = new Stats();\n loadedByPackage.put(pkg, stats);\n }\n stats.total++;\n if(((LazyElement)decl).isLoaded()){\n loaded++;\n stats.loaded++;\n }\n }\n }\n return loaded;\n }\n\n public void printStats() {\n synchronized(getLock()){\n Map<Package, Stats> loadedByPackage = new HashMap<Package, Stats>();\n int loaded = inspectForStats(typeDeclarationsByName, loadedByPackage)\n + inspectForStats(valueDeclarationsByName, loadedByPackage);\n logVerbose(\"[Model loader: \"+loaded+\"(loaded)/\"+(typeDeclarationsByName.size()+valueDeclarationsByName.size())+\"(total) declarations]\");\n for(Entry<Package, Stats> packageEntry : loadedByPackage.entrySet()){\n logVerbose(\"[ Package \"+packageEntry.getKey().getNameAsString()+\": \"\n +packageEntry.getValue().loaded+\"(loaded)/\"+packageEntry.getValue().total+\"(total) declarations]\");\n }\n }\n }\n\n private static Package getPackage(Object decl) {\n if(decl == null)\n return null;\n if(decl instanceof Package)\n return (Package) decl;\n return getPackage(((Declaration)decl).getContainer());\n }\n \n protected void logMissingOracleType(String type) {\n logVerbose(\"Hopefully harmless completion failure in model loader: \"+type\n +\". This is most likely when the JDK depends on Oracle private classes that we can't find.\"\n +\" As a result some model information will be incomplete.\");\n }\n\n public void setupSourceFileObjects(List<?> treeHolders) {\n }\n\n public static boolean isJDKModule(String name) {\n return JDKUtils.isJDKModule(name)\n || JDKUtils.isOracleJDKModule(name);\n }\n \n @Override\n public Module getLoadedModule(String moduleName, String version) {\n return findModule(moduleName, version);\n }\n\n public Module getLanguageModule() {\n return modules.getLanguageModule();\n }\n\n public Module findModule(String name, String version){\n return moduleManager.findLoadedModule(name, version);\n }\n \n public Module getJDKBaseModule() {\n return findModule(JAVA_BASE_MODULE_NAME, JDKUtils.jdk.version);\n }\n\n public Module findModuleForFile(File file){\n File path = file.getParentFile();\n while (path != null) {\n String name = path.getPath().replaceAll(\"[\\\\\\\\/]\", \".\");\n // FIXME: this would load any version of this module\n Module m = getLoadedModule(name, null);\n if (m != null) {\n return m;\n }\n path = path.getParentFile();\n }\n return modules.getDefaultModule();\n }\n\n public abstract Module findModuleForClassMirror(ClassMirror classMirror);\n \n protected boolean isTypeHidden(Module module, String qualifiedName){\n return module.getNameAsString().equals(JAVA_BASE_MODULE_NAME)\n && qualifiedName.equals(\"java.lang.Object\");\n }\n \n public Package findPackage(String quotedPkgName) {\n synchronized(getLock()){\n String pkgName = quotedPkgName.replace(\"$\", \"\");\n // in theory we only have one package with the same name per module in javac\n for(Package pkg : packagesByName.values()){\n if(pkg.getNameAsString().equals(pkgName))\n return pkg;\n }\n return null;\n }\n }\n\n /**\n * See explanation in cacheModulelessPackages() below. This is called by LanguageCompiler during loadCompiledModules().\n */\n public LazyPackage findOrCreateModulelessPackage(String pkgName) {\n synchronized(getLock()){\n LazyPackage pkg = modulelessPackages.get(pkgName);\n if(pkg != null)\n return pkg;\n pkg = new LazyPackage(this);\n // FIXME: some refactoring needed\n pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split(\"\\\\.\")));\n modulelessPackages.put(pkgName, pkg);\n return pkg;\n }\n }\n \n /**\n * Stef: this sucks balls, but the typechecker wants Packages created before we have any Module set up, including for parsing a module\n * file, and because the model loader looks up packages and caches them using their modules, we can't really have packages before we\n * have modules. Rather than rewrite the typechecker, we create moduleless packages during parsing, which means they are not cached with\n * their modules, and after the loadCompiledModules step above, we fix the package modules. Remains to be done is to move the packages\n * created from their cache to the right per-module cache.\n */\n public void cacheModulelessPackages() {\n synchronized(getLock()){\n for(LazyPackage pkg : modulelessPackages.values()){\n String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkg.getQualifiedNameString());\n if (pkg.getModule() != null) {\n packagesByName.put(cacheKeyByModule(pkg.getModule(), quotedPkgName), pkg);\n }\n }\n modulelessPackages.clear();\n }\n }\n\n /**\n * Stef: after a lot of attempting, I failed to make the CompilerModuleManager produce a LazyPackage when the ModuleManager.initCoreModules\n * is called for the default package. Because it is called by the PhasedUnits constructor, which is called by the ModelLoader constructor,\n * which means the model loader is not yet in the context, so the CompilerModuleManager can't obtain it to pass it to the LazyPackage\n * constructor. A rewrite of the logic of the typechecker scanning would fix this, but at this point it's just faster to let it create\n * the wrong default package and fix it before we start parsing anything.\n */\n public void fixDefaultPackage() {\n synchronized(getLock()){\n Module defaultModule = modules.getDefaultModule();\n Package defaultPackage = defaultModule.getDirectPackage(\"\");\n if(defaultPackage instanceof LazyPackage == false){\n LazyPackage newPkg = findOrCreateModulelessPackage(\"\");\n List<Package> defaultModulePackages = defaultModule.getPackages();\n if(defaultModulePackages.size() != 1)\n throw new RuntimeException(\"Assertion failed: default module has more than the default package: \"+defaultModulePackages.size());\n defaultModulePackages.clear();\n defaultModulePackages.add(newPkg);\n newPkg.setModule(defaultModule);\n defaultPackage.setModule(null);\n }\n }\n }\n\n public boolean isImported(Module moduleScope, Module importedModule) {\n if(ModelUtil.equalModules(moduleScope, importedModule))\n return true;\n if(isImportedSpecialRules(moduleScope, importedModule))\n return true;\n boolean isMaven = isAutoExportMavenDependencies() && isMavenModule(moduleScope);\n if(isMaven && isMavenModule(importedModule))\n return true;\n Set<Module> visited = new HashSet<Module>();\n visited.add(moduleScope);\n for(ModuleImport imp : moduleScope.getImports()){\n if(ModelUtil.equalModules(imp.getModule(), importedModule))\n return true;\n if((imp.isExport() || isMaven) && isImportedTransitively(imp.getModule(), importedModule, visited))\n return true;\n }\n return false;\n }\n\n private boolean isMavenModule(Module moduleScope) {\n return moduleScope.isJava() && ModuleUtil.isMavenModule(moduleScope.getNameAsString());\n }\n \n private boolean isImportedSpecialRules(Module moduleScope, Module importedModule) {\n String importedModuleName = importedModule.getNameAsString();\n // every Java module imports the JDK\n // ceylon.language imports the JDK\n if((moduleScope.isJava()\n || ModelUtil.equalModules(moduleScope, getLanguageModule()))\n && (JDKUtils.isJDKModule(importedModuleName)\n || JDKUtils.isOracleJDKModule(importedModuleName)))\n return true;\n // everyone imports the language module\n if(ModelUtil.equalModules(importedModule, getLanguageModule()))\n return true;\n if(ModelUtil.equalModules(moduleScope, getLanguageModule())){\n // this really sucks, I suppose we should set that up better somewhere else\n if((importedModuleName.equals(\"com.redhat.ceylon.compiler.java\")\n || importedModuleName.equals(\"com.redhat.ceylon.typechecker\")\n || importedModuleName.equals(\"com.redhat.ceylon.common\")\n || importedModuleName.equals(\"com.redhat.ceylon.model\")\n || importedModuleName.equals(\"com.redhat.ceylon.module-resolver\"))\n && importedModule.getVersion().equals(Versions.CEYLON_VERSION_NUMBER))\n return true;\n if(importedModuleName.equals(\"org.jboss.modules\")\n && importedModule.getVersion().equals(Versions.DEPENDENCY_JBOSS_MODULES_VERSION))\n return true;\n }\n return false;\n }\n \n private boolean isImportedTransitively(Module moduleScope, Module importedModule, Set<Module> visited) {\n if(!visited.add(moduleScope))\n return false;\n boolean isMaven = isAutoExportMavenDependencies() && isMavenModule(moduleScope);\n for(ModuleImport imp : moduleScope.getImports()){\n // only consider exported transitive deps\n if(!imp.isExport() && !isMaven)\n continue;\n if(ModelUtil.equalModules(imp.getModule(), importedModule))\n return true;\n if(isImportedSpecialRules(imp.getModule(), importedModule))\n return true;\n if(isImportedTransitively(imp.getModule(), importedModule, visited))\n return true;\n }\n return false;\n }\n\n protected boolean isModuleOrPackageDescriptorName(String name) {\n return name.equals(NamingBase.MODULE_DESCRIPTOR_CLASS_NAME) || name.equals(NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME);\n }\n \n protected void loadJavaBaseArrays(){\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE);\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_BOOLEAN_ARRAY, DeclarationType.TYPE);\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_BYTE_ARRAY, DeclarationType.TYPE);\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_SHORT_ARRAY, DeclarationType.TYPE);\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_INT_ARRAY, DeclarationType.TYPE);\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_LONG_ARRAY, DeclarationType.TYPE);\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_FLOAT_ARRAY, DeclarationType.TYPE);\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_DOUBLE_ARRAY, DeclarationType.TYPE);\n convertToDeclaration(getJDKBaseModule(), JAVA_LANG_CHAR_ARRAY, DeclarationType.TYPE);\n }\n \n /**\n * To be overridden by subclasses, defaults to false.\n */\n protected boolean isAutoExportMavenDependencies(){\n return false;\n }\n\n /**\n * To be overridden by subclasses, defaults to false.\n */\n protected boolean isFlatClasspath(){\n return false;\n }\n\n private static void setDeclarationAliases(Declaration decl, AnnotatedMirror mirror){\n AnnotationMirror annot = mirror.getAnnotation(AbstractModelLoader.CEYLON_LANGUAGE_ALIASES_ANNOTATION);\n if (annot != null) {\n @SuppressWarnings(\"unchecked\")\n List<String> value = (List<String>) annot.getValue(\"aliases\");\n if(value != null && !value.isEmpty())\n decl.setAliases(value);\n }\n }\n}",
"public interface ContentAwareArtifactResult extends ArtifactResult {\n Collection<String> getPackages();\n Collection<String> getEntries();\n byte[] getContents(String path);\n URI getContentUri(String path);\n List<String> getFileNames(String path);\n}",
"public class JvmBackendUtil {\n public static boolean isInitialLowerCase(String name) {\n return !name.isEmpty() && isLowerCase(name.codePointAt(0));\n }\n\n public static boolean isLowerCase(int codepoint) {\n return Character.isLowerCase(codepoint) || codepoint == '_';\n }\n\n public static String getName(List<String> parts){\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < parts.size(); i++) {\n sb.append(parts.get(i));\n if (i < parts.size() - 1) {\n sb.append('.');\n }\n }\n return sb.toString();\n }\n\n public static String getMirrorName(AnnotatedMirror mirror) {\n String name;\n AnnotationMirror annot = mirror.getAnnotation(AbstractModelLoader.CEYLON_NAME_ANNOTATION);\n if (annot != null) {\n name = (String)annot.getValue();\n } else {\n name = mirror.getName();\n name = name.isEmpty() ? name : NamingBase.stripLeadingDollar(name);\n if (mirror instanceof ClassMirror\n && JvmBackendUtil.isInitialLowerCase(name)\n && name.endsWith(\"_\")\n && mirror.getAnnotation(AbstractModelLoader.CEYLON_CEYLON_ANNOTATION) != null) {\n name = name.substring(0, name.length()-1);\n }\n }\n return name;\n }\n\n public static boolean isSubPackage(String moduleName, String pkgName) {\n return pkgName.equals(moduleName)\n || pkgName.startsWith(moduleName+\".\");\n }\n\n /**\n * Removes the given character from the given string. More efficient than using String.replace\n * which uses regexes.\n */\n public static String removeChar(char c, String string) {\n int nextChar = string.indexOf(c);\n if(nextChar == -1)\n return string;\n int start = 0;\n StringBuilder ret = new StringBuilder(string.length()-1);// we remove at least one\n while(nextChar != -1){\n ret.append(string, start, nextChar);\n start = nextChar+1;\n nextChar = string.indexOf(c, start);\n }\n // don't forget the end part\n ret.append(string, start, string.length());\n return ret.toString();\n }\n\n public static String strip(String name, boolean isCeylon, boolean isShared) {\n String stripped = NamingBase.stripLeadingDollar(name);\n String privSuffix = NamingBase.Suffix.$priv$.name();\n if(isCeylon && !isShared && name.endsWith(privSuffix))\n return stripped.substring(0, stripped.length() - privSuffix.length());\n return stripped;\n }\n\n /**\n * Determines whether the declaration is a non-transient non-parameter value \n * (not a getter)\n * @param decl The declaration\n * @return true if the declaration is a value\n */\n public static boolean isValue(Declaration decl) {\n return (decl instanceof Value)\n && !((Value)decl).isParameter()\n && !((Value)decl).isTransient();\n }\n\n /**\n * Determines whether the declaration's is a method\n * @param decl The declaration\n * @return true if the declaration is a method\n */\n public static boolean isMethod(Declaration decl) {\n return (decl instanceof Function)\n && !((Function)decl).isParameter();\n }\n\n public static boolean isCeylon(TypeDeclaration declaration) {\n return ModelUtil.isCeylonDeclaration(declaration);\n }\n\n public static Declaration getTopmostRefinedDeclaration(Declaration decl){\n return getTopmostRefinedDeclaration(decl, null);\n }\n\n public static Declaration getTopmostRefinedDeclaration(Declaration decl, Map<Function, Function> methodOverrides){\n if (decl instanceof FunctionOrValue\n && ((FunctionOrValue)decl).isParameter()\n && decl.getContainer() instanceof Class) {\n // Parameters in a refined class are not considered refinements themselves\n // We have in find the refined attribute\n Class c = (Class)decl.getContainer();\n boolean isAlias = c.isAlias();\n boolean isActual = c.isActual();\n // aliases and actual classes actually do refine their extended type parameters so the same rules apply wrt\n // boxing and stuff\n if (isAlias || isActual) {\n Functional ctor = null;\n int index = c.getParameterList().getParameters().indexOf(findParamForDecl(((TypedDeclaration)decl)));\n // ATM we only consider aliases if we're looking at aliases, and same for actual, not mixing the two.\n // Note(Stef): not entirely sure about that one, what about aliases of actual classes?\n while ((isAlias && c.isAlias())\n || (isActual && c.isActual())) {\n ctor = (isAlias && c.isAlias()) ? (Functional)((ClassAlias)c).getConstructor() : c;\n Type et = c.getExtendedType();\n c = et!=null && et.isClass() ? (Class)et.getDeclaration() : null;\n // handle compile errors\n if(c == null)\n return null;\n }\n if (isActual) {\n ctor = c;\n }\n // be safe\n if(ctor == null \n || ctor.getParameterLists() == null\n || ctor.getParameterLists().isEmpty()\n || ctor.getFirstParameterList() == null\n || ctor.getFirstParameterList().getParameters() == null\n || ctor.getFirstParameterList().getParameters().size() <= index)\n return null;\n decl = ctor.getFirstParameterList().getParameters().get(index).getModel();\n }\n if (decl.isShared()) {\n Declaration refinedDecl = c.getRefinedMember(decl.getName(), getSignature(decl), false);//?? ellipsis=false??\n if(refinedDecl != null && !ModelUtil.equal(refinedDecl, decl)) {\n return getTopmostRefinedDeclaration(refinedDecl, methodOverrides);\n }\n }\n return decl;\n } else if(decl instanceof FunctionOrValue\n && ((FunctionOrValue)decl).isParameter() // a parameter\n && ((decl.getContainer() instanceof Function && !(((Function)decl.getContainer()).isParameter())) // that's not parameter of a functional parameter \n || decl.getContainer() instanceof Specification // or is a parameter in a specification\n || (decl.getContainer() instanceof Function \n && ((Function)decl.getContainer()).isParameter() \n && createMethod((Function)decl.getContainer())))) {// or is a class functional parameter\n // Parameters in a refined method are not considered refinements themselves\n // so we have to look up the corresponding parameter in the container's refined declaration\n Functional func = (Functional)getParameterized((FunctionOrValue)decl);\n if(func == null)\n return decl;\n Declaration kk = getTopmostRefinedDeclaration((Declaration)func, methodOverrides);\n // error recovery\n if(kk instanceof Functional == false)\n return decl;\n Functional refinedFunc = (Functional) kk;\n // shortcut if the functional doesn't override anything\n if (ModelUtil.equal((Declaration)refinedFunc, (Declaration)func)) {\n return decl;\n }\n if (func.getParameterLists().size() != refinedFunc.getParameterLists().size()) {\n // invalid input\n return decl;\n }\n for (int ii = 0; ii < func.getParameterLists().size(); ii++) {\n if (func.getParameterLists().get(ii).getParameters().size() != refinedFunc.getParameterLists().get(ii).getParameters().size()) {\n // invalid input\n return decl;\n }\n // find the index of the parameter in the declaration\n int index = 0;\n for (Parameter px : func.getParameterLists().get(ii).getParameters()) {\n if (px.getModel() == null || px.getModel().equals(decl)) {\n // And return the corresponding parameter from the refined declaration\n return refinedFunc.getParameterLists().get(ii).getParameters().get(index).getModel();\n }\n index++;\n }\n continue;\n }\n }else if(methodOverrides != null\n && decl instanceof Function\n && ModelUtil.equal(decl.getRefinedDeclaration(), decl)\n && decl.getContainer() instanceof Specification\n && ((Specification)decl.getContainer()).getDeclaration() instanceof Function\n && ((Function) ((Specification)decl.getContainer()).getDeclaration()).isShortcutRefinement()\n // we do all the previous ones first because they are likely to filter out false positives cheaper than the\n // hash lookup we do next to make sure it is really one of those cases\n && methodOverrides.containsKey(decl)){\n // special case for class X() extends T(){ m = function() => e; } which we inline\n decl = methodOverrides.get(decl);\n }\n Declaration refinedDecl = decl.getRefinedDeclaration();\n if(refinedDecl != null && !ModelUtil.equal(refinedDecl, decl))\n return getTopmostRefinedDeclaration(refinedDecl);\n return decl;\n }\n\n public static Parameter findParamForDecl(TypedDeclaration decl) {\n String attrName = decl.getName();\n return findParamForDecl(attrName, decl);\n }\n \n public static Parameter findParamForDecl(String attrName, TypedDeclaration decl) {\n Parameter result = null;\n if (decl.getContainer() instanceof Functional) {\n Functional f = (Functional)decl.getContainer();\n result = f.getParameter(attrName);\n }\n return result;\n }\n\n public static Declaration getParameterized(FunctionOrValue methodOrValue) {\n if (!methodOrValue.isParameter()) {\n return null;\n }\n Scope scope = methodOrValue.getContainer();\n if (scope instanceof Specification) {\n return ((Specification)scope).getDeclaration();\n } else if (scope instanceof Declaration) {\n return (Declaration)scope;\n } \n return null;\n }\n\n public static boolean createMethod(FunctionOrValue model) {\n return model instanceof Function\n && model.isParameter()\n && model.isClassMember()\n && (model.isShared() || model.isCaptured());\n }\n\n public static boolean supportsReified(Declaration declaration){\n if(declaration instanceof ClassOrInterface){\n // Java constructors don't support reified type arguments\n return isCeylon((TypeDeclaration) declaration);\n }else if(declaration instanceof Function){\n if (((Function)declaration).isParameter()) {\n // those can never be parameterised\n return false;\n }\n if(declaration.isToplevel())\n return true;\n // Java methods don't support reified type arguments\n Function m = (Function) getTopmostRefinedDeclaration(declaration);\n // See what its container is\n ClassOrInterface container = ModelUtil.getClassOrInterfaceContainer(m);\n // a method which is not a toplevel and is not a class method, must be a method within method and\n // that must be Ceylon so it supports it\n if(container == null)\n return true;\n return supportsReified(container);\n }else if(declaration instanceof Constructor){\n // Java constructors don't support reified type arguments\n return isCeylon((Constructor) declaration);\n }else{\n return false;\n }\n }\n \n public static boolean isCompanionClassNeeded(TypeDeclaration decl) {\n return decl instanceof Interface \n && BooleanUtil.isNotFalse(((Interface)decl).isCompanionClassNeeded());\n }\n\n /**\n * Determines whether the given attribute should be accessed and assigned \n * via a {@code VariableBox}\n */\n public static boolean isBoxedVariable(TypedDeclaration attr) {\n return ModelUtil.isNonTransientValue(attr)\n && ModelUtil.isLocalNotInitializer(attr)\n && ((attr.isVariable() && attr.isCaptured())\n // self-captured objects must also be boxed like variables\n || attr.isSelfCaptured());\n }\n\n public static boolean isJavaArray(TypeDeclaration decl) {\n if(decl instanceof Class == false)\n return false;\n Class c = (Class) decl;\n String name = c.getQualifiedNameString();\n return name.equals(\"java.lang::ObjectArray\")\n || name.equals(\"java.lang::ByteArray\")\n || name.equals(\"java.lang::ShortArray\")\n || name.equals(\"java.lang::IntArray\")\n || name.equals(\"java.lang::LongArray\")\n || name.equals(\"java.lang::FloatArray\")\n || name.equals(\"java.lang::DoubleArray\")\n || name.equals(\"java.lang::BooleanArray\")\n || name.equals(\"java.lang::CharArray\");\n }\n}",
"public class Module \n implements Referenceable, Annotated, Comparable<Module> {\n\n public static final String LANGUAGE_MODULE_NAME = \"ceylon.language\";\n public static final String DEFAULT_MODULE_NAME = \"default\";\n\n private List<String> name;\n private String version;\n private int major;\n private int minor;\n private List<Package> packages = \n new ArrayList<Package>();\n private List<ModuleImport> imports = \n new ArrayList<ModuleImport>();\n private Module languageModule;\n private boolean available;\n private boolean isDefault;\n private List<Annotation> annotations = \n new ArrayList<Annotation>();\n private Unit unit;\n private String memoisedName;\n private TypeCache cache = new TypeCache();\n private String signature;\n private List<ModuleImport> overridenImports = null;\n private Backends nativeBackends = Backends.ANY;\n\n public Module() {}\n \n /**\n * Whether or not the module is available in the\n * source path or the repository\n */\n public boolean isAvailable() {\n return available;\n }\n\n public void setAvailable(boolean available) {\n this.available = available;\n }\n\n public List<String> getName() {\n return name;\n }\n\n public void setName(List<String> name) {\n this.name = name;\n }\n\n public List<Package> getPackages() {\n return packages;\n }\n\n public List<ModuleImport> getImports() {\n return Collections.unmodifiableList(imports);\n }\n \n public void addImport(ModuleImport modImport) {\n imports.add(modImport);\n }\n \n public Module getLanguageModule() {\n return languageModule;\n }\n \n public void setLanguageModule(Module languageModule) {\n this.languageModule = languageModule;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n \n /**\n * Get all packages belonging to this module and modules \n * transitively imported by this module that are visible\n * to this module. \n */\n public List<Package> getAllVisiblePackages() {\n List<Package> list = \n new ArrayList<Package>(getPackages());\n addVisiblePackagesOfTransitiveDependencies(list, \n new HashSet<String>(), true);\n return list;\n }\n \n private void addVisiblePackagesOfTransitiveDependencies(\n List<Package> list, \n Set<String> alreadyScannedModules, \n boolean firstLevel) {\n for (ModuleImport mi: getImports()) {\n if (firstLevel || mi.isExport()) {\n Module importedModule = mi.getModule();\n String imn = importedModule.getNameAsString();\n if (alreadyScannedModules.add(imn)) {\n for (Package p: \n importedModule.getPackages()) {\n if (p.isShared()) {\n list.add(p);\n }\n }\n importedModule.addVisiblePackagesOfTransitiveDependencies(\n list, alreadyScannedModules, false);\n }\n }\n }\n }\n \n /**\n * Get all packages belonging to this module and modules \n * transitively imported by this module, including \n * packages that aren't visible to this module. \n */\n public List<Package> getAllReachablePackages() {\n List<Package> list = new ArrayList<Package>();\n list.addAll(getPackages());\n addAllPackagesOfTransitiveDependencies(list, \n new HashSet<String>());\n return list;\n }\n\n private void addAllPackagesOfTransitiveDependencies(\n List<Package> list, \n Set<String> alreadyScannedModules) {\n for (ModuleImport mi: getImports()) {\n Module importedModule = mi.getModule();\n String imn = importedModule.getNameAsString();\n if (alreadyScannedModules.add(imn)) {\n for (Package p: importedModule.getPackages()) {\n list.add(p);\n }\n importedModule.addVisiblePackagesOfTransitiveDependencies(\n list, alreadyScannedModules, false);\n }\n }\n }\n \n public Map<String, DeclarationWithProximity> \n getAvailableDeclarations(String startingWith, \n int proximity) {\n Map<String, DeclarationWithProximity> result = \n new TreeMap<String,DeclarationWithProximity>();\n for (Package p: getAllVisiblePackages()) {\n String packageName = \n p.getNameAsString();\n boolean isLanguageModule = \n packageName.equals(LANGUAGE_MODULE_NAME);\n boolean isDefaultPackage = \n packageName.isEmpty();\n if (!isDefaultPackage) {\n for (Declaration d: p.getMembers()) {\n try {\n if (isResolvable(d) && \n d.isShared() && \n !isOverloadedVersion(d) &&\n isNameMatching(startingWith, d)) {\n String name = d.getName();\n boolean isSpecialValue = \n isLanguageModule &&\n name.equals(\"true\") || \n name.equals(\"false\") || \n name.equals(\"null\");\n boolean isSpecialType = \n isLanguageModule &&\n name.equals(\"String\") ||\n name.equals(\"Integer\") ||\n name.equals(\"Float\") ||\n name.equals(\"Character\") ||\n name.equals(\"Boolean\") ||\n name.equals(\"Byte\") ||\n name.equals(\"Object\") ||\n name.equals(\"Anything\");\n int prox;\n if (isSpecialValue) {\n prox = -1;\n }\n else if (isSpecialType) {\n //just less than toplevel\n //declarations of the package\n prox = proximity+2;\n }\n else if (isLanguageModule) {\n //just less than toplevel\n //declarations of the package\n prox = proximity+3;\n }\n else {\n //unimported declarations\n //that may be imported\n prox = proximity+4;\n }\n result.put(d.getQualifiedNameString(), \n new DeclarationWithProximity(d, \n prox, !isLanguageModule));\n }\n }\n catch (Exception e) {}\n }\n }\n }\n if (\"Nothing\".startsWith(startingWith)) {\n result.put(\"Nothing\", \n new DeclarationWithProximity(\n new NothingType(unit),\n //same as other \"special\" \n //language module declarations\n proximity+2));\n }\n return result;\n }\n\n protected boolean isJdkModule(String moduleName) {\n // overridden by subclasses\n return false;\n }\n\n protected boolean isJdkPackage(String moduleName, \n String packageName) {\n // overridden by subclasses\n return false;\n }\n\n public Package getDirectPackage(String name) {\n for (Package pkg: packages) {\n if (pkg.getQualifiedNameString().equals(name)) {\n return pkg;\n }\n }\n return null;\n }\n \n public Package getPackage(String name) {\n Package pkg = getDirectPackage(name);\n if(pkg != null)\n return pkg;\n for (ModuleImport mi: imports) {\n pkg = mi.getModule().getDirectPackage(name);\n if(pkg != null)\n return pkg;\n }\n return null;\n }\n \n public Package getRootPackage() {\n return getPackage(getNameAsString());\n }\n \n public String getNameAsString() {\n if (memoisedName == null){\n StringBuilder sb = new StringBuilder();\n for (int i=0, s=name.size(); i<s; i++) {\n sb.append(name.get(i));\n if (i < name.size()-1) {\n sb.append('.');\n }\n }\n memoisedName = sb.toString();\n }\n return memoisedName;\n }\n\n @Override\n public String toString() {\n return \"module \" + getNameAsString() + \n \" \\\"\" + getVersion() + \"\\\"\";\n }\n \n /**\n * Is this the default module hosting all units outside \n * of an explicit module\n */\n public boolean isDefault() {\n return isDefault;\n }\n\n public void setDefault(boolean isDefault) {\n this.isDefault = isDefault;\n }\n\n @Override\n public List<Annotation> getAnnotations() {\n return annotations;\n }\n\n public boolean isJava() {\n return false;\n }\n\n public boolean isNative() {\n return !getNativeBackends().none();\n }\n \n public Backends getNativeBackends() {\n return nativeBackends;\n }\n \n public void setNativeBackends(Backends backends) {\n this.nativeBackends=backends;\n }\n \n @Override\n public Unit getUnit() {\n return unit;\n }\n \n public void setUnit(Unit unit) {\n this.unit = unit;\n }\n\n public int getMajor() {\n return major;\n }\n\n public void setMajor(int major) {\n this.major = major;\n }\n\n public int getMinor() {\n return minor;\n }\n\n public void setMinor(int minor) {\n this.minor = minor;\n }\n\n @Override\n public int compareTo(Module other) {\n if (this == other) {\n return 0;\n }\n // default first\n if (isDefault()) {\n return -1;\n }\n String name = this.getNameAsString();\n String otherName = other.getNameAsString();\n int cmp = name.compareTo(otherName);\n if (cmp != 0) {\n return cmp;\n }\n // we don't care about how versions are compared, we \n // just care that the order is consistent\n String version = this.getVersion();\n String otherVersion = other.getVersion();\n return version.compareTo(otherVersion);\n }\n\n public TypeCache getCache(){\n return cache;\n }\n\n public void clearCache(TypeDeclaration declaration) {\n TypeCache cache = getCache();\n if (cache != null){\n cache.clearForDeclaration(declaration);\n }\n // FIXME: propagate to modules that import this module transitively\n // Done in the IDE JDTModule\n }\n \n public String getSignature() {\n if (signature == null) {\n if (isDefault()) {\n signature = getNameAsString();\n }\n else {\n signature = getNameAsString() + \n \"/\" + getVersion();\n }\n }\n return signature;\n }\n\n public List<ModuleImport> getOverridenImports() {\n return overridenImports == null ? null :\n unmodifiableList(overridenImports);\n }\n\n public boolean overrideImports(\n List<ModuleImport> newModuleImports) {\n if (overridenImports == null \n && newModuleImports != null) {\n overridenImports = imports;\n imports = newModuleImports;\n return true;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return getSignature().hashCode();\n }\n \n @Override\n public boolean equals(Object obj) {\n if (obj instanceof Module) {\n Module b = (Module) obj;\n return getSignature().equals(b.getSignature());\n }\n else {\n return false;\n }\n }\n}",
"public class ModuleImport implements Annotated {\n private boolean optional;\n private boolean export;\n private Module module;\n private Backends nativeBackends;\n private List<Annotation> annotations = new ArrayList<Annotation>();\n private ModuleImport overridenModuleImport = null;\n\n public ModuleImport(Module module, boolean optional, boolean export) {\n this(module, optional, export, (Backend)null);\n }\n\n public ModuleImport(Module module, boolean optional, boolean export, Backend backend) {\n this(module, optional, export, backend != null ? backend.asSet() : Backends.ANY);\n }\n\n public ModuleImport(Module module, boolean optional, boolean export, Backends backends) {\n this.module = module;\n this.optional = optional;\n this.export = export;\n this.nativeBackends = backends;\n }\n\n public boolean isOptional() {\n return optional;\n }\n\n public boolean isExport() {\n return export;\n }\n\n public Module getModule() {\n return module;\n }\n \n public boolean isNative() {\n return !getNativeBackends().none();\n }\n \n public Backends getNativeBackends() {\n return nativeBackends;\n }\n \n @Override\n public List<Annotation> getAnnotations() {\n return annotations;\n }\n\n public ModuleImport getOverridenModuleImport() {\n return overridenModuleImport;\n }\n\n public boolean override(ModuleImport moduleImportOverride) {\n if (overridenModuleImport == null\n \t\t&& moduleImportOverride != null) {\n this.overridenModuleImport = new ModuleImport(module, optional, export, nativeBackends);\n module = moduleImportOverride.getModule();\n optional = moduleImportOverride.isOptional();\n export = moduleImportOverride.isExport();\n nativeBackends = moduleImportOverride.getNativeBackends();\n return true;\n }\n return false;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n if (export) sb.append(\"shared \");\n if (optional) sb.append(\"optional \");\n if (!nativeBackends.none()) {\n sb.append(\"native(\")\n .append(nativeBackends)\n .append(\") \");\n }\n sb.append(\"import \")\n .append(module.getNameAsString())\n .append(\" \\\"\")\n .append(module.getVersion())\n .append(\"\\\"\");\n return sb.toString();\n }\n}",
"public class Package \n implements ImportableScope, Referenceable, Annotated {\n\n private List<String> name;\n private Module module;\n private List<Unit> units = \n new ArrayList<Unit>();\n private boolean shared = false;\n private List<Annotation> annotations = \n new ArrayList<Annotation>();\n private Unit unit;\n private String nameAsString;\n \n @Override\n public boolean isToplevel() {\n return false;\n }\n \n public Module getModule() {\n return module;\n }\n\n public void setModule(Module module) {\n this.module = module;\n }\n\n public List<String> getName() {\n return name;\n }\n\n public void setName(List<String> name) {\n this.name = name;\n }\n \n public Iterable<Unit> getUnits() {\n synchronized (units) {\n return new ArrayList<Unit>(units);\n }\n }\n \n public void addUnit(Unit unit) {\n synchronized (units) {\n units.add(unit);\n members=null;\n }\n }\n \n public void removeUnit(Unit unit) {\n synchronized (units) {\n units.remove(unit);\n members=null;\n }\n }\n \n public boolean isShared() {\n return shared;\n }\n \n public void setShared(boolean shared) {\n this.shared = shared;\n }\n \n private List<Declaration> members;\n \n @Override\n public List<Declaration> getMembers() {\n synchronized (units) {\n //return getMembersInternal();\n if (members==null) {\n members = getMembersInternal();\n }\n return members;\n }\n }\n \n @Override\n public void addMember(Declaration declaration) {\n members=null;\n }\n \n private List<Declaration> getMembersInternal() {\n List<Declaration> result = \n new ArrayList<Declaration>();\n for (Unit unit: units) {\n for (Declaration d: unit.getDeclarations()) {\n if (d.getContainer().equals(this)) {\n result.add(d);\n }\n }\n }\n return result;\n }\n\n @Override\n public Scope getContainer() {\n return null;\n }\n\n @Override\n public Scope getScope() {\n return null;\n }\n\n public String getNameAsString() {\n if (nameAsString == null){\n nameAsString = formatPath(name);\n }\n return nameAsString;\n }\n\n @Override\n public String toString() {\n return \"package \" + getNameAsString();\n }\n \n @Override\n public String getQualifiedNameString() {\n return getNameAsString();\n }\n \n /**\n * Search only inside the package, ignoring imports\n */\n @Override\n public Declaration getMember(String name, \n List<Type> signature, boolean ellipsis) {\n return getDirectMember(name, signature, ellipsis);\n }\n\n @Override\n public Declaration getDirectMember(String name, \n List<Type> signature, boolean ellipsis) {\n return lookupMember(getMembers(), \n name, signature, ellipsis);\n }\n\n @Override\n public Declaration getDirectMemberForBackend(String name, \n Backends backends) {\n return lookupMemberForBackend(getMembers(), \n name, backends);\n }\n\n @Override\n public Type getDeclaringType(Declaration d) {\n if (d.isClassMember()) {\n Class containingAnonClass =\n (Class) d.getContainer();\n if (containingAnonClass.isAnonymous()) {\n return containingAnonClass.getType();\n }\n }\n return null;\n }\n\n /**\n * Search in the package, taking into account\n * imports\n */\n @Override\n public Declaration getMemberOrParameter(Unit unit, \n String name, List<Type> signature, \n boolean ellipsis) {\n //this implements the rule that imports hide \n //toplevel members of a package\n //TODO: would it be better to look in the given unit \n // first, before checking imports?\n Declaration d = \n unit.getImportedDeclaration(name, \n signature, ellipsis);\n if (d!=null) {\n return d;\n }\n d = getDirectMember(name, signature, ellipsis);\n if (d!=null) {\n return d;\n }\n return unit.getLanguageModuleDeclaration(name);\n }\n \n @Override\n public boolean isInherited(Declaration d) {\n return false;\n }\n \n @Override\n public TypeDeclaration getInheritingDeclaration(Declaration d) {\n return null;\n }\n \n @Override\n public Map<String,DeclarationWithProximity> \n getMatchingDeclarations(Unit unit, String startingWith, \n int proximity) {\n Map<String,DeclarationWithProximity> result = \n getMatchingDirectDeclarations(startingWith, \n //package toplevels - just less than \n //explicitly imported declarations\n proximity+1);\n if (unit!=null) {\n result.putAll(unit.getMatchingImportedDeclarations(\n startingWith, proximity));\n }\n Map<String,DeclarationWithProximity> importables = \n getModule()\n .getAvailableDeclarations(\n startingWith, proximity);\n List<Map.Entry<String,DeclarationWithProximity>> \n entriesToAdd =\n new ArrayList\n <Map.Entry<String,DeclarationWithProximity>>\n (importables.size());\n for (Map.Entry<String,DeclarationWithProximity> e: \n importables.entrySet()) {\n boolean already = false;\n DeclarationWithProximity existing = e.getValue();\n for (DeclarationWithProximity importable: \n result.values()) {\n Declaration id = importable.getDeclaration();\n Declaration ed = existing.getDeclaration();\n if (id.equals(ed)) {\n already = true;\n break;\n }\n }\n if (!already) {\n entriesToAdd.add(e);\n }\n }\n for (Map.Entry<String,DeclarationWithProximity> e:\n entriesToAdd) {\n result.put(e.getKey(), e.getValue());\n }\n return result;\n }\n\n public Map<String,DeclarationWithProximity> \n getMatchingDirectDeclarations(String startingWith, \n int proximity) {\n Map<String,DeclarationWithProximity> result = \n new TreeMap<String,DeclarationWithProximity>();\n for (Declaration d: getMembers()) {\n if (isResolvable(d) && \n !isOverloadedVersion(d) && \n isNameMatching(startingWith, d)) {\n result.put(d.getName(unit), \n new DeclarationWithProximity(d, \n proximity));\n }\n }\n return result;\n }\n\n public Map<String,DeclarationWithProximity> \n getImportableDeclarations(Unit unit, String startingWith, \n List<Import> imports, int proximity) {\n Map<String,DeclarationWithProximity> result = \n new TreeMap<String,DeclarationWithProximity>();\n for (Declaration d: getMembers()) {\n if (isResolvable(d) && d.isShared() && \n !isOverloadedVersion(d) &&\n isNameMatching(startingWith, d)) {\n boolean already = false;\n for (Import i: imports) {\n if (!i.isWildcardImport() && \n i.getDeclaration().equals(d)) {\n already = true;\n break;\n }\n }\n if (!already) {\n result.put(d.getName(), \n new DeclarationWithProximity(d, \n proximity));\n }\n }\n }\n return result;\n }\n \n @Override\n public List<Annotation> getAnnotations() {\n return annotations;\n }\n\n @Override\n public int hashCode() {\n // use the cached version, profiling says \n // List.hashCode is expensive\n return getNameAsString().hashCode();\n }\n \n @Override\n public boolean equals(Object obj) {\n if (obj instanceof Package) {\n Package p = (Package) obj;\n return p.getNameAsString()\n .equals(getNameAsString());\n }\n else {\n return false;\n }\n }\n \n @Override\n public Unit getUnit() {\n return unit;\n }\n \n public void setUnit(Unit unit) {\n this.unit = unit;\n }\n \n @Override\n public Backends getScopedBackends() {\n return getModule().getNativeBackends();\n }\n}"
] | import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import com.redhat.ceylon.model.cmr.ArtifactResult;
import com.redhat.ceylon.model.cmr.JDKUtils;
import com.redhat.ceylon.model.cmr.PathFilter;
import com.redhat.ceylon.model.loader.AbstractModelLoader;
import com.redhat.ceylon.model.loader.ContentAwareArtifactResult;
import com.redhat.ceylon.model.loader.JvmBackendUtil;
import com.redhat.ceylon.model.typechecker.model.Module;
import com.redhat.ceylon.model.typechecker.model.ModuleImport;
import com.redhat.ceylon.model.typechecker.model.Package; | package com.redhat.ceylon.model.loader.model;
/**
* Represents a lazy Module declaration.
*
* @author Stéphane Épardaud <[email protected]>
*/
public abstract class LazyModule extends Module {
private boolean isJava = false;
protected Set<String> jarPackages = new HashSet<String>();
public LazyModule() {
}
@Override | public Package getDirectPackage(String name) { | 7 |
fflewddur/archivo | src/net/straylightlabs/archivo/controller/ArchiveQueueManager.java | [
"public class Archivo extends Application {\n private Stage primaryStage;\n private final MAKManager maks;\n private final StringProperty statusText;\n private final ExecutorService rpcExecutor;\n private final UserPrefs prefs;\n private RootLayoutController rootController;\n private RecordingListController recordingListController;\n private RecordingDetailsController recordingDetailsController;\n private final ArchiveQueueManager archiveQueueManager;\n private final CrashReportController crashReportController;\n private ArchiveHistory archiveHistory;\n private GlyphFont symbolFont;\n\n private final static Logger logger = LoggerFactory.getLogger(Archivo.class);\n public final static TelemetryController telemetryController = new TelemetryController();\n\n public static final String APPLICATION_NAME = \"Archivo\";\n public static final String APPLICATION_RDN = \"net.straylightlabs.archivo\";\n public static final int APP_MAJOR_VERSION = 1;\n public static final int APP_MINOR_VERSION = 1;\n public static final int APP_RELEASE_VERSION = 0;\n public static final boolean IS_BETA = false;\n public static final int BETA_VERSION = 0;\n public static final String APPLICATION_VERSION;\n public static final String USER_AGENT;\n public static final Path LOG_PATH = Paths.get(OSHelper.getDataDirectory().toString(), \"log.txt\");\n private static final int WINDOW_MIN_HEIGHT = 400;\n private static final int WINDOW_MIN_WIDTH = 555;\n private static final Path ARCHIVE_HISTORY_PATH = Paths.get(OSHelper.getDataDirectory().toString(), \"history.xml\");\n\n static {\n if (IS_BETA) {\n APPLICATION_VERSION = String.format(\n \"%d.%d.%d Beta %d\", APP_MAJOR_VERSION, APP_MINOR_VERSION, APP_RELEASE_VERSION, BETA_VERSION\n );\n } else {\n APPLICATION_VERSION = String.format(\"%d.%d.%d\", APP_MAJOR_VERSION, APP_MINOR_VERSION, APP_RELEASE_VERSION);\n }\n USER_AGENT = String.format(\"%s/%s\", APPLICATION_NAME, APPLICATION_VERSION);\n }\n\n public Archivo() {\n super();\n prefs = new UserPrefs();\n maks = new MAKManager();\n prefs.loadMAKs(maks);\n if (prefs.getShareTelemetry()) {\n telemetryController.enable();\n }\n setLogLevel();\n telemetryController.setUserId(prefs.getUserId());\n crashReportController = new CrashReportController(prefs.getUserId());\n statusText = new SimpleStringProperty();\n rpcExecutor = Executors.newSingleThreadExecutor();\n archiveQueueManager = new ArchiveQueueManager(this);\n }\n\n /**\n * If the user has requested debugging mode, set the root logger to the DEBUG level\n */\n private void setLogLevel() {\n if (prefs.getDebugMode() || Archivo.IS_BETA) {\n ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(\n ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME\n );\n root.setLevel(Level.DEBUG);\n }\n }\n\n @Override\n public void start(Stage primaryStage) throws Exception {\n if (!prefs.parseParameters(getParameters())) {\n cleanShutdown();\n }\n\n logger.info(\"Starting up {} {}...\", APPLICATION_NAME, APPLICATION_VERSION);\n logVMInfo();\n\n loadSymbolFont();\n archiveHistory = ArchiveHistory.loadFrom(ARCHIVE_HISTORY_PATH);\n\n this.primaryStage = primaryStage;\n this.primaryStage.setTitle(APPLICATION_NAME);\n this.primaryStage.setMinHeight(WINDOW_MIN_HEIGHT);\n this.primaryStage.setMinWidth(WINDOW_MIN_WIDTH);\n restoreWindowDimensions();\n\n initRootLayout();\n\n String mak = maks.currentMAK();\n if (mak == null) {\n try {\n SetupDialog dialog = new SetupDialog(primaryStage);\n mak = dialog.promptUser();\n maks.addMAK(mak);\n prefs.saveMAKs(maks);\n } catch (IllegalStateException e) {\n logger.error(\"Error getting MAK from user: \", e);\n cleanShutdown();\n }\n }\n\n initRecordingList();\n initRecordingDetails();\n\n archiveQueueManager.addObserver(rootController);\n\n primaryStage.setOnCloseRequest(e -> {\n e.consume();\n if (confirmTaskCancellation()) {\n archiveQueueManager.cancelAllArchiveTasks();\n cleanShutdown();\n }\n });\n\n prefs.addNetworkChangedListener(((observable, oldValue, newValue) -> recordingListController.startTivoSearch()));\n telemetryController.sendStartupEvent();\n checkForUpdates();\n }\n\n private void loadSymbolFont() {\n URL fontUrl = getClass().getClassLoader().getResource(\"resources/fontawesome.otf\");\n logger.debug(\"Loading font resource at {}\", fontUrl);\n if (fontUrl == null) {\n logger.error(\"Error loading symbol font\");\n } else {\n symbolFont = new FontAwesome(fontUrl.toString());\n }\n }\n\n public GlyphFont getSymbolFont() {\n return symbolFont;\n }\n\n public Glyph getGlyph(Enum<?> glyphName) {\n if (symbolFont == null) {\n logger.warn(\"No symbol font available\");\n return null;\n }\n return symbolFont.create(glyphName);\n }\n\n private void logVMInfo() {\n logger.info(\"Running on Java {} from {}\", System.getProperty(\"java.version\"), System.getProperty(\"java.vendor\"));\n logger.info(\"System is {} (version = {}, arch = {})\", System.getProperty(\"os.name\"),\n System.getProperty(\"os.version\"), System.getProperty(\"os.arch\"));\n for (Path root : FileSystems.getDefault().getRootDirectories()) {\n try {\n FileStore store = Files.getFileStore(root);\n logger.info(\"Volume {} has {} MB free of {} MB\", root,\n store.getUsableSpace() / 1024 / 1024, store.getTotalSpace() / 1024 / 1024);\n } catch (FileSystemException e) {\n // Ignore these\n } catch (IOException e) {\n logger.error(\"Error getting available disk space for volume {}: \", root, e);\n }\n }\n }\n\n private void checkForUpdates() {\n Task<SoftwareUpdateDetails> updateCheck = new UpdateCheckTask();\n updateCheck.setOnSucceeded(event -> {\n SoftwareUpdateDetails update = updateCheck.getValue();\n if (update.isAvailable()) {\n logger.info(\"Update check: A newer version of {} is available!\", APPLICATION_NAME);\n showUpdateDialog(update);\n } else {\n logger.info(\"Update check: This is the latest version of {} ({})\", APPLICATION_NAME, APPLICATION_VERSION);\n }\n });\n updateCheck.setOnFailed(event -> logger.error(\"Error checking for updates: \", event.getSource().getException()));\n Executors.newSingleThreadExecutor().submit(updateCheck);\n }\n\n private void showUpdateDialog(SoftwareUpdateDetails updateDetails) {\n Alert alert = new Alert(Alert.AlertType.INFORMATION);\n alert.setTitle(\"Update Available\");\n alert.setHeaderText(String.format(\"A new version of %s is available\", Archivo.APPLICATION_NAME));\n alert.setContentText(String.format(\"%s %s was released on %s.\\n\\nNotable changes include %s.\\n\\n\" +\n \"Would you like to install the update now?\\n\\n\",\n Archivo.APPLICATION_NAME, updateDetails.getVersion(),\n updateDetails.getReleaseDate().format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)),\n updateDetails.getSummary()));\n\n ButtonType deferButtonType = new ButtonType(\"No, I'll Update Later\", ButtonBar.ButtonData.NO);\n ButtonType updateButtonType = new ButtonType(\"Yes, Let's Update Now\", ButtonBar.ButtonData.YES);\n\n alert.getButtonTypes().setAll(deferButtonType, updateButtonType);\n ((Button) alert.getDialogPane().lookupButton(deferButtonType)).setDefaultButton(false);\n ((Button) alert.getDialogPane().lookupButton(updateButtonType)).setDefaultButton(true);\n\n Optional<ButtonType> result = alert.showAndWait();\n if ((result.isPresent() && result.get() == updateButtonType)) {\n try {\n Desktop.getDesktop().browse(updateDetails.getLocation().toURI());\n } catch (URISyntaxException | IOException e) {\n Archivo.logger.error(\"Error opening a web browser to download '{}': \", updateDetails.getLocation(), e);\n }\n }\n }\n\n public void cleanShutdown() {\n if (!confirmTaskCancellation()) {\n return;\n }\n\n archiveHistory.save();\n saveWindowDimensions();\n\n int waitTimeMS = 100;\n int msLimit = 15000;\n if (archiveQueueManager.hasTasks()) {\n setStatusText(\"Exiting...\");\n try {\n int msWaited = 0;\n archiveQueueManager.cancelAllArchiveTasks();\n while (archiveQueueManager.hasTasks() && msWaited < msLimit) {\n Thread.sleep(waitTimeMS);\n msWaited += waitTimeMS;\n }\n } catch (InterruptedException e) {\n logger.error(\"Interrupted while waiting for archive tasks to shutdown: \", e);\n }\n }\n\n boolean reportingCrashes = crashReportController.hasCrashReport() && getUserPrefs().getShareTelemetry();\n if (reportingCrashes) {\n setStatusText(\"Exiting...\");\n Task<Void> crashReportTask = crashReportController.buildTask();\n crashReportTask.setOnSucceeded(event -> shutdown());\n crashReportTask.setOnFailed(event -> shutdown());\n Executors.newSingleThreadExecutor().submit(crashReportTask);\n } else {\n shutdown();\n }\n }\n\n private void shutdown() {\n logger.info(\"Shutting down.\");\n Platform.exit();\n System.exit(0);\n }\n\n /**\n * If there are active tasks, prompt the user before exiting.\n * Returns true if the user wants to cancel all tasks and exit.\n */\n private boolean confirmTaskCancellation() {\n if (archiveQueueManager.hasTasks()) {\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n alert.setTitle(\"Cancel Task Confirmation\");\n alert.setHeaderText(\"Really cancel all tasks and exit?\");\n alert.setContentText(\"You are currently archiving recordings from your TiVo. Are you sure you want to \" +\n \"close Archivo and cancel these tasks?\");\n\n ButtonType cancelButtonType = new ButtonType(\"Cancel tasks and exit\", ButtonBar.ButtonData.NO);\n ButtonType keepButtonType = new ButtonType(\"Keep archiving\", ButtonBar.ButtonData.CANCEL_CLOSE);\n\n alert.getButtonTypes().setAll(cancelButtonType, keepButtonType);\n ((Button) alert.getDialogPane().lookupButton(cancelButtonType)).setDefaultButton(false);\n ((Button) alert.getDialogPane().lookupButton(keepButtonType)).setDefaultButton(true);\n\n Optional<ButtonType> result = alert.showAndWait();\n if (!result.isPresent()) {\n logger.error(\"No result from alert dialog\");\n return false;\n } else {\n return (result.get() == cancelButtonType);\n }\n }\n return true;\n }\n\n private void saveWindowDimensions() {\n if (primaryStage.isMaximized()) {\n getUserPrefs().setWindowMaximized(true);\n } else {\n getUserPrefs().setWindowMaximized(false);\n getUserPrefs().setWindowWidth((int) primaryStage.getWidth());\n getUserPrefs().setWindowHeight((int) primaryStage.getHeight());\n }\n }\n\n private void restoreWindowDimensions() {\n Archivo.logger.debug(\"Restoring window width of {}\", getUserPrefs().getWindowWidth());\n Archivo.logger.debug(\"Restoring window height of {}\", getUserPrefs().getWindowHeight());\n Archivo.logger.debug(\"Restoring window maximized: {}\", getUserPrefs().isWindowMaximized());\n primaryStage.setWidth(getUserPrefs().getWindowWidth());\n primaryStage.setHeight(getUserPrefs().getWindowHeight());\n primaryStage.setMaximized(getUserPrefs().isWindowMaximized());\n }\n\n private void initRootLayout() {\n try {\n FXMLLoader loader = new FXMLLoader();\n loader.setLocation(Archivo.class.getResource(\"view/RootLayout.fxml\"));\n BorderPane rootLayout = loader.load();\n\n rootController = loader.getController();\n rootController.setMainApp(this);\n rootController.disableMenuItems();\n\n Scene scene = new Scene(rootLayout);\n URL styleUrl = getClass().getClassLoader().getResource(\"resources/style.css\");\n if (styleUrl != null) {\n scene.getStylesheets().add(styleUrl.toExternalForm());\n }\n primaryStage.setScene(scene);\n\n primaryStage.getIcons().addAll(\n new Image(getClass().getClassLoader().getResourceAsStream(\"resources/archivo-16.png\")),\n new Image(getClass().getClassLoader().getResourceAsStream(\"resources/archivo-32.png\")),\n new Image(getClass().getClassLoader().getResourceAsStream(\"resources/archivo-64.png\")),\n new Image(getClass().getClassLoader().getResourceAsStream(\"resources/archivo-96.png\")),\n new Image(getClass().getClassLoader().getResourceAsStream(\"resources/archivo-128.png\")),\n new Image(getClass().getClassLoader().getResourceAsStream(\"resources/archivo-48.png\"))\n );\n primaryStage.show();\n } catch (IOException e) {\n logger.error(\"Error initializing main window: \", e);\n }\n }\n\n private void initRecordingList() {\n assert (rootController != null);\n\n try {\n FXMLLoader loader = new FXMLLoader();\n loader.setLocation(Archivo.class.getResource(\"view/RecordingList.fxml\"));\n\n recordingListController = new RecordingListController(this);\n loader.setController(recordingListController);\n\n Pane recordingList = loader.load();\n rootController.getMainGrid().add(recordingList, 0, 0);\n rootController.setMenuBindings(recordingListController);\n\n recordingListController.startTivoSearch();\n } catch (IOException e) {\n logger.error(\"Error initializing recording list: \", e);\n }\n }\n\n private void initRecordingDetails() {\n assert (rootController != null);\n assert (recordingListController != null);\n\n try {\n FXMLLoader loader = new FXMLLoader();\n loader.setLocation(Archivo.class.getResource(\"view/RecordingDetails.fxml\"));\n\n recordingDetailsController = new RecordingDetailsController(this);\n loader.setController(recordingDetailsController);\n\n Pane recordingDetails = loader.load();\n rootController.getMainGrid().add(recordingDetails, 0, 1);\n } catch (IOException e) {\n logger.error(\"Error initializing recording details: \", e);\n }\n }\n\n public void enqueueRecordingForArchiving(Recording recording) {\n if (!archiveQueueManager.enqueueArchiveTask(recording, getActiveTivo(), getMak())) {\n logger.error(\"Error adding recording to queue\");\n }\n }\n\n public void cancelArchiving(Recording recording) {\n archiveQueueManager.cancelArchiveTask(recording);\n }\n\n /**\n * Cancel all of the current and queued Archive tasks\n */\n public void cancelAll() {\n archiveQueueManager.cancelAllArchiveTasks();\n }\n\n public void archiveSelection() {\n List<Recording> toArchive = new ArrayList<>();\n for (Recording recording : recordingListController.getRecordingSelection().getRecordingsWithChildren()) {\n if (recording.isSeriesHeading()) {\n continue;\n }\n boolean archive;\n if (getUserPrefs().getOrganizeArchivedShows()) {\n archive = setOrganizedPath(recording);\n } else {\n SaveFileDialog dialog = new SaveFileDialog(getPrimaryStage(), recording, prefs);\n archive = dialog.showAndWait();\n }\n if (!archive) {\n break;\n }\n logger.info(\"Archive recording {} to {} (file type = {})...\",\n recording.getFullTitle(), recording.getDestination(), recording.getDestinationType()\n );\n toArchive.add(recording);\n }\n if (getUserPrefs().getOrganizeArchivedShows()) {\n List<Recording> destExists = toArchive.stream().filter(recording -> Files.exists(recording.getDestination())).collect(Collectors.toList());\n destExists.addAll(RecordingsExistDialog.getRecordingsWithDuplicateDestination(toArchive));\n if (destExists.size() > 0) {\n RecordingsExistDialog recordingsExistDialog = new RecordingsExistDialog(this, toArchive, destExists, prefs);\n if (!recordingsExistDialog.showAndWait()) {\n // The the user canceled the dialog, don't archive anything\n return;\n }\n }\n }\n // Enqueue selected recordings for archiving\n for (Recording recording : toArchive) {\n recording.setStatus(ArchiveStatus.QUEUED);\n enqueueRecordingForArchiving(recording);\n }\n }\n\n\n\n private boolean setOrganizedPath(Recording recording) {\n Path path = null;\n try {\n FileType fileType = FileType.fromDescription(getUserPrefs().getMostRecentFileType());\n path = Paths.get(\n getLastFolder().toString(),\n recording.getDefaultNestedPath().toString() + fileType.getExtension().substring(1)\n );\n Files.createDirectories(path.getParent());\n recording.setDestinationType(fileType);\n recording.setDestination(path);\n return true;\n } catch (IOException e) {\n logger.error(\"Error creating directory '{}': \", path.getParent(), e);\n }\n return false;\n }\n\n public void deleteFromTivo(List<Recording> recordings) {\n for (Recording recording : recordings) {\n Archivo.logger.info(\"User requested we delete {}\", recording.getFullTitle());\n Tivo tivo = getActiveTivo();\n if (tivo != null) {\n if (confirmDelete(recording, tivo)) {\n sendDeleteCommand(recording, tivo);\n }\n } else {\n Archivo.logger.error(\"No TiVo is selected to delete from\");\n }\n }\n }\n\n private boolean confirmDelete(Recording recording, Tivo tivo) {\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n alert.setTitle(\"Remove Recording Confirmation\");\n alert.setHeaderText(\"Really remove this recording?\");\n alert.setContentText(String.format(\"Are you sure you want to delete %s from %s?\",\n recording.getFullTitle(), tivo.getName()));\n\n ButtonType deleteButtonType = new ButtonType(\"Delete\", ButtonBar.ButtonData.NO);\n ButtonType keepButtonType = new ButtonType(\"Cancel\", ButtonBar.ButtonData.CANCEL_CLOSE);\n\n alert.getButtonTypes().setAll(deleteButtonType, keepButtonType);\n ((Button) alert.getDialogPane().lookupButton(deleteButtonType)).setDefaultButton(false);\n ((Button) alert.getDialogPane().lookupButton(keepButtonType)).setDefaultButton(true);\n\n Optional<ButtonType> result = alert.showAndWait();\n if (!result.isPresent()) {\n logger.error(\"No result from alert dialog\");\n return false;\n } else {\n return (result.get() == deleteButtonType);\n }\n }\n\n private void sendDeleteCommand(Recording recording, Tivo tivo) {\n assert (recording != null);\n assert (tivo != null);\n\n setStatusText(String.format(\"Deleting '%s' from %s...\", recording.getTitle(), tivo.getName()));\n primaryStage.getScene().setCursor(Cursor.WAIT);\n MindCommandRecordingUpdate command = new MindCommandRecordingUpdate(recording.getRecordingId(), tivo.getBodyId());\n MindTask task = new MindTask(tivo.getClient(), command);\n task.setOnSucceeded(event -> {\n recordingListController.updateTivoDetails(tivo);\n recordingListController.removeRecording(recording);\n primaryStage.getScene().setCursor(Cursor.DEFAULT);\n });\n task.setOnFailed(event -> {\n Throwable e = event.getSource().getException();\n Archivo.logger.error(\"Error fetching recordings from {}: \", tivo.getName(), e);\n clearStatusText();\n primaryStage.getScene().setCursor(Cursor.DEFAULT);\n showErrorMessage(\"Problem deleting recording\",\n String.format(\"Unfortunately we encountered a problem while removing '%s' from %s. \" +\n \"This usually means that either your computer or your TiVo has lost \" +\n \"its network connection.%n%nError message: %s\",\n recording.getTitle(), tivo.getName(), e.getLocalizedMessage())\n );\n });\n rpcExecutor.submit(task);\n }\n\n public void expandShows() {\n recordingListController.expandShows();\n }\n\n public void collapseShows() {\n recordingListController.collapseShows();\n }\n\n public Stage getPrimaryStage() {\n return primaryStage;\n }\n\n private Tivo getActiveTivo() {\n return recordingListController.getSelectedTivo();\n }\n\n public ExecutorService getRpcExecutor() {\n return rpcExecutor;\n }\n\n public StringProperty statusTextProperty() {\n return statusText;\n }\n\n public void setStatusText(String status) {\n logger.info(\"Setting status to '{}'\", status);\n statusText.set(status);\n rootController.showStatus();\n }\n\n public void clearStatusText() {\n logger.info(\"TaskStatus cleared\");\n rootController.hideStatus();\n }\n\n public void showPreferencesDialog() {\n PreferencesDialog preferences = new PreferencesDialog(getPrimaryStage(), this);\n preferences.show();\n }\n\n public void showErrorMessage(String header, String message) {\n showErrorMessageWithAction(header, message, null, null);\n }\n\n public boolean showErrorMessageWithAction(String header, String message, String action) {\n return showErrorMessageWithAction(header, message, action, null);\n }\n\n public boolean showErrorMessageWithAction(String header, String message, String action,\n EventHandler<ActionEvent> eventHandler) {\n Alert alert = new Alert(Alert.AlertType.ERROR);\n alert.setTitle(\"Something went wrong...\");\n alert.setHeaderText(header);\n\n VBox contentPane = new VBox();\n HyperlinkLabel contentText = new HyperlinkLabel(message);\n contentText.setPrefWidth(500);\n contentPane.setPadding(new Insets(30, 15, 20, 15));\n contentPane.getChildren().add(contentText);\n alert.getDialogPane().setContent(contentPane);\n\n if (eventHandler != null) {\n contentText.setOnAction(eventHandler);\n contentText.addEventHandler(ActionEvent.ACTION, (event) -> alert.close());\n }\n\n ButtonType closeButtonType = new ButtonType(\"Close\", ButtonBar.ButtonData.CANCEL_CLOSE);\n ButtonType actionButtonType = new ButtonType(action, ButtonBar.ButtonData.YES);\n ButtonType reportButtonType = new ButtonType(\"Report Problem\", ButtonBar.ButtonData.HELP_2);\n alert.getButtonTypes().setAll(closeButtonType, reportButtonType);\n if (action != null) {\n alert.getButtonTypes().add(actionButtonType);\n ((Button) alert.getDialogPane().lookupButton(closeButtonType)).setDefaultButton(false);\n ((Button) alert.getDialogPane().lookupButton(reportButtonType)).setDefaultButton(false);\n ((Button) alert.getDialogPane().lookupButton(actionButtonType)).setDefaultButton(true);\n }\n\n Optional<ButtonType> result = alert.showAndWait();\n while (result.isPresent() && result.get() == reportButtonType) {\n rootController.reportProblem(null);\n result = alert.showAndWait();\n }\n return (result.isPresent() && result.get() == actionButtonType);\n }\n\n public void tryNextMAK() {\n String nextMak = maks.tryNextMAK();\n if (nextMak == null) {\n promptForMAK();\n } else {\n updateMAK(nextMak);\n }\n }\n\n private void promptForMAK() {\n ChangeMAKDialog dialog = new ChangeMAKDialog(primaryStage, maks.currentMAK());\n try {\n updateMAK(dialog.promptUser());\n } catch (IllegalStateException e) {\n cleanShutdown();\n }\n }\n\n private void updateMAK(String newMak) {\n if (newMak == null || newMak.isEmpty()) {\n logger.error(\"MAK cannot be empty\");\n } else {\n maks.addMAK(newMak);\n prefs.saveMAKs(maks);\n recordingListController.updateMak(newMak);\n }\n }\n\n public RecordingDetailsController getRecordingDetailsController() {\n return recordingDetailsController;\n }\n\n @SuppressWarnings(\"unused\")\n public RecordingListController getRecordingListController() {\n return recordingListController;\n }\n\n public ArchiveHistory getArchiveHistory() {\n return archiveHistory;\n }\n\n public ArchiveQueueManager getArchiveQueueManager() {\n return archiveQueueManager;\n }\n\n public UserPrefs getUserPrefs() {\n return prefs;\n }\n\n public String getMak() {\n return maks.currentMAK();\n }\n\n public void setLastDevice(Tivo tivo) {\n prefs.setLastDevice(tivo);\n }\n\n public Tivo getLastDevice() {\n return prefs.getLastDevice(maks.currentMAK());\n }\n\n public Path getLastFolder() {\n return prefs.getLastFolder();\n }\n\n public void crashOccurred() {\n crashReportController.crashOccurred();\n }\n\n public static void main(String[] args) {\n launch(args);\n }\n}",
"public class ArchiveHistory {\n private final Path location;\n private final Map<String, ArchiveHistoryItem> items;\n\n private final static String ATT_ID = \"id\";\n private final static String ATT_DATE = \"date\";\n private final static String ATT_PATH = \"path\";\n\n private final static Logger logger = LoggerFactory.getLogger(ArchiveHistory.class);\n private final static DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();\n\n public static ArchiveHistory loadFrom(Path location) {\n ArchiveHistory ah = new ArchiveHistory(location);\n if (ah.exists()) {\n ah.load();\n }\n return ah;\n }\n\n private ArchiveHistory(Path location) {\n this.location = location;\n this.items = new HashMap<>();\n }\n\n private boolean exists() {\n return Files.isRegularFile(location);\n }\n\n private void load() {\n logger.info(\"Loading archive history from {}\", location);\n try (InputStream historyReader = Files.newInputStream(location)) {\n DocumentBuilder builder = builderFactory.newDocumentBuilder();\n Document doc = builder.parse(historyReader);\n NodeList itemList = doc.getElementsByTagName(\"Item\");\n for (int i = 0; i < itemList.getLength(); i++) {\n Node item = itemList.item(i);\n NamedNodeMap attributes = item.getAttributes();\n String id = attributes.getNamedItem(ATT_ID).getTextContent();\n LocalDate date = LocalDate.parse(attributes.getNamedItem(ATT_DATE).getTextContent());\n Path location = Paths.get(attributes.getNamedItem(ATT_PATH).getTextContent());\n ArchiveHistoryItem historyItem = new ArchiveHistoryItem(id, date, location);\n items.put(id, historyItem);\n }\n } catch (ParserConfigurationException | SAXException | IOException e) {\n logger.error(\"Error loading archive history: \", e);\n }\n }\n\n public void save() {\n logger.info(\"Saving archive history to {}\", location);\n try (BufferedWriter historyWriter = Files.newBufferedWriter(location)) {\n DocumentBuilder builder = builderFactory.newDocumentBuilder();\n Document doc = builder.newDocument();\n Element root = doc.createElement(\"HistoryItems\");\n doc.appendChild(root);\n items.entrySet().forEach(entry -> {\n ArchiveHistoryItem item = entry.getValue();\n Element element = doc.createElement(\"Item\");\n element.setAttribute(ATT_ID, item.getRecordingId());\n element.setAttribute(ATT_DATE, item.getDateArchived().toString());\n element.setAttribute(ATT_PATH, item.getLocation().toString());\n root.appendChild(element);\n });\n Transformer transformer = TransformerFactory.newInstance().newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"4\");\n DOMSource source = new DOMSource(doc);\n StreamResult historyFile = new StreamResult(historyWriter);\n transformer.transform(source, historyFile);\n } catch (ParserConfigurationException | TransformerException | IOException e) {\n logger.error(\"Error saving archive history: \", e);\n }\n }\n\n public boolean contains(Recording recording) {\n verifyRecordingIsValid(recording);\n\n return items.containsKey(recording.getRecordingId());\n }\n\n private void verifyRecordingIsValid(Recording recording) {\n if (recording == null) {\n throw new IllegalArgumentException(\"Recording can't be null\");\n }\n }\n\n public ArchiveHistoryItem get(Recording recording) {\n verifyRecordingIsValid(recording);\n\n ArchiveHistoryItem item = items.get(recording.getRecordingId());\n if (item == null) {\n throw new IllegalArgumentException(\n String.format(\"No history exists for recording '%s'\", recording.getRecordingId())\n );\n }\n\n return item;\n }\n\n public void add(Recording recording) {\n verifyRecordingIsValid(recording);\n\n ArchiveHistoryItem historyItem = new ArchiveHistoryItem(\n recording.getRecordingId(), LocalDate.now(), recording.getDestination()\n );\n items.put(historyItem.getRecordingId(), historyItem);\n }\n\n public static class ArchiveHistoryItem {\n private final LocalDate dateArchived;\n private final Path location;\n private final String recordingId;\n\n public ArchiveHistoryItem(String recordingId, LocalDate dateArchived, Path location) {\n this.recordingId = recordingId;\n this.dateArchived = dateArchived;\n this.location = location;\n }\n\n public String getRecordingId() {\n return recordingId;\n }\n\n public Path getLocation() {\n return location;\n }\n\n public LocalDate getDateArchived() {\n return dateArchived;\n }\n }\n}",
"public class ArchiveStatus implements Comparable<ArchiveStatus> {\n private final TaskStatus status;\n private final double progress;\n private final int secondsRemaining;\n private final int retriesUsed;\n private final int retriesRemaining;\n private final double kbs; // KB per sec\n private final String message;\n private final String tooltip;\n\n public final static int TIME_UNKNOWN = -1;\n public final static int INDETERMINATE = -1;\n public final static ArchiveStatus EMPTY = new ArchiveStatus(TaskStatus.NONE);\n public final static ArchiveStatus QUEUED = new ArchiveStatus(TaskStatus.QUEUED);\n public final static ArchiveStatus FINISHED = new ArchiveStatus(TaskStatus.FINISHED);\n public final static ArchiveStatus DOWNLOADED = new ArchiveStatus(TaskStatus.DOWNLOADED);\n\n private ArchiveStatus(TaskStatus status) {\n this.status = status;\n progress = 0;\n secondsRemaining = 0;\n kbs = 0;\n retriesUsed = 0;\n retriesRemaining = 0;\n message = \"\";\n tooltip = \"\";\n }\n\n private ArchiveStatus(TaskStatus status, int retriesUsed, int retriesRemaining, int secondsRemaining) {\n this.status = status;\n progress = 0;\n this.secondsRemaining = secondsRemaining;\n kbs = 0;\n this.retriesUsed = retriesUsed;\n this.retriesRemaining = retriesRemaining;\n message = \"\";\n tooltip = \"\";\n }\n\n private ArchiveStatus(TaskStatus status, double progress, int secondsRemaining) {\n this.status = status;\n this.progress = progress;\n this.secondsRemaining = secondsRemaining;\n kbs = 0;\n retriesUsed = 0;\n retriesRemaining = 0;\n message = \"\";\n tooltip = \"\";\n }\n\n private ArchiveStatus(TaskStatus status, double progress, int secondsRemaining, double kbs) {\n this.status = status;\n this.progress = progress;\n this.secondsRemaining = secondsRemaining;\n this.kbs = kbs;\n retriesUsed = 0;\n retriesRemaining = 0;\n message = \"\";\n tooltip = \"\";\n }\n\n private ArchiveStatus(TaskStatus status, String message) {\n this.status = status;\n progress = 0;\n secondsRemaining = 0;\n kbs = 0;\n retriesUsed = 0;\n retriesRemaining = 0;\n this.message = message;\n tooltip = null;\n }\n\n private ArchiveStatus(TaskStatus status, String message, String tooltip) {\n this.status = status;\n progress = 0;\n secondsRemaining = 0;\n kbs = 0;\n retriesUsed = 0;\n retriesRemaining = 0;\n this.message = message;\n this.tooltip = tooltip;\n }\n\n public TaskStatus getStatus() {\n return status;\n }\n\n public String getMessage() {\n return message;\n }\n\n public double getProgress() {\n return progress;\n }\n\n public int getSecondsRemaining() {\n return secondsRemaining;\n }\n\n public double getKilobytesPerSecond() {\n return kbs;\n }\n\n @SuppressWarnings(\"unused\")\n public int getRetriesUsed() {\n return retriesUsed;\n }\n\n public int getRetriesRemaining() {\n return retriesRemaining;\n }\n\n public String getTooltip() {\n return tooltip;\n }\n\n public static ArchiveStatus createConnectingStatus(int secondsToWait, int failures, int retriesRemaining) {\n return new ArchiveStatus(TaskStatus.CONNECTING, failures, retriesRemaining, secondsToWait);\n }\n\n public static ArchiveStatus createDownloadingStatus(double progress, int secondsRemaining, double kbs) {\n if (progress >= 1.0) {\n progress = .99;\n }\n return new ArchiveStatus(TaskStatus.DOWNLOADING, progress, secondsRemaining, kbs);\n }\n\n public static ArchiveStatus createRemuxingStatus(double progress, int secondsRemaining) {\n if (progress >= 1.0) {\n progress = .99;\n }\n return new ArchiveStatus(TaskStatus.REMUXING, progress, secondsRemaining);\n }\n\n public static ArchiveStatus createFindingCommercialsStatus(double progress, int secondsRemaining) {\n if (progress >= 1.0) {\n progress = .99;\n }\n return new ArchiveStatus(TaskStatus.FINDING_COMMERCIALS, progress, secondsRemaining);\n }\n\n public static ArchiveStatus createRemovingCommercialsStatus(double progress, int secondsRemaining) {\n if (progress >= 1.0) {\n progress = .99;\n }\n return new ArchiveStatus(TaskStatus.REMOVING_COMMERCIALS, progress, secondsRemaining);\n }\n\n public static ArchiveStatus createTranscodingStatus(double progress, int secondsRemaining) {\n if (progress >= 1.0) {\n progress = .99;\n }\n return new ArchiveStatus(TaskStatus.TRANSCODING, progress, secondsRemaining);\n }\n\n public static ArchiveStatus createErrorStatus(Throwable e) {\n if (e instanceof ArchiveTaskException) {\n ArchiveTaskException ate = (ArchiveTaskException) e;\n return new ArchiveStatus(TaskStatus.ERROR, ate.getLocalizedMessage(), ate.getTooltip());\n } else {\n return new ArchiveStatus(TaskStatus.ERROR, e.getLocalizedMessage());\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof ArchiveStatus)) {\n return false;\n } else if (obj == this) {\n return true;\n }\n\n ArchiveStatus other = (ArchiveStatus) obj;\n return (this.status == other.status && Double.compare(this.progress, other.progress) == 0 &&\n this.secondsRemaining == other.secondsRemaining && this.message.equals(other.message));\n }\n\n @Override\n public int hashCode() {\n int hash = 17;\n hash = hash * 31 + status.ordinal();\n long bits = Double.doubleToLongBits(progress);\n hash = hash * 31 + (int) (bits ^ (bits >>> 32));\n hash = hash * 31 + secondsRemaining;\n hash = hash * 31 + message.hashCode();\n return hash;\n }\n\n @Override\n public int compareTo(ArchiveStatus o) {\n if (this.status != o.status) {\n return this.status.ordinal() - o.status.ordinal();\n } else if (Double.compare(this.progress, o.progress) != 0) {\n return Double.compare(this.progress, o.progress);\n } else if (!this.message.equals(o.message)) {\n return this.message.compareTo(o.message);\n }\n return 0;\n }\n\n @Override\n public String toString() {\n return \"ArchiveStatus{\" +\n \"status=\" + status +\n \", progress=\" + progress +\n \", secondsRemaining=\" + secondsRemaining +\n \", message='\" + message + '\\'' +\n '}';\n }\n\n public enum TaskStatus {\n TRANSCODING,\n REMOVING_COMMERCIALS,\n FINDING_COMMERCIALS,\n REMUXING,\n CONNECTING,\n DOWNLOADING,\n DOWNLOADED,\n QUEUED,\n FINISHED,\n ERROR,\n NONE;\n\n public boolean isCancelable() {\n switch (this) {\n case NONE:\n case FINISHED:\n case ERROR:\n return false;\n case QUEUED:\n case CONNECTING:\n case DOWNLOADING:\n case DOWNLOADED:\n case TRANSCODING:\n case REMOVING_COMMERCIALS:\n case FINDING_COMMERCIALS:\n case REMUXING:\n return true;\n default:\n throw new AssertionError(\"Unknown TaskStatus\");\n }\n }\n\n public boolean isRemovable() {\n switch (this) {\n case NONE:\n case FINISHED:\n case ERROR:\n return true;\n case QUEUED:\n case CONNECTING:\n case DOWNLOADING:\n case DOWNLOADED:\n case TRANSCODING:\n case REMOVING_COMMERCIALS:\n case FINDING_COMMERCIALS:\n case REMUXING:\n return false;\n default:\n throw new AssertionError(\"Unknown TaskStatus\");\n }\n }\n }\n}",
"public class Recording {\n // Items displayed in the RecordingListView need to be observable properties\n private final StringProperty title;\n private final StringProperty fullTitle;\n private final ObjectProperty<Duration> duration;\n private final ObjectProperty<LocalDateTime> dateRecorded;\n private final ObjectProperty<LocalDate> dateArchived;\n private final ObjectProperty<ArchiveStatus> status;\n private final ObjectProperty<Path> destination;\n private final ObjectProperty<FileExistsAction> fileExistsAction;\n // Denotes Recordings used as the header line for the series in RecordingListView\n private final BooleanProperty isSeriesHeading;\n private final BooleanProperty isArchivable;\n private final BooleanProperty isCancellable;\n private final BooleanProperty isPlayable;\n private final BooleanProperty isRemovable;\n\n private final String recordingId;\n private final String bodyId;\n private final String seriesTitle;\n private final String episodeTitle;\n private final int seriesNumber;\n private final List<Integer> episodeNumbers;\n private final Channel channel;\n private final String description;\n private final URL imageURL;\n private final LocalDate originalAirDate;\n private final RecordingState state;\n private final RecordingReason reason;\n private final boolean isCopyable;\n private final LocalDateTime expectedDeletion;\n private final Type collectionType;\n\n // Denotes Recordings that are child nodes in the RecordingListView\n private boolean isChildRecording;\n private final int numEpisodes;\n // Combine season and episode number(s) into a more useful string\n private final String seasonAndEpisode;\n private FileType destinationType;\n\n public final static int DESIRED_IMAGE_WIDTH = 200;\n public final static int DESIRED_IMAGE_HEIGHT = 150;\n private final static char EM_DASH = '\\u2014';\n private final static String UNTITLED_TEXT = \"Untitled\";\n\n private Recording(Builder builder) {\n recordingId = builder.recordingId;\n bodyId = builder.bodyId;\n seriesTitle = builder.seriesTitle;\n episodeTitle = builder.episodeTitle;\n seriesNumber = builder.seriesNumber;\n episodeNumbers = builder.episodeNumbers;\n channel = builder.channel;\n description = builder.description;\n imageURL = builder.imageURL;\n originalAirDate = builder.originalAirDate;\n state = builder.state;\n reason = builder.reason;\n isCopyable = builder.isCopyable;\n expectedDeletion = builder.expectedDeletion;\n collectionType = builder.collectionType;\n\n isChildRecording = builder.isChildRecording;\n numEpisodes = builder.numEpisodes;\n seasonAndEpisode = buildSeasonAndEpisode(seriesNumber, episodeNumbers);\n\n isSeriesHeading = new SimpleBooleanProperty(builder.isSeriesHeading);\n title = new SimpleStringProperty(buildTitle());\n fullTitle = new SimpleStringProperty(buildSingleRecordingTitle());\n duration = new SimpleObjectProperty<>(Duration.ofSeconds(builder.secondsLong));\n dateRecorded = new SimpleObjectProperty<>(builder.dateRecorded);\n dateArchived = new SimpleObjectProperty<>();\n status = new SimpleObjectProperty<>(ArchiveStatus.EMPTY);\n destination = new SimpleObjectProperty<>();\n fileExistsAction = new SimpleObjectProperty<>(FileExistsAction.REPLACE);\n isArchivable = new SimpleBooleanProperty(isArchivable());\n isCancellable = new SimpleBooleanProperty(false);\n isPlayable = new SimpleBooleanProperty(false);\n isRemovable = new SimpleBooleanProperty(isRemovable());\n }\n\n /**\n * Build a UI-friendly String describing the season and episode number.\n */\n private String buildSeasonAndEpisode(int seriesNumber, List<Integer> episodeNumbers) {\n StringBuilder sb = new StringBuilder();\n int numEpisodes = episodeNumbers.size();\n if (seriesNumber > 0) {\n sb.append(String.format(\"Season %d\", seriesNumber));\n if (numEpisodes > 0) {\n sb.append(\" \");\n }\n }\n if (numEpisodes > 0) {\n if (numEpisodes > 1) {\n sb.append(\"Episodes \");\n for (int i = 0; i < numEpisodes - 2; i++) {\n sb.append(String.format(\"%d, \", episodeNumbers.get(i)));\n }\n sb.append(String.format(\"%d & %d\", episodeNumbers.get(numEpisodes - 2), episodeNumbers.get(numEpisodes - 1)));\n } else {\n sb.append(String.format(\"Episode %d\", episodeNumbers.get(0)));\n }\n }\n return sb.toString();\n }\n\n /**\n * Build a UI-friendly title that consists of the series name + episode name for regular recordings,\n * and just the series name for header recordings.\n */\n private String buildTitle() {\n if (isSeriesHeading.get()) {\n return buildSeriesHeadingTitle();\n } else if (isChildRecording) {\n return buildChildRecordingTitle();\n } else {\n return buildSingleRecordingTitle();\n }\n }\n\n private String buildSeriesHeadingTitle() {\n if (seriesTitle != null) {\n return seriesTitle;\n } else {\n return UNTITLED_TEXT;\n }\n }\n\n private String buildChildRecordingTitle() {\n if (episodeTitle != null) {\n return episodeTitle;\n } else if (seriesTitle != null && hasSeasonAndEpisode()) {\n return String.format(\"%s %c %s\", seriesTitle, EM_DASH, seasonAndEpisode);\n } else if (seriesTitle != null) {\n return seriesTitle;\n } else {\n return UNTITLED_TEXT;\n }\n }\n\n /**\n * Build a title for a recording that is not grouped with others from the same series.\n */\n private String buildSingleRecordingTitle() {\n if (seriesTitle != null && episodeTitle != null) {\n return String.format(\"%s %c %s\", seriesTitle, EM_DASH, episodeTitle);\n } else if (seriesTitle != null) {\n return seriesTitle;\n } else if (episodeTitle != null) {\n return episodeTitle;\n } else {\n return UNTITLED_TEXT;\n }\n }\n\n private boolean isArchivable() {\n return isCopyable && !isInProgress() && !status.get().getStatus().isCancelable();\n }\n\n private boolean isRemovable() {\n return status.get().getStatus().isRemovable();\n }\n\n public String getRecordingId() {\n return recordingId;\n }\n\n public String getBodyId() {\n return bodyId;\n }\n\n public String getSeriesTitle() {\n return seriesTitle;\n }\n\n public String getEpisodeTitle() {\n return episodeTitle;\n }\n\n private boolean hasSeasonAndEpisode() {\n return (seriesNumber > 0 || episodeNumbers.size() > 0);\n }\n\n public String getSeasonAndEpisode() {\n return seasonAndEpisode;\n }\n\n public Channel getChannel() {\n return channel;\n }\n\n public String getDescription() {\n return description;\n }\n\n public URL getImageURL() {\n return imageURL;\n }\n\n public LocalDate getOriginalAirDate() {\n return originalAirDate;\n }\n\n @SuppressWarnings(\"unused\")\n public RecordingState getState() {\n return state;\n }\n\n @SuppressWarnings(\"unused\")\n public RecordingReason getReason() {\n return reason;\n }\n\n public boolean isCopyProtected() {\n return !isCopyable;\n }\n\n public boolean isSuggestion() {\n return reason == RecordingReason.TIVO_SUGGESTION;\n }\n\n public boolean isInProgress() {\n return state == RecordingState.IN_PROGRESS;\n }\n\n /**\n * Returns true if this recording matches the originalAirDate, or there was no original air date.\n */\n public boolean isOriginalRecording() {\n assert (dateRecorded != null);\n assert (dateRecorded.getValue() != null);\n\n return originalAirDate == null || (originalAirDate.getYear() == dateRecorded.getValue().getYear() &&\n originalAirDate.getDayOfYear() == dateRecorded.getValue().getDayOfYear());\n }\n\n public void isChildRecording(boolean val) {\n isChildRecording = val;\n title.setValue(buildTitle());\n }\n\n public int getNumEpisodes() {\n return numEpisodes;\n }\n\n public ObjectProperty<Path> destinationProperty() {\n return destination;\n }\n\n public Path getDestination() {\n return destination.getValue();\n }\n\n public void setDestination(Path val) {\n destination.setValue(val);\n }\n\n public FileType getDestinationType() {\n return destinationType;\n }\n\n public void setDestinationType(FileType type) {\n destinationType = type;\n }\n\n public ObjectProperty<FileExistsAction> fileExistsActionProperty() {\n return fileExistsAction;\n }\n\n public void setFileExistsAction(FileExistsAction action) {\n fileExistsAction.setValue(action);\n }\n\n public FileExistsAction getFileExistsAction() {\n return fileExistsAction.getValue();\n }\n\n public LocalDateTime getExpectedDeletion() {\n return expectedDeletion;\n }\n\n public String getFullTitle() {\n return buildSingleRecordingTitle();\n }\n\n public String getDefaultFlatFilename() {\n return buildDefaultFlatFilename();\n }\n\n public Path getDefaultNestedPath() {\n return buildDefaultNestedPath();\n }\n\n /**\n * Build a sensible default filename that includes as much relevant available information as possible.\n */\n private String buildDefaultFlatFilename() {\n StringJoiner components = new StringJoiner(\" - \");\n int numComponents = 1; // We always add a title\n\n if (seriesTitle != null && !seriesTitle.isEmpty()) {\n components.add(seriesTitle);\n } else {\n // Ensure we have *something* for the title\n components.add(UNTITLED_TEXT);\n }\n\n if (hasSeasonAndEpisode()) {\n components.add(String.format(\"S%02dE%s\", seriesNumber, getEpisodeNumberRange()));\n numComponents++;\n }\n\n if (episodeTitle != null && !episodeTitle.isEmpty()) {\n components.add(episodeTitle);\n numComponents++;\n }\n\n // If we only have a title and this isn't a movie, check the value of the original air date; if it's within\n // one week of the recording date, use it, otherwise, assume the original air date refers to the start\n // of the series and use the date the show was recorded. If there is no original air date, use the recording\n // date instead.\n if (numComponents == 1 && collectionType != Type.MOVIE) {\n LocalDate dateRecorded = getDateRecorded().toLocalDate();\n if (originalAirDate != null && originalAirDate.plusWeeks(1).isAfter(dateRecorded)) {\n components.add(originalAirDate.format(DateTimeFormatter.ISO_LOCAL_DATE));\n } else {\n components.add(getDateRecorded().format(DateTimeFormatter.ISO_LOCAL_DATE));\n }\n }\n\n\n return filterUnsafeChars(components.toString());\n }\n\n /**\n * Build a sensible default nested filename.\n * Try to follow Plex's guidelines at\n * https://support.plex.tv/hc/en-us/articles/200220687-Naming-Series-Season-Based-TV-Shows\n */\n private Path buildDefaultNestedPath() {\n List<String> nestedComponents = new ArrayList<>();\n\n if (collectionType == Type.MOVIE) {\n nestedComponents.add(\"Movies\");\n } else {\n nestedComponents.add(\"TV Shows\");\n }\n\n if (seriesTitle != null && !seriesTitle.isEmpty()) {\n nestedComponents.add(filterUnsafeChars(seriesTitle));\n }\n\n if (seriesNumber > 0) {\n nestedComponents.add(String.format(\"Season %02d\", seriesNumber));\n }\n\n nestedComponents.add(buildDefaultFlatFilename());\n\n if (nestedComponents.size() == 4) {\n return Paths.get(\n nestedComponents.get(0), nestedComponents.get(1), nestedComponents.get(2), nestedComponents.get(3)\n );\n } else if (nestedComponents.size() == 3) {\n return Paths.get(nestedComponents.get(0), nestedComponents.get(1), nestedComponents.get(2));\n } else if (nestedComponents.size() == 2) {\n return Paths.get(nestedComponents.get(0), nestedComponents.get(1));\n } else {\n return Paths.get(nestedComponents.get(0));\n }\n }\n\n private String getEpisodeNumberRange() {\n if (episodeNumbers.size() == 1) {\n return String.format(\"%02d\", episodeNumbers.get(0));\n } else if (episodeNumbers.size() == 2) {\n return String.format(\"%02d-E%02d\", episodeNumbers.get(0), episodeNumbers.get(1));\n } else {\n return episodeNumbers.stream().map(Object::toString).collect(Collectors.joining(\",\"));\n }\n }\n\n /**\n * Remove invalid filename characters from @filename.\n * Replace invalid characters with a space if they are between to two valid characters.\n */\n private String filterUnsafeChars(String filename) {\n StringBuilder sb = new StringBuilder();\n boolean prevCharIsSpace = false;\n for (Character c : filename.toCharArray()) {\n int type = Character.getType(c);\n if (Character.isLetterOrDigit(c) || c == '\\'' || c == '.' || c == '&' || c == ',' || c == '!' ||\n type == Character.DASH_PUNCTUATION) {\n sb.append(c);\n prevCharIsSpace = false;\n } else if (type != Character.OTHER_PUNCTUATION) {\n // Don't even add a space for OTHER_PUNCTUATION\n if (Character.isWhitespace(c) && !prevCharIsSpace) {\n sb.append(c);\n prevCharIsSpace = true;\n } else if (!prevCharIsSpace) {\n // Replace an invalid character with a space\n sb.append(' ');\n prevCharIsSpace = true;\n }\n }\n }\n return sb.toString();\n }\n\n public String getTitle() {\n return title.get();\n }\n\n public StringProperty titleProperty() {\n return title;\n }\n\n public StringProperty fullTitleProperty() { return fullTitle; }\n\n public Duration getDuration() {\n return duration.get();\n }\n\n public ObjectProperty<Duration> durationProperty() {\n return duration;\n }\n\n public LocalDateTime getDateRecorded() {\n return dateRecorded.get();\n }\n\n public ObjectProperty<LocalDateTime> dateRecordedProperty() {\n return dateRecorded;\n }\n\n @SuppressWarnings(\"unused\")\n public ObjectProperty<LocalDate> dateArchivedProperty() { return dateArchived; }\n\n public void setDateArchived(LocalDate date) {\n dateArchived.setValue(date);\n }\n\n public LocalDate getDateArchived() {\n return dateArchived.get();\n }\n\n public ArchiveStatus getStatus() {\n return status.get();\n }\n\n public void setStatus(ArchiveStatus status) {\n this.status.setValue(status);\n updateIsArchivable();\n updateIsCancellable();\n updateIsPlayable();\n }\n\n public ObjectProperty<ArchiveStatus> statusProperty() {\n return status;\n }\n\n public boolean isSeriesHeading() {\n return isSeriesHeading.get();\n }\n\n @SuppressWarnings(\"unused\")\n public BooleanProperty seriesHeadingProperty() {\n return isSeriesHeading;\n }\n\n public BooleanProperty isArchivableProperty() {\n return isArchivable;\n }\n\n public BooleanProperty isCancellableProperty() {\n return isCancellable;\n }\n\n public BooleanProperty isPlayableProperty() {\n return isPlayable;\n }\n\n public BooleanProperty isRemovableProperty() {\n return isRemovable;\n }\n\n private void updateIsArchivable() {\n boolean isArchivable = isArchivable();\n if (this.isArchivable.get() != isArchivable) {\n this.isArchivable.set(isArchivable);\n }\n }\n\n private void updateIsCancellable() {\n boolean isCancellable = !isSeriesHeading.get() && status.getValue().getStatus().isCancelable();\n if (this.isCancellable.get() != isCancellable) {\n this.isCancellable.set(isCancellable);\n }\n }\n\n private void updateIsPlayable() {\n boolean isPlayable = !isSeriesHeading.get() && status.getValue().getStatus() == ArchiveStatus.TaskStatus.FINISHED;\n if (this.isPlayable.get() != isPlayable) {\n this.isPlayable.set(isPlayable);\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Recording recording = (Recording) o;\n\n return !(recordingId != null ? !recordingId.equals(recording.recordingId) : recording.recordingId != null) &&\n !(seriesTitle != null ? !seriesTitle.equals(recording.seriesTitle) : recording.seriesTitle != null);\n }\n\n @Override\n public int hashCode() {\n int result = recordingId != null ? recordingId.hashCode() : 0;\n result = 31 * result + (seriesTitle != null ? seriesTitle.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"Recording{\" +\n \"title=\" + title +\n \", dateRecorded=\" + dateRecorded +\n \", status=\" + status +\n \", isSeriesHeading=\" + isSeriesHeading +\n \", isArchivable=\" + isArchivable +\n \", isCancellable=\" + isCancellable +\n \", isPlayable=\" + isPlayable +\n \", isRemovable=\" + isRemovable +\n \", recordingId='\" + recordingId + '\\'' +\n \", bodyId='\" + bodyId + '\\'' +\n \", seriesTitle='\" + seriesTitle + '\\'' +\n \", episodeTitle='\" + episodeTitle + '\\'' +\n \", duration=\" + duration +\n \", seriesNumber=\" + seriesNumber +\n \", episodeNumbers=\" + episodeNumbers +\n \", channel=\" + channel +\n \", description='\" + description + '\\'' +\n \", imageURL=\" + imageURL +\n \", originalAirDate=\" + originalAirDate +\n \", state=\" + state +\n \", reason=\" + reason +\n \", isCopyable=\" + isCopyable +\n \", expectedDeletion=\" + expectedDeletion +\n \", collectionType=\" + collectionType +\n \", isChildRecording=\" + isChildRecording +\n \", numEpisodes=\" + numEpisodes +\n \", seasonAndEpisode='\" + seasonAndEpisode + '\\'' +\n \", destination=\" + destination +\n \", destinationType=\" + destinationType +\n '}';\n }\n\n public enum Type {\n SERIES,\n MOVIE;\n\n public static Type from(String val) {\n switch (val) {\n case \"movie\":\n return MOVIE;\n default:\n return SERIES;\n }\n }\n }\n\n public enum FileExistsAction {\n OK,\n REPLACE,\n CANCEL\n }\n\n public static class Builder {\n private String recordingId;\n private String bodyId;\n private String seriesTitle;\n private int seriesNumber;\n private String episodeTitle;\n private List<Integer> episodeNumbers;\n private Channel channel;\n private int secondsLong;\n private LocalDateTime dateRecorded;\n private String description;\n private URL imageURL;\n private LocalDate originalAirDate;\n private RecordingState state;\n private RecordingReason reason;\n private boolean isCopyable;\n private boolean isSeriesHeading;\n private boolean isChildRecording;\n private int numEpisodes;\n private LocalDateTime expectedDeletion;\n private Type collectionType;\n\n public Builder() {\n // Set default values\n episodeNumbers = Collections.emptyList();\n description = \"No description available\";\n state = RecordingState.UNKNOWN;\n reason = RecordingReason.UNKNOWN;\n }\n\n public Builder recordingId(String val) {\n recordingId = val;\n return this;\n }\n\n public Builder bodyId(String val) {\n bodyId = val;\n return this;\n }\n\n public Builder seriesTitle(String val) {\n seriesTitle = val;\n return this;\n }\n\n public Builder episodeTitle(String val) {\n episodeTitle = val;\n return this;\n }\n\n public Builder seriesNumber(int val) {\n seriesNumber = val;\n return this;\n }\n\n public Builder episodeNumbers(List<Integer> val) {\n episodeNumbers = val;\n return this;\n }\n\n @SuppressWarnings(\"unused\")\n public Builder channel(String name, String number, URL logoURL) {\n channel = new Channel(name, number, logoURL);\n return this;\n }\n\n public Builder channel(Channel val) {\n channel = val;\n return this;\n }\n\n public Builder secondsLong(int val) {\n secondsLong = val;\n return this;\n }\n\n public Builder recordedOn(LocalDateTime val) {\n dateRecorded = val;\n return this;\n }\n\n public Builder description(String val) {\n description = val;\n return this;\n }\n\n public Builder image(URL val) {\n imageURL = val;\n return this;\n }\n\n public Builder originalAirDate(LocalDate val) {\n originalAirDate = val;\n return this;\n }\n\n public Builder state(RecordingState val) {\n state = val;\n return this;\n }\n\n public Builder reason(RecordingReason val) {\n reason = val;\n return this;\n }\n\n public Builder copyable(boolean val) {\n isCopyable = val;\n return this;\n }\n\n public Builder isSeriesHeading(boolean val) {\n isSeriesHeading = val;\n return this;\n }\n\n @SuppressWarnings(\"unused\")\n public Builder isChildRecording(boolean val) {\n isChildRecording = val;\n return this;\n }\n\n public Builder numEpisodes(int val) {\n numEpisodes = val;\n return this;\n }\n\n public Builder expectedDeletion(LocalDateTime val) {\n expectedDeletion = val;\n return this;\n }\n\n public Builder collectionType(String val) {\n collectionType = Type.from(val);\n return this;\n }\n\n public Recording build() {\n return new Recording(this);\n }\n }\n}",
"public class Tivo {\n private final String name;\n private final String tsn;\n private final Set<InetAddress> addresses;\n private final int port;\n private String mak;\n private long storageBytesUsed;\n private long storageBytesTotal;\n private String bodyId;\n private MindRPC client;\n\n private static final String JSON_NAME = \"name\";\n private static final String JSON_TSN = \"tsn\";\n private static final String JSON_ADDRESSES = \"addresses\";\n private static final String JSON_PORT = \"port\";\n private static final String DEFAULT_NAME = \"TiVo\";\n private static final String DEFAULT_TSN = \"unknown\";\n private static final int DEFAULT_PORT = 1413;\n\n private Tivo(Builder builder) {\n name = builder.name;\n tsn = builder.tsn;\n addresses = builder.addresses;\n port = builder.port;\n mak = builder.mak;\n bodyId = \"-\";\n }\n\n public void updateMak(String newMak) {\n this.mak = newMak;\n client = null;\n }\n\n public void updateAddresses(Set<InetAddress> addresses) {\n this.addresses.clear();\n this.addresses.addAll(addresses);\n }\n\n public String getName() {\n return name;\n }\n\n public Set<InetAddress> getAddresses() {\n return Collections.unmodifiableSet(addresses);\n }\n\n public String getBodyId() {\n return bodyId;\n }\n\n public void setBodyId(String val) {\n bodyId = val;\n }\n\n public long getStorageBytesUsed() {\n return storageBytesUsed;\n }\n\n public void setStorageBytesUsed(long val) {\n storageBytesUsed = val;\n }\n\n public long getStorageBytesTotal() {\n return storageBytesTotal;\n }\n\n public void setStorageBytesTotal(long val) {\n storageBytesTotal = val;\n }\n\n public MindRPC getClient() {\n initRPCClientIfNeeded();\n return client;\n }\n\n private void initRPCClientIfNeeded() {\n if (client == null) {\n client = new MindRPC(addresses.iterator().next(), port, mak);\n }\n }\n\n @Override\n public int hashCode() {\n int result = name.hashCode();\n result = 31 * result + tsn.hashCode();\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Tivo)) {\n return false;\n }\n\n Tivo o = (Tivo) obj;\n return (name.equals(o.name) && tsn.equals(o.tsn));\n }\n\n @Override\n public String toString() {\n return String.format(\"Tivo[name=%s, tsn=%s, addresses=%s, port=%d]\", name, tsn, addresses, port);\n }\n\n /**\n * Convert this Tivo to a JSON object.\n *\n * @return A new JSONObject representing this Tivo\n */\n public JSONObject toJSON() {\n JSONObject json = new JSONObject();\n json.put(JSON_NAME, name);\n json.put(JSON_TSN, tsn);\n json.put(JSON_PORT, port);\n Base64.Encoder encoder = Base64.getEncoder();\n String[] encodedAddresses = new String[addresses.size()];\n Iterator<InetAddress> iterator = addresses.iterator();\n int i = 0;\n while (iterator.hasNext()) {\n encodedAddresses[i] = encoder.encodeToString(iterator.next().getAddress());\n i++;\n }\n json.put(JSON_ADDRESSES, new JSONArray(encodedAddresses));\n return json;\n }\n\n /**\n * Create a new Tivo object from a JSON String.\n *\n * @param json String containing the Tivo object in JSON\n * @param mak Media access key to use for the resulting Tivo\n * @return A new Tivo object\n * @throws IllegalArgumentException on invalid address\n */\n public static Tivo fromJSON(final String json, final String mak) throws IllegalArgumentException {\n JSONObject jo = new JSONObject(json);\n String name = jo.getString(JSON_NAME);\n String tsn = jo.getString(JSON_TSN);\n int port = jo.getInt(JSON_PORT);\n JSONArray jsonAddresses = jo.getJSONArray(JSON_ADDRESSES);\n Set<InetAddress> addresses = new HashSet<>();\n Base64.Decoder decoder = Base64.getDecoder();\n for (int i = 0; i < jsonAddresses.length(); i++) {\n try {\n addresses.add(InetAddress.getByAddress(decoder.decode(jsonAddresses.getString(i))));\n } catch (UnknownHostException e) {\n throw new IllegalArgumentException(\"TiVo address in invalid: \" + e.getLocalizedMessage());\n }\n }\n\n return new Builder().name(name).tsn(tsn).port(port).addresses(addresses).mak(mak).build();\n }\n\n public static Tivo fromIP(final InetAddress address, final String mak) {\n return new Builder().name(DEFAULT_NAME).tsn(DEFAULT_TSN).port(DEFAULT_PORT).\n addresses(Collections.singleton(address)).mak(mak).build();\n }\n\n public static class Builder {\n private String name;\n private Set<InetAddress> addresses;\n private String tsn;\n private int port;\n private String mak;\n\n public Builder name(String val) {\n name = val;\n return this;\n }\n\n public Builder addresses(Set<InetAddress> val) {\n addresses = val;\n return this;\n }\n\n public Builder tsn(String val) {\n tsn = val;\n return this;\n }\n\n public Builder port(int val) {\n port = val;\n return this;\n }\n\n public Builder mak(String val) {\n mak = val;\n return this;\n }\n\n public Tivo build() {\n failOnInvalidState();\n return new Tivo(this);\n }\n\n private void failOnInvalidState() {\n if (name == null) {\n throw new IllegalStateException(\"Field 'name' cannot be null\");\n }\n if (mak == null) {\n throw new IllegalStateException(\"Field 'mak' cannot be null\");\n }\n if (addresses == null) {\n throw new IllegalStateException(\"Field 'addresses' cannot be null\");\n }\n if (tsn == null) {\n throw new IllegalStateException(\"Field 'tsn' cannot be null\");\n }\n if (port == 0) {\n throw new IllegalStateException(\"Field 'port' cannot be 0\");\n }\n }\n }\n\n public static class StringConverter extends javafx.util.StringConverter<Tivo> {\n @Override\n public String toString(Tivo object) {\n return object.getName();\n }\n\n @Override\n public Tivo fromString(String string) {\n return null;\n }\n }\n}"
] | import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.straylightlabs.archivo.Archivo;
import net.straylightlabs.archivo.model.ArchiveHistory;
import net.straylightlabs.archivo.model.ArchiveStatus;
import net.straylightlabs.archivo.model.Recording;
import net.straylightlabs.archivo.model.Tivo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDate;
import java.util.Observable;
import java.util.concurrent.ConcurrentHashMap; | /*
* Copyright 2015-2016 Todd Kulesza <[email protected]>.
*
* This file is part of Archivo.
*
* Archivo 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 3 of the License, or
* (at your option) any later version.
*
* Archivo 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 Archivo. If not, see <http://www.gnu.org/licenses/>.
*/
package net.straylightlabs.archivo.controller;
/**
* Enqueue archive requests for processing via a background thread, and allow archive tasks to be canceled.
* Alerts its observes when the queue size changes between empty and not-empty.
*/
public class ArchiveQueueManager extends Observable {
private final Archivo mainApp;
private final ExecutorService executorService;
private final ConcurrentHashMap<Recording, ArchiveTask> queuedTasks;
private final Lock downloadLock;
private final Lock processingLock;
private static final int POOL_SIZE = 2;
private final static Logger logger = LoggerFactory.getLogger(ArchiveQueueManager.class);
public ArchiveQueueManager(Archivo mainApp) {
this.mainApp = mainApp;
executorService = Executors.newFixedThreadPool(POOL_SIZE);
downloadLock = new ReentrantLock();
processingLock = new ReentrantLock();
queuedTasks = new ConcurrentHashMap<>();
}
public boolean enqueueArchiveTask(Recording recording, Tivo tivo, String mak) {
try {
ArchiveTask task = new ArchiveTask(recording, tivo, mak, mainApp.getUserPrefs(), downloadLock, processingLock);
task.setOnRunning(event -> mainApp.setStatusText(String.format("Archiving %s...", recording.getFullTitle())));
task.setOnSucceeded(event -> {
logger.info("ArchiveTask succeeded for {}", recording.getFullTitle());
updateArchiveHistory(recording);
removeTask(recording);
recording.setDateArchived(LocalDate.now()); | recording.setStatus(ArchiveStatus.FINISHED); | 2 |
jenkinsci/gitlab-plugin | src/test/java/com/dabsquared/gitlabjenkins/util/CommitStatusUpdaterTest.java | [
"@ExportedBean\npublic final class CauseData {\n private final ActionType actionType;\n private final Integer sourceProjectId;\n private final Integer targetProjectId;\n private final String branch;\n private final String sourceBranch;\n private final String userName;\n private final String userUsername;\n private final String userEmail;\n private final String sourceRepoHomepage;\n private final String sourceRepoName;\n private final String sourceNamespace;\n private final String sourceRepoUrl;\n private final String sourceRepoSshUrl;\n private final String sourceRepoHttpUrl;\n private final String mergeRequestTitle;\n private final String mergeRequestDescription;\n private final Integer mergeRequestId;\n private final Integer mergeRequestIid;\n private final String mergeRequestState;\n private final String mergedByUser;\n private final String mergeRequestAssignee;\n private final Integer mergeRequestTargetProjectId;\n private final String targetBranch;\n private final String targetRepoName;\n private final String targetNamespace;\n private final String targetRepoSshUrl;\n private final String targetRepoHttpUrl;\n private final String triggeredByUser;\n private final String before;\n private final String after;\n private final String lastCommit;\n private final String targetProjectUrl;\n private final String triggerPhrase;\n private final String ref;\n private final String beforeSha;\n private final String isTag;\n private final String sha;\n private final String status;\n private final String stages;\n private final String createdAt;\n private final String finishedAt;\n private final String buildDuration;\n\n @GeneratePojoBuilder(withFactoryMethod = \"*\")\n CauseData(ActionType actionType, Integer sourceProjectId, Integer targetProjectId, String branch, String sourceBranch, String userName,\n String userUsername, String userEmail, String sourceRepoHomepage, String sourceRepoName, String sourceNamespace, String sourceRepoUrl,\n String sourceRepoSshUrl, String sourceRepoHttpUrl, String mergeRequestTitle, String mergeRequestDescription, Integer mergeRequestId,\n Integer mergeRequestIid, Integer mergeRequestTargetProjectId, String targetBranch, String targetRepoName, String targetNamespace, String targetRepoSshUrl,\n String targetRepoHttpUrl, String triggeredByUser, String before, String after, String lastCommit, String targetProjectUrl,\n String triggerPhrase, String mergeRequestState, String mergedByUser, String mergeRequestAssignee, String ref, String isTag,\n\t String sha, String beforeSha, String status, String stages, String createdAt, String finishedAt, String buildDuration) {\n this.actionType = Objects.requireNonNull(actionType, \"actionType must not be null.\");\n this.sourceProjectId = Objects.requireNonNull(sourceProjectId, \"sourceProjectId must not be null.\");\n this.targetProjectId = Objects.requireNonNull(targetProjectId, \"targetProjectId must not be null.\");\n this.branch = Objects.requireNonNull(branch, \"branch must not be null.\");\n this.sourceBranch = Objects.requireNonNull(sourceBranch, \"sourceBranch must not be null.\");\n this.userName = Objects.requireNonNull(userName, \"userName must not be null.\");\n this.userUsername = userUsername == null ? \"\" : userUsername;\n this.userEmail = userEmail == null ? \"\" : userEmail;\n this.sourceRepoHomepage = sourceRepoHomepage == null ? \"\" : sourceRepoHomepage;\n this.sourceRepoName = Objects.requireNonNull(sourceRepoName, \"sourceRepoName must not be null.\");\n this.sourceNamespace = Objects.requireNonNull(sourceNamespace, \"sourceNamespace must not be null.\");\n this.sourceRepoUrl = sourceRepoUrl == null ? sourceRepoSshUrl : sourceRepoUrl;\n this.sourceRepoSshUrl = Objects.requireNonNull(sourceRepoSshUrl, \"sourceRepoSshUrl must not be null.\");\n this.sourceRepoHttpUrl = Objects.requireNonNull(sourceRepoHttpUrl, \"sourceRepoHttpUrl must not be null.\");\n this.mergeRequestTitle = Objects.requireNonNull(mergeRequestTitle, \"mergeRequestTitle must not be null.\");\n this.mergeRequestDescription = mergeRequestDescription == null ? \"\" : mergeRequestDescription;\n this.mergeRequestId = mergeRequestId;\n this.mergeRequestIid = mergeRequestIid;\n this.mergeRequestState = mergeRequestState == null ? \"\" : mergeRequestState;\n this.mergedByUser = mergedByUser == null ? \"\" : mergedByUser;\n this.mergeRequestAssignee = mergeRequestAssignee == null ? \"\" : mergeRequestAssignee;\n this.mergeRequestTargetProjectId = mergeRequestTargetProjectId;\n this.targetBranch = Objects.requireNonNull(targetBranch, \"targetBranch must not be null.\");\n this.targetRepoName = Objects.requireNonNull(targetRepoName, \"targetRepoName must not be null.\");\n this.targetNamespace = Objects.requireNonNull(targetNamespace, \"targetNamespace must not be null.\");\n this.targetRepoSshUrl = Objects.requireNonNull(targetRepoSshUrl, \"targetRepoSshUrl must not be null.\");\n this.targetRepoHttpUrl = Objects.requireNonNull(targetRepoHttpUrl, \"targetRepoHttpUrl must not be null.\");\n this.triggeredByUser = Objects.requireNonNull(triggeredByUser, \"triggeredByUser must not be null.\");\n this.before = before == null ? \"\" : before;\n this.after = after == null ? \"\" : after;\n this.lastCommit = Objects.requireNonNull(lastCommit, \"lastCommit must not be null\");\n this.targetProjectUrl = targetProjectUrl;\n this.triggerPhrase = triggerPhrase;\n this.ref = ref;\n this.isTag = isTag;\n this.sha = sha;\n this.beforeSha = beforeSha;\n this.status = status;\n this.stages = stages;\n this.createdAt = createdAt;\n this.finishedAt = finishedAt;\n this.buildDuration = buildDuration;\n }\n\n @Exported\n public Map<String, String> getBuildVariables() {\n MapWrapper<String, String> variables = new MapWrapper<>(new HashMap<String, String>());\n variables.put(\"gitlabBranch\", branch);\n variables.put(\"gitlabSourceBranch\", sourceBranch);\n variables.put(\"gitlabActionType\", actionType.name());\n variables.put(\"gitlabUserName\", userName);\n variables.put(\"gitlabUserUsername\", userUsername == null ? \"\" : userUsername);\n variables.put(\"gitlabUserEmail\", userEmail);\n variables.put(\"gitlabSourceRepoHomepage\", sourceRepoHomepage);\n variables.put(\"gitlabSourceRepoName\", sourceRepoName);\n variables.put(\"gitlabSourceNamespace\", sourceNamespace);\n variables.put(\"gitlabSourceRepoURL\", sourceRepoUrl);\n variables.put(\"gitlabSourceRepoSshUrl\", sourceRepoSshUrl);\n variables.put(\"gitlabSourceRepoHttpUrl\", sourceRepoHttpUrl);\n variables.put(\"gitlabMergeRequestTitle\", mergeRequestTitle);\n variables.put(\"gitlabMergeRequestDescription\", mergeRequestDescription);\n variables.put(\"gitlabMergeRequestId\", mergeRequestId == null ? \"\" : mergeRequestId.toString());\n variables.put(\"gitlabMergeRequestIid\", mergeRequestIid == null ? \"\" : mergeRequestIid.toString());\n variables.put(\"gitlabMergeRequestTargetProjectId\", mergeRequestTargetProjectId == null ? \"\" : mergeRequestTargetProjectId.toString());\n variables.put(\"gitlabMergeRequestLastCommit\", lastCommit);\n variables.putIfNotNull(\"gitlabMergeRequestState\", mergeRequestState);\n variables.putIfNotNull(\"gitlabMergedByUser\", mergedByUser);\n variables.putIfNotNull(\"gitlabMergeRequestAssignee\", mergeRequestAssignee);\n variables.put(\"gitlabTargetBranch\", targetBranch);\n variables.put(\"gitlabTargetRepoName\", targetRepoName);\n variables.put(\"gitlabTargetNamespace\", targetNamespace);\n variables.put(\"gitlabTargetRepoSshUrl\", targetRepoSshUrl);\n variables.put(\"gitlabTargetRepoHttpUrl\", targetRepoHttpUrl);\n variables.put(\"gitlabBefore\", before);\n variables.put(\"gitlabAfter\", after);\n variables.put(\"ref\", ref);\n variables.put(\"beforeSha\", beforeSha);\n variables.put(\"isTag\", isTag);\n variables.put(\"sha\", sha);\n variables.put(\"status\", status);\n variables.put(\"stages\", stages);\n variables.put(\"createdAt\", createdAt);\n variables.put(\"finishedAt\", finishedAt);\n variables.put(\"duration\", buildDuration);\n variables.putIfNotNull(\"gitlabTriggerPhrase\", triggerPhrase);\n return variables;\n }\n\n @Exported\n public Integer getSourceProjectId() {\n return sourceProjectId;\n }\n\n @Exported\n public Integer getTargetProjectId() {\n return targetProjectId;\n }\n\n @Exported\n public String getBranch() {\n return branch;\n }\n\n @Exported\n public String getSourceBranch() {\n return sourceBranch;\n }\n\n @Exported\n public ActionType getActionType() {\n return actionType;\n }\n\n @Exported\n public String getUserName() {\n return userName;\n }\n\n @Exported\n public String getUserUsername() {\n return userUsername;\n }\n\n @Exported\n public String getUserEmail() {\n return userEmail;\n }\n\n @Exported\n public String getSourceRepoHomepage() {\n return sourceRepoHomepage;\n }\n\n @Exported\n public String getSourceRepoName() {\n return sourceRepoName;\n }\n\n @Exported\n public String getSourceNamespace() {\n return sourceNamespace;\n }\n\n @Exported\n public String getSourceRepoUrl() {\n return sourceRepoUrl;\n }\n\n @Exported\n public String getSourceRepoSshUrl() {\n return sourceRepoSshUrl;\n }\n\n @Exported\n public String getSourceRepoHttpUrl() {\n return sourceRepoHttpUrl;\n }\n\n @Exported\n public String getMergeRequestTitle() {\n return mergeRequestTitle;\n }\n\n @Exported\n public String getMergeRequestDescription() {\n return mergeRequestDescription;\n }\n\n @Exported\n public Integer getMergeRequestId() {\n return mergeRequestId;\n }\n\n @Exported\n public Integer getMergeRequestIid() {\n return mergeRequestIid;\n }\n\n @Exported\n public Integer getMergeRequestTargetProjectId() {\n return mergeRequestTargetProjectId;\n }\n\n @Exported\n public String getTargetBranch() {\n return targetBranch;\n }\n\n @Exported\n public String getTargetRepoName() {\n return targetRepoName;\n }\n\n @Exported\n public String getTargetNamespace() {\n return targetNamespace;\n }\n\n @Exported\n public String getTargetRepoSshUrl() {\n return targetRepoSshUrl;\n }\n\n @Exported\n public String getTargetRepoHttpUrl() {\n return targetRepoHttpUrl;\n }\n\n @Exported\n public String getTriggeredByUser() {\n return triggeredByUser;\n }\n\n @Exported\n public String getBefore() {\n return before;\n }\n\n @Exported\n public String getAfter() {\n return after;\n }\n\n @Exported\n public String getLastCommit() {\n return lastCommit;\n }\n\n @Exported\n public String getTargetProjectUrl() {\n return targetProjectUrl;\n }\n\n @Exported\n public String getRef() { return ref; }\n\n @Exported\n public String getIsTag() { return isTag; }\n\n @Exported\n public String getSha() { return sha; }\n\n @Exported\n public String getBeforeSha() {return beforeSha; }\n\n @Exported\n public String getStatus() { return status; }\n\n @Exported\n public String getStages() { return stages; }\n\n @Exported\n public String getCreatedAt() { return createdAt; }\n\n @Exported\n public String getFinishedAt() { return finishedAt; }\n\n @Exported\n public String getBuildDuration() { return buildDuration; }\n\n\n String getShortDescription() {\n return actionType.getShortDescription(this);\n }\n\n @Exported\n public String getMergeRequestState() {\n\t\treturn mergeRequestState;\n\t}\n\n @Exported\n\tpublic String getMergedByUser() {\n\t\treturn mergedByUser;\n\t}\n\n @Exported\n\tpublic String getMergeRequestAssignee() {\n\t\treturn mergeRequestAssignee;\n\t}\n\n @Exported\n\tpublic MergeRequest getMergeRequest() {\n if (mergeRequestId == null) {\n return null;\n }\n\n return new MergeRequest(mergeRequestId, mergeRequestIid, sourceBranch, targetBranch, mergeRequestTitle,\n sourceProjectId, targetProjectId, mergeRequestDescription, mergeRequestState);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n CauseData causeData = (CauseData) o;\n return new EqualsBuilder()\n .append(actionType, causeData.actionType)\n .append(sourceProjectId, causeData.sourceProjectId)\n .append(targetProjectId, causeData.targetProjectId)\n .append(branch, causeData.branch)\n .append(sourceBranch, causeData.sourceBranch)\n .append(userName, causeData.userName)\n .append(userUsername, causeData.userUsername)\n .append(userEmail, causeData.userEmail)\n .append(sourceRepoHomepage, causeData.sourceRepoHomepage)\n .append(sourceRepoName, causeData.sourceRepoName)\n .append(sourceNamespace, causeData.sourceNamespace)\n .append(sourceRepoUrl, causeData.sourceRepoUrl)\n .append(sourceRepoSshUrl, causeData.sourceRepoSshUrl)\n .append(sourceRepoHttpUrl, causeData.sourceRepoHttpUrl)\n .append(mergeRequestTitle, causeData.mergeRequestTitle)\n .append(mergeRequestDescription, causeData.mergeRequestDescription)\n .append(mergeRequestId, causeData.mergeRequestId)\n .append(mergeRequestIid, causeData.mergeRequestIid)\n .append(mergeRequestState, causeData.mergeRequestState)\n .append(mergedByUser, causeData.mergedByUser)\n .append(mergeRequestAssignee, causeData.mergeRequestAssignee)\n .append(mergeRequestTargetProjectId, causeData.mergeRequestTargetProjectId)\n .append(targetBranch, causeData.targetBranch)\n .append(targetRepoName, causeData.targetRepoName)\n .append(targetNamespace, causeData.targetNamespace)\n .append(targetRepoSshUrl, causeData.targetRepoSshUrl)\n .append(targetRepoHttpUrl, causeData.targetRepoHttpUrl)\n .append(triggeredByUser, causeData.triggeredByUser)\n .append(before, causeData.before)\n .append(after, causeData.after)\n .append(lastCommit, causeData.lastCommit)\n .append(targetProjectUrl, causeData.targetProjectUrl)\n .append(ref, causeData.getRef())\n .append(isTag, causeData.getIsTag())\n .append(sha, causeData.getSha())\n .append(beforeSha, causeData.getBeforeSha())\n .append(status, causeData.getStatus())\n .append(stages, causeData.getStages())\n .append(createdAt, causeData.getCreatedAt())\n .append(finishedAt, causeData.getFinishedAt())\n .append(buildDuration, causeData.getBuildDuration())\n .isEquals();\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder(17, 37)\n .append(actionType)\n .append(sourceProjectId)\n .append(targetProjectId)\n .append(branch)\n .append(sourceBranch)\n .append(userName)\n .append(userUsername)\n .append(userEmail)\n .append(sourceRepoHomepage)\n .append(sourceRepoName)\n .append(sourceNamespace)\n .append(sourceRepoUrl)\n .append(sourceRepoSshUrl)\n .append(sourceRepoHttpUrl)\n .append(mergeRequestTitle)\n .append(mergeRequestDescription)\n .append(mergeRequestId)\n .append(mergeRequestIid)\n .append(mergeRequestState)\n .append(mergedByUser)\n .append(mergeRequestAssignee)\n .append(mergeRequestTargetProjectId)\n .append(targetBranch)\n .append(targetRepoName)\n .append(targetNamespace)\n .append(targetRepoSshUrl)\n .append(targetRepoHttpUrl)\n .append(triggeredByUser)\n .append(before)\n .append(after)\n .append(lastCommit)\n .append(targetProjectUrl)\n .append(ref)\n .append(isTag)\n .append(sha)\n .append(beforeSha)\n .append(status)\n .append(stages)\n .append(createdAt)\n .append(finishedAt)\n .append(buildDuration)\n .toHashCode();\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this)\n .append(\"actionType\", actionType)\n .append(\"sourceProjectId\", sourceProjectId)\n .append(\"targetProjectId\", targetProjectId)\n .append(\"branch\", branch)\n .append(\"sourceBranch\", sourceBranch)\n .append(\"userName\", userName)\n .append(\"userUsername\", userUsername)\n .append(\"userEmail\", userEmail)\n .append(\"sourceRepoHomepage\", sourceRepoHomepage)\n .append(\"sourceRepoName\", sourceRepoName)\n .append(\"sourceNamespace\", sourceNamespace)\n .append(\"sourceRepoUrl\", sourceRepoUrl)\n .append(\"sourceRepoSshUrl\", sourceRepoSshUrl)\n .append(\"sourceRepoHttpUrl\", sourceRepoHttpUrl)\n .append(\"mergeRequestTitle\", mergeRequestTitle)\n .append(\"mergeRequestDescription\", mergeRequestDescription)\n .append(\"mergeRequestId\", mergeRequestId)\n .append(\"mergeRequestIid\", mergeRequestIid)\n .append(\"mergeRequestState\", mergeRequestState)\n .append(\"mergedByUser\", mergedByUser)\n .append(\"mergeRequestAssignee\", mergeRequestAssignee)\n .append(\"mergeRequestTargetProjectId\", mergeRequestTargetProjectId)\n .append(\"targetBranch\", targetBranch)\n .append(\"targetRepoName\", targetRepoName)\n .append(\"targetNamespace\", targetNamespace)\n .append(\"targetRepoSshUrl\", targetRepoSshUrl)\n .append(\"targetRepoHttpUrl\", targetRepoHttpUrl)\n .append(\"triggeredByUser\", triggeredByUser)\n .append(\"before\", before)\n .append(\"after\", after)\n .append(\"lastCommit\", lastCommit)\n .append(\"targetProjectUrl\", targetProjectUrl)\n .append(\"ref\", ref)\n .append(\"isTag\", isTag)\n .append(\"sha\", sha)\n .append(\"beforeSha\", beforeSha)\n .append(\"status\", status)\n .append(\"stages\", stages)\n .append(\"createdAt\", createdAt)\n .append(\"finishedAt\", finishedAt)\n .append(\"duration\", buildDuration)\n .toString();\n }\n\n public enum ActionType {\n PUSH {\n @Override\n String getShortDescription(CauseData data) {\n return getShortDescriptionPush(data);\n }\n }, TAG_PUSH {\n @Override\n String getShortDescription(CauseData data) {\n return getShortDescriptionPush(data);\n }\n }, MERGE {\n @Override\n String getShortDescription(CauseData data) {\n String forkNamespace = StringUtils.equals(data.getSourceNamespace(), data.getTargetBranch()) ? \"\" : data.getSourceNamespace() + \"/\";\n if (Jenkins.getActiveInstance().getMarkupFormatter() instanceof EscapedMarkupFormatter || data.getTargetProjectUrl() == null) {\n return Messages.GitLabWebHookCause_ShortDescription_MergeRequestHook_plain(String.valueOf(data.getMergeRequestIid()),\n forkNamespace + data.getSourceBranch(),\n data.getTargetBranch());\n } else {\n return Messages.GitLabWebHookCause_ShortDescription_MergeRequestHook_html(String.valueOf(data.getMergeRequestIid()),\n forkNamespace + data.getSourceBranch(),\n data.getTargetBranch(),\n data.getTargetProjectUrl());\n }\n }\n }, NOTE {\n @Override\n String getShortDescription(CauseData data) {\n String triggeredBy = data.getTriggeredByUser();\n String forkNamespace = StringUtils.equals(data.getSourceNamespace(), data.getTargetBranch()) ? \"\" : data.getSourceNamespace() + \"/\";\n if (Jenkins.getActiveInstance().getMarkupFormatter() instanceof EscapedMarkupFormatter || data.getTargetProjectUrl() == null) {\n return Messages.GitLabWebHookCause_ShortDescription_NoteHook_plain(triggeredBy,\n String.valueOf(data.getMergeRequestIid()),\n forkNamespace + data.getSourceBranch(),\n data.getTargetBranch());\n } else {\n return Messages.GitLabWebHookCause_ShortDescription_NoteHook_html(triggeredBy,\n String.valueOf(data.getMergeRequestIid()),\n forkNamespace + data.getSourceBranch(),\n data.getTargetBranch(),\n data.getTargetProjectUrl());\n }\n }\n }, PIPELINE {\n @Override\n String getShortDescription(CauseData data) {\n String getStatus = data.getStatus();\n if (getStatus == null) {\n return Messages.GitLabWebHookCause_ShortDescription_PipelineHook_noStatus();\n } else {\n return Messages.GitLabWebHookCause_ShortDescription_PipelineHook(getStatus);\n }\n }\n };\n\n private static String getShortDescriptionPush(CauseData data) {\n String pushedBy = data.getTriggeredByUser();\n if (pushedBy == null) {\n return Messages.GitLabWebHookCause_ShortDescription_PushHook_noUser();\n } else {\n return Messages.GitLabWebHookCause_ShortDescription_PushHook(pushedBy);\n }\n }\n\n abstract String getShortDescription(CauseData data);\n }\n\n private static class MapWrapper<K, V> extends AbstractMap<K, V> {\n\n private final Map<K, V> map;\n\n MapWrapper(Map<K, V> map) {\n this.map = map;\n }\n\n @Override\n public V put(K key, V value) {\n return map.put(key, value);\n }\n\n @Override\n public Set<Entry<K, V>> entrySet() {\n return map.entrySet();\n }\n\n void putIfNotNull(K key, V value) {\n if (value != null) {\n map.put(key, value);\n }\n }\n }\n}",
"@ExportedBean\npublic class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause {\n\n private final CauseData data;\n\n public GitLabWebHookCause(CauseData data) {\n super(\"\");\n this.data = Objects.requireNonNull(data, \"data must not be null\");\n }\n\n @Exported\n public CauseData getData() {\n return data;\n }\n\n @Override\n public String getShortDescription() {\n return data.getShortDescription();\n }\n}",
"@Extension\npublic class GitLabConnectionConfig extends GlobalConfiguration {\n\n private Boolean useAuthenticatedEndpoint = true;\n private List<GitLabConnection> connections = new ArrayList<>();\n private transient Map<String, GitLabConnection> connectionMap = new HashMap<>();\n\n @DataBoundConstructor\n public GitLabConnectionConfig() {\n load();\n refreshConnectionMap();\n }\n\n public boolean isUseAuthenticatedEndpoint() {\n return useAuthenticatedEndpoint;\n }\n\n @DataBoundSetter\n public void setUseAuthenticatedEndpoint(boolean useAuthenticatedEndpoint) {\n this.useAuthenticatedEndpoint = useAuthenticatedEndpoint;\n save();\n }\n\n public List<GitLabConnection> getConnections() {\n return connections;\n }\n\n public void addConnection(GitLabConnection connection) {\n connections.add(connection);\n connectionMap.put(connection.getName(), connection);\n }\n\n @DataBoundSetter\n public void setConnections(List<GitLabConnection> newConnections) {\n connections = new ArrayList<>();\n connectionMap = new HashMap<>();\n for (GitLabConnection connection: newConnections){\n addConnection(connection);\n }\n save();\n }\n\n public GitLabClient getClient(String connectionName, Item item, String jobCredentialId) {\n if (!connectionMap.containsKey(connectionName)) {\n return null;\n }\n return connectionMap.get(connectionName).getClient(item, jobCredentialId);\n }\n\n private void refreshConnectionMap() {\n connectionMap.clear();\n for (GitLabConnection connection : connections) {\n connectionMap.put(connection.getName(), connection);\n }\n }\n\n //For backwards compatibility. ReadResolve is called on startup\n protected GitLabConnectionConfig readResolve() {\n if (useAuthenticatedEndpoint == null) {\n setUseAuthenticatedEndpoint(false);\n }\n return this;\n }\n\n public static GitLabConnectionConfig get() {\n return ExtensionList.lookupSingleton(GitLabConnectionConfig.class);\n }\n}",
"public interface GitLabClient {\n String getHostUrl();\n\n Project createProject(String projectName);\n\n MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title);\n\n Project getProject(String projectName);\n\n Project updateProject(String projectId, String name, String path);\n\n void deleteProject(String projectId);\n\n void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents);\n\n void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description);\n\n void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description);\n\n void getCommit(String projectId, String sha);\n\n void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch);\n\n void createMergeRequestNote(MergeRequest mr, String body);\n\n List<Awardable> getMergeRequestEmoji(MergeRequest mr);\n\n void awardMergeRequestEmoji(MergeRequest mr, String name);\n\n void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId);\n\n List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage);\n\n List<Branch> getBranches(String projectId);\n\n Branch getBranch(String projectId, String branch);\n\n User getCurrentUser();\n\n User addUser(String email, String username, String name, String password);\n\n User updateUser(String userId, String email, String username, String name, String password);\n\n List<Label> getLabels(String projectId);\n\n List<Pipeline> getPipelines(String projectName);\n}",
"public class GitLabBranchBuild extends AbstractDescribableImpl<GitLabBranchBuild> {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitLabBranchBuild.class);\n\n\n private String name;\n private String projectId;\n private String revisionHash;\n private GitLabConnectionProperty connection;\n\n @DataBoundConstructor\n public GitLabBranchBuild() {\n }\n\n public GitLabBranchBuild(String projectId, String revisionHash) {\n this.name = null;\n this.projectId = projectId;\n this.revisionHash = revisionHash;\n this.connection = null;\n }\n\n @DataBoundSetter\n public void setName(String name) {\n this.name = StringUtils.isEmpty(name) ? null : name;\n }\n\n @DataBoundSetter\n public void setProjectId(String projectId) {\n this.projectId = projectId;\n }\n\n @DataBoundSetter\n public void setRevisionHash(String revisionHash) {\n this.revisionHash = revisionHash;\n }\n\n @DataBoundSetter\n public void setConnection(GitLabConnectionProperty connection) {\n this.connection = connection;\n }\n\n public void setConnection(String connection) {\n this.connection = StringUtils.isEmpty(connection) ? null : new GitLabConnectionProperty(connection);\n }\n\n public String getName() {\n return name;\n }\n\n public String getProjectId() {\n return projectId;\n }\n\n public String getRevisionHash() {\n return revisionHash;\n }\n\n public GitLabConnectionProperty getConnection() {\n return connection;\n }\n\n\n\n @Extension\n public static class DescriptorImpl extends Descriptor<GitLabBranchBuild> {\n @Override\n public String getDisplayName() {\n return \"Gitlab Branch Build\";\n }\n }\n}"
] | import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.dabsquared.gitlabjenkins.cause.CauseData;
import com.dabsquared.gitlabjenkins.cause.CauseDataBuilder;
import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause;
import com.dabsquared.gitlabjenkins.connection.GitLabConnectionConfig;
import com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty;
import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient;
import com.dabsquared.gitlabjenkins.gitlab.api.model.BuildState;
import com.dabsquared.gitlabjenkins.workflow.GitLabBranchBuild;
import hudson.EnvVars;
import hudson.Functions;
import hudson.Util;
import hudson.model.Cause;
import hudson.model.Cause.UpstreamCause;
import hudson.model.Item;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.git.Revision;
import hudson.plugins.git.util.Build;
import hudson.plugins.git.util.BuildData;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import jenkins.model.Jenkins;
import org.eclipse.jgit.lib.ObjectId;
import org.jenkinsci.plugins.displayurlapi.DisplayURLProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations; | package com.dabsquared.gitlabjenkins.util;
/**
* @author Daumantas Stulgis
*/
public class CommitStatusUpdaterTest {
private static final int PROJECT_ID = 1;
private static final String BUILD_URL = "job/Test-Job";
private static final String STAGE = "test";
private static final String REVISION = "1111111";
private static final String JENKINS_URL = "https://gitlab.org/jenkins/";
@Mock Run<?, ?> build;
@Mock TaskListener taskListener;
@Mock GitLabConnectionConfig gitLabConnectionConfig; | @Mock GitLabClient client; | 3 |
MCUpdater/MCUpdater | MCU-API/src/org/mcupdater/util/ServerPackParser.java | [
"public class Version {\n\tpublic static final int MAJOR_VERSION;\n\tpublic static final int MINOR_VERSION;\n\tpublic static final int BUILD_VERSION;\n\tpublic static final String BUILD_BRANCH;\n\tpublic static final String BUILD_LABEL;\n\tstatic {\n\t\tProperties prop = new Properties();\n\t\ttry {\n\t\t\tprop.load(Version.class.getResourceAsStream(\"/version.properties\"));\n\t\t} catch (IOException e) {\n\t\t}\n\t\tMAJOR_VERSION = Integer.valueOf(prop.getProperty(\"major\",\"0\"));\n\t\tMINOR_VERSION = Integer.valueOf(prop.getProperty(\"minor\",\"0\"));\n\t\tBUILD_VERSION = Integer.valueOf(prop.getProperty(\"build_version\",\"0\"));\n\t\tBUILD_BRANCH = prop.getProperty(\"git_branch\",\"unknown\");\n\t\tif( BUILD_BRANCH.equals(\"unknown\") || BUILD_BRANCH.equals(\"master\") ) {\n\t\t\tBUILD_LABEL = \"\";\n\t\t} else {\n\t\t\tBUILD_LABEL = \" (\"+BUILD_BRANCH+\")\";\n\t\t}\n\t}\n\t\n\tpublic static final String API_VERSION = MAJOR_VERSION + \".\" + MINOR_VERSION;\n\tpublic static final String VERSION = \"v\"+MAJOR_VERSION+\".\"+MINOR_VERSION+\".\"+BUILD_VERSION;\n\t\n\tpublic static boolean isVersionOld(String packVersion) {\n\t\tif( packVersion == null ) return false;\t// can't check anything if they don't tell us\n\t\tString parts[] = packVersion.split(\"\\\\.\");\n\t\ttry {\n\t\t\tint mcuParts[] = { MAJOR_VERSION, MINOR_VERSION, BUILD_VERSION };\n\t\t\tfor( int q = 0; q < mcuParts.length && q < parts.length; ++q ) {\n\t\t\t\tint packPart = Integer.valueOf(parts[q]);\n\t\t\t\tif( packPart > mcuParts[q] ) return true;\n\t\t\t\tif( packPart < mcuParts[q] ) return false; // Since we check major, then minor, then build, if the required value < current value, we can stop checking.\n\t\t\t}\n\t\t\treturn false;\n\t\t} catch( NumberFormatException e ) {\n\t\t\tlog(\"Got non-numerical pack format version '\"+packVersion+\"'\");\n\t\t} catch( ArrayIndexOutOfBoundsException e ) {\n\t\t\tlog(\"Got malformed pack format version '\"+packVersion+\"'\");\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static boolean requestedFeatureLevel(String packVersion, String featureLevelVersion) {\n\t\tString packParts[] = packVersion.split(\"\\\\.\");\n\t\tString featureParts[] = featureLevelVersion.split(\"\\\\.\");\n\t\ttry {\n\t\t\tfor (int q = 0; q < featureParts.length; ++q ) {\n\t\t\t\tif (Integer.valueOf(packParts[q]) > Integer.valueOf(featureParts[q])) return true;\n\t\t\t\tif (Integer.valueOf(packParts[q]) < Integer.valueOf(featureParts[q])) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch( NumberFormatException e ) {\n\t\t\tlog(\"Got non-numerical pack format version '\"+packVersion+\"'\");\n\t\t} catch( ArrayIndexOutOfBoundsException e ) {\n\t\t\tlog(\"Got malformed pack format version '\"+packVersion+\"'\");\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static boolean isMasterBranch() {\n\t\treturn BUILD_BRANCH.equals(\"master\");\n\t}\n\tpublic static boolean isDevBranch() {\n\t\treturn BUILD_BRANCH.equals(\"develop\");\n\t}\n\t\n\t// for error logging support\n\tpublic static void setApp( MCUApp app ) {\n\t\t_app = app;\n\t}\n\tprivate static MCUApp _app;\n\tprivate static void log(String msg) {\n\t\tif( _app != null ) {\n\t\t\t_app.log(msg);\n\t\t} else {\n\t\t\tSystem.out.println(msg);\n\t\t}\n\t}\n}",
"public class ConfigFile {\n\tprivate String url;\n\tprivate String path;\n\tprivate String md5;\n\tprivate boolean noOverwrite;\n\t\n\tpublic ConfigFile(String url, String path, boolean noOverwrite, String md5)\n\t{\n\t\tsetUrl(url);\n\t\tsetPath(path);\n\t\tsetNoOverwrite(noOverwrite);\n\t\tsetMD5(md5);\n\t}\n\t\n\tpublic String getUrl()\n\t{\n\t\treturn url;\n\t}\n\t\n\tpublic void setUrl(String url)\n\t{\n\t\tthis.url = url;\n\t}\n\t\n\tpublic String getPath()\n\t{\n\t\treturn path;\n\t}\n\t\n\tpublic void setPath(String path)\n\t{\n\t\tthis.path = path;\n\t}\n\t\n\tpublic boolean isNoOverwrite() {\n\t\treturn noOverwrite;\n\t}\n\n\tpublic void setNoOverwrite(boolean noOverwrite) {\n\t\tthis.noOverwrite = noOverwrite;\n\t}\n\n\tpublic String getMD5()\n\t{\n\t\treturn md5;\n\t}\n\t\n\tpublic void setMD5(String md5)\n\t{\n\t\tif( md5 != null )\n\t\t\tthis.md5 = md5.toLowerCase(Locale.ENGLISH);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn path;\n\t}\n\n}",
"public class GenericModule {\n\tprotected String name = \"\";\n\tprotected String id = \"\";\n\tprotected List<PrioritizedURL> urls = new ArrayList<PrioritizedURL>();\n\tprotected String path = \"\";\n\tprotected String depends = \"\";\n\tprotected boolean required = false;\n\tprotected boolean inJar = false;\n\tprotected int order = 1;\n\tprotected boolean keepMeta = false;\n\tprotected boolean extract = false;\n\tprotected boolean inRoot = false;\n\tprotected boolean isDefault = false;\n\tprotected boolean coreMod = false;\n\tprotected boolean litemod = false;\n\tprotected String md5 = \"\";\n\tprotected ModSide side = ModSide.BOTH;\n\tprotected HashMap<String,String> meta = new HashMap<String,String>();\n\tprotected boolean isLibrary = false;\n\tprotected String launchArgs = \"\";\n\tprotected String jreArgs = \"\";\n\n\tpublic GenericModule(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, String side, String path, HashMap<String, String> meta, boolean isLibrary, boolean litemod, String launchArgs, String jreArgs){\n\t\tthis.setName(name);\n\t\tthis.setId(id);\n\t\tthis.setUrls(url);\n\t\tthis.setDepends(depends);\n\t\tthis.setRequired(required);\n\t\tthis.setInJar(inJar);\n\t\tthis.setJarOrder(jarOrder+1);\n\t\tthis.setKeepMeta(keepMeta);\n\t\tthis.setIsDefault(isDefault);\n\t\tthis.setExtract(extract);\n\t\tthis.setInRoot(inRoot);\n\t\tthis.setCoreMod(coreMod);\n\t\tthis.setMD5(md5);\n\t\tthis.setSide(side);\n\t\tthis.setPath(path);\n\t\tthis.setIsLibrary(isLibrary);\n\t\tthis.setLaunchArgs(launchArgs);\n\t\tthis.setJreArgs(jreArgs);\n\t\tthis.setLitemod(litemod);\n\t\tif(meta != null)\n\t\t{\n\t\t\tthis.setMeta(meta);\n\t\t} else {\n\t\t\tthis.setMeta(new HashMap<String,String>());\n\t\t}\n\t}\n\t\n\tprivate void setJarOrder(int jarOrder) {\n\t\tthis.order = jarOrder;\n\t}\n\n\tpublic String getName()\n\t{\n\t\treturn name;\n\t}\n\t\n\tpublic void setName(String name)\n\t{\n\t\tthis.name=name;\n\t}\n\t\n\tpublic List<URL> getUrls()\n\t{\n\t\tList<URL> result = new ArrayList<URL>();\n\t\tfor (PrioritizedURL entry : urls) {\n\t\t\ttry {\n\t\t\t\tresult.add(new URL(entry.getUrl()));\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic void setUrls(List<PrioritizedURL> urls)\n\t{\n\t\tthis.urls = urls;\n\t}\n\t\n\tpublic void addUrl(PrioritizedURL url)\n\t{\n\t\tthis.urls.add(url);\n\t}\n\t\n\tpublic boolean getRequired()\n\t{\n\t\treturn required;\n\t}\n\t\n\tpublic void setRequired(boolean required)\n\t{\n\t\tthis.required=required;\n\t}\n\t\n\tpublic boolean getInJar()\n\t{\n\t\treturn inJar;\n\t}\n\t\n\tpublic void setInJar(boolean inJar)\n\t{\n\t\tthis.inJar=inJar;\n\t}\n\n\tpublic boolean getExtract() {\n\t\treturn extract;\n\t}\n\n\tpublic void setExtract(boolean extract) {\n\t\tthis.extract = extract;\n\t}\n\n\tpublic boolean getInRoot() {\n\t\treturn inRoot;\n\t}\n\n\tpublic void setInRoot(boolean inRoot) {\n\t\tthis.inRoot = inRoot;\n\t}\n\t\n\tpublic String getMD5() {\n\t\treturn (md5 == null ? \"\" : md5);\n\t}\n\t\n\tpublic void setMD5(String md5) {\n\t\tif( md5 != null )\n\t\t\tthis.md5 = md5.toLowerCase(Locale.ENGLISH);\n\t}\n\n\tpublic boolean getIsDefault() {\n\t\treturn isDefault;\n\t}\n\t\n\tpublic void setIsDefault(boolean isDefault) {\n\t\tthis.isDefault = isDefault;\n\t}\n\n\tpublic boolean getCoreMod() {\n\t\treturn coreMod;\n\t}\n\n\tpublic void setCoreMod(boolean coreMod) {\n\t\tthis.coreMod = coreMod;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getDepends() {\n\t\treturn depends;\n\t}\n\n\tpublic void setDepends(String depends) {\n\t\tthis.depends = depends;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn id;\n\t}\n\n\tpublic ModSide getSide() {\n\t\treturn side;\n\t}\n\n\tpublic void setSide(ModSide side) {\n\t\tthis.side = side;\n\t}\n\tpublic void setSide(String side) {\n\t\tif( side == null || side.length() == 0 ) {\n\t\t\tside = \"BOTH\";\n\t\t} else {\n\t\t\tside = side.toUpperCase();\n\t\t}\n\t\ttry {\n\t\t\tsetSide( ModSide.valueOf(side) );\n\t\t} catch( IllegalArgumentException e ) {\n\t\t\tsetSide( ModSide.BOTH );\n\t\t}\n\t}\n\t\n\tpublic boolean isClientSide() {\n\t\treturn side != ModSide.SERVER;\n\t}\n\tpublic boolean isServerSide() {\n\t\treturn side != ModSide.CLIENT;\n\t}\n\n\tpublic String getPath() {\n\t\treturn path;\n\t}\n\n\tpublic void setPath(String path) {\n\t\tif (path == null) {\n\t\t\tpath = \"\";\n\t\t}\n\t\tthis.path = path;\n\t}\n\n\tpublic int getJarOrder() {\n\t\treturn order;\n\t}\n\n\tpublic boolean getKeepMeta() {\n\t\treturn keepMeta;\n\t}\n\n\tpublic void setKeepMeta(boolean keepMeta) {\n\t\tthis.keepMeta = keepMeta;\n\t}\n\n\tpublic HashMap<String,String> getMeta() {\n\t\treturn meta;\n\t}\n\n\tpublic void setMeta(HashMap<String,String> meta) {\n\t\tthis.meta = meta;\n\t}\n\n\tpublic String getLaunchArgs() {\n\t\treturn launchArgs;\n\t}\n\n\tpublic void setLaunchArgs(String launchArgs) {\n\t\tthis.launchArgs = launchArgs;\n\t}\n\n\tpublic boolean getIsLibrary() {\n\t\treturn isLibrary;\n\t}\n\n\tpublic void setIsLibrary(boolean isLibrary) {\n\t\tthis.isLibrary = isLibrary;\n\t}\n\n\tpublic List<PrioritizedURL> getPrioritizedUrls() {\n\t\treturn this.urls;\n\t}\n\n\tpublic String getJreArgs() {\n\t\treturn jreArgs;\n\t}\n\n\tpublic void setJreArgs(String jreArgs) {\n\t\tthis.jreArgs = jreArgs;\n\t}\n\n\tpublic boolean isLitemod() {\n\t\treturn litemod;\n\t}\n\n\tpublic void setLitemod(boolean litemod) {\n\t\tthis.litemod = litemod;\n\t}\n}",
"public enum ModType {\n\tRegular, Library, Coremod, Jar, Extract, Litemod, Option;\n}",
"public class Module extends GenericModule {\n\tprivate List<ConfigFile> configs = new ArrayList<ConfigFile>();\n\tprivate List<GenericModule> submodules = new ArrayList<GenericModule>();\n\t\n\tpublic Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta, boolean isLibrary, boolean litemod, String launchArgs, String jreArgs, List<GenericModule> submodules){\n\t\tsuper(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,side,path,meta,isLibrary,litemod,launchArgs,jreArgs);\t\n\t\tif(configs != null)\n\t\t{\n\t\t\tthis.configs = configs;\n\t\t} else {\n\t\t\tthis.configs = new ArrayList<ConfigFile>();\n\t\t}\n\t\tthis.submodules.addAll(submodules);\n\t}\n\n\t@Deprecated\n\tpublic Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta){\n\t\tthis(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,configs,side,path,meta,false,false,null,null,null);\n\t}\n\n\t@Deprecated\n\tpublic Module(String name, String id, String url, String depends, boolean required, boolean inJar, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs)\n\t{\n\t\tthis(name, id, makeList(url), depends, required, inJar, 0, true, extract, inRoot, isDefault, coreMod, md5, configs, null, null, null);\n\t}\n\t\n\tprivate static List<PrioritizedURL> makeList(String url) {\n\t\tList<PrioritizedURL> urls = new ArrayList<PrioritizedURL>();\n\t\turls.add(new PrioritizedURL(url, 0));\n\t\treturn urls;\n\t}\n\n\tpublic List<ConfigFile> getConfigs()\n\t{\n\t\treturn configs;\n\t}\n\t\n\tpublic void setConfigs(List<ConfigFile> configs)\n\t{\n\t\tthis.configs = configs;\n\t}\n\t\n\tpublic boolean hasConfigs() {\n\t\treturn (this.configs.size() > 0);\n\t}\n\t\n\tpublic boolean hasSubmodules() {\n\t\treturn (this.submodules.size() > 0);\n\t}\n\t\n\tpublic List<GenericModule> getSubmodules() {\n\t\treturn this.submodules;\n\t}\n\n}"
] | import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.mcupdater.Version;
import org.mcupdater.model.ConfigFile;
import org.mcupdater.model.GenericModule;
import org.mcupdater.model.ModType;
import org.mcupdater.model.Module;
import org.mcupdater.model.PrioritizedURL;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; | NodeList nl;
switch (version) {
case 2:
// Handle ServerPacks designed for MCUpdater 3.0 and later
nl = docEle.getElementsByTagName("Import");
if(nl != null && nl.getLength() > 0) {
for(int i = 0; i < nl.getLength(); i++) {
Element el = (Element)nl.item(i);
modList.addAll(doImportV2(el, dom));
}
}
nl = docEle.getElementsByTagName("Module");
if(nl != null && nl.getLength() > 0)
{
for(int i = 0; i < nl.getLength(); i++)
{
Element el = (Element)nl.item(i);
Module m = getModuleV2(el);
modList.add(m);
}
}
return modList;
case 1:
// Handle ServerPacks designed for MCUpdater 2.7 and earlier
nl = docEle.getElementsByTagName("Module");
if(nl != null && nl.getLength() > 0)
{
for(int i = 0; i < nl.getLength(); i++)
{
Element el = (Element)nl.item(i);
Module m = getModuleV1(el);
modList.add(m);
}
}
return modList;
default:
return null;
}
}
private static List<Module> doImportV2(Element el, Document dom) {
String url = el.getAttribute("url");
if (!url.isEmpty()){
try {
dom = readXmlFromUrl(url);
} catch (DOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return parseDocument(dom, el.getTextContent());
}
private static Module getModuleV2(Element el) {
XPath xpath = XPathFactory.newInstance().newXPath();
try {
String name = el.getAttribute("name");
String id = el.getAttribute("id");
String depends = el.getAttribute("depends");
String side = el.getAttribute("side");
List<PrioritizedURL> urls = new ArrayList<PrioritizedURL>();
NodeList nl;
nl = (NodeList) xpath.evaluate("URL", el, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
Element elURL = (Element) nl.item(i);
String url = elURL.getTextContent();
int priority = parseInt(elURL.getAttribute("priority"));
urls.add(new PrioritizedURL(url, priority));
}
String path = (String) xpath.evaluate("ModPath", el, XPathConstants.STRING);
Element elReq = (Element) el.getElementsByTagName("Required").item(0);
boolean required;
boolean isDefault;
if (elReq == null) {
required = true;
isDefault = true;
} else {
required = parseBooleanWithDefault(elReq.getTextContent(),true);
isDefault = parseBooleanWithDefault(elReq.getAttribute("isDefault"),false);
}
Element elType = (Element) el.getElementsByTagName("ModType").item(0);
boolean inRoot = parseBooleanWithDefault(elType.getAttribute("inRoot"),false);
int order = parseInt(elType.getAttribute("order"));
boolean keepMeta = parseBooleanWithDefault(elType.getAttribute("keepMeta"),false);
String launchArgs = elType.getAttribute("launchArgs");
String jreArgs = elType.getAttribute("jreArgs");
ModType modType = ModType.valueOf(elType.getTextContent());
boolean coremod = false;
boolean jar = false;
boolean library = false;
boolean extract = false;
boolean litemod = false;
switch (modType) {
case Coremod:
coremod = true;
break;
case Extract:
extract = true;
break;
case Jar:
jar = true;
break;
case Library:
library = true;
break;
case Litemod:
litemod = true;
break;
case Option:
throw new RuntimeException("Module type 'Option' not implemented");
default:
break;
}
String md5 = (String) xpath.evaluate("MD5", el, XPathConstants.STRING); | List<ConfigFile> configs = new ArrayList<ConfigFile>(); | 1 |
Roba1993/octo-chat | src/main/java/de/robertschuette/octochat/chats/ChatHandler.java | [
"public class ChatData {\n private Chat chat;\n private String userId;\n private String userName;\n private String lastMessage;\n private String lastMessageTime;\n private boolean lastMessageUnread;\n private boolean isOnline;\n\n /**\n * Constructor to create a new chat data object.\n *\n * @param chat set the chat\n * @param userId id of the user\n * @param userName name of the user\n */\n public ChatData(Chat chat, String userId, String userName) {\n this.chat = chat;\n this.userId = userId;\n this.userName = userName;\n\n lastMessage = \"\";\n lastMessageTime = \"\";\n }\n\n @Override\n public String toString() {\n return \"> \"+userId+\" # \"+userName+\" : \"+lastMessage+\" - \"+lastMessageTime\n +\" \"+(lastMessageUnread ? \"new\" : \"old\")+\" \"+(isOnline ? \"on\" : \"off\") ;\n }\n\n /*************** Getter & Setter *****************/\n public Chat getChat() {\n return chat;\n }\n\n public void setChat(Chat chat) {\n this.chat = chat;\n }\n\n public String getUserId() {\n return userId;\n }\n\n public void setUserId(String userId) {\n this.userId = userId;\n }\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public String getLastMessage() {\n return lastMessage;\n }\n\n public void setLastMessage(String lastMessage) {\n this.lastMessage = lastMessage;\n }\n\n public String getLastMessageTime() {\n return lastMessageTime;\n }\n\n public void setLastMessageTime(String lastMessageTime) {\n this.lastMessageTime = lastMessageTime;\n }\n\n public boolean isLastMessageUnread() {\n return lastMessageUnread;\n }\n\n public void setLastMessageUnread(boolean lastMessageUnread) {\n this.lastMessageUnread = lastMessageUnread;\n }\n\n public boolean isOnline() {\n return isOnline;\n }\n\n public void setIsOnline(boolean isOnline) {\n this.isOnline = isOnline;\n }\n}",
"public class ChatDataStore {\n private ChatHandler chatHandler;\n private List<ChatData> chatData;\n\n public ChatDataStore(ChatHandler chatHandler) {\n this.chatHandler = chatHandler;\n\n chatData = new ArrayList<>();\n }\n\n\n /**\n * This function receives a new chat data object and compares the\n * provider and userId with the chats in the store.\n *\n * If no match is found, the new chat get added to the store. When the\n * last message is unread the store sends a notification with the last message\n * to the operating system.\n *\n * When a match is found, the match get updated. When the last message is unread and\n * different then the old one from the store, the function sends an notification with the\n * message to the operating system\n *\n * @param newCd the new chat data\n */\n public void updateChat(ChatData newCd) {\n // loop over all chat data entries\n for(ChatData cd : chatData) {\n // check if the id and provider is the same\n if(cd.getChat().equals(newCd.getChat()) &&\n cd.getUserId().equals(newCd.getUserId())) {\n\n // check if the new message flag is set new\n if(newCd.isLastMessageUnread() && !cd.isLastMessageUnread()) {\n // check if notifications are enabled\n if(chatHandler.getChatHandlerSettings().isNotifications() &&\n cd.getChat().getChatSettings().isNotifications()) {\n // send the notification\n OsSpecific.getSpecific().setSpecificNotification(newCd.getUserName(), newCd.getLastMessage());\n }\n }\n\n // update the values\n cd.setUserName(newCd.getUserName() != null ? newCd.getUserName() : cd.getUserName());\n cd.setLastMessage(newCd.getLastMessage() != null ? newCd.getLastMessage() : cd.getLastMessage());\n cd.setLastMessageTime(newCd.getLastMessageTime() != null ? newCd.getLastMessageTime() : cd.getLastMessageTime());\n cd.setLastMessageUnread(newCd.isLastMessageUnread());\n cd.setIsOnline(newCd.isOnline());\n\n // end this function\n return;\n }\n }\n\n // when we reach this section the chat isn't in the store\n // add the chat\n chatData.add(newCd);\n\n // when the message is unread, send notification\n if(newCd.isLastMessageUnread()) {\n // check if notifications are enabled\n if(chatHandler.getChatHandlerSettings().isNotifications() &&\n newCd.getChat().getChatSettings().isNotifications()) {\n OsSpecific.getSpecific().setSpecificNotification(newCd.getUserName(), newCd.getLastMessage());\n }\n }\n }\n\n /**\n * This function adds a new chat data to the store\n *\n * @param cd the new chat data\n */\n public void addChat(ChatData cd) {\n chatData.add(cd);\n }\n\n /**\n * Returns the number of unread messages.\n *\n * @return number of unread messages\n */\n public int getNumberUnread() {\n int i=0;\n\n // loop over the store and count\n for(ChatData cd : chatData) {\n if(cd.isLastMessageUnread()) {\n i++;\n }\n }\n\n return i;\n }\n}",
"public class ChatHandlerSettings {\n\n private boolean notifications;\n\n\n public ChatHandlerSettings() {\n notifications = true;\n }\n\n /************** Getter & Setter ************/\n public boolean isNotifications() {\n return notifications;\n }\n\n public void setNotifications(boolean notifications) {\n this.notifications = notifications;\n }\n}",
"public class ChatSettings {\n\n private String name;\n private boolean notifications;\n\n\n /**\n * Constructor to create a setting object.\n *\n * @param name unique name of the chat\n */\n public ChatSettings(String name) {\n this.name = name;\n notifications = true;\n }\n\n\n /******** Getter & Setter **************/\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public boolean isNotifications() {\n return notifications;\n }\n\n public void setNotifications(boolean notifications) {\n this.notifications = notifications;\n }\n}",
"public class Util {\n private static String resourcesPath;\n\n /**\n * This function returns the absolute path to the\n * resources directory as String.\n *\n * @return resources dir path\n */\n public static String getResourcesPath() {\n if(resourcesPath != null) {\n return resourcesPath;\n }\n\n String jarDir = \".\";\n\n // get the path of the .jar\n try {\n CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource();\n File jarFile = new File(codeSource.getLocation().toURI().getPath());\n jarDir = jarFile.getParentFile().getPath();\n } catch (URISyntaxException e) {\n e.printStackTrace();\n }\n\n File f = new File(jarDir+\"/data\");\n if(f.exists() && f.isDirectory()) {\n resourcesPath = jarDir+\"/data/\";\n }\n else {\n resourcesPath = jarDir+\"/\";\n }\n\n return resourcesPath;\n }\n\n\n /**\n * Function to get the whole dom tree as String\n * ONLY FOR DEV-ANALYSE!!!\n *\n * @param doc dom to parse\n * @return dom as string\n */\n public static String getStringFromDoc(Document doc) {\n try {\n DOMSource domSource = new DOMSource(doc);\n StringWriter writer = new StringWriter();\n StreamResult result = new StreamResult(writer);\n TransformerFactory tf = TransformerFactory.newInstance();\n Transformer transformer = tf.newTransformer();\n transformer.transform(domSource, result);\n writer.flush();\n return writer.toString();\n } catch (TransformerException ex) {\n ex.printStackTrace();\n return null;\n }\n }\n}"
] | import de.robertschuette.octochat.model.ChatData;
import de.robertschuette.octochat.model.ChatDataStore;
import de.robertschuette.octochat.model.ChatHandlerSettings;
import de.robertschuette.octochat.model.ChatSettings;
import de.robertschuette.octochat.util.Util;
import javafx.scene.control.SplitPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.*;
import java.util.ArrayList;
import java.util.List; | package de.robertschuette.octochat.chats;
/**
* This class holds the main logic of this application and
* routes the main actions.
*
* @author Robert Schütte
*/
public class ChatHandler extends SplitPane implements Runnable {
private ChatDataStore cds;
private List<Chat> chats;
private StackPane chatArea;
private Pane selectionArea;
private ChatHandlerSettings chatHandlerSettings;
private String xmlPath;
public ChatHandler(String xmlPath) {
this.xmlPath = xmlPath;
// create the necessary objects
chats = new ArrayList<>();
cds = new ChatDataStore(this);
chatHandlerSettings = new ChatHandlerSettings();
// create the selection area
selectionArea = new Pane();
// create chat area
chatArea = new StackPane();
// add the panes
this.getItems().addAll(selectionArea, chatArea);
this.setDividerPositions(0.1f);
// load the settings from the xml settings file
loadChatHandlerState();
// when no chats exist - create fb and wa chat
if(chats.size() < 1) {
addChat(new ChatFacebook(this, new ChatSettings("Facebook")));
addChat(new ChatWhatsapp(this, new ChatSettings("Whats App")));
}
// start this thread
new Thread(this).start();
}
/**
* Register a new chat in this chat handler. The chat is now
* clickable in the side and configurable over this handler.
*
* @param chat the chat to add
*/
public void addChat(Chat chat) {
// add the chat to the list
chats.add(chat);
// set the chat not visible if one already exist
if(chats.size() > 1) {
chat.setVisible(false);
}
// add to chat window
chatArea.getChildren().add(chat);
// add the image
addSelectionImage(chat, 0, chats.indexOf(chat) * 50);
}
/**
* Removes the given chat from the handler.
*
* @param chat to remove
*/
public void removeChat(Chat chat) {
// remove from the list
chats.remove(chat);
// remove from the chat area
chatArea.getChildren().remove(chat);
// redraw the selection area
redrawSelectionArea();
}
/**
* This function updates a specific chat data. When a new
* message was found, we send automatically a new notification.
*
* @param chatData the chatdata
*/ | public void updateChatData(ChatData chatData) { | 0 |
tangqifa/Common-App-Architecture | app/src/main/java/com/kejiwen/architecture/activity/ProductCustomerListActivity.java | [
"public class ListViewHelper<DATA> {\r\n private IDataAdapter<DATA> dataAdapter;\r\n private PullToRefreshAdapterViewBase<? extends ListView> pullToRefreshPinnedHeaderListView;\r\n private IDataSource<DATA> dataSource;\r\n private ListView mListView;\r\n private Context context;\r\n private OnStateChangeListener<DATA> onStateChangeListener;\r\n private AsyncTask<Void, Void, DATA> asyncTask;\r\n private long loadDataTime = -1;\r\n /**\r\n * 是否还有更多数据。如果服务器返回的数据为空的话,就说明没有更多数据了,也就没必要自动加载更多数据\r\n */\r\n private boolean hasMoreData = true;\r\n private ILoadView mLoadView;\r\n private ILoadMoreView mLoadMoreView;\r\n public static ILoadViewFactory loadViewFactory = new DeFaultLoadViewFactory();\r\n\r\n public ListViewHelper(PullToRefreshAdapterViewBase<? extends ListView> pullToRefreshAdapterViewBase) {\r\n this(pullToRefreshAdapterViewBase, loadViewFactory.madeLoadView(), loadViewFactory.madeLoadMoreView());\r\n }\r\n\r\n public ListViewHelper(PullToRefreshAdapterViewBase<? extends ListView> pullToRefreshAdapterViewBase, ILoadView loadView,\r\n ILoadMoreView loadMoreView) {\r\n super();\r\n this.context = pullToRefreshAdapterViewBase.getContext().getApplicationContext();\r\n this.autoLoadMore = true;\r\n this.pullToRefreshPinnedHeaderListView = pullToRefreshAdapterViewBase;\r\n mListView = pullToRefreshPinnedHeaderListView.getRefreshableView();\r\n mListView.setOverScrollMode(View.OVER_SCROLL_NEVER);\r\n mListView.setCacheColorHint(Color.TRANSPARENT);\r\n pullToRefreshPinnedHeaderListView.setOnRefreshListener(new OnRefreshListener211());\r\n mListView.setOnScrollListener(onScrollListener);\r\n mListView.setOnItemSelectedListener(onItemSelectedListener);\r\n pullToRefreshPinnedHeaderListView.setMode(Mode.PULL_FROM_START);\r\n mLoadView = loadView;\r\n mLoadView.init(mListView, onClickRefresListener);\r\n\r\n mLoadMoreView = loadMoreView;\r\n mLoadMoreView.init(mListView, onClickLoadMoreListener);\r\n }\r\n\r\n /**\r\n * 设置LoadView的factory,用于创建使用者自定义的加载失败,加载中,加载更多等布局\r\n *\r\n * @param fractory\r\n */\r\n public static void setLoadViewFractory(ILoadViewFactory fractory) {\r\n loadViewFactory = fractory;\r\n }\r\n\r\n /**\r\n * 设置数据源,用于加载数据\r\n *\r\n * @param dataSource\r\n */\r\n public void setDataSource(IDataSource<DATA> dataSource) {\r\n this.dataSource = dataSource;\r\n }\r\n\r\n /**\r\n * 设置适配器,用于显示数据\r\n *\r\n * @param adapter\r\n */\r\n public void setAdapter(IDataAdapter<DATA> adapter) {\r\n mListView.setAdapter(adapter);\r\n this.dataAdapter = adapter;\r\n }\r\n\r\n /**\r\n * 设置Banner,用于显示广告展示\r\n *\r\n */\r\n public void setBanner(View view) {\r\n mListView.addHeaderView(view);\r\n }\r\n /**\r\n * 设置状态监听,监听开始刷新,刷新成功,开始加载更多,加载更多成功\r\n *\r\n * @param onStateChangeListener\r\n */\r\n public void setOnStateChangeListener(OnStateChangeListener<DATA> onStateChangeListener) {\r\n this.onStateChangeListener = onStateChangeListener;\r\n }\r\n\r\n public void setOnItemClickListener(OnItemClickListener onItemClickListener) {\r\n pullToRefreshPinnedHeaderListView.setOnItemClickListener(onItemClickListener);\r\n }\r\n\r\n /**\r\n * 刷新,开启异步线程,并且显示加载中的界面,当数据加载完成自动还原成加载完成的布局,并且刷新列表数据\r\n */\r\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\r\n public void refresh() {\r\n if (dataAdapter == null || dataSource == null) {\r\n if (pullToRefreshPinnedHeaderListView != null) {\r\n pullToRefreshPinnedHeaderListView.onRefreshComplete();\r\n }\r\n return;\r\n }\r\n if (asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n asyncTask.cancel(true);\r\n }\r\n asyncTask = new AsyncTask<Void, Void, DATA>() {\r\n protected void onPreExecute() {\r\n mLoadMoreView.showNormal();\r\n if (dataAdapter.isEmpty()) {\r\n mLoadView.showLoading();\r\n pullToRefreshPinnedHeaderListView.onRefreshComplete();\r\n } else {\r\n pullToRefreshPinnedHeaderListView.showHeadRefreshing();\r\n }\r\n if (onStateChangeListener != null) {\r\n onStateChangeListener.onStartRefresh(dataAdapter);\r\n }\r\n }\r\n\r\n ;\r\n\r\n @Override\r\n protected DATA doInBackground(Void... params) {\r\n try {\r\n return dataSource.refresh();\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n return null;\r\n }\r\n\r\n protected void onPostExecute(DATA result) {\r\n if (result == null) {\r\n if (dataAdapter.isEmpty()) {\r\n mLoadView.showFail();\r\n } else {\r\n mLoadView.tipFail();\r\n }\r\n } else {\r\n loadDataTime = System.currentTimeMillis();\r\n dataAdapter.setData(result, true);\r\n dataAdapter.notifyDataSetChanged();\r\n if (dataAdapter.isEmpty()) {\r\n mLoadView.showEmpty();\r\n } else {\r\n mLoadView.restore();\r\n pullToRefreshPinnedHeaderListView.getRefreshableView().setSelection(0);\r\n }\r\n hasMoreData = dataSource.hasMore();\r\n if (hasMoreData) {\r\n mLoadMoreView.showNormal();\r\n } else {\r\n mLoadMoreView.showNomore();\r\n }\r\n }\r\n if (onStateChangeListener != null) {\r\n onStateChangeListener.onEndRefresh(dataAdapter, result);\r\n }\r\n\r\n pullToRefreshPinnedHeaderListView.onRefreshComplete();\r\n }\r\n\r\n ;\r\n\r\n };\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\r\n asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);\r\n } else {\r\n asyncTask.execute();\r\n }\r\n }\r\n\r\n /**\r\n * 加载更多,开启异步线程,并且显示加载中的界面,当数据加载完成自动还原成加载完成的布局,并且刷新列表数据\r\n */\r\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\r\n public void loadMore() {\r\n if (isLoading()) {\r\n return;\r\n }\r\n if (dataAdapter.isEmpty()) {\r\n refresh();\r\n return;\r\n }\r\n\r\n if (dataAdapter == null || dataSource == null) {\r\n if (pullToRefreshPinnedHeaderListView != null) {\r\n pullToRefreshPinnedHeaderListView.onRefreshComplete();\r\n }\r\n return;\r\n }\r\n if (asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n asyncTask.cancel(true);\r\n }\r\n asyncTask = new AsyncTask<Void, Void, DATA>() {\r\n protected void onPreExecute() {\r\n if (onStateChangeListener != null) {\r\n onStateChangeListener.onStartLoadMore(dataAdapter);\r\n }\r\n mLoadMoreView.showLoading();\r\n }\r\n\r\n @Override\r\n protected DATA doInBackground(Void... params) {\r\n try {\r\n return dataSource.loadMore();\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n return null;\r\n }\r\n\r\n protected void onPostExecute(DATA result) {\r\n if (result == null) {\r\n mLoadView.tipFail();\r\n mLoadMoreView.showFail();\r\n } else {\r\n dataAdapter.setData(result, false);\r\n dataAdapter.notifyDataSetChanged();\r\n if (dataAdapter.isEmpty()) {\r\n mLoadView.showEmpty();\r\n } else {\r\n mLoadView.restore();\r\n }\r\n hasMoreData = dataSource.hasMore();\r\n if (hasMoreData) {\r\n mLoadMoreView.showNormal();\r\n } else {\r\n mLoadMoreView.showNomore();\r\n }\r\n }\r\n if (onStateChangeListener != null) {\r\n onStateChangeListener.onEndLoadMore(dataAdapter, result);\r\n }\r\n }\r\n\r\n ;\r\n };\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\r\n asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);\r\n } else {\r\n asyncTask.execute();\r\n }\r\n }\r\n\r\n /**\r\n * 做销毁操作,比如关闭正在加载数据的异步线程等\r\n */\r\n public void destory() {\r\n if (asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n asyncTask.cancel(true);\r\n asyncTask = null;\r\n }\r\n }\r\n\r\n /**\r\n * 是否正在加载中\r\n *\r\n * @return\r\n */\r\n public boolean isLoading() {\r\n return asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED;\r\n }\r\n\r\n private class OnRefreshListener211<T extends ListView> implements OnRefreshListener2<T> {\r\n\r\n @Override\r\n public void onPullDownToRefresh(PullToRefreshBase<T> refreshView) {\r\n refresh();\r\n }\r\n\r\n @Override\r\n public void onPullUpToRefresh(PullToRefreshBase<T> refreshView) {\r\n loadMore();\r\n }\r\n\r\n }\r\n\r\n public ListView getListView() {\r\n return pullToRefreshPinnedHeaderListView.getRefreshableView();\r\n }\r\n\r\n /**\r\n * 获取上次刷新数据的时间(数据成功的加载),如果数据没有加载成功过,那么返回-1\r\n *\r\n * @return\r\n */\r\n public long getLoadDataTime() {\r\n return loadDataTime;\r\n }\r\n\r\n public OnStateChangeListener<DATA> getOnStateChangeListener() {\r\n return onStateChangeListener;\r\n }\r\n\r\n public IDataAdapter<DATA> getAdapter() {\r\n return dataAdapter;\r\n }\r\n\r\n public IDataSource<DATA> getDataSource() {\r\n return dataSource;\r\n }\r\n\r\n public PullToRefreshAdapterViewBase<? extends ListView> getPullToRefreshAdapterViewBase() {\r\n return pullToRefreshPinnedHeaderListView;\r\n }\r\n\r\n public ILoadView getLoadView() {\r\n return mLoadView;\r\n }\r\n\r\n public ILoadMoreView getLoadMoreView() {\r\n return mLoadMoreView;\r\n }\r\n\r\n public void setAutoLoadMore(boolean autoLoadMore) {\r\n this.autoLoadMore = autoLoadMore;\r\n if (!isLoading()) {\r\n mLoadMoreView.showNormal();\r\n }\r\n }\r\n\r\n private boolean autoLoadMore = true;\r\n\r\n public boolean isAutoLoadMore() {\r\n return autoLoadMore;\r\n }\r\n\r\n private OnClickListener onClickLoadMoreListener = new OnClickListener() {\r\n\r\n @Override\r\n public void onClick(View v) {\r\n loadMore();\r\n }\r\n };\r\n private OnClickListener onClickRefresListener = new OnClickListener() {\r\n\r\n @Override\r\n public void onClick(View v) {\r\n refresh();\r\n }\r\n };\r\n /**\r\n * 滚动到底部自动加载更多数据\r\n */\r\n private OnScrollListener onScrollListener = new OnScrollListener() {\r\n\r\n @Override\r\n public void onScrollStateChanged(AbsListView listView, int scrollState) {\r\n if (autoLoadMore) {\r\n if (hasMoreData) {\r\n if (!pullToRefreshPinnedHeaderListView.isRefreshing()) {// 如果不是刷新状态\r\n\r\n if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && listView.getLastVisiblePosition() + 1 == listView.getCount()) {// 如果滚动到最后一行\r\n\r\n // 如果网络可以用\r\n\r\n if (NetworkUtils.hasNetwork(context)) {\r\n loadMore();\r\n } else {\r\n if (!isLoading()) {\r\n mLoadMoreView.showFail();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {\r\n }\r\n };\r\n /**\r\n * 针对于电视 选择到了底部项的时候自动加载更多数据\r\n */\r\n private OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {\r\n\r\n @Override\r\n public void onItemSelected(AdapterView<?> listView, View view, int position, long id) {\r\n if (autoLoadMore) {\r\n if (hasMoreData) {\r\n if (listView.getLastVisiblePosition() + 1 == listView.getCount()) {// 如果滚动到最后一行\r\n // 如果网络可以用\r\n if (NetworkUtils.hasNetwork(context)) {\r\n loadMore();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void onNothingSelected(AdapterView<?> parent) {\r\n\r\n }\r\n };\r\n\r\n}",
"public class ProductCustomerHistoryListAdapter extends BaseAdapter implements IDataAdapter<List<CustomerItem>> {\r\n private List<CustomerItem> mCustomerItems = new ArrayList<CustomerItem>();\r\n private LayoutInflater mInflater;\r\n private Context mContext;\r\n\r\n public ProductCustomerHistoryListAdapter(Context context) {\r\n super();\r\n mContext = context;\r\n mInflater = LayoutInflater.from(context);\r\n }\r\n\r\n @Override\r\n public int getCount() {\r\n return mCustomerItems.size();\r\n }\r\n\r\n @Override\r\n public Object getItem(int position) {\r\n return null;\r\n }\r\n\r\n @Override\r\n public long getItemId(int position) {\r\n return 0;\r\n }\r\n\r\n @Override\r\n public View getView(final int position, View convertView, ViewGroup parent) {\r\n final CustomerItem item = mCustomerItems.get(position);\r\n final ItemHolder holder;\r\n if (convertView == null) {\r\n convertView = mInflater.inflate(R.layout.product_customer_history_listview_item, parent, false);\r\n holder = new ItemHolder();\r\n holder.nameTv = (TextView)convertView.findViewById(R.id.product_customer_name);\r\n holder.editBt = (ImageButton)convertView.findViewById(R.id.product_customer_edit);\r\n holder.phoneBt = (ImageButton)convertView.findViewById(R.id.product_customer_phone);\r\n holder.typeTv = (TextView)convertView.findViewById(R.id.product_customer_type);\r\n holder.positionTv = (TextView)convertView.findViewById(R.id.product_customer_position);\r\n holder.aliasTv = (TextView)convertView.findViewById(R.id.product_customer_alias);\r\n holder.tipTv = (TextView)convertView.findViewById(R.id.product_customer_tips);\r\n convertView.setTag(holder);\r\n } else {\r\n holder = (ItemHolder) convertView.getTag();\r\n }\r\n\r\n holder.typeTv.setText(item.getType());\r\n holder.nameTv.setText(item.getName());\r\n holder.positionTv.setText(item.getPosition());\r\n holder.aliasTv.setText(item.getAlias());\r\n holder.phoneBt.setOnClickListener(new View.OnClickListener() {\r\n @Override\r\n public void onClick(View view) {\r\n String uri = \"tel:\" + item.getPhone().trim();\r\n Intent intent = new Intent(Intent.ACTION_DIAL);\r\n intent.setData(Uri.parse(uri));\r\n mContext.startActivity(intent);\r\n }\r\n });\r\n holder.editBt.setOnClickListener(new View.OnClickListener() {\r\n @Override\r\n public void onClick(View view) {\r\n Intent intent = new Intent(mContext, NoteActivity.class);\r\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r\n intent.putExtra(\"info\", item.getNote());\r\n intent.putExtra(\"type\",4);\r\n intent.putExtra(\"position\",position);\r\n mContext.startActivity(intent);\r\n }\r\n });\r\n if (!TextUtils.isEmpty(item.getNote())) {\r\n holder.tipTv.setVisibility(View.VISIBLE);\r\n } else {\r\n holder.tipTv.setVisibility(View.GONE);\r\n }\r\n return convertView;\r\n }\r\n\r\n @Override\r\n public void setData(List<CustomerItem> data, boolean isRefresh) {\r\n if (isRefresh) {\r\n mCustomerItems.clear();\r\n }\r\n mCustomerItems.addAll(data);\r\n }\r\n\r\n @Override\r\n public List<CustomerItem> getData() {\r\n return mCustomerItems;\r\n }\r\n\r\n public static class ItemHolder {\r\n TextView aliasTv;\r\n TextView nameTv;\r\n ImageButton editBt;\r\n TextView typeTv;\r\n TextView positionTv;\r\n ImageButton phoneBt;\r\n TextView tipTv;\r\n }\r\n}\r",
"public class ProductCustomerOnSellListAdapter extends BaseAdapter implements IDataAdapter<List<CustomerItem>> {\r\n private List<CustomerItem> mCustomerItems = new ArrayList<CustomerItem>();\r\n private LayoutInflater mInflater;\r\n private Context mContext;\r\n\r\n public ProductCustomerOnSellListAdapter(Context context) {\r\n super();\r\n mContext = context;\r\n mInflater = LayoutInflater.from(context);\r\n }\r\n\r\n @Override\r\n public int getCount() {\r\n return mCustomerItems.size();\r\n }\r\n\r\n @Override\r\n public Object getItem(int position) {\r\n return null;\r\n }\r\n\r\n @Override\r\n public long getItemId(int position) {\r\n return 0;\r\n }\r\n\r\n @Override\r\n public View getView(final int position, View convertView, ViewGroup parent) {\r\n final CustomerItem item = mCustomerItems.get(position);\r\n final ItemHolder holder;\r\n if (convertView == null) {\r\n convertView = mInflater.inflate(R.layout.product_customer_onsell_listview_item, parent, false);\r\n holder = new ItemHolder();\r\n holder.aliasTv = (TextView)convertView.findViewById(R.id.product_customer_alias);\r\n holder.nameTv = (TextView)convertView.findViewById(R.id.product_customer_name);\r\n holder.editBt = (ImageButton)convertView.findViewById(R.id.product_customer_edit);\r\n holder.phoneBt = (ImageButton)convertView.findViewById(R.id.product_customer_phone);\r\n holder.sexTv = (TextView)convertView.findViewById(R.id.product_customer_sex);\r\n holder.riskTv = (TextView)convertView.findViewById(R.id.product_customer_risk);\r\n holder.stateTv = (TextView)convertView.findViewById(R.id.product_customer_state);\r\n holder.tipTv = (TextView)convertView.findViewById(R.id.product_customer_tips);\r\n convertView.setTag(holder);\r\n } else {\r\n holder = (ItemHolder) convertView.getTag();\r\n }\r\n holder.aliasTv.setText(item.getAlias());\r\n holder.sexTv.setText(item.getSex());\r\n holder.aliasTv.setText(item.getAlias());\r\n holder.riskTv.setText(item.getRisk());\r\n holder.nameTv.setText(item.getName());\r\n holder.stateTv.setText(item.getState());\r\n holder.phoneBt.setOnClickListener(new View.OnClickListener() {\r\n @Override\r\n public void onClick(View view) {\r\n String uri = \"tel:\" + item.getPhone().trim();\r\n Intent intent = new Intent(Intent.ACTION_DIAL);\r\n intent.setData(Uri.parse(uri));\r\n mContext.startActivity(intent);\r\n\r\n }\r\n });\r\n holder.editBt.setOnClickListener(new View.OnClickListener() {\r\n @Override\r\n public void onClick(View view) {\r\n Intent intent = new Intent(mContext, NoteActivity.class);\r\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r\n intent.putExtra(\"info\", item.getNote());\r\n intent.putExtra(\"type\",3);\r\n intent.putExtra(\"position\",position);\r\n mContext.startActivity(intent);\r\n }\r\n });\r\n if (!TextUtils.isEmpty(item.getNote())) {\r\n holder.tipTv.setVisibility(View.VISIBLE);\r\n } else {\r\n holder.tipTv.setVisibility(View.GONE);\r\n }\r\n return convertView;\r\n }\r\n\r\n @Override\r\n public void setData(List<CustomerItem> data, boolean isRefresh) {\r\n if (isRefresh) {\r\n mCustomerItems.clear();\r\n }\r\n mCustomerItems.addAll(data);\r\n }\r\n\r\n @Override\r\n public List<CustomerItem> getData() {\r\n return mCustomerItems;\r\n }\r\n\r\n public static class ItemHolder {\r\n TextView nameTv;\r\n TextView aliasTv;\r\n ImageButton editBt;\r\n TextView riskTv;\r\n TextView sexTv;\r\n ImageButton phoneBt;\r\n TextView stateTv;\r\n TextView tipTv;\r\n }\r\n}\r",
"public class ProductCustomerHistoryDataSource implements IDataSource<List<CustomerItem>> {\r\n public static List<CustomerItem> mLists;\r\n private int page = 1;\r\n private int maxPage = 1;\r\n\r\n @Override\r\n public List<CustomerItem> refresh() throws Exception {\r\n if (mLists == null) {\r\n mLists = loadData(1);\r\n }\r\n return mLists;\r\n }\r\n\r\n @Override\r\n public List<CustomerItem> loadMore() throws Exception {\r\n if (mLists == null) {\r\n mLists = loadData(page + 1);\r\n }\r\n return mLists;\r\n }\r\n private List<CustomerItem> loadData(int page) throws Exception {\r\n // 这里用百度首页模拟网络请求,如果网路出错的话,直接抛异常不会执行后面的获取books的语句\r\n //HttpUtils.executeGet(\"http://www.baidu.com\");\r\n\r\n List<CustomerItem> customerItems = new ArrayList<CustomerItem>();\r\n\r\n CustomerItem item0 = new CustomerItem();\r\n item0.setName(\"(张艳)\");\r\n item0.setAlias(\"晓艳\");\r\n item0.setPhone(\"13588425804\");\r\n item0.setType(\"激进型\");\r\n item0.setPosition(\"持仓100万\");\r\n item0.setSex(\"女士\");\r\n customerItems.add(item0);\r\n\r\n CustomerItem item1 = new CustomerItem();\r\n item1.setName(\"(李建国)\");\r\n item1.setAlias(\"建国\");\r\n item1.setPhone(\"13988425804\");\r\n item1.setType(\"激进型\");\r\n item1.setPosition(\"持仓100万\");\r\n item1.setSex(\"先生\");\r\n customerItems.add(item1);\r\n\r\n CustomerItem item2 = new CustomerItem();\r\n item2.setName(\"(唐飞艳)\");\r\n item2.setAlias(\"飞艳\");\r\n item2.setPhone(\"13688433404\");\r\n item2.setType(\"激进型\");\r\n item2.setPosition(\"持仓100万\");\r\n item2.setSex(\"女士\");\r\n customerItems.add(item2);\r\n\r\n CustomerItem item3 = new CustomerItem();\r\n item3.setName(\"(王超)\");\r\n item3.setAlias(\"王总\");\r\n item3.setPhone(\"13288427404\");\r\n item3.setType(\"激进型\");\r\n item3.setPosition(\"持仓100万\");\r\n item3.setSex(\"女士\");\r\n customerItems.add(item3);\r\n\r\n CustomerItem item4 = new CustomerItem();\r\n item4.setName(\"(唐石溪)\");\r\n item4.setAlias(\"唐总\");\r\n item4.setPhone(\"13988425604\");\r\n item4.setType(\"激进型\");\r\n item4.setPosition(\"持仓100万\");\r\n item4.setSex(\"先生\");\r\n customerItems.add(item4);\r\n\r\n this.page = page;\r\n return customerItems;\r\n }\r\n\r\n @Override\r\n public boolean hasMore() {\r\n return page < maxPage;\r\n }\r\n\r\n}\r",
"public class ProductCustomerOnsellDataSource implements IDataSource<List<CustomerItem>> {\r\n public static List<CustomerItem> mLists;\r\n private int page = 1;\r\n private int maxPage = 1;\r\n\r\n @Override\r\n public List<CustomerItem> refresh() throws Exception {\r\n if (mLists == null) {\r\n mLists = loadData(1);\r\n }\r\n return mLists;\r\n }\r\n\r\n @Override\r\n public List<CustomerItem> loadMore() throws Exception {\r\n if (mLists == null) {\r\n mLists = loadData(page + 1);\r\n }\r\n return mLists;\r\n }\r\n\r\n private List<CustomerItem> loadData(int page) throws Exception {\r\n // 这里用百度首页模拟网络请求,如果网路出错的话,直接抛异常不会执行后面的获取books的语句\r\n // HttpUtils.executeGet(\"http://www.baidu.com\");\r\n\r\n List<CustomerItem> customerItems = new ArrayList<CustomerItem>();\r\n\r\n CustomerItem item0 = new CustomerItem();\r\n item0.setName(\"(张晓艳)\");\r\n item0.setAlias(\"晓艳\");\r\n item0.setPhone(\"13588425804\");\r\n item0.setRisk(\"进取型\");\r\n item0.setSex(\"女士\");\r\n item0.setState(\"已预约\");\r\n customerItems.add(item0);\r\n\r\n CustomerItem item1 = new CustomerItem();\r\n item1.setName(\"(李建国)\");\r\n item1.setAlias(\"建国\");\r\n item1.setPhone(\"13988425804\");\r\n item1.setRisk(\"平稳型\");\r\n item1.setSex(\"先生\");\r\n item1.setState(\"已预约\");\r\n customerItems.add(item1);\r\n\r\n CustomerItem item2 = new CustomerItem();\r\n item2.setName(\"(唐飞艳)\");\r\n item2.setAlias(\"飞艳\");\r\n item2.setPhone(\"13688433404\");\r\n item2.setRisk(\"成长型\");\r\n item2.setState(\"无兴趣\");\r\n item2.setSex(\"女士\");\r\n customerItems.add(item2);\r\n\r\n CustomerItem item3 = new CustomerItem();\r\n item3.setName(\"(王超)\");\r\n item3.setAlias(\"王总\");\r\n item3.setState(\"讯问中\");\r\n item3.setPhone(\"13288427404\");\r\n item3.setRisk(\"进取型\");\r\n item3.setSex(\"女士\");\r\n customerItems.add(item3);\r\n\r\n CustomerItem item4 = new CustomerItem();\r\n item4.setName(\"(唐石溪)\");\r\n item4.setAlias(\"唐总\");\r\n item4.setState(\"已预约\");\r\n item4.setPhone(\"13988425604\");\r\n item4.setRisk(\"平衡型\");\r\n item4.setSex(\"先生\");\r\n customerItems.add(item4);\r\n\r\n this.page = page;\r\n return customerItems;\r\n }\r\n\r\n @Override\r\n public boolean hasMore() {\r\n return page < maxPage;\r\n }\r\n\r\n}\r",
"public interface OnBackStackListener {\n public void onBackStack();\n}",
"public class ProductItem {\n private String title;//标题\n private String state;//状态\n private int recommendState;//推荐状态\n private String risk;//风险\n private String rate;//收益\n private String days;//天数\n private String notice;//公告\n private String list;//列表\n private String detail;//详情\n private String startMoney;//起点金额\n private String positionMoney;//持仓金额\n private String leftMoney;//剩余金额\n private String totalMoney;//总金额\n private String comment;\n private boolean tipsVisibility;//tips可见性\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getState() {\n return state;\n }\n\n public void setState(String state) {\n this.state = state;\n }\n\n public String getRate() {\n return rate;\n }\n\n public void setRate(String rate) {\n this.rate = rate;\n }\n\n public String getRisk() {\n return risk;\n }\n\n public void setRisk(String risk) {\n this.risk = risk;\n }\n\n public String getDays() {\n return days;\n }\n\n public void setDays(String days) {\n this.days = days;\n }\n\n public String getNotice() {\n return notice;\n }\n\n public void setNotice(String notice) {\n this.notice = notice;\n }\n\n public String getList() {\n return list;\n }\n\n public void setList(String list) {\n this.list = list;\n }\n\n public String getDetail() {\n return detail;\n }\n\n public void setDetail(String detail) {\n this.detail = detail;\n }\n\n public String getStartMoney() {\n return startMoney;\n }\n\n public void setStartMoney(String startMoney) {\n this.startMoney = startMoney;\n }\n\n public String getLeftMoney() {\n return leftMoney;\n }\n\n public void setLeftMoney(String leftMoney) {\n this.leftMoney = leftMoney;\n }\n\n public String getTotalMoney() {\n return totalMoney;\n }\n\n public void setTotalMoney(String totalMoney) {\n this.totalMoney = totalMoney;\n }\n\n public int getRecommendState() {\n return recommendState;\n }\n\n public void setRecommendState(int recommendState) {\n this.recommendState = recommendState;\n }\n\n public String getPositionMoney() {\n return positionMoney;\n }\n\n public void setPositionMoney(String positionMoney) {\n this.positionMoney = positionMoney;\n }\n\n public boolean isTipsVisibility() {\n return tipsVisibility;\n }\n\n public void setTipsVisibility(boolean tipsVisibility) {\n this.tipsVisibility = tipsVisibility;\n }\n\n public String getComment() {\n return comment;\n }\n\n public void setComment(String comment) {\n this.comment = comment;\n }\n}"
] | import android.os.Bundle;
import android.view.View;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.shizhefei.view.listviewhelper.ListViewHelper;
import com.kejiwen.architecture.R;
import com.kejiwen.architecture.adapter.ProductCustomerHistoryListAdapter;
import com.kejiwen.architecture.adapter.ProductCustomerOnSellListAdapter;
import com.kejiwen.architecture.biz.ProductCustomerHistoryDataSource;
import com.kejiwen.architecture.biz.ProductCustomerOnsellDataSource;
import com.kejiwen.architecture.listener.OnBackStackListener;
import com.kejiwen.architecture.model.ProductItem;
import java.util.List; | package com.kejiwen.architecture.activity;
public class ProductCustomerListActivity extends BaseActivity implements OnBackStackListener, View.OnClickListener {
private final static String TAG = "CustomerProductListActivity";
private ListViewHelper mListViewHelper;
private ProductCustomerHistoryListAdapter mHistoryAdapter;
private ProductCustomerOnSellListAdapter mOnSellAdapter;
private int mListType;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.customer_product_list);
super.onCreate(savedInstanceState);
mListType = getIntent().getIntExtra("type",0);
mTitleBar.setTitle("客户列表");
mTitleBar.setBackButton(R.mipmap.titlebar_back_arrow, this);
PullToRefreshListView refreshListView = (PullToRefreshListView) findViewById(R.id.pullToRefreshListView);
mListViewHelper = new ListViewHelper<List<ProductItem>>(refreshListView);
if (mListType == 0) {
// 设置数据源
mOnSellAdapter = new ProductCustomerOnSellListAdapter(this); | mListViewHelper.setDataSource(new ProductCustomerOnsellDataSource()); | 4 |
curtisullerich/attendance | src/main/java/edu/iastate/music/marching/attendance/model/interact/AbsenceManager.java | [
"public class Lang {\n\n\tpublic static final String ERROR_MESSAGE_NO_DIRECTOR = \"There is no director registered. You cannot register for an account yet.\";\n\tpublic static final String ERROR_INVALID_PRIMARY_REGISTER_EMAIL= \"Not a valid email, try logging in with your student account\";\n\tpublic static final String ERROR_ABSENCE_FOR_NULL_USER = \"Tried to create absence for null user\";\n}",
"@Entity(kind = \"Absence\", allocateIdsBy = 0)\npublic class Absence {\n\n\tpublic static enum Status {\n\t\tPending, Approved, Denied;\n\n\t\tprivate String mDisplayString;\n\n\t\tprivate Status() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\n\t\tpublic boolean isApproved() {\n\t\t\treturn this == Approved;\n\t\t}\n\n\t\tpublic boolean isDenied() {\n\t\t\treturn this == Denied;\n\t\t}\n\n\t\tpublic boolean isPending() {\n\t\t\treturn this == Pending;\n\t\t}\n\t}\n\n\tpublic enum Type {\n\t\tAbsence, Tardy, EarlyCheckOut;\n\n\t\tprivate String mDisplayString;\n\n\t\tprivate Type() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tprivate Type(String display_string) {\n\t\t\tmDisplayString = display_string;\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\n\t\tpublic boolean isAbsence() {\n\t\t\treturn Absence.equals(this);\n\t\t}\n\n\t\tpublic boolean isEarlyCheckOut() {\n\t\t\treturn EarlyCheckOut.equals(this);\n\t\t}\n\n\t\tpublic boolean isTardy() {\n\t\t\treturn Tardy.equals(this);\n\t\t}\n\t};\n\n\tpublic static final String FIELD_EVENT = \"event\";\n\tpublic static final String FIELD_STUDENT = \"student\";\n\tpublic static final String FIELD_TYPE = \"type\";\n\n\t@Id\n\tprivate long id;\n\n\tprivate Type type;\n\n\tprivate Status status;\n\n\t@Index\n\t@Activate\n\tprivate Event event;\n\n\t@Index\n\t@Activate\n\tprivate User student;\n\n\tprivate Date start;\n\n\tprivate Date end;\n\n\t@Store(false)\n\tprivate DateTime cachedCheckout;\n\n\t@Store(false)\n\tprivate DateTime cachedCheckin;\n\t@Store(false)\n\tprivate Interval cachedInterval;\n\n\t/**\n\t * Create absence through AbsenceController (DataModel.absence().create(...)\n\t */\n\tAbsence() {\n\t}\n\n\tpublic static boolean isContainedIn(Absence a, ReadableInterval i) {\n\t\tif (a.getType() == null || i == null)\n\t\t\treturn false;\n\n\t\tChronology chron = i.getChronology();\n\n\t\tswitch (a.getType()) {\n\t\tcase Absence:\n\t\t\treturn i.contains(a.getInterval(chron));\n\t\tcase EarlyCheckOut:\n\t\t\tDateTime checkout = a.getCheckout(chron);\n\t\t\treturn i.contains(checkout);\n\t\tcase Tardy:\n\t\t\tDateTime checkin = a.getCheckin(chron);\n\t\t\treturn i.contains(checkin);\n\t\tdefault:\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\t}\n\n\tpublic DateTime getCheckin(DateTimeZone zone) {\n\t\tif (getType().isTardy())\n\t\t\treturn new DateTime(this.start, zone);\n\t\telse\n\t\t\tthrow new IllegalStateException(\"Intervals only valid for absences\");\n\t}\n\n\tpublic DateTime getCheckin(Chronology chron) {\n\t\tif (getType().isTardy())\n\t\t\treturn new DateTime(this.start, chron);\n\t\telse\n\t\t\tthrow new IllegalStateException(\"Intervals only valid for absences\");\n\t}\n\n\tpublic DateTime getCheckout(DateTimeZone zone) {\n\t\tif (getType().isEarlyCheckOut())\n\t\t\treturn new DateTime(this.start, zone);\n\t\telse\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Checkouts only valid for early checkouts\");\n\t}\n\n\tpublic DateTime getCheckout(Chronology chron) {\n\t\tif (getType().isEarlyCheckOut())\n\t\t\treturn new DateTime(this.start, chron);\n\t\telse\n\t\t\tthrow new IllegalStateException(\"Intervals only valid for absences\");\n\t}\n\n\t@Deprecated\n\tpublic Date getDatetime() {\n\t\treturn start;\n\t}\n\n\t@Deprecated\n\tpublic Date getEnd() {\n\t\treturn end;\n\t}\n\n\tpublic Event getEvent() {\n\t\treturn event;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Time-span of an absence\n\t */\n\tpublic Interval getInterval(DateTimeZone zone) {\n\t\tif (getType().isAbsence()) {\n\t\t\treturn new Interval(new DateTime(this.start, zone), new DateTime(\n\t\t\t\t\tthis.end, zone));\n\n\t\t} else\n\t\t\tthrow new IllegalStateException(\"Intervals only valid for absences\");\n\t}\n\n\t/**\n\t * Time-span of an absence\n\t */\n\tpublic Interval getInterval(Chronology chron) {\n\t\tif (getType().isAbsence()) {\n\t\t\treturn new Interval(new DateTime(this.start, chron), new DateTime(\n\t\t\t\t\tthis.end, chron));\n\n\t\t} else\n\t\t\tthrow new IllegalStateException(\"Intervals only valid for absences\");\n\t}\n\n\t@Deprecated\n\tpublic Date getStart() {\n\t\treturn start;\n\t}\n\n\tpublic Status getStatus() {\n\t\treturn this.status;\n\t}\n\n\tpublic User getStudent() {\n\t\treturn student;\n\t}\n\n\tpublic Type getType() {\n\t\treturn this.type;\n\t}\n\n\tpublic void setCheckin(DateTime datetime) {\n\t\tif (getType().isTardy())\n\t\t\tthis.start = datetime.toDate();\n\t\telse\n\t\t\tthrow new IllegalStateException(\"Check-in times only valid for tardies\");\n\n\t}\n\n\tpublic void setCheckout(DateTime datetime) {\n\t\tif (getType().isEarlyCheckOut())\n\t\t\tthis.start = datetime.toDate();\n\t\telse\n\t\t\tthrow new IllegalStateException(\"Checkout times only valid for early check outs\");\n\n\t}\n\n\tpublic void setEvent(Event event) {\n\t\tthis.event = event;\n\t}\n\n\tpublic void setInterval(Interval interval) {\n\t\tif (getType().isAbsence()) {\n\t\t\tthis.end = interval.getEnd().toDate();\n\t\t\tthis.start = interval.getStart().toDate();\n\t\t} else\n\t\t\tthrow new IllegalStateException(\"Intervals only valid for absences\");\n\n\t}\n\n\tpublic void setStatus(Status status) {\n\t\tthis.status = status;\n\t}\n\n\tpublic void setStudent(User student) {\n\t\tthis.student = student;\n\t}\n\n\tpublic void setType(Type type) {\n\t\tthis.type = type;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn student.toString() + \" Start: \" + start.toString() + \" End: \"\n\t\t\t\t+ end.toString();\n\t}\n\n\tpublic static long parseKey(String keyStr) {\n\t\treturn Long.parseLong(keyStr);\n\t}\n}",
"@Entity(kind = \"Event\", allocateIdsBy = 0)\npublic class Event {\n\n\tpublic enum Type {\n\t\tRehearsal, Performance;\n\t\tprivate String mDisplayString;\n\n\t\tprivate Type() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tprivate Type(String display_string) {\n\t\t\tmDisplayString = display_string;\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\n\t\tpublic boolean isPerformance() {\n\t\t\treturn Performance.equals(this);\n\t\t}\n\n\t\tpublic boolean isRehearsal() {\n\t\t\treturn Rehearsal.equals(this);\n\t\t}\n\n\t}\n\n\tpublic static final String FIELD_START = \"start\";\n\tpublic static final String FIELD_END = \"end\";\n\n\tpublic static final String FIELD_TYPE = \"type\";\n\n\t@Id\n\tprivate long id;\n\n\t@Index\n\tprivate Date start;\n\n\t@Index\n\tprivate Date end;\n\n\tprivate Type type;\n\n\t/**\n\t * No-args constructor for datastore\n\t */\n\tEvent() {\n\n\t}\n\n\t@Deprecated\n\tpublic Date getDate() {\n\t\treturn start;\n\t}\n\n\t@Deprecated\n\tpublic Date getEnd() {\n\t\treturn end;\n\t}\n\n\tpublic long getId() {\n\t\treturn this.id;\n\t}\n\n\tpublic Interval getInterval(DateTimeZone zone) {\n\t\treturn new Interval(new DateTime(start, zone), new DateTime(end, zone));\n\t}\n\n\t@Deprecated\n\tpublic Date getStart() {\n\t\treturn start;\n\t}\n\n\tpublic Type getType() {\n\t\treturn this.type;\n\t}\n\n\tpublic void setInterval(Interval interval) {\n\t\tthis.start = interval.getStart().toDate();\n\t\tthis.end = interval.getEnd().toDate();\n\t}\n\n\tpublic void setType(Event.Type type) {\n\t\tthis.type = type;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Start: \" + start.toString() + \" End: \" + end.toString();\n\t}\n}",
"@Entity(kind = \"Form\", allocateIdsBy = 0)\npublic class Form {\n\n\tpublic static enum Status {\n\t\tPending, Approved, Denied;\n\t\tprivate String mDisplayString;\n\n\t\tprivate Status() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\n\t\tpublic boolean isPending() {\n\t\t\treturn this == Pending;\n\t\t}\n\n\t\tpublic boolean isApproved() {\n\t\t\treturn this == Approved;\n\t\t}\n\n\t\tpublic boolean isDenied() {\n\t\t\treturn this == Denied;\n\t\t}\n\t};\n\n\tpublic static enum Type {\n\t\tPerformanceAbsence, ClassConflict, TimeWorked;\n\n\t\tprivate String mDisplayString;\n\n\t\tprivate Type() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tprivate Type(String display_string) {\n\t\t\tmDisplayString = display_string;\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\n\t\tpublic boolean isClassConflict() {\n\t\t\treturn this == ClassConflict;\n\t\t}\n\n\t\tpublic boolean isPerformanceAbsence() {\n\t\t\treturn this == PerformanceAbsence;\n\t\t}\n\n\t\tpublic boolean isTimeWorked() {\n\t\t\treturn this == TimeWorked;\n\t\t}\n\t};\n\n\tpublic static final String FIELD_STUDENT = \"student\";\n\tpublic static final String HASHED_ID = \"hashedId\";\n\n\t@Id\n\tprivate long id;\n\n\t@Index\n\t@Activate\n\tprivate User student;\n\n\t@Index\n\tprivate Type type;\n\n\tprivate Status status;\n\n\tprivate boolean applied;\n\n\tprivate Absence.Type absenceType;\n\n\[email protected](Text.class)\n\tprivate String details;\n\n\tprivate Date startDate;\n\tprivate Date endDate;\n\tprivate Date submissionTime;\n\n\tprivate String startTime;\n\tprivate String endTime;\n\n\t// Strings to be used by Class Conflict Form\n\tprivate String dept;\n\tprivate String course;\n\tprivate String section;\n\n\tprivate String building;\n\tprivate int day;\n\tprivate boolean late;\n\tprivate int minutesWorked;\n\tprivate int minutesToOrFrom;\n\n\t/**\n\t * Create users through FormController\n\t * (DataTrain.get().getFormsController().createFormA(...)\n\t */\n\tForm() {\n\t}\n\n\tpublic Absence.Type getAbsenceType() {\n\t\treturn absenceType;\n\t}\n\n\tpublic String getBuilding() {\n\t\treturn building;\n\t}\n\n\tpublic String getCourse() {\n\t\treturn course;\n\t}\n\n\tpublic WeekDay getDayOfWeek() {\n\t\treturn WeekDay.valueOf(day);\n\t}\n\n\tpublic String getDept() {\n\t\treturn dept;\n\t}\n\n\tpublic String getDetails() {\n\t\treturn this.details;\n\t}\n\n\t@Deprecated\n\tpublic Date getEnd() {\n\t\treturn endDate;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic Interval getInterval(DateTimeZone zone) {\n\t\treturn new Interval(new DateTime(this.startDate, zone), new DateTime(\n\t\t\t\tthis.endDate, zone));\n\t}\n\n\tpublic int getMinutesToOrFrom() {\n\t\treturn this.minutesToOrFrom;\n\t}\n\n\tpublic int getMinutesWorked() {\n\t\treturn minutesWorked;\n\t}\n\n\tpublic String getSection() {\n\t\treturn section;\n\t}\n\n\t@Deprecated\n\tpublic Date getStart() {\n\t\treturn startDate;\n\t}\n\n\tpublic Status getStatus() {\n\t\treturn this.status;\n\t}\n\n\tpublic String getStatusString() {\n\t\treturn this.status.toString();\n\t}\n\n\tpublic User getStudent() {\n\t\treturn this.student;\n\t}\n\n\tpublic DateTime getSubmissionDateTime() {\n\t\treturn new DateTime(submissionTime);\n\t}\n\n\t@Deprecated\n\tpublic Date getSubmissionTime() {\n\t\treturn submissionTime;\n\t}\n\n\tpublic Type getType() {\n\t\treturn this.type;\n\t}\n\n\tpublic boolean isApplied() {\n\t\treturn applied;\n\t}\n\n\tpublic boolean isLate() {\n\t\treturn late;\n\t}\n\n\tpublic void setAbsenceType(Absence.Type absenceType) {\n\t\tthis.absenceType = absenceType;\n\t}\n\n\tpublic void setApplied(boolean applied) {\n\t\tif (this.applied) {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Once a Time Worked Form has been applied, it can never be applied again.\");\n\t\t}\n\t\tthis.applied = applied;\n\t}\n\n\tpublic void setBuilding(String building) {\n\t\tthis.building = building;\n\t}\n\n\tpublic void setCourse(String course) {\n\t\tthis.course = course;\n\t}\n\n\tpublic void setDayOfWeek(WeekDay day) {\n\t\tthis.day = day.DayOfWeek;\n\t}\n\n\tpublic void setDept(String dept) {\n\t\tthis.dept = dept;\n\t}\n\n\tpublic void setDetails(String details) {\n\t\tthis.details = details;\n\t}\n\n\tpublic void setInterval(Interval interval) {\n\t\tthis.startDate = interval.getStart().toDate();\n\t\tthis.endDate = interval.getEnd().toDate();\n\t}\n\n\tpublic void setLate(boolean late) {\n\t\tthis.late = late;\n\t}\n\n\tpublic void setMinutesToOrFrom(int minutesToOrFrom) {\n\t\tthis.minutesToOrFrom = minutesToOrFrom;\n\t}\n\n\tpublic void setMinutesWorked(int minutesWorked) {\n\t\tthis.minutesWorked = minutesWorked;\n\t}\n\n\tpublic void setSection(String section) {\n\t\tthis.section = section;\n\t}\n\n\tpublic void setStatus(Status status) {\n\t\tthis.status = status;\n\t}\n\n\tpublic void setStudent(User student) {\n\t\tthis.student = student;\n\t}\n\n\tpublic void setSubmissionTime(DateTime submissionTime) {\n\t\tthis.submissionTime = submissionTime.toDate();\n\t}\n\n\tpublic void setType(Type type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic LocalTime getStartTime() {\n\t\tif (getType() != Type.ClassConflict)\n\t\t\tthrow new UnsupportedOperationException();\n\t\telse\n\t\t\treturn LocalTime.parse(this.startTime);\n\t}\n\n\tpublic LocalTime getEndTime() {\n\t\tif (getType() != Type.ClassConflict)\n\t\t\tthrow new UnsupportedOperationException();\n\t\telse\n\t\t\treturn LocalTime.parse(this.endTime);\n\t}\n\n\tpublic void setStartTime(LocalTime startTime) {\n\t\tif (getType() != Type.ClassConflict)\n\t\t\tthrow new UnsupportedOperationException();\n\t\telse\n\t\t\tthis.startTime = startTime.toString();\n\t}\n\n\tpublic void setEndTime(LocalTime endTime) {\n\t\tif (getType() != Type.ClassConflict)\n\t\t\tthrow new UnsupportedOperationException();\n\t\telse\n\t\t\tthis.endTime = endTime.toString();\n\t}\n}",
"public class ModelFactory {\n\n\tpublic static Absence newAbsence(Absence.Type type, User student) {\n\t\tAbsence a = new Absence();\n\t\ta.setType(type);\n\t\ta.setStudent(student);\n\t\treturn a;\n\t}\n\n\tpublic static AppData newAppData() {\n\t\treturn new AppData();\n\t}\n\n\tpublic static Event newEvent(Event.Type type, Interval interval) {\n\t\tEvent e = new Event();\n\t\te.setType(type);\n\t\te.setInterval(interval);\n\t\treturn e;\n\t}\n\n\tpublic static Form newForm(Form.Type type, User student) {\n\t\tForm form = new Form();\n\t\tform.setType(type);\n\t\tform.setStudent(student);\n\t\tform.setBuilding(\"\");\n\t\treturn form;\n\t}\n\n\tpublic static ImportData newImportData() {\n\t\treturn new ImportData();\n\t}\n\n\tpublic static Object newInstance(Class<?> toType)\n\t\t\tthrows InstantiationException, IllegalAccessException {\n\t\treturn toType.newInstance();\n\t}\n\n\tpublic static MobileDataUpload newMobileDataUpload(User uploader,\n\t\t\tDateTime uploadTime, String uploadData) {\n\t\tMobileDataUpload upload = new MobileDataUpload();\n\t\tupload.setUploader(uploader);\n\t\tupload.setTimestamp(uploadTime);\n\t\tupload.setData(uploadData);\n\t\treturn upload;\n\t}\n\n\tpublic static StandardObjectDatastore newObjectDatastore() {\n\t\treturn new AttendanceDatastore();\n\t}\n\n\tpublic static User newUser(User.Type type, Email email, String univID) {\n\t\tUser u = new User();\n\t\tu.setType(type);\n\t\tu.setPrimaryEmail(email);\n\t\tu.setUniversityID(univID);\n\t\treturn u;\n\t}\n}",
"@Entity(kind = \"User\", allocateIdsBy = 0)\npublic class User implements Serializable {\n\n\tpublic enum Grade {\n\t\tA, B, C, D, F;\n\t\tprivate String mDisplayString;\n\n\t\tprivate Grade() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tprivate Grade(String display_string) {\n\t\t\tmDisplayString = display_string;\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\t}\n\n\tpublic enum Section {\n\t\tPiccolo, Clarinet, AltoSax(\"Alto Sax\"), TenorSax(\"Tenor Sax\"), Trumpet, Trombone, Bass_Trombone(\n\t\t\t\t\"Bass trombone\"), Mellophone, Baritone, Sousaphone, Guard, DrumMajor(\n\t\t\t\t\"Drum Major\"), Staff, Drumline_Cymbals(\"Drumline: Cymbals\"), Drumline_Tenors(\n\t\t\t\t\"Drumline: Tenors\"), Drumline_Snare(\"Drumline: Snare\"), Drumline_Bass(\n\t\t\t\t\"Drumline: Bass\"), Twirler;\n\n\t\tprivate String mDisplayString;\n\n\t\tprivate Section() {\n\t\t\tmDisplayString = this.toString();\n\t\t}\n\n\t\tprivate Section(String display_string) {\n\t\t\tmDisplayString = display_string;\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn mDisplayString;\n\t\t}\n\n\t\tpublic String getValue() {\n\t\t\treturn name();\n\t\t}\n\t}\n\n\tpublic enum Type {\n\t\tStudent, TA, Director;\n\n\t\tpublic boolean isDirector() {\n\t\t\treturn this.equals(Director);\n\t\t}\n\n\t\tpublic boolean isStudent() {\n\t\t\treturn this.equals(Student);\n\t\t}\n\n\t\tpublic boolean isTa() {\n\t\t\treturn this.equals(TA);\n\t\t}\n\t}\n\n\tprivate static final long serialVersionUID = 1421557192976557704L;\n\n\tpublic static final String FIELD_TYPE = \"type\";\n\n\tpublic static final String FIELD_ID = \"id\";\n\n\tpublic static final String FIELD_PRIMARY_EMAIL = \"email\";\n\n\tpublic static final String FIELD_SECONDARY_EMAIL = \"secondEmail\";\n\n\tpublic static final String FIELD_UNIVERSITY_ID = \"universityID\";\n\n\tprivate Type type;\n\n\tprivate Grade grade;\n\n\t@Id\n\tprivate String id;\n\n\tprivate Email email;\n\n\tprivate Email secondEmail;\n\n\tprivate String universityID;\n\n\tprivate Section section;\n\n\tprivate String firstName;\n\n\tprivate String lastName;\n\n\tprivate int year;\n\n\tprivate String major;\n\n\tprivate String rank;\n\n\tprivate boolean showApproved;\n\n\t// number of minutes available from submitted TimeWorked forms\n\tprivate int minutesAvailable;\n\n\t// number of unexcused minutes absent so far this semester\n\tprivate int minutesMissed;\n\n\t/**\n\t * Create users through UserController (DataModel.users().create(...)\n\t */\n\tUser() {\n\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o == null)\n\t\t\treturn false;\n\n\t\t// emails are unique, so compare based on them\n\t\tif (o instanceof User) {\n\t\t\tUser u = (User) o;\n\n\t\t\tif (this.email == null || this.email.getEmail() == null\n\t\t\t\t\t|| u.email == null || u.email.getEmail() == null) {\n\t\t\t\tif (this.email == null && u.email == null) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (this.email.getEmail() == null\n\t\t\t\t\t\t&& u.email.getEmail() == null) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.email.equals(u.email))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\tpublic Grade getGrade() {\n\n\t\treturn this.grade;\n\t}\n\n\tpublic String getId() {\n\t\treturn this.id;\n\t}\n\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\tpublic String getMajor() {\n\t\treturn major;\n\t}\n\n\tpublic int getMinutesAvailable() {\n\t\treturn minutesAvailable;\n\t}\n\n\tpublic String getName() {\n\t\treturn this.getFirstName() + \" \" + this.getLastName();\n\t}\n\n\t/**\n\t * Iowa State specific, instead use getId()\n\t * \n\t * @return net id of the user\n\t */\n\t@Deprecated\n\tpublic String getNetID() {\n\t\treturn this.id;\n\t}\n\n\tpublic Email getPrimaryEmail() {\n\t\treturn this.email;\n\t}\n\n\tpublic String getRank() {\n\t\treturn this.rank;\n\t}\n\n\tpublic Email getSecondaryEmail() {\n\t\treturn this.secondEmail;\n\t}\n\n\tpublic Section getSection() {\n\t\treturn section;\n\t}\n\n\tpublic Type getType() {\n\t\treturn this.type;\n\t}\n\n\tpublic String getUniversityID() {\n\t\treturn universityID;\n\t}\n\n\tpublic int getYear() {\n\t\treturn year;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tif (this.email == null || this.email.getEmail() == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn this.email.hashCode();\n\t}\n\n\tpublic boolean isShowApproved() {\n\t\treturn this.showApproved;\n\t}\n\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\tpublic void setGrade(Grade grade) {\n\t\tthis.grade = grade;\n\t}\n\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\tpublic void setMajor(String major) {\n\t\tthis.major = major;\n\t}\n\n\tpublic void setMinutesAvailable(int minutesAvailable) {\n\t\tthis.minutesAvailable = minutesAvailable;\n\t}\n\n\tpublic void setPrimaryEmail(Email email) {\n\t\tthis.email = email;\n\t\t// TODO https://github.com/curtisullerich/attendance/issues/170\n\t\t// This shouldn't be in the model, it should happen in the controllers\n\t\t// somehow\n\t\tif (email.getEmail().indexOf('%') == -1) {\n\t\t\tthis.id = email.getEmail().substring(0,\n\t\t\t\t\temail.getEmail().indexOf('@'));\n\t\t} else {\n\t\t\tthis.id = email.getEmail().substring(0,\n\t\t\t\t\temail.getEmail().indexOf('%'));\n\t\t}\n\t}\n\n\tpublic void setRank(String rank) {\n\t\tthis.rank = rank;\n\t}\n\n\tpublic void setSecondaryEmail(Email email) {\n\t\tthis.secondEmail = email;\n\t}\n\n\tpublic void setSection(Section section) {\n\t\tthis.section = section;\n\t}\n\n\tpublic void setShowApproved(boolean show) {\n\t\tthis.showApproved = show;\n\t}\n\n\tpublic void setType(Type type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic void setUniversityID(String new_universityID) {\n\t\tthis.universityID = new_universityID;\n\t}\n\n\tpublic void setYear(int year) {\n\t\tthis.year = year;\n\t}\n\n\tpublic void setMinutesMissed(int minutes) {\n\t\tthis.minutesMissed = minutes;\n\t}\n\n\tpublic int getMinutesMissed() {\n\t\treturn this.minutesMissed;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getName();\n\t}\n\n}"
] | import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.code.twig.FindCommand.RootFindCommand;
import com.google.code.twig.ObjectDatastore;
import edu.iastate.music.marching.attendance.Lang;
import edu.iastate.music.marching.attendance.model.store.Absence;
import edu.iastate.music.marching.attendance.model.store.Event;
import edu.iastate.music.marching.attendance.model.store.Form;
import edu.iastate.music.marching.attendance.model.store.ModelFactory;
import edu.iastate.music.marching.attendance.model.store.User; | LOG.warning("BLERG");
}
formDayOnAbsenceWeek = aStart.withDayOfWeek(formDayOfWeek)
.toDateMidnight();
break;
case Tardy:
DateTime checkin = absence.getCheckin(zone);
formDayOnAbsenceWeek = checkin.withDayOfWeek(formDayOfWeek)
.toDateMidnight();
break;
case EarlyCheckOut:
DateTime checkout = absence.getCheckout(zone);
formDayOnAbsenceWeek = checkout.withDayOfWeek(formDayOfWeek)
.toDateMidnight();
break;
default:
throw new UnsupportedOperationException();
}
int minutesToOrFrom = form.getMinutesToOrFrom();
DateTime effectiveStartTime = form.getStartTime()
.toDateTime(formDayOnAbsenceWeek).minusMinutes(minutesToOrFrom);
DateTime effectiveEndTime = form.getEndTime()
.toDateTime(formDayOnAbsenceWeek).plusMinutes(minutesToOrFrom);
Interval effectiveFormInterval = new Interval(effectiveStartTime,
effectiveEndTime);
return effectiveFormInterval;
}
/**
* This does not store any changes in the database!
*
* Note that this is only valid for forms A, B, and C. Form D has separate
* validation that occurs when a Form D is approved AND verified.
*
* @param absence
* @param form
* @return
*/
private boolean shouldBeAutoApproved(Absence absence, Form form) {
DateTimeZone zone = this.train.appData().get().getTimeZone();
if (form.getStatus() != Form.Status.Approved) {
// form must be approved!
return false;
}
if (absence.getStatus() != Absence.Status.Pending) {
// only pending absences can be auto-approved
return false;
}
if (form.getStudent() == null || absence.getStudent() == null) {
throw new IllegalArgumentException(
"Student was null in the absence or form.");
}
if (absence.getEvent() == null) {
throw new IllegalArgumentException("Absence had a null event.");
}
if (!form.getStudent().equals(absence.getStudent())) {
throw new IllegalArgumentException(
"Can't check absence against a form from another student.");
}
switch (form.getType()) {
case PerformanceAbsence:
// Performance absence request
if (absence.getEvent().getType() != Event.Type.Performance) {
// nope!
return false;
} else {
// TODO use Absence.isContainedIn(...)?
if (form.getInterval(zone).contains(
absence.getEvent().getInterval(zone))) {
return true;
}
}
break;
case ClassConflict:
Event e = absence.getEvent();
if (e.getType() != Event.Type.Rehearsal) {
return false;
}
Interval effectiveFormInterval = getEffectiveFormInterval(absence,
form, zone);
return Absence.isContainedIn(absence, effectiveFormInterval);
case TimeWorked:
// this does not auto-approve here. It does that upon an upDateTime
// of a
// Form D in the forms controller
break;
}
return false;
}
/**
* This is deprecated because the start and end DateTime are not sufficient
* to identify a single event. Type must also be specified. This is needed
* in the current implementation of the mobile app, though.
*
* @param student
* @param start
* @param end
* @return
*/
@Deprecated
public Absence createOrUpdateAbsence(User student, Interval interval) {
if (student == null) {
throw new IllegalArgumentException(Lang.ERROR_ABSENCE_FOR_NULL_USER);
}
| Absence absence = ModelFactory | 4 |
mangstadt/vinnie | src/main/java/com/github/mangstadt/vinnie/io/VObjectWriter.java | [
"public static String escapeNewlines(String string) {\n\tStringBuilder sb = null;\n\tchar prev = 0;\n\tfor (int i = 0; i < string.length(); i++) {\n\t\tchar c = string.charAt(i);\n\n\t\tif (c == '\\r' || c == '\\n') {\n\t\t\tif (sb == null) {\n\t\t\t\tsb = new StringBuilder(string.length() * 2);\n\t\t\t\tsb.append(string, 0, i);\n\t\t\t}\n\n\t\t\tif (c == '\\n' && prev == '\\r') {\n\t\t\t\t/*\n\t\t\t\t * Do not write a second newline escape sequence if the\n\t\t\t\t * newline sequence is \"\\r\\n\".\n\t\t\t\t */\n\t\t\t} else {\n\t\t\t\tsb.append(\"\\\\n\");\n\t\t\t}\n\t\t} else if (sb != null) {\n\t\t\tsb.append(c);\n\t\t}\n\n\t\tprev = c;\n\t}\n\treturn (sb == null) ? string : sb.toString();\n}",
"public enum SyntaxStyle {\n\t/**\n\t * \"Old style\" syntax (vCard 2.1 and vCal 1.0).\n\t */\n\tOLD,\n\n\t/**\n\t * \"New style\" syntax (vCard 3.0/4.0 and iCal 2.0).\n\t */\n\tNEW\n}",
"public class VObjectParameters implements Iterable<Map.Entry<String, List<String>>> {\n\tprivate final Map<String, List<String>> multimap;\n\n\t/**\n\t * Creates an empty list of parameters.\n\t */\n\tpublic VObjectParameters() {\n\t\tmultimap = new LinkedHashMap<String, List<String>>(); //preserve insertion order of keys\n\t}\n\n\t/**\n\t * <p>\n\t * Creates a list of parameters backed by the given map. Any changes made to\n\t * the given map will effect the parameter list and vice versa.\n\t * </p>\n\t * <p>\n\t * If the given map is not empty, care should be taken to ensure that all of\n\t * its keys are in uppercase before passing it into this constructor.\n\t * </p>\n\t * @param map the map\n\t */\n\tpublic VObjectParameters(Map<String, List<String>> map) {\n\t\tmultimap = map;\n\t}\n\n\t/**\n\t * Copies an existing list of parameters.\n\t * @param original the existing list\n\t */\n\tpublic VObjectParameters(VObjectParameters original) {\n\t\tthis();\n\t\tfor (Map.Entry<String, List<String>> entry : original) {\n\t\t\tString name = entry.getKey();\n\t\t\tList<String> values = entry.getValue();\n\t\t\tmultimap.put(name, new ArrayList<String>(values));\n\t\t}\n\t}\n\n\t/**\n\t * Gets the values that are assigned to a key.\n\t * @param key the key\n\t * @return the values or null if the key does not exist\n\t */\n\tpublic List<String> get(String key) {\n\t\tkey = sanitizeKey(key);\n\t\treturn _get(key);\n\t}\n\n\t/**\n\t * @param key assumed to already be in uppercase\n\t */\n\tprivate List<String> _get(String key) {\n\t\treturn multimap.get(key);\n\t}\n\n\t/**\n\t * Inserts a value.\n\t * @param key the key\n\t * @param value the value to add\n\t */\n\tpublic void put(String key, String value) {\n\t\tkey = sanitizeKey(key);\n\t\t_put(key, value);\n\t}\n\n\t/**\n\t * @param key assumed to already be in uppercase\n\t * @param value the value to add\n\t */\n\tprivate void _put(String key, String value) {\n\t\tList<String> list = _get(key);\n\t\tif (list == null) {\n\t\t\tlist = new ArrayList<String>();\n\t\t\tmultimap.put(key, list);\n\t\t}\n\t\tlist.add(value);\n\t}\n\n\t/**\n\t * Inserts multiple values.\n\t * @param key the key\n\t * @param values the values to add\n\t */\n\tpublic void putAll(String key, String... values) {\n\t\tif (values.length == 0) {\n\t\t\treturn;\n\t\t}\n\t\tkey = sanitizeKey(key);\n\t\t_putAll(key, values);\n\t}\n\n\t/**\n\t * @param key assumed to already be in uppercase\n\t * @param values the values to add\n\t */\n\tprivate void _putAll(String key, String... values) {\n\t\tList<String> list = _get(key);\n\t\tif (list == null) {\n\t\t\tlist = new ArrayList<String>();\n\t\t\tmultimap.put(key, list);\n\t\t}\n\t\tlist.addAll(Arrays.asList(values));\n\t}\n\n\t/**\n\t * Replaces all the values of the given key with the given value.\n\t * @param key the key\n\t * @param value the value\n\t * @return the replaced values or null if the key didn't exist\n\t */\n\tpublic List<String> replace(String key, String value) {\n\t\tkey = sanitizeKey(key);\n\t\tList<String> replaced = _removeAll(key);\n\t\t_put(key, value);\n\t\treturn replaced;\n\t}\n\n\t/**\n\t * Replaces all the values of the given key with the given values.\n\t * @param key the key\n\t * @param values the values\n\t * @return the replaced values or null if the key didn't exist\n\t */\n\tpublic List<String> replaceAll(String key, String... values) {\n\t\tkey = sanitizeKey(key);\n\t\tList<String> replaced = _removeAll(key);\n\t\tif (values.length > 0) {\n\t\t\t_putAll(key, values);\n\t\t}\n\t\treturn replaced;\n\t}\n\n\t/**\n\t * Removes a value.\n\t * @param key the key\n\t * @param value the value to remove\n\t * @return true if the value was found, false if not\n\t */\n\tpublic boolean remove(String key, String value) {\n\t\tList<String> values = get(key);\n\t\treturn (values == null) ? false : values.remove(value);\n\t}\n\n\t/**\n\t * Removes all values associated with a key, along with the key itself.\n\t * @param key the key\n\t * @return the removed values or null if the key didn't exist\n\t */\n\tpublic List<String> removeAll(String key) {\n\t\tkey = sanitizeKey(key);\n\t\treturn _removeAll(key);\n\t}\n\n\t/**\n\t * @param key assumed to already be in uppercase\n\t */\n\tprivate List<String> _removeAll(String key) {\n\t\treturn multimap.remove(key);\n\t}\n\n\t/**\n\t * Clears the multimap.\n\t */\n\tpublic void clear() {\n\t\tmultimap.clear();\n\t}\n\n\t/**\n\t * Gets the first value assigned to the given key.\n\t * @param key the key\n\t * @return the value or null if the given key does not have any values\n\t */\n\tpublic String first(String key) {\n\t\tList<String> values = get(key);\n\t\treturn (values == null || values.isEmpty()) ? null : values.get(0);\n\t}\n\n\t/**\n\t * Determines if a \"quoted-printable encoding\" parameter exists.\n\t * @return true if the parameter exists, false if not\n\t */\n\tpublic boolean isQuotedPrintable() {\n\t\tfor (String key : new String[] { \"ENCODING\", null }) {\n\t\t\tList<String> values = _get(key);\n\t\t\tif (values == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (String value : values) {\n\t\t\t\tif (\"QUOTED-PRINTABLE\".equalsIgnoreCase(value)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Gets the CHARSET parameter.\n\t * @return the character set or null if a character set is not defined\n\t * @throws IllegalCharsetNameException if the character set name contains\n\t * illegal characters\n\t * @throws UnsupportedCharsetException if the local JVM does not recognized\n\t * the character set\n\t */\n\tpublic Charset getCharset() throws IllegalCharsetNameException, UnsupportedCharsetException {\n\t\tString charsetStr = first(\"CHARSET\");\n\t\treturn (charsetStr == null) ? null : Charset.forName(charsetStr);\n\t}\n\n\t/**\n\t * Gets the map that backs this parameters list.\n\t * @return the map\n\t */\n\tpublic Map<String, List<String>> getMap() {\n\t\treturn multimap;\n\t}\n\n\t/**\n\t * Creates an iterator over all the parameters (for use in foreach loops).\n\t * @return the iterator\n\t */\n\tpublic Iterator<Entry<String, List<String>>> iterator() {\n\t\treturn multimap.entrySet().iterator();\n\t}\n\n\t/**\n\t * Converts the given key to uppercase. Call this method before passing a\n\t * key to the multimap.\n\t * @param key the key\n\t * @return the sanitized key\n\t */\n\tprivate String sanitizeKey(String key) {\n\t\treturn (key == null) ? null : key.toUpperCase();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn multimap.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) return true;\n\t\tif (obj == null) return false;\n\t\tif (getClass() != obj.getClass()) return false;\n\t\tVObjectParameters other = (VObjectParameters) obj;\n\t\treturn multimap.equals(other.multimap);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn multimap.toString();\n\t}\n}",
"public class VObjectProperty {\n\tprivate String group;\n\tprivate String name;\n\tprivate VObjectParameters parameters;\n\tprivate String value;\n\n\t/**\n\t * Creates an empty property.\n\t */\n\tpublic VObjectProperty() {\n\t\tthis(null, null);\n\t}\n\n\t/**\n\t * Create a new property.\n\t * @param name the property name (should contain only letters, numbers, and\n\t * dashes; letters should be uppercase by convention)\n\t * @param value the property value\n\t */\n\tpublic VObjectProperty(String name, String value) {\n\t\tthis(null, name, value);\n\t}\n\n\t/**\n\t * Creates a new property\n\t * @param group the group name (should contain only letters, numbers, and\n\t * dashes; can be null)\n\t * @param name the property name (should contain only letters, numbers, and\n\t * dashes; letters should be uppercase by convention)\n\t * @param value the property value\n\t */\n\tpublic VObjectProperty(String group, String name, String value) {\n\t\tthis(group, name, new VObjectParameters(), value);\n\t}\n\n\t/**\n\t * Creates a new property\n\t * @param group the group name (should contain only letters, numbers, and\n\t * dashes; can be null)\n\t * @param name the property name (should contain only letters, numbers, and\n\t * dashes; letters should be uppercase by convention)\n\t * @param parameters the property parameters (cannot be null)\n\t * @param value the property value\n\t */\n\tpublic VObjectProperty(String group, String name, VObjectParameters parameters, String value) {\n\t\tthis.group = group;\n\t\tthis.name = name;\n\t\tthis.parameters = parameters;\n\t\tthis.value = value;\n\t}\n\n\t/**\n\t * Gets the group name (note: iCalendar properties do not use group names).\n\t * @return the group name or null if the property doesn't have one\n\t */\n\tpublic String getGroup() {\n\t\treturn group;\n\t}\n\n\t/**\n\t * Sets the group name (note: iCalendar properties do not use group names).\n\t * @param group the group name or null to remove (should contain only\n\t * letters, numbers, and dashes)\n\t */\n\tpublic void setGroup(String group) {\n\t\tthis.group = group;\n\t}\n\n\t/**\n\t * Gets the property name.\n\t * @return the property name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * Sets the property name.\n\t * @param name the property name (should contain only letters, numbers, and\n\t * dashes; letters should be uppercase by convention)\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * Gets the parameters.\n\t * @return the parameters\n\t */\n\tpublic VObjectParameters getParameters() {\n\t\treturn parameters;\n\t}\n\n\t/**\n\t * Sets the parameters.\n\t * @param parameters the parameters (cannot be null)\n\t */\n\tpublic void setParameters(VObjectParameters parameters) {\n\t\tthis.parameters = parameters;\n\t}\n\n\t/**\n\t * Gets the property value.\n\t * @return the property value\n\t */\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\t/**\n\t * Sets the property value.\n\t * @param value the property value\n\t */\n\tpublic void setValue(String value) {\n\t\tthis.value = value;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((group == null) ? 0 : group.hashCode());\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\tresult = prime * result + ((parameters == null) ? 0 : parameters.hashCode());\n\t\tresult = prime * result + ((value == null) ? 0 : value.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) return true;\n\t\tif (obj == null) return false;\n\t\tif (getClass() != obj.getClass()) return false;\n\t\tVObjectProperty other = (VObjectProperty) obj;\n\t\tif (group == null) {\n\t\t\tif (other.group != null) return false;\n\t\t} else if (!group.equals(other.group)) return false;\n\t\tif (name == null) {\n\t\t\tif (other.name != null) return false;\n\t\t} else if (!name.equals(other.name)) return false;\n\t\tif (parameters == null) {\n\t\t\tif (other.parameters != null) return false;\n\t\t} else if (!parameters.equals(other.parameters)) return false;\n\t\tif (value == null) {\n\t\t\tif (other.value != null) return false;\n\t\t} else if (!value.equals(other.value)) return false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"VObjectProperty [group=\" + group + \", name=\" + name + \", parameters=\" + parameters + \", value=\" + value + \"]\";\n\t}\n}",
"public class AllowedCharacters {\n\tprivate static final int LENGTH = 128;\n\tprivate final BitSet bitSet;\n\tprivate final boolean allowNonAscii;\n\n\t/**\n\t * Creates an allowed character list based on the given {@link BitSet}.\n\t * @param bitSet the bit set\n\t * @param allowNonAscii true to allow characters outside of the 7-bit ASCII\n\t * character set (character codes greater than 127), false to only allow\n\t * 7-bit ASCII\n\t */\n\tpublic AllowedCharacters(BitSet bitSet, boolean allowNonAscii) {\n\t\tthis.bitSet = bitSet;\n\t\tthis.allowNonAscii = allowNonAscii;\n\t}\n\n\t/**\n\t * Gets the underlying {@link BitSet} object.\n\t * @return the {@link BitSet} object\n\t */\n\tpublic BitSet bitSet() {\n\t\treturn bitSet;\n\t}\n\n\t/**\n\t * Determines if this allowed character list permits characters that are not\n\t * part of 7-bit ASCII (character codes greater than 127).\n\t * @return true if non-ASCII characters are allowed, false if not\n\t */\n\tpublic boolean isNonAsciiAllowed() {\n\t\treturn allowNonAscii;\n\t}\n\n\t/**\n\t * Determines if a string only contains allowed characters.\n\t * @param string the string\n\t * @return true if the string only contains allowed characters, false if not\n\t */\n\tpublic boolean check(String string) {\n\t\tfor (int i = 0; i < string.length(); i++) {\n\t\t\tchar c = string.charAt(i);\n\t\t\tif (c >= LENGTH) {\n\t\t\t\tif (!allowNonAscii) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!bitSet.get(c)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns an allowed character list that is the opposite of this allowed\n\t * character list (in other words, characters that are NOT allowed).\n\t * @return the reverse list\n\t */\n\tpublic AllowedCharacters flip() {\n\t\tBitSet bitSet = (BitSet) this.bitSet.clone();\n\t\tbitSet.flip(0, LENGTH);\n\t\treturn new AllowedCharacters(bitSet, !allowNonAscii);\n\t}\n\n\t/**\n\t * Generates a string representation of this allowed character list.\n\t * Non-printable characters are represented by their character codes.\n\t * @return the string\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn toString(false);\n\t}\n\n\t/**\n\t * Generates a string representation of this allowed character list.\n\t * Non-printable characters are represented by their character codes.\n\t * @param printableOnly true to only include printable characters in the\n\t * string, false to include all characters\n\t * @return the string\n\t */\n\tpublic String toString(boolean printableOnly) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append('[');\n\t\tfor (int i = 0; i < LENGTH; i++) {\n\t\t\tif (!bitSet.get(i)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString toPrint = null;\n\n\t\t\tchar c = (char) i;\n\t\t\tswitch (c) {\n\t\t\tcase ' ':\n\t\t\t\ttoPrint = \"<space>\";\n\t\t\t\tbreak;\n\t\t\tcase '\\r':\n\t\t\t\ttoPrint = \"\\\\r\";\n\t\t\t\tbreak;\n\t\t\tcase '\\n':\n\t\t\t\ttoPrint = \"\\\\n\";\n\t\t\t\tbreak;\n\t\t\tcase '\\t':\n\t\t\t\ttoPrint = \"\\\\t\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (i < 32 || i == 127) {\n\t\t\t\t\tif (printableOnly) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\ttoPrint = \"(\" + i + \")\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsb.append(' ');\n\t\t\tif (toPrint == null) {\n\t\t\t\tsb.append(c);\n\t\t\t} else {\n\t\t\t\tsb.append(toPrint);\n\t\t\t}\n\t\t}\n\t\tsb.append(\" ]\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * Builder class for creating new instances of {@link AllowedCharacters}.\n\t */\n\tpublic static class Builder {\n\t\tprivate final BitSet bitSet;\n\t\tprivate boolean allowNonAscii;\n\n\t\t/**\n\t\t * Creates a new builder.\n\t\t */\n\t\tpublic Builder() {\n\t\t\tbitSet = new BitSet(LENGTH);\n\t\t\tallowNonAscii = false;\n\t\t}\n\n\t\t/**\n\t\t * Initializes the builder with an existing {@link AllowedCharacters}\n\t\t * object.\n\t\t * @param original the object to copy\n\t\t */\n\t\tpublic Builder(AllowedCharacters original) {\n\t\t\tbitSet = (BitSet) original.bitSet.clone();\n\t\t\tallowNonAscii = original.allowNonAscii;\n\t\t}\n\n\t\t/**\n\t\t * Allow all characters.\n\t\t * @return this\n\t\t */\n\t\tpublic Builder allowAll() {\n\t\t\tbitSet.set(0, LENGTH);\n\t\t\tallowNonAscii = true;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Allow characters within the given range.\n\t\t * @param from the character to start at\n\t\t * @param to the character to end at (inclusive)\n\t\t * @return this\n\t\t */\n\t\tpublic Builder allow(int from, int to) {\n\t\t\tbitSet.set(from, to + 1);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Allow all the characters in the given string.\n\t\t * @param characters the string containing the allowable characters\n\t\t * @return this\n\t\t */\n\t\tpublic Builder allow(String characters) {\n\t\t\tsetAll(characters, true);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Allow the given character.\n\t\t * @param c the character\n\t\t * @return this\n\t\t */\n\t\tpublic Builder allow(char c) {\n\t\t\tbitSet.set(c);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Allows all characters that are considered \"printable\" (32-126\n\t\t * inclusive). This does NOT include tabs, carriage returns, or line\n\t\t * feeds. This DOES include spaces.\n\t\t * @return this\n\t\t */\n\t\tpublic Builder allowPrintable() {\n\t\t\treturn allow(32, 126);\n\t\t}\n\n\t\t/**\n\t\t * Allows all characters outside the range of 7-bit ASCII.\n\t\t * @return this\n\t\t */\n\t\tpublic Builder allowNonAscii() {\n\t\t\tallowNonAscii = true;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Reject all the characters in the given string.\n\t\t * @param characters the string containing the illegal characters\n\t\t * @return this\n\t\t */\n\t\tpublic Builder except(String characters) {\n\t\t\tsetAll(characters, false);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Reject the given character.\n\t\t * @param c the character\n\t\t * @return this\n\t\t */\n\t\tpublic Builder except(char c) {\n\t\t\tbitSet.set(c, false);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Constructs the final {@link AllowedCharacters} object.\n\t\t * @return the object\n\t\t */\n\t\tpublic AllowedCharacters build() {\n\t\t\treturn new AllowedCharacters(bitSet, allowNonAscii);\n\t\t}\n\n\t\tprivate void setAll(String characters, boolean value) {\n\t\t\tfor (int i = 0; i < characters.length(); i++) {\n\t\t\t\tchar c = characters.charAt(i);\n\t\t\t\tbitSet.set(c, value);\n\t\t\t}\n\t\t}\n\t}\n}",
"public class VObjectValidator {\n\tprivate static final Map<SyntaxStyle, Map<Boolean, AllowedCharacters>> propertyName = new EnumMap<SyntaxStyle, Map<Boolean, AllowedCharacters>>(SyntaxStyle.class);\n\tstatic {\n\t\tboolean strict;\n\t\tSyntaxStyle syntax;\n\n\t\tsyntax = SyntaxStyle.OLD;\n\t\t{\n\t\t\tMap<Boolean, AllowedCharacters> map = new HashMap<Boolean, AllowedCharacters>();\n\t\t\tstrict = false;\n\t\t\t{\n\t\t\t\t//@formatter:off\n\t\t\t\tmap.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t.allowAll()\n\t\t\t\t\t.except(\"\\r\\n:.;\")\n\t\t\t\t.build());\n\t\t\t\t//@formatter:on\n\t\t\t}\n\n\t\t\tstrict = true;\n\t\t\t{\n\t\t\t\t//@formatter:off\n\t\t\t\tmap.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t.allowPrintable()\n\t\t\t\t\t.except(\"[]=:.,\")\n\t\t\t\t\n\t\t\t\t\t/*\n\t\t\t\t\t * Note: The specification's formal grammar allows semicolons to\n\t\t\t\t\t * be present in property name. This may be a mistake because\n\t\t\t\t\t * this would break the syntax. This validator will treat\n\t\t\t\t\t * semicolons as invalid in this context.\n\t\t\t\t\t * \n\t\t\t\t\t * The specifications state that semicolons can be included in\n\t\t\t\t\t * parameter values by escaping them with a backslash--however,\n\t\t\t\t\t * the specification is not clear as to whether this is also\n\t\t\t\t\t * permitted in property names.\n\t\t\t\t\t * \n\t\t\t\t\t * vCard 2.1: Section 2.1.2\n\t\t\t\t\t * vCal 1.0: Section 2, \"Property\" sub-heading\n\t\t\t\t\t */\n\t\t\t\t\t.except(';')\n\t\t\t\t.build());\n\t\t\t\t//@formatter:on\n\t\t\t}\n\n\t\t\tpropertyName.put(syntax, map);\n\t\t}\n\n\t\tsyntax = SyntaxStyle.NEW;\n\t\t{\n\t\t\tMap<Boolean, AllowedCharacters> map = new HashMap<Boolean, AllowedCharacters>();\n\t\t\tstrict = false;\n\t\t\t{\n\t\t\t\t//same as old style syntax\n\t\t\t\tmap.put(strict, propertyName.get(SyntaxStyle.OLD).get(strict));\n\t\t\t}\n\n\t\t\tstrict = true;\n\t\t\t{\n\t\t\t\t//@formatter:off\n\t\t\t\tmap.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t.allow('A', 'Z')\n\t\t\t\t\t.allow('a', 'z')\n\t\t\t\t\t.allow('0', '9')\n\t\t\t\t\t.allow('-')\n\t\t\t\t.build());\n\t\t\t\t//@formatter:on\n\t\t\t}\n\n\t\t\tpropertyName.put(syntax, map);\n\t\t}\n\t}\n\n\tprivate static final Map<SyntaxStyle, Map<Boolean, AllowedCharacters>> group = propertyName;\n\n\tprivate static final Map<SyntaxStyle, Map<Boolean, AllowedCharacters>> parameterName = new EnumMap<SyntaxStyle, Map<Boolean, AllowedCharacters>>(SyntaxStyle.class);\n\tstatic {\n\t\tboolean strict;\n\t\tSyntaxStyle syntax;\n\n\t\tsyntax = SyntaxStyle.OLD;\n\t\t{\n\t\t\tMap<Boolean, AllowedCharacters> map = new HashMap<Boolean, AllowedCharacters>();\n\t\t\tstrict = false;\n\t\t\t{\n\t\t\t\t//@formatter:off\n\t\t\t\tmap.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t.allowAll()\n\t\t\t\t\t.except(\"\\r\\n:;=\")\n\t\t\t\t.build());\n\t\t\t\t//@formatter:on\n\t\t\t}\n\n\t\t\tstrict = true;\n\t\t\t{\n\t\t\t\t//same as property name\n\t\t\t\tmap.put(strict, propertyName.get(syntax).get(strict));\n\t\t\t}\n\n\t\t\tparameterName.put(syntax, map);\n\t\t}\n\n\t\tsyntax = SyntaxStyle.NEW;\n\t\t{\n\t\t\tMap<Boolean, AllowedCharacters> map = new HashMap<Boolean, AllowedCharacters>();\n\t\t\tstrict = false;\n\t\t\t{\n\t\t\t\t//same as old style syntax\n\t\t\t\tmap.put(strict, parameterName.get(SyntaxStyle.OLD).get(strict));\n\t\t\t}\n\n\t\t\tstrict = true;\n\t\t\t{\n\t\t\t\t//same as property name\n\t\t\t\tmap.put(strict, propertyName.get(syntax).get(strict));\n\t\t\t}\n\n\t\t\tparameterName.put(syntax, map);\n\t\t}\n\t}\n\n\tprivate static final Map<SyntaxStyle, Map<Boolean, Map<Boolean, AllowedCharacters>>> parameterValue = new EnumMap<SyntaxStyle, Map<Boolean, Map<Boolean, AllowedCharacters>>>(SyntaxStyle.class);\n\tstatic {\n\t\tboolean strict, caretEncoding;\n\t\tSyntaxStyle syntax;\n\n\t\tsyntax = SyntaxStyle.OLD;\n\t\t{\n\t\t\tMap<Boolean, Map<Boolean, AllowedCharacters>> map = new HashMap<Boolean, Map<Boolean, AllowedCharacters>>();\n\t\t\tcaretEncoding = false;\n\t\t\t{\n\t\t\t\tMap<Boolean, AllowedCharacters> map2 = new HashMap<Boolean, AllowedCharacters>();\n\t\t\t\tstrict = false;\n\t\t\t\t{\n\t\t\t\t\t//@formatter:off\n\t\t\t\t\tmap2.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t\t.allowAll()\n\t\t\t\t\t\t.except(\"\\r\\n:\")\n\t\t\t\t\t.build());\n\t\t\t\t\t//@formatter:on\n\t\t\t\t}\n\n\t\t\t\tstrict = true;\n\t\t\t\t{\n\t\t\t\t\t//same as parameter name, except semicolons are allowed\n\t\t\t\t\t//@formatter:off\n\t\t\t\t\tAllowedCharacters paramName = parameterName.get(syntax).get(strict);\n\t\t\t\t\tmap2.put(strict, new AllowedCharacters.Builder(paramName)\n\t\t\t\t\t\t.allow(';')\n\t\t\t\t\t.build());\n\t\t\t\t\t//@formatter::on\n\t\t\t\t}\n\t\t\t\tmap.put(caretEncoding, map2);\n\t\t\t}\n\n\t\t\tcaretEncoding = true;\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Same as when caret encoding is disabled because\n\t\t\t\t * old style syntax does not support caret encoding.\n\t\t\t\t */\n\t\t\t\tmap.put(caretEncoding, map.get(false));\n\t\t\t}\n\n\t\t\tparameterValue.put(syntax, map);\n\t\t}\n\n\t\tsyntax = SyntaxStyle.NEW;\n\t\t{\n\t\t\tMap<Boolean, Map<Boolean, AllowedCharacters>> map = new HashMap<Boolean, Map<Boolean, AllowedCharacters>>();\n\t\t\tcaretEncoding = false;\n\t\t\t{\n\t\t\t\tMap<Boolean, AllowedCharacters> map2 = new HashMap<Boolean, AllowedCharacters>();\n\t\t\t\tstrict = false;\n\t\t\t\t{\n\t\t\t\t\t//@formatter:off\n\t\t\t\t\tmap2.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t\t.allowAll()\n\t\t\t\t\t\t.except(\"\\r\\n\\\"\")\n\t\t\t\t\t.build());\n\t\t\t\t\t//@formatter:on\n\t\t\t\t}\n\n\t\t\t\tstrict = true;\n\t\t\t\t{\n\t\t\t\t\t//@formatter:off\n\t\t\t\t\tmap2.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t\t.allowPrintable()\n\t\t\t\t\t\t.allowNonAscii()\n\t\t\t\t\t\t.allow('\\t')\n\t\t\t\t\t\t.except('\"')\n\t\t\t\t\t.build());\n\t\t\t\t\t//@formatter:on\n\t\t\t\t}\n\n\t\t\t\tmap.put(caretEncoding, map2);\n\t\t\t}\n\n\t\t\tcaretEncoding = true;\n\t\t\t{\n\t\t\t\tMap<Boolean, AllowedCharacters> map2 = new HashMap<Boolean, AllowedCharacters>();\n\t\t\t\tstrict = false;\n\t\t\t\t{\n\t\t\t\t\t//@formatter:off\n\t\t\t\t\tmap2.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t\t.allowAll()\n\t\t\t\t\t.build());\n\t\t\t\t\t//@formatter:on\n\t\t\t\t}\n\n\t\t\t\tstrict = true;\n\t\t\t\t{\n\t\t\t\t\t//@formatter:off\n\t\t\t\t\tmap2.put(strict, new AllowedCharacters.Builder()\n\t\t\t\t\t\t.allowPrintable()\n\t\t\t\t\t\t.allowNonAscii()\n\t\t\t\t\t\t.allow(\"\\r\\n\\t\")\n\t\t\t\t\t.build());\n\t\t\t\t\t//@formatter:on\n\t\t\t\t}\n\n\t\t\t\tmap.put(caretEncoding, map2);\n\t\t\t}\n\n\t\t\tparameterValue.put(syntax, map);\n\t\t}\n\t}\n\n\t/**\n\t * Validates a property name.\n\t * @param name the property name\n\t * @param syntax the syntax style to validate against\n\t * @param strict false to allow all characters as long as they don't break\n\t * the syntax, true for spec-compliant validation\n\t * @return true if the property name is valid, false if not\n\t */\n\tpublic static boolean validatePropertyName(String name, SyntaxStyle syntax, boolean strict) {\n\t\treturn allowedCharactersPropertyName(syntax, strict).check(name);\n\t}\n\n\t/**\n\t * Gets the list of allowed characters for property names.\n\t * @param syntax the syntax style\n\t * @param strict false for the non-strict list, true for the spec-compliant\n\t * list\n\t * @return the character list\n\t */\n\tpublic static AllowedCharacters allowedCharactersPropertyName(SyntaxStyle syntax, boolean strict) {\n\t\treturn propertyName.get(syntax).get(strict);\n\t}\n\n\t/**\n\t * Validates a group name.\n\t * @param group the group name\n\t * @param syntax the syntax style to validate against\n\t * @param strict false to allow all characters as long as they don't break\n\t * the syntax, true for spec-compliant validation\n\t * @return true if the group name is valid, false if not\n\t */\n\tpublic static boolean validateGroupName(String group, SyntaxStyle syntax, boolean strict) {\n\t\treturn allowedCharactersGroup(syntax, strict).check(group);\n\t}\n\n\t/**\n\t * Gets the list of allowed characters for group names.\n\t * @param syntax the syntax style\n\t * @param strict false for the non-strict list, true for the spec-compliant\n\t * list\n\t * @return the character list\n\t */\n\tpublic static AllowedCharacters allowedCharactersGroup(SyntaxStyle syntax, boolean strict) {\n\t\treturn group.get(syntax).get(strict);\n\t}\n\n\t/**\n\t * Validates a parameter name.\n\t * @param name the parameter name\n\t * @param syntax the syntax style to validate against\n\t * @param strict false to allow all characters as long as they don't break\n\t * the syntax, true for spec-compliant validation\n\t * @return true if the parameter name is valid, false if not\n\t */\n\tpublic static boolean validateParameterName(String name, SyntaxStyle syntax, boolean strict) {\n\t\treturn allowedCharactersParameterName(syntax, strict).check(name);\n\t}\n\n\t/**\n\t * Gets the list of allowed characters for parameter names.\n\t * @param syntax the syntax style\n\t * @param strict false for the non-strict list, true for the spec-compliant\n\t * list\n\t * @return the character list\n\t */\n\tpublic static AllowedCharacters allowedCharactersParameterName(SyntaxStyle syntax, boolean strict) {\n\t\treturn parameterName.get(syntax).get(strict);\n\t}\n\n\t/**\n\t * Validates a parameter value.\n\t * @param value the parameter value\n\t * @param syntax the syntax style to validate against\n\t * @param caretEncoding true if caret encoding is enabled, false if not\n\t * @param strict false to allow all characters as long as they don't break\n\t * the syntax, true for spec-compliant validation\n\t * @return true if the parameter value is valid, false if not\n\t */\n\tpublic static boolean validateParameterValue(String value, SyntaxStyle syntax, boolean caretEncoding, boolean strict) {\n\t\treturn allowedCharactersParameterValue(syntax, caretEncoding, strict).check(value);\n\t}\n\n\t/**\n\t * Gets the list of allowed characters for parameter values.\n\t * @param syntax the syntax style\n\t * @param caretEncoding true if caret encoding is enabled, false if not\n\t * @param strict false for the non-strict list, true for the spec-compliant\n\t * list\n\t * @return the character list\n\t */\n\tpublic static AllowedCharacters allowedCharactersParameterValue(SyntaxStyle syntax, boolean caretEncoding, boolean strict) {\n\t\treturn parameterValue.get(syntax).get(caretEncoding).get(strict);\n\t}\n\n\tprivate VObjectValidator() {\n\t\t//hide\n\t}\n}"
] | import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import com.github.mangstadt.vinnie.SyntaxStyle;
import com.github.mangstadt.vinnie.VObjectParameters;
import com.github.mangstadt.vinnie.VObjectProperty;
import com.github.mangstadt.vinnie.validate.AllowedCharacters;
import com.github.mangstadt.vinnie.validate.VObjectValidator;
import static com.github.mangstadt.vinnie.Utils.escapeNewlines;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.Writer; | /*
* MIT License
*
* Copyright (c) 2016 Michael Angstadt
*
* 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 com.github.mangstadt.vinnie.io;
/**
* <p>
* Writes data to a vobject data stream.
* </p>
* <p>
* <b>Example:</b>
* </p>
*
* <pre class="brush:java">
* Writer writer = ...
* VObjectWriter vobjectWriter = new VObjectWriter(writer, SyntaxStyle.NEW);
* vobjectWriter.writeBeginComponent("VCARD");
* vobjectWriter.writeVersion("4.0");
* vobjectWriter.writeProperty("FN", "John Doe");
* vobjectWriter.writeEndComponent("VCARD");
* vobjectWriter.close();
* </pre>
*
* <p>
* <b>Invalid characters</b>
* </p>
* <p>
* If property data contains any invalid characters, the {@code writeProperty}
* method throws an {@link IllegalArgumentException} and the property is not
* written. A character is considered to be invalid if it cannot be encoded or
* escaped, and would break the vobject syntax if written.
* </p>
* <p>
* The rules regarding which characters are considered invalid is fairly
* complex. Here are some general guidelines:
* </p>
* <ul>
* <li>Try to limit group names, property names, and parameter names to
* alphanumerics and hyphens.</li>
* <li>Avoid the use of newlines, double quotes, and colons inside of parameter
* values. They can be used in some contexts, but not others.</li>
* </ul>
*
* <p>
* <b>Newlines in property values</b>
* </p>
* <p>
* All newline characters ("\r" or "\n") within property values are
* automatically escaped.
* </p>
* <p>
* In old-style syntax, the property value will be encoded in quoted-printable
* encoding.
* </p>
*
* <pre class="brush:java">
* StringWriter sw = new StringWriter();
* VObjectWriter vobjectWriter = new VObjectWriter(sw, SyntaxStyle.OLD);
* vobjectWriter.writeProperty("NOTE", "one\r\ntwo");
* vobjectWriter.close();
*
* assertEquals("NOTE;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:one=0D=0Atwo\r\n", sw.toString());
* </pre>
*
* <p>
* In new-style syntax, the newline characters will be replaced with the "\n"
* escape sequence (Windows newline sequences are replaced with a single "\n"
* even though they consist of two characters).
* </p>
*
* <pre class="brush:java">
* StringWriter sw = new StringWriter();
* VObjectWriter vobjectWriter = new VObjectWriter(sw, SyntaxStyle.NEW);
* vobjectWriter.writeProperty("NOTE", "one\r\ntwo");
* vobjectWriter.close();
*
* assertEquals("NOTE:one\\ntwo\r\n", sw.toString());
* </pre>
*
* <p>
* <b>Quoted-printable Encoding</b>
* </p>
* <p>
* If a property has a parameter named ENCODING that has a value of
* QUOTED-PRINTABLE (case-insensitive), then the property's value will
* automatically be written in quoted-printable encoding.
* </p>
*
* <pre class="brush:java">
* StringWriter sw = new StringWriter();
* VObjectWriter vobjectWriter = new VObjectWriter(sw, ...);
*
* VObjectProperty note = new VObjectProperty("NOTE", "¡Hola, mundo!");
* note.getParameters().put("ENCODING", "QUOTED-PRINTABLE");
* vobjectWriter.writeProperty(note);
* vobjectWriter.close();
*
* assertEquals("NOTE;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:=C2=A1Hola, mundo!\r\n", sw.toString());
* </pre>
* <p>
* A nameless parameter may also be used for backwards compatibility with
* old-style syntax.
* </p>
*
* <pre class="brush:java">
* VObjectProperty note = new VObjectProperty("NOTE", "¡Hola, mundo!");
* note.getParameters().put(null, "QUOTED-PRINTABLE");
* vobjectWriter.writeProperty(note);
* </pre>
* <p>
* By default, the property value is encoded under the UTF-8 character set when
* encoded in quoted-printable encoding. This can be changed by specifying a
* CHARSET parameter. If the character set is not recognized by the local JVM,
* then UTF-8 will be used.
* </p>
*
* <pre class="brush:java">
* StringWriter sw = new StringWriter();
* VObjectWriter vobjectWriter = new VObjectWriter(sw, ...);
*
* VObjectProperty note = new VObjectProperty("NOTE", "¡Hola, mundo!");
* note.getParameters().put("ENCODING", "QUOTED-PRINTABLE");
* note.getParameters().put("CHARSET", "Windows-1252");
* vobjectWriter.writeProperty(note);
* vobjectWriter.close();
*
* assertEquals("NOTE;ENCODING=QUOTED-PRINTABLE;CHARSET=Windows-1252:=A1Hola, mundo!\r\n", sw.toString());
* </pre>
*
* <p>
* <b>Circumflex Accent Encoding</b>
* </p>
* <p>
* Newlines and double quote characters are not permitted inside of parameter
* values unless circumflex accent encoding is enabled. It is turned off by
* default.
* </p>
* <p>
* Note that this encoding mechanism is defined in a separate specification and
* may not be supported by the consumer of the vobject data. Also note that it
* can only be used with new-style syntax.
* </p>
*
* <pre class="brush:java">
* StringWriter sw = new StringWriter();
* VObjectWriter vobjectWriter = new VObjectWriter(sw, SyntaxStyle.NEW);
* vobjectWriter.setCaretEncodingEnabled(true);
*
* VObjectProperty note = new VObjectProperty("NOTE", "The truth is out there.");
* note.getParameters().put("X-AUTHOR", "Fox \"Spooky\" Mulder");
* vobjectWriter.writeProperty(note);
* vobjectWriter.close();
*
* assertEquals("NOTE;X-AUTHOR=Fox ^'Spooky^' Mulder:The truth is out there.\r\n", sw.toString());
* </pre>
*
* <p>
* <b>Line Folding</b>
* </p>
* <p>
* Lines longer than 75 characters are automatically folded, as per the
* vCard/iCalendar recommendation.
* </p>
*
* <pre class="brush:java">
* StringWriter sw = new StringWriter();
* VObjectWriter vobjectWriter = new VObjectWriter(sw, ...);
*
* vobjectWriter.writeProperty("NOTE", "Lorem ipsum dolor sit amet\, consectetur adipiscing elit. Vestibulum ultricies tempor orci ac dignissim.");
* vobjectWriter.close();
*
* assertEquals(
* "NOTE:Lorem ipsum dolor sit amet\\, consectetur adipiscing elit. Vestibulum u\r\n" +
* " ltricies tempor orci ac dignissim.\r\n"
* , sw.toString());
* </pre>
* <p>
* The line folding length can be adjusted to a length of your choosing. In
* addition, passing in a "null" line length will disable line folding.
* </p>
*
* <pre class="brush:java">
* StringWriter sw = new StringWriter();
* VObjectWriter vobjectWriter = new VObjectWriter(sw, ...);
* vobjectWriter.getFoldedLineWriter().setLineLength(null);
*
* vobjectWriter.writeProperty("NOTE", "Lorem ipsum dolor sit amet\, consectetur adipiscing elit. Vestibulum ultricies tempor orci ac dignissim.");
* vobjectWriter.close();
*
* assertEquals("NOTE:Lorem ipsum dolor sit amet\\, consectetur adipiscing elit. Vestibulum ultricies tempor orci ac dignissim.\r\n", sw.toString());
* </pre>
*
* <p>
* You may also specify what kind of folding whitespace to use. The default is a
* single space character, but this can be changed to any combination of tabs
* and spaces. Note that new-style syntax requires the folding whitespace to be
* EXACTLY ONE character long.
* </p>
*
* <pre class="brush:java">
* StringWriter sw = new StringWriter();
* VObjectWriter vobjectWriter = new VObjectWriter(sw, ...);
* vobjectWriter.getFoldedLineWriter().setIndent("\t");
*
* vobjectWriter.writeProperty("NOTE", "Lorem ipsum dolor sit amet\, consectetur adipiscing elit. Vestibulum ultricies tempor orci ac dignissim.");
* vobjectWriter.close();
*
* assertEquals(
* "NOTE:Lorem ipsum dolor sit amet\\, consectetur adipiscing elit. Vestibulum u\r\n" +
* "\tltricies tempor orci ac dignissim.\r\n"
* , sw.toString());
* </pre>
* @author Michael Angstadt
*/
public class VObjectWriter implements Closeable, Flushable {
private final FoldedLineWriter writer;
private boolean caretEncodingEnabled = false;
private SyntaxStyle syntaxStyle;
private final AllowedCharacters allowedPropertyNameChars;
private final AllowedCharacters allowedGroupChars;
private final AllowedCharacters allowedParameterNameChars;
private AllowedCharacters allowedParameterValueChars;
/**
* Creates a new vobject writer.
* @param writer the output stream
* @param syntaxStyle the syntax style to use
*/
public VObjectWriter(Writer writer, SyntaxStyle syntaxStyle) {
this.writer = new FoldedLineWriter(writer);
this.syntaxStyle = syntaxStyle;
| allowedGroupChars = VObjectValidator.allowedCharactersGroup(syntaxStyle, false); | 5 |
AussieGuy0/SDgen | src/main/java/au/com/anthonybruno/writer/WriterFactory.java | [
"public class CsvSettings extends FlatFileSettings {\n\n public static final char DEFAULT_DELIMITER = ',';\n\n private final char delimiter;\n\n public CsvSettings(boolean includeHeaders) {\n this(includeHeaders, DEFAULT_DELIMITER);\n }\n\n public CsvSettings(boolean includeHeaders, char delimiter) {\n super(includeHeaders);\n this.delimiter = delimiter;\n }\n\n public char getDelimiter() {\n return delimiter;\n }\n\n public static class Builder {\n private char delimiter = DEFAULT_DELIMITER;\n private boolean includeHeaders = true;\n\n public Builder setDelimiter(char delimiter) {\n this.delimiter = delimiter;\n return this;\n }\n\n public Builder setIncludeHeaders(boolean includeHeaders) {\n this.includeHeaders = includeHeaders;\n return this;\n }\n\n public CsvSettings build() {\n return new CsvSettings(includeHeaders, delimiter);\n }\n }\n\n}",
"public class FixedWidthSettings extends FlatFileSettings {\n\n private final List<FixedWidthField> fixedWidthFields;\n\n public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) {\n super(includeHeaders);\n this.fixedWidthFields = fields;\n }\n\n public List<FixedWidthField> getFixedWidthFields() {\n return fixedWidthFields;\n }\n}",
"public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> {\n\n public AbstractCsvWriter(Writer writer, CsvSettings settings) {\n super(writer, settings);\n }\n}",
"public class UnivocityCsvWriter extends AbstractCsvWriter {\n\n private final CsvWriter csvWriter;\n\n public UnivocityCsvWriter(Writer writer, CsvSettings settings) {\n super(writer, settings);\n CsvWriterSettings csvWriterSettings = new CsvWriterSettings();\n csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter());\n this.csvWriter = new CsvWriter(writer, csvWriterSettings);\n }\n\n @Override\n public void writeRow(List<String> row) {\n for (String value : row) {\n csvWriter.addValue(value);\n }\n csvWriter.writeValuesToRow();\n }\n\n @Override\n public void close() {\n csvWriter.close();\n }\n\n @Override\n public void writeRecord(Record record) {\n List<String> values = new ArrayList<>();\n record.forEach((value) -> {\n values.add(value.toString());\n });\n writeRow(values);\n }\n}",
"public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> {\n\n public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) {\n super(writer, settings);\n }\n\n}",
"public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter {\n\n private FixedWidthWriter fixedWidthWriter;\n\n\n public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) {\n super(writer, settings);\n FixedWidthFields fixedWidthFields = new FixedWidthFields();\n settings.getFixedWidthFields().forEach((field) -> {\n fixedWidthFields.addField(field.getLength());\n });\n FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields);\n this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings);\n }\n\n @Override\n public void writeRow(List<String> row) {\n fixedWidthWriter.writeRow(row);\n fixedWidthWriter.writeValuesToRow();\n }\n\n @Override\n public void writeRecord(Record record) {\n List<String> values = new ArrayList<>();\n record.forEach((value) -> {\n values.add(value.toString());\n });\n writeRow(values);\n }\n\n @Override\n public void close() {\n fixedWidthWriter.close();\n }\n}"
] | import au.com.anthonybruno.settings.CsvSettings;
import au.com.anthonybruno.settings.FixedWidthSettings;
import au.com.anthonybruno.writer.csv.AbstractCsvWriter;
import au.com.anthonybruno.writer.csv.UnivocityCsvWriter;
import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter;
import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter;
import java.io.Writer; | package au.com.anthonybruno.writer;
public class WriterFactory {
public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { | return new UnivocityCsvWriter(writer, csvSettings); | 3 |
jinahya/bit-io | src/main/java/com/github/jinahya/bit/io/AbstractBitOutput.java | [
"static int mask(final int size) {\n return MASKS[size - 1];\n}",
"static int requireValidSizeByte(final boolean unsigned, final int size) {\n if (size <= 0) {\n throw new IllegalArgumentException(\"size(\" + size + \") <= 0\");\n }\n if (size > Byte.SIZE) {\n throw new IllegalArgumentException(\"invalid size(\" + size + \") > \" + Byte.SIZE);\n }\n if (unsigned && size == Byte.SIZE) {\n throw new IllegalArgumentException(\"invalid size(\" + size + \") for unsigned byte\");\n }\n return size;\n}",
"static int requireValidSizeChar(final int size) {\n if (size <= 0) {\n throw new IllegalArgumentException(\"size(\" + size + \") <= 0\");\n }\n if (size > Character.SIZE) {\n throw new IllegalArgumentException(\"size(\" + size + \") > \" + Character.SIZE);\n }\n return size;\n}",
"static int requireValidSizeInt(final boolean unsigned, final int size) {\n if (size <= 0) {\n throw new IllegalArgumentException(\"size(\" + size + \") <= 0\");\n }\n if (size > Integer.SIZE) {\n throw new IllegalArgumentException(\"invalid size(\" + size + \") > \" + Integer.SIZE);\n }\n if (unsigned && size == Integer.SIZE) {\n throw new IllegalArgumentException(\"invalid size(\" + size + \") for unsigned integer\");\n }\n return size;\n}",
"static int requireValidSizeLong(final boolean unsigned, final int size) {\n if (size <= 0) {\n throw new IllegalArgumentException(\"size(\" + size + \") <= 0\");\n }\n if (size > Long.SIZE) {\n throw new IllegalArgumentException(\"invalid size(\" + size + \") > \" + Long.SIZE);\n }\n if (unsigned && size == Long.SIZE) {\n throw new IllegalArgumentException(\"invalid size(\" + size + \") for unsigned long\");\n }\n return size;\n}",
"static int requireValidSizeShort(final boolean unsigned, final int size) {\n if (size <= 0) {\n throw new IllegalArgumentException(\"size(\" + size + \") <= 0\");\n }\n if (size > Short.SIZE) {\n throw new IllegalArgumentException(\"invalid size(\" + size + \") > \" + Short.SIZE);\n }\n if (unsigned && size == Short.SIZE) {\n throw new IllegalArgumentException(\"invalid size(\" + size + \") for unsigned short\");\n }\n return size;\n}"
] | import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort; | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, 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.
* #L%
*/
/**
* An abstract class for implementing {@link BitInput} interface.
*
* @author Jin Kwon <jinahya_at_gmail.com>
* @see AbstractBitInput
* @see DefaultBitOutput
*/
public abstract class AbstractBitOutput implements BitOutput {
// -----------------------------------------------------------------------------------------------------------------
/**
* Creates a new instance.
*/
protected AbstractBitOutput() {
super();
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Writes given {@value java.lang.Byte#SIZE}-bit unsigned integer.
*
* @param value the {@value java.lang.Byte#SIZE}-bit unsigned integer to write.
* @throws IOException if an I/O error occurs.
*/
protected abstract void write(int value) throws IOException;
// -----------------------------------------------------------------------------------------------------------------
/**
* Writes an unsigned {@code int} value of specified bit size which is, in maximum, {@value java.lang.Byte#SIZE}.
*
* @param size the number of lower bits to write; between {@code 1} and {@value java.lang.Byte#SIZE}, both
* inclusive.
* @param value the value to write.
* @throws IOException if an I/O error occurs.
* @see #write(int)
*/
private void unsigned8(final int size, final int value) throws IOException {
final int required = size - available;
if (required > 0) {
unsigned8(available, value >> required);
unsigned8(required, value);
return;
}
octet <<= size;
octet |= value & mask(size);
available -= size;
if (available == 0) {
assert octet >= 0 && octet < 256;
write(octet);
count++;
octet = 0x00;
available = Byte.SIZE;
}
}
// --------------------------------------------------------------------------------------------------------- boolean
@Override
public void writeBoolean(final boolean value) throws IOException {
writeInt(true, 1, value ? 1 : 0);
}
// ------------------------------------------------------------------------------------------------------------ byte
@Override
public void writeByte(final boolean unsigned, final int size, final byte value) throws IOException { | writeInt(unsigned, requireValidSizeByte(unsigned, size), value); | 1 |
redferret/planet | src/worlds/planet/geosphere/GeoCell.java | [
"public class Vec2 {\n\n private float x, y;\n\n public Vec2() {\n this(0, 0);\n }\n\n public Vec2(Vec2 toCopy) {\n this(toCopy.x, toCopy.y);\n }\n\n public Vec2(float x, float y) {\n this.x = x;\n this.y = y;\n }\n\n public float getX() {\n return x;\n }\n\n public float getY() {\n return y;\n }\n \n public Vec2 copy() {\n return new Vec2(this);\n }\n \n public void add(Vec2 p) {\n this.x += p.x;\n this.y += p.y;\n }\n\n public void mul(Vec2 p) {\n this.x *= p.x;\n this.y *= p.y;\n }\n \n public void div(float n) {\n this.x /= n;\n this.y /= n;\n }\n\n public void normalize() {\n float mag = mag();\n if (mag != 0) {\n div(mag);\n }\n }\n \n public void set(Vec2 p) {\n this.x = p.x;\n this.y = p.y;\n }\n\n public void neg() {\n x = -x;\n y = -y;\n }\n\n public float mag() {\n return (float) Math.sqrt((x * x + y * y));\n }\n\n public Vec2 truncate() {\n return new Vec2((int) x, (int) y);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null || !(obj instanceof Vec2)) {\n return false;\n } else {\n Vec2 o = (Vec2) obj;\n return o.x == x && o.y == y;\n }\n }\n\n @Override\n public int hashCode() {\n int hash = 5;\n hash = 17 * hash + (int) this.x;\n hash = 17 * hash + (int) this.y;\n return hash;\n }\n\n @Override\n public String toString() {\n StringBuilder str = new StringBuilder();\n str.append(\"[\").append(x).append(\", \").append(y).append(\"]\");\n return str.toString();\n }\n\n public boolean isZero() {\n return mag() == 0;\n }\n\n public void zero() {\n this.set(new Vec2());\n }\n\n}",
"public class Util {\n\n public static Vector2f scalePositionForTerrain(float x, float y, int quadWidth) {\n return new Vector2f((x * 2) - quadWidth, (y * 2) - quadWidth);\n }\n \n /**\n * Selects all the positions that are around the position 'from'. This method\n * does not select resources or cells from the map but builds a list of\n * positions to use to select resources. The last element of this list if the\n * Vec2 from.\n *\n * @param from The center position\n * @param size Width of the surface\n * @return The calculated positions around the center point 'from'\n */\n public static Vec2[] getCellIndexesFrom(Vec2 from, int size) {\n int tx, ty, mx, my;\n int x = (int) from.getX(), y = (int) from.getY();\n int xl = DIR_X_INDEX.length;\n Vec2[] points = new Vec2[xl];\n int worldSize = size;\n for (int s = 0; s < xl; s++) {\n\n tx = x + DIR_X_INDEX[s];\n ty = y + DIR_Y_INDEX[s];\n\n // Check the boundaries\n mx = checkBounds(tx, worldSize);\n my = checkBounds(ty, worldSize);\n\n Vec2 p = new Vec2(mx, my);\n points[s] = p;\n }\n return points;\n }\n \n /**\n * To help create height maps, heat maps, etc, the method takes a list of\n * colors, the colors are then interpolated with each other evenly across the\n * returned sample array. Depending on the width, the number of color samples\n * returned should be greater than the number of colors given. The width\n * specifies the number of samples that will be returned.\n *\n * @param colors The list of colors\n * @param width The number of colors after interpolation\n * @return The samples array\n */\n public static float[][] constructSamples(Color[] colors, int width) {\n\n if (colors.length > width) {\n throw new IndexOutOfBoundsException(\"The width of the gradient is invalid\");\n }\n\n float[] dist = new float[colors.length];\n float distAmount = 1f / colors.length, totalDist = 0;\n\n for (int i = 0; i < colors.length; i++) {\n\n dist[i] = totalDist;\n totalDist += distAmount;\n\n }\n\n dist[colors.length - 1] = 1.0f;\n\n return constructGradient(colors, dist, width);\n\n }\n\n /**\n * In some cases you may not want an even distribution of each color given in\n * the colors array after interpolation. The distribution array must be the\n * same length as the colors array and add up to 1.0f For example, for three\n * colors <code>dist = {0.0f, 0.35f, 1.0f};</code>\n *\n * @param colors The list of colors\n * @param dist The list of distributions for each color\n * @param width The number of colors after interpolation\n * @return The samples array\n */\n public static float[][] constructGradient(Color[] colors, float[] dist, int width) {\n\n float[][] colorArray = new float[width][4];\n\n BufferedImage bufferImg = new BufferedImage(width, 1, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2d = bufferImg.createGraphics();\n\n Point2D start = new Point2D.Float(0, 0);\n Point2D end = new Point2D.Float(width, 0);\n\n LinearGradientPaint lgp = new LinearGradientPaint(start, end, dist, colors);\n\n g2d.setPaint(lgp);\n g2d.fillRect(0, 0, width, 1);\n g2d.dispose();\n\n int[][] buffer = new int[width][4];\n for (int x = 0, y = 0; x < width; x++) {\n bufferImg.getRaster().getPixel(x, y, buffer[x]);\n for (int a = 0; a < 4; a++) {\n colorArray[x][a] = buffer[x][a] / 255f;\n }\n }\n \n return colorArray;\n\n }\n\n /**\n * After interpolation the samples can be converted to an array of Colors.\n *\n * @param samples The list of samples\n * @return The list of colors given by the samples array.\n */\n public static Color[] constructColors(int[][] samples) {\n\n Color[] colors = new Color[samples.length];\n\n final int RED = 0, GREEN = 1, BLUE = 2, ALPHA = 3;\n\n for (int i = 0; i < colors.length; i++) {\n\n colors[i] = new Color(samples[i][RED], samples[i][GREEN],\n samples[i][BLUE], samples[i][ALPHA]);\n\n }\n\n return colors;\n\n }\n\n /**\n * Wraps the value tx if greater or equal to b, and if tx is less than 0, then\n * tx will equal tx - b, otherwise the tx value is just returned. b represents\n * the bounds of tx and tx is the test variable.\n *\n * @param tx The test value\n * @param b The bounds\n * @return The corrected tx value\n */\n public static int checkBounds(int tx, int b) {\n return (tx >= b) ? tx - b : (tx < 0) ? b + tx : tx;\n }\n\n public static float calcHeatRadiation(float temperature) {\n return 5.7e-8f * ((float) Math.pow(temperature, 3)) * PlanetCell.area;\n }\n \n public static float calcMass(float height, long base, float density) {\n return (height * base * density);\n }\n\n public static float calcHeight(float mass, long base, float density) {\n return mass / (base * density);\n }\n\n public static float changeMass(float massToChange, Layer from, Layer to) {\n return changeMass(massToChange, from.getDensity(), to.getDensity());\n }\n\n public static float changeMass(float massToChange, float fromDensity, float toDensity) {\n return (massToChange * fromDensity) / toDensity;\n }\n\n public static float calcDepth(Layer layer, float gravity, float maxPressure) {\n return calcDepth(layer.getDensity(), gravity, maxPressure);\n }\n\n public static float calcDepth(float density, float gravity, float maxPressure) {\n return (maxPressure / (gravity * density));\n }\n\n public static float calcPressure(float density, float gravity, float depth) {\n return depth * density * gravity;\n }\n\n public static float calcLimit(float x) {\n return 0.9f / (1 + (float) Math.exp(2 * x - 4)) + 0.1f;\n }\n\n public static float clamp(float heightDiff, float min, float max) {\n return (heightDiff < min) ? min : (heightDiff > max ? max : heightDiff);\n }\n\n public static float maxOf(float lessThan, float of, float then) {\n return of > lessThan ? of : then;\n }\n\n public static List<Vec2> fillPoints(Vec2 center, int radius) {\n List<Vec2> points = new ArrayList<>();\n List<Vec2> circleList;\n int x = (int) center.getX();\n int y = (int) center.getY();\n int wRadius = radius;\n\n while (wRadius > 0) {\n circleList = selectCirclePoints(wRadius, x, y);\n wRadius -= 1;\n points.addAll(circleList);\n }\n wRadius = radius;\n while (wRadius > 0) {\n circleList = selectCirclePoints(wRadius, x - 1, y);\n wRadius -= 1;\n points.addAll(circleList);\n }\n\n Stream<Vec2> distinctList = points.stream().distinct();\n\n List<Vec2> nPoints = new ArrayList<>();\n distinctList.forEach(point -> {\n nPoints.add(point);\n });\n\n return nPoints;\n }\n\n /**\n * Uses the \"Fast Bresenham Type Algorithm For Drawing Circles\" taken from \"A\n * Fast Bresenham Type Algorithm For Drawing Circles\" John Kennedy et. all.\n *\n * @param radius\n * @param cx\n * @param cy\n * @return\n */\n public static List<Vec2> selectCirclePoints(int radius, int cx, int cy) {\n int xChange = 1 - (2 * radius), yChange = 1;\n int radiusError = 0, x = radius, y = 0;\n List<Vec2> points = new ArrayList<>();\n\n while (x >= y) {\n plotCirclePoints(points, x, y, cx, cy);\n y++;\n radiusError += yChange;\n yChange += 2;\n if (((2 * radiusError) + xChange) > 0) {\n x--;\n radiusError += xChange;\n xChange += 2;\n }\n }\n\n return points;\n }\n\n /**\n * @param points\n * @param xy\n * @param cxcy\n */\n private static void plotCirclePoints(List<Vec2> points, int x, int y,\n int cx, int cy) {\n points.add(new Vec2(cx + x, cy + y));\n points.add(new Vec2(cx - x, cy + y));\n points.add(new Vec2(cx - x, cy - y));\n points.add(new Vec2(cx + x, cy - y));\n points.add(new Vec2(cx + y, cy + x));\n points.add(new Vec2(cx - y, cy + x));\n points.add(new Vec2(cx - y, cy - x));\n points.add(new Vec2(cx + y, cy - x));\n }\n\n public static <C extends Cell> List<C> getLargestCellsFrom(C central, List<C> cells, Comparator<C> cellComparator) {\n\n if (central == null) {\n throw new IllegalArgumentException(\"Central cell can't be null\");\n }\n List<C> largestCellsToCentral = new ArrayList<>();\n cells.forEach(cell -> {\n if (cellComparator.compare(cell, central) > 0) {\n largestCellsToCentral.add(cell);\n }\n });\n return largestCellsToCentral;\n }\n \n public static <C extends Cell> List<C> getLowestCellsFrom(C central, List<C> cells, Comparator<C> cellComparator) {\n\n if (central == null) {\n throw new IllegalArgumentException(\"Central cell can't be null\");\n }\n List<C> lowestCellsToCentral = new ArrayList<>();\n cells.forEach(cell -> {\n if (cellComparator.compare(cell, central) < 0) {\n lowestCellsToCentral.add(cell);\n }\n });\n return lowestCellsToCentral;\n }\n\n private Util() {\n }\n}",
"public abstract class Planet {\n\n protected TimeScale timescale;\n private static Planet current;\n private final PlanetSurface planetSurface;\n\n public static enum TimeScale {\n Geological, Evolutionary, Civilization, None\n }\n\n static {\n current = null;\n }\n\n /**\n * Constructs a new Planet.\n *\n * @param totalSize The number of cells of one side of the surface (width) + 1\n * @param cellLength The length of one side of a cell in meters.\n * @param surfaceThreadsDelay How fast does the planet thread(s) update\n * @param threadCount The number of threadReferences that work on the map\n */\n public Planet(int totalSize, int cellLength, int surfaceThreadsDelay, int threadCount) {\n Logger.getLogger(SurfaceMap.class.getName()).log(Level.INFO, \"New Planet\");\n current = this;\n PlanetCell.area = cellLength * cellLength;\n PlanetCell.length = cellLength;\n timescale = TimeScale.None;\n planetSurface = new PlanetSurface(totalSize, surfaceThreadsDelay, threadCount);\n }\n\n protected final void startThreads() {\n planetSurface.startThreads();\n }\n\n public final void play() {\n planetSurface.playThreads();\n }\n\n public final void pause() {\n planetSurface.pauseThreads();\n }\n\n public final void shutdown() {\n planetSurface.killAllThreads();\n }\n \n public PlanetSurface getSurface() {\n return planetSurface;\n }\n\n /**\n * References the most recent instantiated instance of this class.\n *\n * @return A reference to the current Planet\n */\n public final static Planet instance() {\n return current;\n }\n\n public boolean isTimeScale(TimeScale scale) {\n return scale == timescale;\n }\n\n public final TimeScale getTimeScale() {\n return timescale;\n }\n\n public void setTimescale(TimeScale timescale) {\n this.timescale = timescale;\n }\n \n}",
"public class PlanetCell extends GeoCell {\n\n public static int area, length;\n\n static {\n length = 1;\n area = 1;\n }\n\n public PlanetCell() {\n this(0, 0);\n }\n\n public PlanetCell(int x, int y) {\n super(x, y);\n }\n\n}",
"public class PlanetSurface extends Geosphere {\n\n public static boolean suppressMantelHeating;\n public static boolean suppressAtmosphere;\n\n static {\n suppressMantelHeating = false;\n suppressAtmosphere = false;\n }\n\n public PlanetSurface(int totalSize, int threadsDelay, int threadCount) {\n super(totalSize, threadsDelay, threadCount);\n\n }\n\n}",
"public final static Planet instance() {\n return current;\n}",
"public abstract class Surface extends SurfaceMap<PlanetCell> {\n\n /**\n * The number of years that pass for each step of erosion\n */\n public static long GEOUPDATE;\n private long geologicalTimeStamp;\n\n /**\n * The age of the planet in years\n */\n public static AtomicLong planetAge;\n \n /**\n * The number of years that pass for each update to the geosphere\n */\n public static long timeStep;\n\n public final static int HEIGHTMAP = 0;\n public final static int STRATAMAP = 1;\n public final static int LANDOCEAN = 2;\n\n private static final int DEFAULT_THREAD_DELAY = 50;\n\n private final MinMaxHeightFactory mhFactory;\n\n static {\n timeStep = 7125000;\n }\n\n /**\n * Constructs a new Surface with an empty map.\n *\n * @param totalSize The size of the surface\n * @param threadsDelay The amount of time to delay each frame in milliseconds.\n * @param threadCount The number of threads that will work on the map\n */\n public Surface(int totalSize, int threadsDelay, int threadCount) {\n super(totalSize, DEFAULT_THREAD_DELAY);\n setupThreads(threadCount, threadsDelay);\n setupDefaultMap(threadCount);\n mhFactory = new MinMaxHeightFactory(this);\n produceTasks(mhFactory);\n reset();\n }\n\n /**\n * Resets the surface to an empty map and resets the planet's age. This method\n * should be calling the <code>buildMap()</code> method.\n */\n @Override\n public final void reset() {\n planetAge = new AtomicLong(0);\n geologicalTimeStamp = 0;\n pauseThreads();\n buildMap();\n addTaskToThreads(new SetParentThreads());\n playThreads();\n }\n\n public long getPlanetAge() {\n return planetAge.get();\n }\n\n public void updatePlanetAge() {\n long curPlanetAge = planetAge.getAndAdd(timeStep);\n if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) {\n geologicalTimeStamp = curPlanetAge;\n }\n }\n\n @Override\n public PlanetCell generateCell(int x, int y) {\n return new PlanetCell(x, y);\n }\n\n public float getHighestHeight() {\n return mhFactory.getHighestHeight();\n }\n\n public float getLowestHeight() {\n return mhFactory.getLowestHeight();\n }\n\n}"
] | import java.awt.Color;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import engine.util.Vec2;
import java.util.Set;
import worlds.planet.Util;
import worlds.planet.Planet;
import worlds.planet.PlanetCell;
import worlds.planet.PlanetSurface;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ThreadLocalRandom;
import static worlds.planet.Planet.instance;
import static worlds.planet.Surface.*; | package worlds.planet.geosphere;
/**
* A GeoCell is a Cell representing land Geologically. The cell contains strata
* and specialized methods for adding and/or removing from the strata.
*
* @author Richard DeSilvey
*/
public class GeoCell extends Mantle {
/**
* The list of strata for this cell
*/
private Deque<Layer> strata;
/**
* Tracks the total thickness of the strata.
*/
private float totalStrataThickness;
/**
* The total height makes adding up each layer faster. Each time a layer
* is removed or it's thickness is altered the totalMass is updated. The units
* are in kilograms.
*/
private float totalMass;
/**
* The total volume is calculated each time layer is added or removed or
* updated and is used to determine the average density of this cell in cubic
* meters.
*/
private float totalVolume;
/**
* The amount of this cell that is currently submerged in the mantel.
*/
private float curAmountSubmerged;
private float crustTemperature;
/**
* A Point that is represented as the velocity for Plate Tectonics. When a
* plate collides with a sibling (Cell owned by the same plate) the collision
* is inelastic and will reduce it's velocity as well as moving a little
* bit of it's energy through the system.
*/
private Vec2 velocity;
public static float[][] heightMap;
public final static int MAX_HEIGHT_INDEX = 17;
/**
* The ratio for indexing onto the height map array, by taking a cell height
* and dividing it by this value will give the proper index to the height map.
*/
public static int heightIndexRatio = 17 / MAX_HEIGHT_INDEX;
static {
Color[] heightColors = {new Color(255, 255, 204), new Color(51, 153, 51),
new Color(157, 166, 175), new Color(255, 255, 255)};
| heightMap = Util.constructSamples(heightColors, MAX_HEIGHT_INDEX); | 1 |
coil-lighting/udder | udder/src/main/java/com/coillighting/udder/effect/BloomEffect.java | [
"public class BoundingCube {\n\n protected double minX = 0.0;\n protected double minY = 0.0;\n protected double minZ = 0.0;\n\n protected double maxX = 0.0;\n protected double maxY = 0.0;\n protected double maxZ = 0.0;\n\n protected double width = 0.0;\n protected double height = 0.0;\n protected double depth = 0.0;\n\n /** Create a 3D bounding box with the given location and dimensions. */\n public BoundingCube(double minX, double minY, double minZ,\n double width, double height, double depth)\n {\n this.minX = minX;\n this.minY = minY;\n this.minZ = minZ;\n\n this.width = width;\n this.height = height;\n this.depth = depth;\n\n this.maxX = width + minX;\n this.maxY = height + minY;\n this.maxZ = depth + minZ;\n }\n\n /** Create a 2D bounding box as a BoundingCube in the XY plane. */\n public BoundingCube(double minX, double minY,\n double width, double height)\n {\n this(minX, minY, 0.0, width, height, 0.0);\n }\n\n public final boolean isEmpty() {\n return width < 0.0 || height < 0.0 || depth < 0.0;\n }\n\n public final boolean contains(double x, double y, double z) {\n if(this.isEmpty()) {\n return false;\n } else {\n return x >= minX && x <= maxX\n && y >= minY && y <= maxY\n && z >= minZ && z <= maxZ;\n }\n }\n\n public final boolean contains(Point3D pt) {\n if(pt != null) {\n return this.contains(pt.getX(), pt.getY(), pt.getZ());\n } else {\n return false;\n }\n }\n\n public String toString() {\n return \"x:[\" + minX + \", \" + maxX + \"] y:[\" + minY + \", \" + maxY + \"] z:[\" + minZ + \", \" + maxZ + \"] w:\" + width + \" h:\" + height + \" d:\" + depth + \"w/h:\" + (width/height);\n }\n\n public final double getMinX() {\n return minX;\n }\n\n public final void setMinX(double minX) {\n this.minX = minX;\n }\n\n public final double getMinY() {\n return minY;\n }\n\n public final void setMinY(double minY) {\n this.minY = minY;\n }\n\n public final double getMinZ() {\n return minZ;\n }\n\n public final void setMinZ(double minZ) {\n this.minZ = minZ;\n }\n\n public final double getWidth() {\n return width;\n }\n\n public final void setWidth(double width) {\n this.width = width;\n }\n\n public final double getHeight() {\n return height;\n }\n\n public final void setHeight(double height) {\n this.height = height;\n }\n\n public final double getDepth() {\n return depth;\n }\n\n public final void setDepth(double depth) {\n this.depth = depth;\n }\n\n public final double getMaxX() {\n return minX + width;\n }\n\n public final double getMaxY() {\n return minY + height;\n }\n\n public final double getMaxZ() {\n return minZ + depth;\n }\n}",
"public class TriangularSequence extends Object {\n\n /** An implementation of triangular_number(float) that accepts ints. */\n public static final double triangularNumber(int n) throws ArithmeticException {\n return triangularNumber((double)n);\n }\n\n /** An implementation of triangular_number(float) that accepts longs. */\n public static final double triangularNumber(long n) throws ArithmeticException {\n return triangularNumber((double)n);\n }\n\n /** Return the nth triangular number.\n * Definition: http://en.wikipedia.org/wiki/Triangular_number\n */\n public static final double triangularNumber(double n) throws ArithmeticException {\n if(n < 0.0) {\n throw new ArithmeticException(\"Cannot return the nth triangular number for negative n.\");\n } else {\n double a = 2.0*n + 1.0;\n return (a*a - 1.0) / 8.0;\n }\n }\n\n /** Inverse of triangular_number(n). Given a triangular number x,\n * return n, such that the nth triangular number is x. Since values of\n * x that are not perfectly triangular will not have an integer n\n * value, but will fall between two integer n-offsets, we return a\n * double. The fractional portion indicates that x falls between two\n * triangular numbers.\n *\n * Beware: float point imprecision applies. This implementation is just\n * good enough for oscillate_triangular_root_color.\n */\n public static final double triangularRoot(double x) throws ArithmeticException {\n if(x < 0.0) {\n throw new ArithmeticException(\"Cannot take the triangular root of a negative number.\");\n } else {\n return (Math.sqrt(8.0*x + 1.0) - 1.0) / 2.0;\n }\n }\n\n /** Map the pixel at offset to a thread colors (where color cycle frequency\n * = len(palette)), given some scale multiplier (in space per thread).\n *\n * offset: In pixel space. This is the spatial distance of the pixel you\n * want to color. Must be positive. TODO: support negative offsets?\n *\n * scale: Distince in pixels allocated to the spatial range\n * corresponding to x in [1, frequency). Must be positive.\n * TODO: clarify this comment\n *\n * palette: Integer keys to some external collection of color elements.\n * A palette of length 1 will yield monotone results. Length 2 creates\n * a binary blinker. 3 is a three-way blinker, and so on.\n *\n * Impl schematic:\n * | dxnorm ||||||||||||||||||||||\n * x0------->x1\n * x0----------------------------->x2\n * n0 n1\n */\n public static final int oscillatingTriangularRootColor(double offset,\n double scale, int[] palette) throws ArithmeticException\n {\n double x1 = offset / scale;\n double n0 = (double)(int)triangularRoot(x1);\n double x0 = triangularNumber(n0);\n double n1 = n0 + 1.0;\n double x2 = triangularNumber(n1);\n double dxnorm = (x1 - x0) / (x2 - x0);\n\n double color_index = dxnorm * (double)palette.length;\n// double tmp_color_index = color_index; //TEMP\n\n // Because 3.0 * 0.333333333 is rounding down to 0.0, not up to 1.0...\n // In case color_index_float % 1 is ~= 0.999999999998, harmless otherwise.\n // Bump it up to the next color if it's very close in order to make up for\n // floating point imprecision:\n color_index += 0.00000001; // TODO improve this value's precision\n int palette_index = (int)color_index;\n if(palette_index >= palette.length) {\n palette_index = palette.length - 1;\n }\n// System.out.println(\"color_index \" + tmp_color_index + \"=> \" + color_index + \" pixd \" + palette_index + \" = dxnorm \" + dxnorm + \" palette.len \" + (double)palette.length); // TEMP\n return palette[palette_index];\n }\n\n public static final int[] triangularSequence(int length, int[] palette)\n throws ArithmeticException\n {\n return triangularSequence(length, (double)palette.length, palette);\n }\n\n public static final int[] triangularSequence(int length, double scale,\n int[] palette) throws ArithmeticException\n {\n int[] seq = new int[length];\n for(int i=0; i<length; i++) {\n seq[i] = oscillatingTriangularRootColor((double)i, scale, palette);\n }\n return seq;\n }\n\n public static void testTriangularSequence() {\n for(int x0=0; x0<3000; x0++) {\n double n = triangularRoot(x0);\n double x1 = triangularNumber(n);\n A.assertApproxEquals(x0, x1, 0.000000001);\n }\n\n try {\n triangularNumber(-0.1);\n throw new AssertionError(\"Negative triangular numbers should fail.\");\n } catch(ArithmeticException e) {}\n\n try {\n triangularNumber(-1.0);\n throw new AssertionError(\"Negative triangular numbers should fail.\");\n } catch(ArithmeticException e) {}\n\n try {\n triangularNumber(-2.0);\n throw new AssertionError(\"Negative triangular numbers should fail.\");\n } catch(ArithmeticException e) {}\n\n try {\n triangularNumber(-2);\n throw new AssertionError(\"Negative triangular numbers should fail.\");\n } catch(ArithmeticException e) {}\n\n try {\n triangularNumber(-4);\n throw new AssertionError(\"Negative triangular numbers should fail.\");\n } catch(ArithmeticException e) {}\n }\n\n public static void testTriangularRoot() {\n double tolerance = 0.00000000001; // floating point slop\n\n try {\n triangularRoot(-0.1);\n throw new AssertionError(\"Negative roots should fail.\");\n } catch(ArithmeticException e) {}\n\n try {\n triangularRoot(-1.0);\n throw new AssertionError(\"Negative roots should fail.\");\n } catch(ArithmeticException e) {}\n\n try {\n triangularRoot(-2.0);\n throw new AssertionError(\"Negative roots should fail.\");\n } catch(ArithmeticException e) {}\n\n try {\n triangularRoot(-2);\n throw new AssertionError(\"Negative roots should fail.\");\n } catch(ArithmeticException e) {}\n\n try {\n triangularRoot(-4);\n throw new AssertionError(\"Negative roots should fail.\");\n } catch(ArithmeticException e) {}\n\n A.assertEquals(triangularRoot(0.0), 0.0);\n A.assertEquals(triangularRoot(0), 0.0);\n\n A.assertApproxEquals(triangularRoot(0.5), 0.61803398875, tolerance);\n\n A.assertEquals(triangularRoot(1.0), 1.0);\n A.assertEquals(triangularRoot(1), 1.0);\n\n A.assertApproxEquals(triangularRoot(1.5), 1.30277563773, tolerance);\n\n A.assertApproxEquals(triangularRoot(2.0), 1.56155281281, tolerance);\n A.assertApproxEquals(triangularRoot(2), 1.56155281281, tolerance);\n\n A.assertEquals(triangularRoot(3.0), 2.0);\n A.assertEquals(triangularRoot(3), 2.0);\n\n A.assertEquals(triangularRoot(6.0), 3.0);\n A.assertEquals(triangularRoot(6), 3.0);\n\n A.assertEquals(triangularRoot(10.0), 4.0);\n A.assertEquals(triangularRoot(10), 4.0);\n\n A.assertEquals(triangularRoot(15.0), 5.0);\n A.assertEquals(triangularRoot(15), 5.0);\n\n A.assertApproxEquals(triangularRoot(18.0), 5.5207972894, tolerance);\n A.assertApproxEquals(triangularRoot(18), 5.5207972894, tolerance);\n\n A.assertEquals(triangularRoot(21.0), 6.0);\n A.assertEquals(triangularRoot(21), 6.0);\n\n // verify inverse operations\n int[] xs = {\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,\n };\n double[] ns = {\n 0.0, 1.0, 3.0, 6.0, 10.0, 15.0, 21.0, 28.0, 36.0, 45.0,\n 55.0, 66.0, 78.0, 91.0, 105.0, 120.0, 136.0, 153.0,\n };\n for(int i=0; i<xs.length; i++) {\n int x = xs[i];\n double n = triangularNumber(x);\n A.assertApproxEquals(n, ns[i], tolerance);\n A.assertApproxEquals(triangularRoot(n), (double)x, tolerance);\n }\n }\n\n public static void testOscillatingTriangularRootColor() {\n int[] seq = null;\n\n int[] palette1 = {0,};\n // print ''.join(oscillate_triangular_root_color(x, 1.0, palette1).ljust(6) for x in xs)\n seq = triangularSequence(18, palette1);\n A.assertSeqEquivalent(seq, \"aaaaaaaaaaaaaaaaaa\");\n\n int[] palette2 = {0, 1,};\n seq = triangularSequence(42, palette2);\n A.assertSeqEquivalent(seq, \"abaabbaaabbbaaaabbbbaaaaabbbbbaaaaaabbbbbb\");\n\n int[] palette3 = {0, 1, 2,};\n seq = triangularSequence(63, palette3);\n A.assertSeqEquivalent(seq, \"abcaabbccaaabbbcccaaaabbbbccccaaaaabbbbbcccccaaaaaabbbbbbcccccc\");\n\n int[] palette4 = {0, 1, 2, 3,};\n seq = triangularSequence(84, palette4);\n A.assertSeqEquivalent(seq, \"abcdaabbccddaaabbbcccdddaaaabbbbccccddddaaaaabbbbbcccccdddddaaaaaabbbbbbccccccdddddd\");\n\n // scale > len(palette) by factor of 2 - Verify every symbol appears 2x.\n seq = triangularSequence(84*2, 8.0, palette4);\n A.assertSeqEquivalent(seq, \"aabbccddaaaabbbbccccddddaaaaaabbbbbbccccccddddddaaaaaaaabbbbbbbbccccccccddddddddaaaaaaaaaabbbbbbbbbbccccccccccddddddddddaaaaaaaaaaaabbbbbbbbbbbbccccccccccccdddddddddddd\");\n\n // scale < len(palette) by half - Verify every 2nd b and d get skipped.\n seq = triangularSequence(84/2, 2.0, palette4);\n A.assertSeqEquivalent(seq, \"acabcdaabccdaabbccddaaabbcccddaaabbbcccddd\");\n\n // scale == len(palette) with a longer len - Check both variants.\n int[] palette5 = {0, 1, 2, 3, 4};\n seq = triangularSequence(105, 5.0, palette5);\n String expected = \"abcdeaabbccddeeaaabbbcccdddeeeaaaabbbbccccddddeeeeaaaaabbbbbcccccdddddeeeeeaaaaaabbbbbbccccccddddddeeeeee\";\n A.assertSeqEquivalent(seq, expected);\n seq = triangularSequence(105, palette5);\n A.assertSeqEquivalent(seq, expected);\n\n A.assertEquals(oscillatingTriangularRootColor(21.0, 3.0, palette3), 0);\n A.assertEquals(oscillatingTriangularRootColor(22.0, 3.0, palette3), 1);\n A.assertEquals(oscillatingTriangularRootColor(23.0, 3.0, palette3), 1);\n }\n\n public static void testTest() {\n A.assertEquals(0.0, 0.0);\n A.assertEquals(-1.0, -1.0);\n A.assertEquals(1.5, 1.5);\n\n try {\n A.assertEquals(1.0, 2.0);\n throw new RuntimeException(\"Failed to raise assertion where 1.0 != 2.0.\");\n } catch(AssertionError e) {}\n\n A.assertEquals(\"abc\", \"abc\");\n A.assertEquals(null, null);\n A.assertEquals(\"\", \"\");\n\n try {\n A.assertEquals(\"ab\", \"cde\");\n throw new RuntimeException(\"Failed to raise assertion where ab != cde.\");\n } catch(AssertionError e) {}\n\n A.assertApproxEquals(1.0, 1.0, 0.0);\n A.assertApproxEquals(-1.0, -2.0, 2.0);\n A.assertApproxEquals(1.000001, 1.000002, 0.0000011);\n\n try {\n A.assertApproxEquals(2.0, 2.5, 0.4999);\n throw new RuntimeException(\"Failed to raise assertion where 2.0 !~= 2.5.\");\n } catch(AssertionError e) {}\n\n A.assertNaN(Double.NaN);\n A.assertNaN(Math.sqrt(-1.0));\n A.assertNaN(Math.sqrt(-2.3));\n A.assertEquals(123.0/0.0, Double.POSITIVE_INFINITY);\n A.assertEquals(-124.0/0.0, Double.NEGATIVE_INFINITY);\n\n A.assertSeqEquivalent(null, null);\n int[] empty = {};\n A.assertSeqEquivalent(empty, \"\");\n\n int[] single0 = {0,};\n A.assertSeqEquivalent(single0, \"a\");\n int[] single1 = {1,};\n A.assertSeqEquivalent(single1, \"b\");\n int[] single2 = {2,};\n A.assertSeqEquivalent(single2, \"c\");\n\n int[] double0 = {0,1};\n A.assertSeqEquivalent(double0, \"ab\");\n int[] double1 = {1,2};\n A.assertSeqEquivalent(double1, \"bc\");\n int[] double2 = {2,3};\n A.assertSeqEquivalent(double2, \"cd\");\n\n int[] mult6 = {0,1,2,3,4,5};\n A.assertSeqEquivalent(mult6, \"abcdef\");\n int[] mult7 = {2,2,2,2,0,0,0};\n A.assertSeqEquivalent(mult7, \"ccccaaa\");\n int[] mult8 = {1,2,2,3,1,4,5,0};\n A.assertSeqEquivalent(mult8, \"bccdbefa\");\n\n try {\n A.assertSeqEquivalent(single0, \"b\");\n throw new RuntimeException(\"Failed to raise assertion where 0 !=> b.\");\n } catch(AssertionError e) {}\n\n try {\n A.assertSeqEquivalent(single1, \"a\");\n throw new RuntimeException(\"Failed to raise assertion where 1 !=> a.\");\n } catch(AssertionError e) {}\n\n try {\n A.assertSeqEquivalent(double1, \"aa\");\n throw new RuntimeException(\"Failed to raise assertion where 01 !=> aa.\");\n } catch(AssertionError e) {}\n\n try {\n A.assertSeqEquivalent(mult6, \"abcde\");\n throw new RuntimeException(\"Failed to raise assertion where 012345 !=> abcde.\");\n } catch(AssertionError e) {}\n\n try {\n A.assertSeqEquivalent(mult6, \"abcdefg\");\n throw new RuntimeException(\"Failed to raise assertion where 012345 !=> abcdefg.\");\n } catch(AssertionError e) {}\n\n try {\n A.assertSeqEquivalent(mult6, \"\");\n throw new RuntimeException(\"Failed to raise assertion where 012345 !=> ''.\");\n } catch(AssertionError e) {}\n\n try {\n A.assertSeqEquivalent(mult8, \"ccdbefab\");\n throw new RuntimeException(\"Failed to raise assertion where 12231450 !=> ccdbefab.\");\n } catch(AssertionError e) {}\n }\n\n public static void main(String[] args) {\n System.out.println(\"testTest\");\n testTest();\n System.out.println(\"testTriangularRoot\");\n testTriangularRoot();\n System.out.println(\"testTriangularSequence\");\n testTriangularSequence();\n System.out.println(\"testOscillatingTriangularRootColor\");\n testOscillatingTriangularRootColor();\n }\n}",
"public class TimePoint {\n\n /** The nomimally \"real\" time at which this frame was initialized. Although\n * this time is required by some animations which need to synchronize their\n * effects with the outside world -- a dusk/dawn almanac scheduler, for\n * instance -- you should ordinarily never refer to the realTimeMillis in\n * your animation functions. Instead, use TimePoint.sceneTimeMillis in\n * order to give the user the opportunity to apply timebase distortions.\n * Initialized with System.currentTimeMillis().\n *\n * Not to be confused with TimePoint.sceneTimeMillis.\n */\n private long realTimeMillis = 0;\n\n /** The reference time for all elements of the current scene. By using this\n * offset as the current time for timebase calculations in your animators,\n * you allow the user to apply timebase distortions, a powerful creative\n * tool. For ideas of what you might do with timebase distortions, sit\n * down with an old Invisibl Skratch Piklz, then imagine stretching and\n * reversing your graphical animations as if they were audio, at high rez.\n * This time is compatible with, but not necessarily identical to, the\n * \"real\" millisecond time offset returned by System.currentTimeMillis().\n * When a show is playing back in nominally real time, with no timebase\n * transformations or distortions, then this value will by convention\n * equal TimePoint.realTimeMillis minus the realTimeMillis when the show\n * started, and then this value will count up monotonically thereafter.\n * However, there is no guarantee that the user will choose to follow such\n * a straightforward path through time.\n *\n * Not to be confused with TimePoint.realTimeMillis.\n */\n private long sceneTimeMillis = 0;\n\n /** An integer counting the current frame. Normally a show begins at frame\n * 0 and proceeds to count up, +1 per frame, but there is no guarantee that\n * a user will configure a show to count incrementally. There is even no\n * guarantee that frameIndex will monotonically increase. However, a normal\n * show which doesn't replay its own history will by convention simply\n * start from 0 and monotonically increment +1 per animation loop.\n */\n private long frameIndex = 0;\n\n public TimePoint(long realTimeMillis, long sceneTimeMillis, long frameIndex) {\n this.realTimeMillis = realTimeMillis;\n this.sceneTimeMillis = sceneTimeMillis;\n this.frameIndex = frameIndex;\n }\n\n /** Copy constructor. */\n public TimePoint(TimePoint timePoint) {\n this.realTimeMillis = timePoint.realTimeMillis;\n this.sceneTimeMillis = timePoint.sceneTimeMillis;\n this.frameIndex = timePoint.frameIndex;\n }\n\n /** Initialize a TimePoint with the current system time as its nominally\n * \"real\" time offset. Start counting the scene time from 0 and frameIndex\n * at 0.\n */\n public TimePoint() {\n this.realTimeMillis = System.currentTimeMillis();\n this.sceneTimeMillis = 0;\n this.frameIndex = 0;\n }\n\n /** Return a new immutable TimePoint, incrementing frameIndex and updating\n * realTimeMillis and sceneTimeMillis on the assumption that the show is\n * taking a straightforward and undistorted path through time.\n */\n public TimePoint next() {\n long realTime = System.currentTimeMillis();\n long sceneTimeOffsetMillis = this.realTimeMillis - this.sceneTimeMillis;\n return new TimePoint(\n realTime,\n realTime - sceneTimeOffsetMillis,\n 1 + this.frameIndex);\n }\n\n public long realTimeMillis() {\n return this.realTimeMillis;\n }\n\n public long sceneTimeMillis() {\n return this.sceneTimeMillis;\n }\n\n public long getFrameIndex() {\n return this.frameIndex;\n }\n\n public String toString() {\n return \"\" + this.sceneTimeMillis + \"ms [#\" + this.frameIndex + ']';\n }\n\n}",
"public class Device extends Object {\n\n /** This Device's address in some arbitrary address space. For the dairy,\n * this address is in the space of a single OPC channel.\n *\n * FUTURE Multiple channels/universes.\n *\n * Not public because no effects should be computed on the basis of a\n * Device's address.\n */\n protected int addr = 0;\n\n /** A dirt simple grouping mechanism. Each Device belongs to exactly one\n * group (for now). For the Dairy installation, this will indicate gate\n * 0 or gate 1, in case an Animator cares which group the Device is in.\n *\n * Public because device group computations happen in the hottest inner loop.\n */\n public int group=0;\n\n /** Position in model space. Public because device positional\n * computations happen in the hottest inner loop.\n */\n public double x = 0.0;\n public double y = 0.0;\n public double z = 0.0;\n\n public Device(int addr, int group, double x, double y, double z) {\n if(addr < 0) {\n throw new IllegalArgumentException(\"Invalid Device address: \" + addr);\n } else if(group < 0) {\n throw new IllegalArgumentException(\"Negative group index: \" + addr);\n }\n this.addr = addr;\n this.group = group;\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n public String toString() {\n return \"Device @\"+addr+\" [\"+group+\"] (\"+x+\",\"+y+\",\"+z+\")\";\n }\n\n public int getAddr() {\n return this.addr;\n }\n\n public int getGroup() {\n return this.group;\n }\n\n // TODO refactor x, y and z as a double[] for consistency with other classes? or refactor as a Point3D (see below). We should standardize here.\n public double[] getPoint() {\n return new double[]{x, y, z};\n }\n\n public Point3D getPoint3D() {\n return new Point3D(x, y, z);\n }\n\n /** Return the 3D bounding box for the given devices. */\n public static BoundingCube getDeviceBoundingCube(Device[] devices) {\n if(devices==null) {\n return null;\n } else {\n // FIXME: determine the real min and max values that will compare properly.\n // A seed value of Double.MAX_VALUE did not work with all comparisons here. WTF?\n // For now you must place your devices within this cube, sorry:\n final double MAX_VALUE = 999999999.0;\n final double MIN_VALUE = -999999999.0;\n\n double minx=MAX_VALUE;\n double maxx=MIN_VALUE;\n double miny=MAX_VALUE;\n double maxy=MIN_VALUE;\n double minz=MAX_VALUE;\n double maxz=MIN_VALUE;\n\n for(Device d: devices) {\n double x = d.x;\n double y = d.y;\n double z = d.z;\n if(x < minx) minx = x;\n if(x > maxx) maxx = x;\n if(y < miny) miny = y;\n if(y > maxy) maxy = y;\n if(z < minz) minz = z;\n if(z > maxz) maxz = z;\n }\n return new BoundingCube(minx, miny, minz,\n maxx-minx, maxy-miny, maxz-minz);\n }\n }\n}",
"public class Pixel {\n\n // FIXME I think the json mapper is not using the standard constructor for these!\n /** These are public for fast, direct access.*/\n public float r=0.0f;\n public float g=0.0f;\n public float b=0.0f;\n\n public static Pixel black() {\n return new Pixel(0.0f, 0.0f, 0.0f);\n }\n\n public static Pixel white() {\n return new Pixel(1.0f, 1.0f, 1.0f);\n }\n\n public Pixel() {}\n\n public Pixel(float r, float g, float b) {\n this.setColor(r, g, b);\n }\n\n public Pixel(Pixel pixel) {\n this.setColor(pixel.r, pixel.g, pixel.b);\n }\n\n public final void setColor(float r, float g, float b) {\n this.r = r;\n this.g = g;\n this.b = b;\n }\n\n public final void scale(float scale) {\n this.r *= scale;\n this.g *= scale;\n this.b *= scale;\n }\n\n public final void setColor(Pixel pixel) {\n if(pixel == null) {\n throw new NullPointerException(\"A null pixel has no color.\");\n } else {\n this.setColor(pixel.r, pixel.g, pixel.b);\n }\n }\n\n /** If you don't know what blendOp to use, just use MaxBlendOp until you\n * have time to experiment with other options.\n *\n * FUTURE A variant that takes an RGB(A) BlendMode (a mode might have per-channel blendops)\n */\n public final void blendWith(Pixel foreground, float level, BlendOp blendOp) {\n if(blendOp == null) {\n throw new NullPointerException(\"BlendOp is required.\");\n } else if(foreground != null) {\n if(level > 0.0) {\n float rr = blendOp.blend(this.r, foreground.r);\n float gg = blendOp.blend(this.g, foreground.g);\n float bb = blendOp.blend(this.b, foreground.b);\n if(level < 1.0) {\n // If level isn't 100%, merge the background with the\n // blended color according the balance prescribed by level.\n final float blendedScale = Pixel.clipChannel(level);\n final float bgScale = 1.0f - blendedScale;\n\n rr = blendedScale * rr + bgScale * this.r;\n gg = blendedScale * gg + bgScale * this.g;\n bb = blendedScale * bb + bgScale * this.b;\n }\n this.r = rr;\n this.g = gg;\n this.b = bb;\n }\n }\n }\n\n /** Compare this Pixel to another by value. */\n public final boolean equals(Pixel pixel) {\n return pixel != null && pixel.r == this.r && pixel.g == this.g\n && pixel.b == this.b;\n }\n\n /** Clip each component to the range 0.0..1.0, inclusive. */\n public final void clip() {\n this.r = Pixel.clipChannel(this.r);\n this.g = Pixel.clipChannel(this.g);\n this.b = Pixel.clipChannel(this.b);\n }\n\n private static final float clipChannel(float value) {\n if(value <= 0.0f) {\n return 0.0f;\n } else if(value >= 1.0f) {\n return 1.0f;\n } else {\n return value;\n }\n }\n\n public String toString() {\n return \"Pixel(\" + r + \", \" + g + \", \" + b + \")\";\n }\n\n /** Some loss of precision is inevitable. Include alpha. */\n public String toHexRGBA() {\n return String.format(\"%08X\", this.toRGBA() & 0xFFFFFFFF);\n }\n\n /** Some loss of precision is inevitable. Skip alpha. */\n public String toHexRGB() {\n return String.format(\"%06X\", this.toRGB() & 0xFFFFFF);\n }\n\n /** Return an int approximation of this pixel value, encoded 0x00RRGGBB.\n * Skip alpha. If you interpret this pixel as ARGB, alpha will read as 0.\n */\n public final int toRGB() {\n float conv = 255.99f;\n int rr = (int)(this.r * conv);\n int gg = (int)(this.g * conv);\n int bb = (int)(this.b * conv);\n return 0x00000000 | (rr << 16) | (gg << 8) | bb;\n }\n\n /** Return an int approximation of this pixel value, encoded 0xRRGGBBAA.\n * Set alpha to 100% (255).\n */\n public final int toRGBA() {\n int aa = 0xFF; // placeholder\n return (this.toRGB() << 8) | aa;\n }\n\n /** Return an int approximation of this pixel value, encoded 0xAARRGGBB.\n * Set alpha to 100% (255).\n */\n public final int toARGB() {\n int aa = 0xFF; // placeholder\n return this.toRGB() | (aa << 24);\n }\n\n /** Ignore alpha for now. (FUTURE) */\n public final void setRGBAColor(int rgba) {\n this.setRGBColor(rgba >> 8);\n }\n\n /** Also works with argb, since alpha is ignored. */\n public final void setRGBColor(int rgb) {\n float conv = 255.0f;\n int rr = (rgb >> 16) & 0xFF;\n int gg = (rgb >> 8) & 0xFF;\n int bb = rgb & 0xFF;\n this.r = (float)rr / conv;\n this.g = (float)gg / conv;\n this.b = (float)bb / conv;\n }\n\n /** Ignore alpha for now (see above). */\n public static Pixel fromRGBA(int rgba) {\n return Pixel.fromRGB(rgba >> 8);\n }\n\n /** Also works for ARGB, since alpha is ignored. */\n public static Pixel fromRGB(int rgb) {\n float conv = 255.0f;\n int rr = (rgb >> 16) & 0xFF;\n int gg = (rgb >> 8) & 0xFF;\n int bb = rgb & 0xFF;\n return new Pixel(\n (float)rr / conv,\n (float)gg / conv,\n (float)bb / conv);\n }\n\n public final void setBlack() {\n this.setColor(0.0f, 0.0f, 0.0f);\n }\n\n public final void setWhite() {\n this.setColor(1.0f, 1.0f, 1.0f);\n }\n\n public final void setRed() {\n this.setColor(1.0f, 0.0f, 0.0f);\n }\n\n public final void setGreen() {\n this.setColor(0.0f, 1.0f, 0.0f);\n }\n\n public final void setBlue() {\n this.setColor(0.0f, 0.0f, 1.0f);\n }\n\n}"
] | import com.coillighting.udder.geometry.BoundingCube;
import com.coillighting.udder.geometry.TriangularSequence;
import com.coillighting.udder.mix.TimePoint;
import com.coillighting.udder.model.Device;
import com.coillighting.udder.model.Pixel;
import static com.coillighting.udder.util.LogUtil.log; | package com.coillighting.udder.effect;
/**
* A multicolor Blooming Leaf that can vary the discrete threadcount in its
* pattern. Easier to see than to explain this traditional weave.
*
* TODO Document this separately. It's a good example of what Udder was for.
*/
public class BloomEffect extends EffectBase {
/** Checkerboard (traditional for Blooming Leaf weaves). */
public static final int DEFAULT_PALETTE_SIZE = 2;
protected int[] repertoire = BloomTiling.REPERTOIRES[DEFAULT_PALETTE_SIZE];
protected Pixel[] palette = {Pixel.white(), Pixel.black()};
protected int[][] tiling = BloomTiling.TILINGS_2D[repertoire.length];
// FUTURE parameterize scale modulation
// scale: device space units per thread
protected double scale = 1.0;
protected double scaleIncrement = 0.05;
/** Reflect the effect down the middle. */
protected boolean enableBilateralSym = true;
/** Reflect the reflection. (Do nothing if enableBilateralSym is false.)
* Traditional for Blooming Leaves.
*/
protected boolean enableNestedBilateralSym = true;
protected BoundingCube deviceBounds = null;
protected boolean enableX = true;
protected double devMinX = 0.0;
protected double devWidth = 0.0;
protected double xCenterOffset = 0.0;
protected double xQuarterOffset = 0.0;
protected boolean enableY = true;
protected double devMinY = 0.0;
protected double devHeight = 0.0;
protected double yCenterOffset = 0.0;
protected double yQuarterOffset = 0.0;
// Enabling Z+reflection at the Dairy, which consists of two parallel planes,
// is visually identical to rendering in XY 2D as long as this effect is
// not rotated in space (which it is not). So we'll optimize by skipping
// the Z axis for now.
//
// FUTURE: Enable the Z axis.
// FUTURE: Make a volumetric demo with a legible Z axis, Cubatron-style.
// protected double devMinZ = 0.0;
// protected double devDepth = 0.0;
// protected double zCenterOffset = 0.0;
// protected double zQuarterOffset = 0.0;
public Class getStateClass() {
return BloomEffectState.class;
}
public Object getState() {
return new BloomEffectState(this.copyPalette(), enableBilateralSym,
enableNestedBilateralSym, enableX, enableY);
}
public Pixel[] copyPalette() {
Pixel[] p = null;
if(palette != null) {
p = new Pixel[palette.length];
for(int i = 0; i < palette.length; i++) {
p[i] = new Pixel(palette[i]);
}
}
return p;
}
public void setState(Object state) throws ClassCastException {
BloomEffectState command = (BloomEffectState) state;
Pixel[] p = command.getPalette();
// Deep copy the given palette, filling in missing items with black.
// Ignore extra colors.
if(p != null && p.length > 0) {
int size = p.length;
int max = BloomTiling.REPERTOIRES.length + 1;
if(size > max) {
size = max;
}
repertoire = BloomTiling.REPERTOIRES[size];
tiling = BloomTiling.TILINGS_2D[repertoire.length];
palette = new Pixel[size];
for(int i=0; i<size; i++) {
Pixel color = p[i];
if(color == null) {
color = Pixel.black();
} else {
color = new Pixel(color);
}
palette[i] = color;
}
}
Boolean bilateral = command.getEnableBilateralSym();
if(bilateral != null) {
enableBilateralSym = bilateral;
}
Boolean nested = command.getEnableNestedBilateralSym();
if(nested != null) {
enableNestedBilateralSym = nested;
}
Boolean x = command.getEnableX();
if(x != null) {
enableX = x;
}
Boolean y = command.getEnableY();
if(y != null) {
enableY = y;
}
}
public void patchDevices(Device[] devices) {
super.patchDevices(devices);
deviceBounds = Device.getDeviceBoundingCube(devices);
devMinX = deviceBounds.getMinX();
devMinY = deviceBounds.getMinY();
devWidth = deviceBounds.getWidth();
devHeight = deviceBounds.getHeight();
xCenterOffset = devWidth * 0.5;
xQuarterOffset = devWidth * 0.25;
yCenterOffset = devHeight * 0.5;
yQuarterOffset = devHeight * 0.25;
// devMinZ = deviceBounds.getMinZ();
// devDepth = deviceBounds.getDepth();
// zCenterOffset = devDepth * 0.5;
// zQuarterOffset = devDepth * 0.25;
}
public void animate(TimePoint timePoint) {
Device dev = null;
double[] xyz = null;
double xoffset = 0.0;
double yoffset = 0.0;
// x and y palette index
int px = 0;
int py = 0;
for (int i = 0; i < devices.length; i++) {
dev = devices[i];
xyz = dev.getPoint();
// Symmetry is implemented as a transformation of each coordinate.
if(enableX) {
xoffset = xyz[0] - devMinX;
if(enableBilateralSym) {
if(xoffset > xCenterOffset) {
xoffset = devWidth - xoffset;
}
if(enableNestedBilateralSym && xoffset > xQuarterOffset) {
xoffset = xCenterOffset - xoffset;
}
} | px = TriangularSequence.oscillatingTriangularRootColor(xoffset, scale, repertoire); | 1 |
nikfoundas/etcd-viewer | src/main/java/org/github/etcd/service/impl/ClusterManagerImpl.java | [
"public enum ApiVersion {\n V2, V3\n}",
"public interface ClusterManager {\n\n boolean exists(String name);\n EtcdCluster getCluster(String name);\n\n EtcdCluster addCluster(String name, String etcdPeerAddress, ApiVersion apiVersion);\n void removeCluster(String name);\n\n List<EtcdCluster> getClusters();\n\n List<String> getClusterNames();\n\n void refreshCluster(String name);\n\n}",
"public class EtcdCluster {\n\n private static final long REFRESH_EXPIRATION_MILLIS = 1L * 60L * 1000L; // 10 minutes\n\n private String name;\n private List<EtcdMember> members;\n\n private boolean refreshed = false;\n private boolean authEnabled;\n private String address;\n private ApiVersion apiVersion;\n\n private Date lastRefreshTime;\n\n public EtcdCluster() {\n }\n public EtcdCluster(String name, String address, ApiVersion apiVersion) {\n this.name = name;\n this.address = address;\n this.apiVersion = apiVersion;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public List<EtcdMember> getMembers() {\n return members;\n }\n public void setMembers(List<EtcdMember> members) {\n this.members = members;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n public boolean isRefreshed() {\n return refreshed;\n }\n public void setRefreshed(boolean refreshed) {\n this.refreshed = refreshed;\n }\n public Date getLastRefreshTime() {\n return lastRefreshTime;\n }\n public void setLastRefreshTime(Date lastRefreshTime) {\n this.lastRefreshTime = lastRefreshTime;\n }\n public boolean isAuthEnabled() {\n return authEnabled;\n }\n public void setAuthEnabled(boolean authEnabled) {\n this.authEnabled = authEnabled;\n }\n public ApiVersion getApiVersion() {\n return apiVersion;\n }\n public void setApiVersion(ApiVersion apiVersion) {\n this.apiVersion = apiVersion;\n }\n public boolean mustRefresh() {\n if (!refreshed) {\n return true;\n } else {\n return System.currentTimeMillis() - lastRefreshTime.getTime() > REFRESH_EXPIRATION_MILLIS;\n }\n }\n @Override\n public String toString() {\n return \"EtcdCluster [name=\" + name + \", address=\" + address + \"]\";\n }\n}",
"public interface EtcdProxyFactory {\n EtcdProxy getEtcdProxy(String registry, String clientURL, ApiVersion apiVersion);\n EtcdProxy getEtcdProxy(String registry);\n}",
"public class EtcdMember {\n private String id;\n private String name;\n private List<String> peerURLs;\n private List<String> clientURLs;\n private String state;\n private String version;\n public String getId() {\n return id;\n }\n public void setId(String id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public List<String> getPeerURLs() {\n return peerURLs;\n }\n public void setPeerURLs(List<String> peerURLs) {\n this.peerURLs = peerURLs;\n }\n public List<String> getClientURLs() {\n return clientURLs;\n }\n public void setClientURLs(List<String> clientURLs) {\n this.clientURLs = clientURLs;\n }\n public String getState() {\n return state;\n }\n public void setState(String state) {\n this.state = state;\n }\n public String getVersion() {\n return version;\n }\n public void setVersion(String version) {\n this.version = version;\n }\n @Override\n public String toString() {\n return \"EtcdMember [id=\" + id + \", name=\" + name + \", peerURLs=\"\n + peerURLs + \", clientURLs=\" + clientURLs + \", state=\" + state\n + \"]\";\n }\n}",
"public interface EtcdProxy extends AutoCloseable {\n\n void close();\n /**\n * Performs an http <b>GET</b> to the <b>/version</b> endpoint\n *\n * @return etcd registry version\n */\n String getVersion();\n\n Boolean isAuthEnabled();\n\n /**\n * Performs an http <b>GET</b> to the <b>/v2/stats/self</b> endpoint\n *\n * @return etcd node self statistics\n */\n EtcdSelfStats getSelfStats();\n\n /**\n * If the reported etcd version is 0.4.x it uses the peer address\n * <b>http://<host>:7001/</b> and performs an http <b>GET</b>\n * against the <b>/v2/admin/machines</b> endpoint. Otherwise it\n * uses the default client provided address URL and performs an\n * http <b>GET</b> to the <b>/v2/members</b> endpoint.\n *\n * @return the list of etcd cluster members and their roles\n */\n List<EtcdMember> getMembers();\n\n /**\n * Performs an http GET to the /v2/keys/{key} endpoint.\n * If the supplied key is not found it throws an exception\n * indicating so.\n *\n * @param key The key-value key parameter\n * @return The requested key-value or directory node\n */\n EtcdNode getNode(String key);\n\n /**\n * Performs an http PUT to the /v2/keys/{key} endpoint by\n * submitting a url encoded form. This form contains the\n * 'value' parameter if it is a value node or the 'dir=true'\n * parameter if it is a directory. The 'prevExist' parameter\n * is sent always as false to indicate that this node does\n * not exist already. If the supplied node contains TTL then\n * the 'ttl' parameter is set as well.\n *\n * @param node The key-value pair or directory to save\n */\n void saveNode(EtcdNode node);\n\n /**\n * Performs an http PUT to the /v2/keys/{key} endpoint by\n * submitting a url encoded form. This form contains the\n * 'value' parameter if it is a value node or the 'dir=true'\n * parameter if it is a directory. The 'prevExist' parameter\n * is sent always as true to indicate that this node must\n * exist already. The 'ttl' parameter is always set to the\n * supplied TTL value if it is set otherwise it is sent as\n * empty '' to enable removing TTL from key-value pairs\n * or directories.\n *\n * @param node The key-value pair or directory to update\n * @return The node before the update\n */\n EtcdNode updateNode(EtcdNode node);\n\n /**\n * Performs an http DELETE to the /v2/keys/{key} endpoint.\n * If the supplied node is a directory then the query\n * parameter ?dir=true is appended to the endpoint url.\n\n * @param node The key-value pair or directory to delete.\n * @return The deleted node\n */\n EtcdNode deleteNode(EtcdNode node);\n\n /**\n * Performs an http DELETE to the /v2/keys/{key} endpoint.\n * If the supplied node is a directory then the query\n * parameter ?dir=true is appended to the endpoint url.\n\n * @param node The key-value pair or directory to delete.\n * @param recursive if it is set to true then even non\n * empty directory nodes can be removed. It appends the\n * ?recursive=true query parameter and skips the ?dir=true.\n * @return The deleted node\n */\n EtcdNode deleteNode(EtcdNode node, boolean recursive);\n\n}",
"public class EtcdSelfStats {\n\n private String id;\n private String name;\n private LeaderInfo leaderInfo;\n\n private Long recvAppendRequestCnt;\n private Double recvBandwidthRate;\n private Double recvPkgRate;\n\n private Long sendAppendRequestCnt;\n private Double sendBandwidthRate;\n private Double sendPkgRate;\n\n private String startTime;\n private String state;\n\n @Override\n public String toString() {\n return \"EtcdSelfStats [id=\" + id + \", name=\" + name + \", leaderInfo=\"\n + leaderInfo + \", state=\" + state + \"]\";\n }\n public String getId() {\n return id;\n }\n public void setId(String id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getState() {\n return state;\n }\n public void setState(String state) {\n this.state = state;\n }\n public String getStartTime() {\n return startTime;\n }\n public void setStartTime(String startTime) {\n this.startTime = startTime;\n }\n public LeaderInfo getLeaderInfo() {\n return leaderInfo;\n }\n public void setLeaderInfo(LeaderInfo leaderInfo) {\n this.leaderInfo = leaderInfo;\n }\n public Long getRecvAppendRequestCnt() {\n return recvAppendRequestCnt;\n }\n public void setRecvAppendRequestCnt(Long recvAppendRequestCnt) {\n this.recvAppendRequestCnt = recvAppendRequestCnt;\n }\n public Double getRecvPkgRate() {\n return recvPkgRate;\n }\n public void setRecvPkgRate(Double recvPkgRate) {\n this.recvPkgRate = recvPkgRate;\n }\n public Double getRecvBandwidthRate() {\n return recvBandwidthRate;\n }\n public void setRecvBandwidthRate(Double recvBandwidthRate) {\n this.recvBandwidthRate = recvBandwidthRate;\n }\n public Long getSendAppendRequestCnt() {\n return sendAppendRequestCnt;\n }\n public void setSendAppendRequestCnt(Long sendAppendRequestCnt) {\n this.sendAppendRequestCnt = sendAppendRequestCnt;\n }\n public Double getSendBandwidthRate() {\n return sendBandwidthRate;\n }\n public void setSendBandwidthRate(Double sendBandwidthRate) {\n this.sendBandwidthRate = sendBandwidthRate;\n }\n public Double getSendPkgRate() {\n return sendPkgRate;\n }\n public void setSendPkgRate(Double sendPkgRate) {\n this.sendPkgRate = sendPkgRate;\n }\n\n public static class LeaderInfo {\n private String leader;\n private String uptime;\n private String startTime;\n public String getLeader() {\n return leader;\n }\n public void setLeader(String leader) {\n this.leader = leader;\n }\n public String getUptime() {\n return uptime;\n }\n public void setUptime(String uptime) {\n this.uptime = uptime;\n }\n public String getStartTime() {\n return startTime;\n }\n public void setStartTime(String startTime) {\n this.startTime = startTime;\n }\n @Override\n public String toString() {\n return \"LeaderInfo [leader=\" + leader + \"]\";\n }\n }\n}"
] | import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.github.etcd.service.ApiVersion;
import org.github.etcd.service.ClusterManager;
import org.github.etcd.service.EtcdCluster;
import org.github.etcd.service.EtcdProxyFactory;
import org.github.etcd.service.api.EtcdMember;
import org.github.etcd.service.api.EtcdProxy;
import org.github.etcd.service.api.EtcdSelfStats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.github.etcd.service.impl;
public class ClusterManagerImpl implements ClusterManager {
private static final Logger log = LoggerFactory.getLogger(ClusterManager.class);
private static final Comparator<EtcdMember> MEMBER_SORTER = new Comparator<EtcdMember>() {
@Override
public int compare(EtcdMember o1, EtcdMember o2) {
return o1.getName().compareTo(o2.getName());
}
};
private static final Map<String, String> STATE_MAPPINGS = new HashMap<>();
static {
STATE_MAPPINGS.put("leader", "leader");
STATE_MAPPINGS.put("follower", "follower");
STATE_MAPPINGS.put("StateLeader", "leader");
STATE_MAPPINGS.put("StateFollower", "follower");
}
@Inject
private EtcdProxyFactory proxyFactory;
private Map<String, EtcdCluster> clusters = Collections.synchronizedMap(new LinkedHashMap<String, EtcdCluster>());
private static final String DEFAULT_ETCD_CLIENT = "ETCD_CLIENT_URL";
public ClusterManagerImpl() {
String etcdAddress = System.getenv(DEFAULT_ETCD_CLIENT);
if (etcdAddress == null) {
etcdAddress = System.getProperty(DEFAULT_ETCD_CLIENT, "http://localhost:2379");
}
addCluster("default", etcdAddress, ApiVersion.V3);
// addCluster("kvm", "http://192.168.122.201:2379/");
}
@Override
public boolean exists(String name) {
return clusters.containsKey(name);
}
@Override
public EtcdCluster getCluster(String name) {
return name == null ? null : clusters.get(name);
}
@Override
public EtcdCluster addCluster(String name, String etcdPeerAddress, ApiVersion apiVersion) {
EtcdCluster cluster = new EtcdCluster(name, etcdPeerAddress, apiVersion);
clusters.put(name, cluster);
return cluster;
}
@Override
public void removeCluster(String name) {
clusters.remove(name);
}
@Override
public List<EtcdCluster> getClusters() {
return new ArrayList<>(clusters.values());
}
@Override
public List<String> getClusterNames() {
return new ArrayList<>(clusters.keySet());
}
@Override
public void refreshCluster(String name) {
if (name == null) {
return;
}
EtcdCluster cluster = clusters.get(name);
// default leader address is the provided one
String leaderAddress = cluster.getAddress();
ApiVersion apiVersion = cluster.getApiVersion();
List<EtcdMember> members;
| try (EtcdProxy proxy = proxyFactory.getEtcdProxy(name, leaderAddress, apiVersion)) { | 5 |
isel-leic-mpd/mpd-2017-i41d | aula31-weather-groupingBy/src/main/java/weather/WeatherService.java | [
"public class HttpRequest implements IRequest {\n @Override\n public Iterable<String> getContent(String path) {\n List<String> res = new ArrayList<>();\n try (InputStream in = new URL(path).openStream()) {\n /*\n * Consumir o Inputstream e adicionar dados ao res\n */\n try(BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {\n String line;\n while ((line = reader.readLine()) != null) {\n res.add(line);\n }\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n return res;\n }\n}",
"public class WeatherWebApi {\n\n private static final String WEATHER_TOKEN;\n private static final String WEATHER_HOST = \"http://api.worldweatheronline.com\";\n private static final String WEATHER_PAST = \"/premium/v1/past-weather.ashx\";\n private static final String WEATHER_PAST_ARGS =\n \"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s\";\n private static final String WEATHER_SEARCH=\"/premium/v1/search.ashx?query=%s\";\n private static final String WEATHER_SEARCH_ARGS=\"&format=tab&key=%s\";\n\n static {\n try {\n URL keyFile = ClassLoader.getSystemResource(\"worldweatheronline-app-key.txt\");\n if(keyFile == null) {\n throw new IllegalStateException(\n \"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt\");\n } else {\n InputStream keyStream = keyFile.openStream();\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {\n WEATHER_TOKEN = reader.readLine();\n }\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n private final IRequest req;\n\n public WeatherWebApi(IRequest req) {\n this.req = req;\n }\n\n /**\n * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****\n */\n\n public Iterable<LocationDto> search(String query) {\n String path = WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;\n String url = String.format(path, query, WEATHER_TOKEN);\n Iterable<String> content = () -> req.getContent(url).iterator();\n Iterable<String> iterable =\tfilter(content, (String s) -> !s.startsWith(\"#\"));\n return map(iterable, LocationDto::valueOf);\n }\n\n /**\n * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****\n */\n public Iterable<WeatherInfoDto> pastWeather(\n double lat,\n double log,\n LocalDate from,\n LocalDate to\n ) {\n String query = lat + \",\" + log;\n String path = WEATHER_HOST + WEATHER_PAST +\n String.format(WEATHER_PAST_ARGS, query, from, to, WEATHER_TOKEN);\n Iterable<String> content = () -> req.getContent(path).iterator();\n Iterable<String> stringIterable = filter(content, s->!s.startsWith(\"#\"));\n Iterable<String>filtered = skip(stringIterable,1);\t// Skip line: Not Available\n int[] counter = {0};\n Predicate<String> isEvenLine = item -> ++counter[0] % 2==0;\n filtered = filter(filtered,isEvenLine);//even lines filter\n return map(filtered, WeatherInfoDto::valueOf); //to weatherinfo objects\n }\n}",
"public class LocationDto {\n private final ContainerDto[] country;\n private final ContainerDto[] region;\n private final double latitude;\n private final double longitude;\n\n public LocationDto(ContainerDto[] country, ContainerDto[] region, double latitude, double longitude) {\n this.country = country;\n this.region = region;\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n public String getCountry() {\n return country[0].value;\n }\n\n public String getRegion() {\n return region[0].value;\n }\n\n public double getLatitude() {\n return latitude;\n }\n\n public double getLongitude() {\n return longitude;\n }\n\n public static LocationDto valueOf(String line) {\n String[] data = line.split(\"\\t\");\n return new LocationDto(\n ContainerDto.arrayOf(data[1]),\n ContainerDto.arrayOf(data[2]),\n Double.parseDouble(data[3]),\n Double.parseDouble(data[4]));\n }\n\n @Override\n public String toString() {\n return \"LocationDto{\" +\n \"country='\" + getCountry() + '\\'' +\n \", region='\" + getRegion() + '\\'' +\n \", latitude=\" + latitude +\n \", longitude=\" + longitude +\n '}';\n }\n\n static class ContainerDto {\n final String value;\n\n public ContainerDto(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public static ContainerDto[] arrayOf(String s) {\n ContainerDto dto = new ContainerDto(s);\n return new ContainerDto[]{dto};\n }\n }\n}",
"public class WeatherInfoDto {\n private final LocalDate date; // index 0\n private final int tempC; // index 2\n private final String description; // index 10\n private final double precipMM; // index 11\n private final int feelsLikeC; // index 24\n\n public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {\n this.date = date;\n this.tempC = tempC;\n this.description = description;\n this.precipMM = precipMM;\n this.feelsLikeC = feelsLikeC;\n }\n\n public LocalDate getDate() {\n return date;\n }\n\n public int getTempC() {\n return tempC;\n }\n\n public String getDescription() {\n return description;\n }\n\n public double getPrecipMM() {\n return precipMM;\n }\n\n public int getFeelsLikeC() {\n return feelsLikeC;\n }\n\n @Override\n public String toString() {\n return \"WeatherInfoDto{\" +\n date +\n \", tempC=\" + tempC +\n \", '\" + description + '\\'' +\n \", precipMM=\" + precipMM +\n \", feelsLikeC=\" + feelsLikeC +\n '}';\n }\n\n /**\n * Hourly information follows below the day according to the format of\n * /past weather resource of the World Weather Online API\n */\n public static WeatherInfoDto valueOf(String line) {\n String[] data = line.split(\",\");\n return new WeatherInfoDto(\n LocalDate.parse(data[0]),\n Integer.parseInt(data[2]),\n data[10],\n Double.parseDouble(data[11]),\n Integer.parseInt(data[24]));\n }\n}",
"public class Location {\n private final String country;\n private final String region;\n private final double latitude;\n private final double longitude;\n private final Iterable<WeatherInfo> last30daysWeather;\n private final BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather;\n\n public Location(String country, String region, double latitude, double longitude, Iterable<WeatherInfo> last30daysWeather, BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather) {\n this.country = country;\n this.region = region;\n this.latitude = latitude;\n this.longitude = longitude;\n this.last30daysWeather = last30daysWeather;\n this.pastWeather = pastWeather;\n }\n\n public String getCountry() {\n return country;\n }\n\n public String getRegion() {\n return region;\n }\n\n public double getLatitude() {\n return latitude;\n }\n\n public double getLongitude() {\n return longitude;\n }\n\n public Iterable<WeatherInfo> getLast30daysWeather() {\n return last30daysWeather;\n }\n\n public Iterable<WeatherInfo> getPastWeather(LocalDate from, LocalDate to) {\n return pastWeather.apply(from, to);\n }\n\n @Override\n public String toString() {\n return \"Location{\" +\n \"country='\" + country + '\\'' +\n \", region='\" + region + '\\'' +\n \", latitude=\" + latitude +\n \", longitude=\" + longitude +\n \", last30daysWeather=\" + last30daysWeather +\n '}';\n }\n}",
"public class WeatherInfo {\n private final LocalDate date;\n private final int tempC;\n private final String description;\n private final double precipMM;\n private final int feelsLikeC;\n\n public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {\n this.date = date;\n this.tempC = tempC;\n this.description = description;\n this.precipMM = precipMM;\n this.feelsLikeC = feelsLikeC;\n }\n\n public LocalDate getDate() {\n return date;\n }\n\n public int getTempC() {\n return tempC;\n }\n\n public String getDescription() {\n return description;\n }\n\n public double getPrecipMM() {\n return precipMM;\n }\n\n public int getFeelsLikeC() {\n return feelsLikeC;\n }\n\n @Override\n public String toString() {\n return \"WeatherInfo{\" +\n \"date=\" + date +\n \", tempC=\" + tempC +\n \", description='\" + description + '\\'' +\n \", precipMM=\" + precipMM +\n \", feelsLikeC=\" + feelsLikeC +\n '}';\n }\n}"
] | import util.HttpRequest;
import weather.data.WeatherWebApi;
import weather.data.dto.LocationDto;
import weather.data.dto.WeatherInfoDto;
import weather.model.Location;
import weather.model.WeatherInfo;
import java.time.LocalDate;
import java.util.stream.Stream;
import static java.time.LocalDate.now; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* 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 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 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/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 29-03-2017
*/
public class WeatherService {
private final WeatherWebApi api;
public WeatherService(WeatherWebApi api) {
this.api = api;
}
public WeatherService() {
api = new WeatherWebApi(new HttpRequest());
}
public Stream<Location> search(String query) {
return api.search(query).map(this::dtoToLocation);
}
private Location dtoToLocation(LocationDto loc) {
return new Location(
loc.getCountry(),
loc.getRegion(),
loc.getLatitude(),
loc.getLongitude(),
() -> last30daysWeather(loc.getLatitude(), loc.getLongitude()),
(from, to) -> pastWeather(loc.getLatitude(), loc.getLongitude(), from, to));
}
| public Stream<WeatherInfo> last30daysWeather(double lat, double log) { | 5 |
caarmen/scrumchatter | app/src/main/java/ca/rmen/android/scrumchatter/chart/MeetingChartFragment.java | [
"public class Constants {\n public static final String TAG = \"ScrumChatter\";\n public static final String PREF_TEAM_ID = \"team_id\";\n public static final int DEFAULT_TEAM_ID = 1;\n public static final String DEFAULT_TEAM_NAME = \"Team A\";\n}",
"public class Meetings {\n private static final String TAG = Constants.TAG + \"/\" + Meetings.class.getSimpleName();\n public static final String EXTRA_MEETING_ID = \"meeting_id\";\n public static final String EXTRA_MEETING_STATE = \"meeting_state\";\n private final FragmentActivity mActivity;\n\n public Meetings(FragmentActivity activity) {\n mActivity = activity;\n }\n\n /**\n * Checks if there are any team members in the given team id. If not, an error dialog is shown. If the team does have members, then we start\n * the MeetingActivity class for a new meeting.\n */\n public Single<Meeting> createMeeting(final int teamId) {\n Log.v(TAG, \"createMeeting in team \" + teamId);\n return Single.fromCallable(() -> {\n Cursor c = mActivity.getContentResolver().query(MemberColumns.CONTENT_URI, new String[]{\"count(*)\"},\n MemberColumns.TEAM_ID + \"=? AND \" + MemberColumns.DELETED + \"= 0\", new String[]{String.valueOf(teamId)}, null);\n if (c != null) {\n try {\n c.moveToFirst();\n int memberCount = c.getInt(0);\n if (memberCount > 0) return Meeting.createNewMeeting(mActivity);\n } finally {\n c.close();\n }\n }\n throw new IllegalArgumentException(\"Can't create meeting for team \" + teamId + \" because it doesn't exist or has no members\");\n })\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n public Single<Meeting> readMeeting(long meetingId) {\n return Single.fromCallable(() -> Meeting.read(mActivity, meetingId))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n /**\n * Shows a confirmation dialog to delete the given meeting.\n */\n public void confirmDelete(final Meeting meeting) {\n Log.v(TAG, \"confirm delete meeting: \" + meeting);\n // Let's ask him if he's sure first.\n Bundle extras = new Bundle(1);\n extras.putLong(EXTRA_MEETING_ID, meeting.getId());\n DialogFragmentFactory.showConfirmDialog(mActivity, mActivity.getString(R.string.action_delete_meeting),\n mActivity.getString(R.string.dialog_message_delete_meeting_confirm, TextUtils.formatDateTime(mActivity, meeting.getStartDate())),\n R.id.action_delete_meeting, extras);\n }\n\n /**\n * Deletes the given meeting from the DB.\n */\n public void delete(final long meetingId) {\n Log.v(TAG, \"delete meeting \" + meetingId);\n // Delete the meeting in a background thread.\n Single.fromCallable(() -> Meeting.read(mActivity, meetingId))\n .subscribeOn(Schedulers.io())\n .observeOn(Schedulers.io())\n .subscribe(Meeting::delete,\n throwable -> Log.v(TAG, \"couldn't delete meeting \" + meetingId, throwable));\n }\n\n /**\n * Read the data for the given meeting, then show an intent chooser to export this data as text.\n */\n public void export(long meetingId) {\n Log.v(TAG, \"export meeting \" + meetingId);\n // Export the meeting in a background thread.\n Single.fromCallable(() -> new MeetingExport(mActivity).exportMeeting(meetingId))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(success -> {\n if (!success) Snackbar.make(mActivity.getWindow().getDecorView().getRootView(), R.string.error_sharing_meeting, Snackbar.LENGTH_LONG).show();\n });\n }\n}",
"public class Meeting {\n private static final String TAG = Constants.TAG + \"/\" + Meeting.class.getSimpleName();\n private final Context mContext;\n private final long mId;\n private final Uri mUri;\n private long mStartDate;\n private State mState;\n private long mDuration;\n\n private Meeting(Context context, long id, long startDate, State state, long duration) {\n mContext = context;\n mId = id;\n mStartDate = startDate;\n mState = state;\n mDuration = duration;\n mUri = Uri.withAppendedPath(MeetingColumns.CONTENT_URI, String.valueOf(id));\n }\n\n /**\n * Read an existing meeting from the DB.\n */\n @NonNull\n public static Meeting read(Context context, long id) {\n Log.v(TAG, \"read meeting with id \" + id);\n // Read the meeting attributes from the DB \n Uri uri = Uri.withAppendedPath(MeetingColumns.CONTENT_URI, String.valueOf(id));\n // Closing the cursorWrapper will also close meetingCursor\n @SuppressLint(\"Recycle\") Cursor meetingCursor = context.getContentResolver().query(uri, null, null, null, null);\n MeetingCursorWrapper cursorWrapper = new MeetingCursorWrapper(meetingCursor);\n //noinspection TryFinallyCanBeTryWithResources\n try {\n if (cursorWrapper.moveToFirst()) {\n\n long duration = cursorWrapper.getTotalDuration();\n long startDate = cursorWrapper.getMeetingDate();\n State state = cursorWrapper.getState();\n return new Meeting(context, id, startDate, state, duration);\n } else {\n Log.v(TAG, \"No meeting for id \" + id);\n throw new IllegalArgumentException(\"No meeting for id \" + id);\n }\n } finally {\n cursorWrapper.close();\n }\n }\n\n /**\n * Read an existing meeting from the DB.\n */\n public static Meeting read(Context context, MeetingCursorWrapper cursorWrapper) {\n long id = cursorWrapper.getId();\n long startDate = cursorWrapper.getMeetingDate();\n long duration = cursorWrapper.getTotalDuration();\n MeetingColumns.State state = cursorWrapper.getState();\n return new Meeting(context, id, startDate, state, duration);\n }\n\n /**\n * Create a new Meeting. This persists the new meeting to the DB.\n */\n @WorkerThread\n public static Meeting createNewMeeting(Context context) {\n Log.v(TAG, \"create new meeting\");\n int teamId = Prefs.getInstance(context).getTeamId();\n ContentValues values = new ContentValues();\n long startDate = System.currentTimeMillis();\n values.put(MeetingColumns.MEETING_DATE, System.currentTimeMillis());\n values.put(MeetingColumns.TEAM_ID, teamId);\n Uri newMeetingUri = context.getContentResolver().insert(MeetingColumns.CONTENT_URI, values);\n if (newMeetingUri != null) {\n long meetingId = Long.parseLong(newMeetingUri.getLastPathSegment());\n return new Meeting(context, meetingId, startDate, State.NOT_STARTED, 0);\n } else {\n throw new IllegalStateException(\"Couldn't create a meeting for values \" + values);\n }\n }\n\n public long getId() {\n return mId;\n }\n\n public long getStartDate() {\n return mStartDate;\n }\n\n public State getState() {\n return mState;\n }\n\n public long getDuration() {\n return mDuration;\n }\n\n /**\n * Updates the start time to now, sets the state to in_progress, and persists the changes.\n */\n void start() {\n /*\n * Change the date of the meeting to now. We do this when the\n * meeting goes from not-started to in-progress. This way it is\n * easier to track the duration of the meeting.\n */\n mStartDate = System.currentTimeMillis();\n mState = State.IN_PROGRESS;\n save();\n }\n\n /**\n * Updates the meeting duration to time elapsed since startDate, sets the state to finished, and persists the changes.\n */\n void stop() {\n mState = State.FINISHED;\n long meetingDuration = System.currentTimeMillis() - mStartDate;\n mDuration = meetingDuration / 1000;\n shutEverybodyUp();\n save();\n }\n\n /**\n * Stop the chronometers of all team members who are still talking. Update\n * the duration for these team members.\n */\n private void shutEverybodyUp() {\n Log.v(TAG, \"shutEverybodyUp\");\n // Query all team members who are still talking in this meeting.\n Uri uri = Uri.withAppendedPath(MeetingMemberColumns.CONTENT_URI, String.valueOf(mId));\n // Closing the cursorWrapper also closes the cursor\n @SuppressLint(\"Recycle\")\n Cursor cursor = mContext.getContentResolver().query(uri,\n new String[] { MeetingMemberColumns.MEMBER_ID, MeetingMemberColumns.DURATION, MeetingMemberColumns.TALK_START_TIME },\n MeetingMemberColumns.TALK_START_TIME + \">0\", null, null);\n if (cursor != null) {\n // Prepare some update statements to set the duration and reset the\n // talk_start_time, for these members.\n ArrayList<ContentProviderOperation> operations = new ArrayList<>();\n MeetingMemberCursorWrapper cursorWrapper = new MeetingMemberCursorWrapper(cursor);\n if (cursorWrapper.moveToFirst()) {\n do {\n // Prepare an update operation for one of these members.\n Builder builder = ContentProviderOperation.newUpdate(MeetingMemberColumns.CONTENT_URI);\n long memberId = cursorWrapper.getMemberId();\n // Calculate the total duration the team member talked\n // during this meeting.\n long duration = cursorWrapper.getDuration();\n long talkStartTime = cursorWrapper.getTalkStartTime();\n long newDuration = duration + (System.currentTimeMillis() - talkStartTime) / 1000;\n builder.withValue(MeetingMemberColumns.DURATION, newDuration);\n builder.withValue(MeetingMemberColumns.TALK_START_TIME, 0);\n builder.withSelection(MeetingMemberColumns.MEMBER_ID + \"=? AND \" + MeetingMemberColumns.MEETING_ID + \"=?\",\n new String[] { String.valueOf(memberId), String.valueOf(mId) });\n operations.add(builder.build());\n } while (cursorWrapper.moveToNext());\n }\n cursorWrapper.close();\n try {\n // Batch update these team members.\n mContext.getContentResolver().applyBatch(ScrumChatterProvider.AUTHORITY, operations);\n } catch (Exception e) {\n Log.v(TAG, \"Couldn't close off meeting: \" + e.getMessage(), e);\n }\n }\n }\n\n /**\n * If the team member is talking, stop them. Otherwise, stop all other team members who may be talking, and start this one.\n */\n void toggleTalkingMember(final long memberId) {\n Log.v(TAG, \"toggleTalkingMember \" + memberId);\n\n // Find out if this member is currently talking:\n // read its talk_start_time and duration fields.\n Uri meetingMemberUri = Uri.withAppendedPath(MeetingMemberColumns.CONTENT_URI, String.valueOf(mId));\n // Closing the cursorWrapper also closes the cursor\n @SuppressLint(\"Recycle\")\n Cursor cursor = mContext.getContentResolver().query(meetingMemberUri,\n new String[] { MeetingMemberColumns.TALK_START_TIME, MeetingMemberColumns.DURATION }, MeetingMemberColumns.MEMBER_ID + \"=?\",\n new String[] { String.valueOf(memberId) }, null);\n long talkStartTime = 0;\n long duration = 0;\n if (cursor != null) {\n MeetingMemberCursorWrapper cursorWrapper = new MeetingMemberCursorWrapper(cursor);\n if (cursorWrapper.moveToFirst()) {\n talkStartTime = cursorWrapper.getTalkStartTime();\n duration = cursorWrapper.getDuration();\n }\n cursorWrapper.close();\n }\n Log.v(TAG, \"Talking member: duration = \" + duration + \", talkStartTime = \" + talkStartTime);\n ContentValues values = new ContentValues(2);\n // The member is currently talking if talkStartTime > 0.\n if (talkStartTime > 0) {\n long justTalkedFor = (System.currentTimeMillis() - talkStartTime) / 1000;\n long newDuration = duration + justTalkedFor;\n values.put(MeetingMemberColumns.DURATION, newDuration);\n values.put(MeetingMemberColumns.TALK_START_TIME, 0);\n } else {\n // shut up any other talking member before this one starts.\n shutEverybodyUp();\n values.put(MeetingMemberColumns.TALK_START_TIME, System.currentTimeMillis());\n }\n\n mContext.getContentResolver().update(MeetingMemberColumns.CONTENT_URI, values,\n MeetingMemberColumns.MEMBER_ID + \"=? AND \" + MeetingMemberColumns.MEETING_ID + \"=?\",\n new String[] { String.valueOf(memberId), String.valueOf(mId) });\n }\n\n /**\n * Delete this meeting from the DB\n */\n public void delete() {\n Log.v(TAG, \"delete \" + this);\n mContext.getContentResolver().delete(mUri, null, null);\n }\n\n /**\n * Update this meeting in the DB.\n */\n private void save() {\n Log.v(TAG, \"save \" + this);\n ContentValues values = new ContentValues(3);\n values.put(MeetingColumns.STATE, mState.ordinal());\n values.put(MeetingColumns.MEETING_DATE, mStartDate);\n values.put(MeetingColumns.TOTAL_DURATION, mDuration);\n mContext.getContentResolver().update(mUri, values, null, null);\n }\n\n @Override\n public String toString() {\n return \"Meeting [mId=\" + mId + \", mUri=\" + mUri + \", mStartDate=\" + mStartDate + \", mState=\" + mState + \", mDuration=\" + mDuration + \"]\";\n }\n\n\n}",
"public class MeetingMemberColumns implements BaseColumns {\n static final String TABLE_NAME = \"meeting_member\";\n public static final Uri CONTENT_URI = Uri.parse(ScrumChatterProvider.CONTENT_URI_BASE + \"/\" + TABLE_NAME);\n\n public static final String _ID = MemberColumns.TABLE_NAME + \".\" + MemberColumns._ID + \" AS \" + BaseColumns._ID;\n public static final String MEETING_ID = \"meeting_id\";\n public static final String MEMBER_ID = \"member_id\";\n public static final String DURATION = \"duration\";\n public static final String TALK_START_TIME = \"talk_start_time\";\n\n}",
"public class MemberColumns implements BaseColumns {\n static final String TABLE_NAME = \"member\";\n public static final Uri CONTENT_URI = Uri.parse(ScrumChatterProvider.CONTENT_URI_BASE + \"/\" + TABLE_NAME);\n\n public static final String _ID = BaseColumns._ID;\n\n public static final String NAME = \"name\";\n public static final String TEAM_ID = \"member_team_id\";\n public static final String DELETED = \"deleted\";\n\n static final String DEFAULT_ORDER = _ID;\n}",
"public class Teams {\n private static final String TAG = Constants.TAG + \"/\" + Teams.class.getSimpleName();\n public static final String EXTRA_TEAM_URI = \"team_uri\";\n public static final String EXTRA_TEAM_ID = \"team_id\";\n private static final String EXTRA_TEAM_NAME = \"team_name\";\n private final FragmentActivity mActivity;\n\n public static class Team {\n private final Uri teamUri;\n public final String teamName;\n\n private Team(Uri teamUri, String teamName) {\n this.teamUri = teamUri;\n this.teamName = teamName;\n }\n\n @Override\n public String toString() {\n return \"Team [teamUri=\" + teamUri + \", teamName=\" + teamName + \"]\";\n }\n\n }\n\n public static final class TeamsData {\n public final Team currentTeam;\n public final List<Team> teams;\n\n private TeamsData(Team currentTeam, List<Team> teams) {\n this.currentTeam = currentTeam;\n this.teams = teams;\n }\n }\n\n public Teams(FragmentActivity activity) {\n mActivity = activity;\n }\n\n /**\n * Upon selecting a team, update the shared preference for the selected team.\n */\n public void switchTeam(final CharSequence teamName) {\n Log.v(TAG, \"switchTeam \" + teamName);\n Schedulers.io().scheduleDirect(() -> {\n Cursor c = mActivity.getContentResolver().query(TeamColumns.CONTENT_URI, new String[] { TeamColumns._ID }, TeamColumns.TEAM_NAME + \" = ?\",\n new String[] { String.valueOf(teamName) }, null);\n if (c != null) {\n try {\n c.moveToFirst();\n if (c.getCount() == 1) {\n int teamId = c.getInt(0);\n Prefs.getInstance(mActivity).setTeamId(teamId);\n } else {\n Log.wtf(TAG, \"Found \" + c.getCount() + \" teams for \" + teamName);\n }\n\n } finally {\n c.close();\n }\n }\n });\n }\n\n /**\n * Show a dialog with a text input for the new team name. Validate that the team doesn't already exist. Upon pressing \"OK\", create the team.\n */\n public void promptCreateTeam() {\n Log.v(TAG, \"promptCreateTeam\");\n DialogFragmentFactory.showInputDialog(mActivity, mActivity.getString(R.string.action_new_team), mActivity.getString(R.string.hint_team_name), null,\n TeamNameValidator.class, R.id.action_team, null);\n }\n\n public void createTeam(final String teamName) {\n Log.v(TAG, \"createTeam, name=\" + teamName);\n // Ignore an empty name.\n if (!TextUtils.isEmpty(teamName)) {\n // Create the new team in a background thread.\n Schedulers.io().scheduleDirect(() -> {\n ContentValues values = new ContentValues(1);\n values.put(TeamColumns.TEAM_NAME, teamName);\n Uri newTeamUri = mActivity.getContentResolver().insert(TeamColumns.CONTENT_URI, values);\n if (newTeamUri != null) {\n int newTeamId = Integer.valueOf(newTeamUri.getLastPathSegment());\n Prefs.getInstance(mActivity).setTeamId(newTeamId);\n }\n });\n }\n }\n\n /**\n * Retrieve the currently selected team. Show a dialog with a text input to rename this team. Validate that the new name doesn't correspond to any other\n * existing team. Upon pressing ok, rename the current team.\n */\n public void promptRenameTeam(final Team team) {\n Log.v(TAG, \"promptRenameTeam, team=\" + team);\n if (team != null) {\n // Show a dialog to input a new team name for the current team.\n Bundle extras = new Bundle(1);\n extras.putParcelable(EXTRA_TEAM_URI, team.teamUri);\n extras.putString(EXTRA_TEAM_NAME, team.teamName);\n DialogFragmentFactory.showInputDialog(mActivity, mActivity.getString(R.string.action_team_rename), mActivity.getString(R.string.hint_team_name),\n team.teamName, TeamNameValidator.class, R.id.action_team_rename, extras);\n }\n }\n\n public void renameTeam(final Uri teamUri, final String teamName) {\n Log.v(TAG, \"renameTeam, uri = \" + teamUri + \", name = \" + teamName);\n\n // Ignore an empty name.\n if (!TextUtils.isEmpty(teamName)) {\n // Rename the team in a background thread.\n Schedulers.io().scheduleDirect(() -> {\n ContentValues values = new ContentValues(1);\n values.put(TeamColumns.TEAM_NAME, teamName);\n mActivity.getContentResolver().update(teamUri, values, null, null);\n });\n }\n }\n\n /**\n * Shows a confirmation dialog to the user to delete a team.\n */\n @MainThread\n public void confirmDeleteTeam(final Team team) {\n Log.v(TAG, \"confirmDeleteTeam, team = \" + team);\n\n getTeamCount()\n .subscribe(teamCount -> {\n // We need at least one team in the app.\n if (teamCount <= 1) {\n DialogFragmentFactory.showInfoDialog(mActivity, R.string.action_team_delete, R.string.dialog_error_one_team_required);\n }\n // Delete this team\n else if (team != null) {\n Bundle extras = new Bundle(1);\n extras.putParcelable(EXTRA_TEAM_URI, team.teamUri);\n DialogFragmentFactory.showConfirmDialog(mActivity, mActivity.getString(R.string.action_team_delete),\n mActivity.getString(R.string.dialog_message_delete_team_confirm, team.teamName), R.id.action_team_delete, extras);\n }\n });\n }\n\n /**\n * Deletes the team and all its members from the DB.\n */\n public void deleteTeam(final Uri teamUri) {\n Log.v(TAG, \"deleteTeam, uri = \" + teamUri);\n Schedulers.io().scheduleDirect(() -> {\n // delete this team\n mActivity.getContentResolver().delete(teamUri, null, null);\n // pick another current team\n selectFirstTeam();\n });\n }\n\n /**\n * Select the first team in our DB.\n */\n private Team selectFirstTeam() {\n Cursor c = mActivity.getContentResolver().query(TeamColumns.CONTENT_URI, new String[] { TeamColumns._ID, TeamColumns.TEAM_NAME }, null, null, null);\n if (c != null) {\n try {\n if (c.moveToFirst()) {\n int teamId = c.getInt(0);\n String teamName = c.getString(1);\n Prefs.getInstance(mActivity).setTeamId(teamId);\n Uri teamUri = Uri.withAppendedPath(TeamColumns.CONTENT_URI, String.valueOf(teamId));\n return new Team(teamUri, teamName);\n }\n } finally {\n c.close();\n }\n }\n return null;\n }\n\n /**\n * @return the Team currently selected by the user.\n */\n @WorkerThread\n private Team getCurrentTeam() {\n // Retrieve the current team name and construct a uri for the team based on the current team id.\n int teamId = Prefs.getInstance(mActivity).getTeamId();\n Uri teamUri = Uri.withAppendedPath(TeamColumns.CONTENT_URI, String.valueOf(teamId));\n Cursor c = mActivity.getContentResolver().query(teamUri, new String[] { TeamColumns.TEAM_NAME }, null, null, null);\n if (c != null) {\n try {\n if (c.moveToFirst()) {\n String teamName = c.getString(0);\n return new Team(teamUri, teamName);\n }\n } finally {\n c.close();\n }\n }\n Log.wtf(TAG, \"Could not get the current team\", new Throwable());\n return selectFirstTeam();\n }\n\n /**\n * Query the teams table, and return a list of all teams, and the current team.\n */\n public Single<TeamsData> getAllTeams() {\n Log.v(TAG, \"getAllTeams\");\n return Single.fromCallable(() -> {\n Log.v(TAG, \"getAllTeams work\");\n List<Team> teams = new ArrayList<>();\n Cursor c = mActivity.getContentResolver().query(\n TeamColumns.CONTENT_URI,\n new String[]{TeamColumns._ID, TeamColumns.TEAM_NAME},\n null, null,\n TeamColumns.TEAM_NAME + \" COLLATE NOCASE\");\n\n if (c != null) {\n try {\n // Add the names of all the teams\n while (c.moveToNext()) {\n int teamId = c.getInt(0);\n String teamName = c.getString(1);\n Uri teamUri = Uri.withAppendedPath(TeamColumns.CONTENT_URI, String.valueOf(teamId));\n teams.add(new Team(teamUri, teamName));\n }\n } finally {\n c.close();\n }\n }\n return new TeamsData(getCurrentTeam(), teams);\n\n })\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n /**\n * @return the total number of teams\n */\n public Single<Integer> getTeamCount() {\n return Single.fromCallable(() -> {\n\n Cursor c = mActivity.getContentResolver().query(TeamColumns.CONTENT_URI, new String[]{\"count(*)\"}, null, null, null);\n if (c != null) {\n try {\n if (c.moveToFirst()) return c.getInt(0);\n } finally {\n c.close();\n }\n }\n return 0;\n }).subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n public Single<Team> readCurrentTeam() {\n return Single.fromCallable(this::getCurrentTeam)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n /**\n * Returns an error if the user entered the name of an existing team. To prevent renaming or creating multiple teams with the same name.\n */\n public static class TeamNameValidator implements InputValidator { // NO_UCD (use private)\n\n public TeamNameValidator() {}\n\n @Override\n public String getError(Context context, CharSequence input, Bundle extras) {\n // teamName is optional. If given, we won't show an error for renaming a team to its current name.\n String teamName = extras == null ? null : extras.getString(Teams.EXTRA_TEAM_NAME);\n\n // In the case of changing a team name, teamName will not be null, and we won't show an error if the name the user enters is the same as the existing team.\n // In the case of adding a new team, mTeamName will be null.\n if (!TextUtils.isEmpty(teamName) && !TextUtils.isEmpty(input) && teamName.equals(input.toString())) return null;\n\n // Query for a team with this name.\n Cursor cursor = context.getContentResolver().query(TeamColumns.CONTENT_URI, new String[] { \"count(*)\" }, TeamColumns.TEAM_NAME + \"=?\",\n new String[] { String.valueOf(input) }, null);\n\n // Now Check if the team member exists.\n if (cursor != null) {\n if (cursor.moveToFirst()) {\n int existingTeamCount = cursor.getInt(0);\n cursor.close();\n if (existingTeamCount > 0) return context.getString(R.string.error_team_exists, input);\n }\n }\n return null;\n }\n }\n\n}",
"@SuppressWarnings(\"unused\")\npublic class Log {\n public static void v(String tag, String message) {\n if (BuildConfig.DEBUG) android.util.Log.v(tag, message);\n }\n\n public static void v(String tag, String message, Throwable t) {\n if (BuildConfig.DEBUG) android.util.Log.v(tag, message, t);\n }\n\n public static void d(String tag, String message) {\n if (BuildConfig.DEBUG) android.util.Log.d(tag, message);\n }\n\n public static void d(String tag, String message, Throwable t) {\n if (BuildConfig.DEBUG) android.util.Log.d(tag, message, t);\n }\n\n public static void i(String tag, String message) {\n android.util.Log.i(tag, message);\n }\n\n public static void i(String tag, String message, Throwable t) {\n android.util.Log.i(tag, message, t);\n }\n\n public static void w(String tag, String message) {\n android.util.Log.w(tag, message);\n }\n\n public static void w(String tag, String message, Throwable t) {\n android.util.Log.w(tag, message, t);\n }\n\n public static void e(String tag, String message) {\n android.util.Log.e(tag, message);\n }\n\n public static void e(String tag, String message, Throwable t) {\n android.util.Log.e(tag, message, t);\n }\n\n public static void wtf(String tag, String message) {\n android.util.Log.wtf(tag, message);\n }\n\n public static void wtf(String tag, String message, Throwable t) {\n android.util.Log.wtf(tag, message, t);\n }\n}",
"public class TextUtils {\n public static String formatDateTime(Context context, long dateMillis) {\n return DateUtils.formatDateTime(context, dateMillis, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);\n }\n\n public static String formatDate(Context context, long dateMillis) {\n return DateUtils.formatDateTime(context, dateMillis, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL |DateUtils.FORMAT_NUMERIC_DATE);\n }\n\n}"
] | import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import ca.rmen.android.scrumchatter.Constants;
import ca.rmen.android.scrumchatter.R;
import ca.rmen.android.scrumchatter.databinding.MeetingChartFragmentBinding;
import ca.rmen.android.scrumchatter.meeting.Meetings;
import ca.rmen.android.scrumchatter.meeting.detail.Meeting;
import ca.rmen.android.scrumchatter.provider.MeetingMemberColumns;
import ca.rmen.android.scrumchatter.provider.MemberColumns;
import ca.rmen.android.scrumchatter.team.Teams;
import ca.rmen.android.scrumchatter.util.Log;
import ca.rmen.android.scrumchatter.util.TextUtils;
import io.reactivex.Single; | /*
* Copyright 2016-2017 Carmen Alvarez
* <p/>
* This file is part of Scrum Chatter.
* <p/>
* Scrum Chatter 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 3 of the License, or
* (at your option) any later version.
* <p/>
* Scrum Chatter 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.
* <p/>
* You should have received a copy of the GNU General Public License
* along with Scrum Chatter. If not, see <http://www.gnu.org/licenses/>.
*/
package ca.rmen.android.scrumchatter.chart;
/**
* Displays charts for one meeting
*/
public class MeetingChartFragment extends Fragment {
private static final String TAG = Constants.TAG + "/" + MeetingChartFragment.class.getSimpleName();
private static final int LOADER_MEMBER_SPEAKING_TIME = 0;
private MeetingChartFragmentBinding mBinding;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v(TAG, "onCreateView");
mBinding = DataBindingUtil.inflate(inflater, R.layout.meeting_chart_fragment, container, false);
return mBinding.getRoot();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(LOADER_MEMBER_SPEAKING_TIME, null, mLoaderCallbacks);
setHasOptionsMenu(true);
loadMeeting(getActivity().getIntent().getLongExtra(Meetings.EXTRA_MEETING_ID, -1));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.meeting_chart_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_share) {
ChartExportTask.export(getContext(), mBinding.memberSpeakingTimeChartContent);
return true;
}
return super.onOptionsItemSelected(item);
}
private final LoaderManager.LoaderCallbacks<Cursor> mLoaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
long meetingId = getActivity().getIntent().getLongExtra(Meetings.EXTRA_MEETING_ID, -1);
String[] projection = new String[]{
MeetingMemberColumns._ID,
MeetingMemberColumns.MEMBER_ID, | MemberColumns.NAME, | 4 |
InMobi/api-monetization | java/src/test/java/com/inmobi/monetization/ads/NativeTest.java | [
"public class Native extends AdFormat {\n\n\tprivate JSONNativeResponseParser jsonParser = new JSONNativeResponseParser();\n\n\tpublic Native() {\n\t\trequestType = AdRequest.NATIVE;\n\t}\n\t\n\tprivate ArrayList<NativeResponse> loadRequestInternal(Request request) {\n\t\terrorCode = null;\n\t\tArrayList<NativeResponse> ads = null;\n\t\trequest.setRequestType(requestType);\n\t\tString response = manager.fetchAdResponseAsString(request);\n\t\terrorCode = manager.getErrorCode();\n\t\tads = jsonParser.fetchNativeAdsFromResponse(response);\n\t\tisRequestInProgress.set(false);\n\t\tif (ads == null) {\n\t\t\terrorCode = new ErrorCode(ErrorCode.NO_FILL,\n\t\t\t\t\t\"Server returned a no-fill.\");\n\t\t} else if (ads.size() == 0) {\n\t\t\terrorCode = new ErrorCode(ErrorCode.NO_FILL,\n\t\t\t\t\t\"Server returned a no-fill.\");\n\t\t}\n\t\treturn ads;\n\t}\n\n\t/**\n\t * This function loads native ads synchronously.\n\t * \n\t * @note Please check for isRequestInProgress to false, before calling this\n\t * function.<br/>\n\t * The function returns null if the request was already in progress.\n\t * Please also provide a valid Request Object. You may check if the\n\t * IMAdRequest object is valid by calling isValid() on the object.\n\t * @return ArrayList containing the NativeResponse objects.\n\t */\n\tpublic synchronized ArrayList<NativeResponse> loadRequest(Request request) {\n\t\tArrayList<NativeResponse> ads = null;\n\t\t\n\t\tif (canLoadRequest(request,requestType) == true) {\n\t\t\tads = loadRequestInternal(request);\n\t\t}\n\t\treturn ads;\n\t}\n\n}",
"public class Slot implements Validator {\n\n\tprivate int adSize = 0;\n\tprivate String position = null;\n\n\t/**\n\t * \n\t * @return The int value corresponding to the slot size.\n\t * \n\t */\n\tpublic int getAdSize() {\n\t\treturn adSize;\n\t}\n\n\t/**\n\t * Use this setter to provide an ad-size.\n\t * \n\t * @param adSize\n\t * The integer value to represent the requested ad-size.</br>\n\t * <b>Note:</b> Must be greater than zero.\n\t */\n\tpublic void setAdSize(int adSize) {\n\t\tif (adSize > 0) {\n\t\t\tthis.adSize = adSize;\n\t\t}\n\t}\n\n\t/**\n\t * \n\t * @return Returns the String value of the position specified.\n\t */\n\tpublic String getPosition() {\n\t\treturn position;\n\t}\n\n\t/**\n\t * \n\t * @param position\n\t * The position in your app where the banner is placed.</br>\n\t * <b>Example:</b> \"top\", \"center\", \"bottom\", etc.\n\t */\n\tpublic void setPosition(String position) {\n\t\tif (!InternalUtil.isBlank(position)) {\n\t\t\tthis.position = position;\n\t\t}\n\n\t}\n\n\tpublic Slot(int adSize, String position) {\n\t\tsetAdSize(adSize);\n\t\tsetPosition(position);\n\t}\n\n\tpublic Slot() {\n\n\t}\n\n\t/**\n\t * Use this method to check if this object has all the required parameters\n\t * present, to be used to construct a JSON request. The required parameters\n\t * would be specific to an ad-format.\n\t * \n\t * @param type\n\t * The AdRequestType - one of Banner,Interstitial or Native.\n\t * @return If the mandatory params are present, then true, otherwise false.\n\t */\n\tpublic boolean isValid() {\n\t\tboolean isValid = true;\n\t\tif (adSize <= 0) {\n\t\t\tisValid = false;\n\t\t}\n\t\treturn isValid;\n\t}\n}",
"public class Device implements Validator {\n\n\tprivate String carrierIP = null;\n\tprivate String userAgent = null;\n\tprivate String gpId = null;\n\tprivate Geo geo = null;\n\n\t/**\n\t * \n\t * @return The String value containing the carrier IP.\n\t */\n\tpublic String getCarrierIP() {\n\t\treturn carrierIP;\n\t}\n\n\t/**\n\t * The String value of the carrier IP, for which the ad thus obtained would\n\t * be send.\n\t * \n\t * @param carrierIP\n\t * Must not be empty.\n\t */\n\tpublic void setCarrierIP(String carrierIP) {\n\t\tif (!InternalUtil.isBlank(carrierIP)) {\n\t\t\tthis.carrierIP = carrierIP;\n\t\t}\n\n\t}\n\n\t/**\n\t * \n\t * \n\t * @return The User-Agent value as set.\n\t */\n\tpublic String getUserAgent() {\n\t\treturn userAgent;\n\t}\n\tprotected void setUserAgent(String ua) {\n\t\tthis.userAgent = ua;\n\t}\n\t/**\n\t * \n\t * @return The Google Play Identifier as set.\n\t */\n\tpublic String getGpId() {\n\t\treturn gpId;\n\t}\n\n\t/**\n\t * \n\t * @param gpId\n\t * The Google Play Advertising Identifier, as obtained from your\n\t * device.\n\t */\n\tprotected void setGpId(String gpId) {\n\t\tif (!InternalUtil.isBlank(gpId)) {\n\t\t\tthis.gpId = gpId;\n\t\t}\n\n\t}\n\n\t/**\n\t * \n\t * @return The Geo, as set for this instance.\n\t */\n\tpublic Geo getGeo() {\n\t\treturn geo;\n\t}\n\n\t/**\n\t * \n\t * @param geo\n\t * The Geo, having the accurate geo coordinate .</br>\n\t * <p>\n\t * <b>Note:</b>\n\t * </p>\n\t * Passing the accurate values increases targeting accuracy.\n\t */\n\tpublic void setGeo(Geo geo) {\n\t\tthis.geo = geo;\n\t}\n\n\tpublic Device(String carrierIP,final Context ctx) {\n\t\tsetCarrierIP(carrierIP);\n\t\tif(ctx != null) {\n\t\t\tsetUserAgent(new WebView(ctx).getSettings().getUserAgentString());\n\t\t\t(new Thread() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tsetGpId(getIdThread(ctx));\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic String getIdThread(Context ctx) {\n\n\t\tInfo adInfo = null;\n\t\tString ID = null;\n\t\ttry {\n\t\t\tadInfo = AdvertisingIdClient.getAdvertisingIdInfo(ctx);\n\t\t\tID = adInfo.getId();\n\t\t} catch (IOException e) {\n\t\t\t// Unrecoverable error connecting to Google Play services (e.g.,\n\t\t\t// the old version of the service doesn't support getting\n\t\t\t// AdvertisingId).\n\n\t\t} catch (GooglePlayServicesNotAvailableException e) {\n\t\t\t// Google Play services is not available entirely.\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t// final String id = adInfo.getId();\n\t\t// final boolean isLAT = adInfo.isLimitAdTrackingEnabled();\n\t\treturn ID;\n\t}\n\n\t/**\n\t * Use this method to check if this Object has all the required parameters\n\t * present, to be used to construct a JSON request. The required parameters\n\t * would be specific to an ad-format.\n\t * \n\t * @return If the mandatory params are present, then true, otherwise false.\n\t */\n\tpublic boolean isValid() {\n\t\tboolean isValid = false;\n\t\tif (carrierIP != null && userAgent != null) {\n\t\t\tisValid = true;\n\t\t} else {\n\t\t\tif (carrierIP == null) {\n\t\t\t\tInternalUtil.Log(\"Carrier IP is mandatory in the request\",LogLevel.ERROR);\n\t\t\t}\n\t\t\tif (userAgent == null) {\n\t\t\t\tInternalUtil.Log(\"Valid Mobile User Agent is mandatory in the request\",LogLevel.ERROR);\n\t\t\t}\n\t\t}\n\n\t\treturn isValid;\n\t}\n}",
"public class Impression implements Validator {\n\n\tpublic static final int DEFAULT_AD_COUNT = 1;\n\tpublic static final int MAX_AD_COUNT = 3;\n\tprivate int noOfAds = DEFAULT_AD_COUNT;\n\tprivate boolean isInterstitial;\n\tprivate String displayManager = \"s_im_java\";\n\tprivate String displayManagerVersion = InternalUtil.LIB_VERSION;\n\tprivate Slot slot;\n\n\tpublic int getNoOfAds() {\n\t\treturn noOfAds;\n\t}\n\n\t/**\n\t * Sets the no. of ads, to be requested in one ad.\n\t * \n\t * @param noOfAds\n\t * Available range: [1-3]. Default value is 1.\n\t */\n\tpublic void setNoOfAds(int noOfAds) {\n\t\tif (noOfAds > 0) {\n\t\t\tif (noOfAds <= MAX_AD_COUNT) {\n\t\t\t\tthis.noOfAds = noOfAds;\n\t\t\t} else {\n\t\t\t\tthis.noOfAds = DEFAULT_AD_COUNT;\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * \n\t * @return If the impression object created is of AdRequestType.INTERSTITIAL\n\t * then true, false otherwise.\n\t */\n\tpublic boolean isInterstitial() {\n\t\treturn isInterstitial;\n\t}\n\n\t/**\n\t * \n\t * @param isInterstitial\n\t * Set this flag to true if the request is of type\n\t * AdRequestType.INTERSTITIAL. Else false otherwise.</br>\n\t * <p>\n\t * <b>Note:</b>\n\t * </p>\n\t * If you're using one of com.inmobi.monetization.ads class, this\n\t * flag can be ignored. The classes internally setup the required\n\t * flag.\n\t * \n\t */\n\tpublic void setInterstitial(boolean isInterstitial) {\n\t\tthis.isInterstitial = isInterstitial;\n\t}\n\n\t/**\n\t * \n\t * @return The display Manager String value as set.\n\t */\n\tpublic String getDisplayManager() {\n\t\treturn displayManager;\n\t}\n\n\t/**\n\t * Set the display manager string as per your request environment.</br>\n\t * <p>\n\t * Examples:\n\t * </p>\n\t * Use <i>c_</i> prefix if your request environment is native iOS/Android\n\t * client.</br> Use <i>s_</i> prefix if your request environment is from\n\t * your server side.</br> Default value is <b>s_imapi</b>.</br>\n\t * <p>\n\t * <b>Note:</b>\n\t * </p>\n\t * Must not be empty.\n\t * \n\t * @param displayManager\n\t */\n\tpublic void setDisplayManager(String displayManager) {\n\t\tif (!InternalUtil.isBlank(displayManager)) {\n\t\t\tthis.displayManager = displayManager;\n\t\t}\n\t}\n\n\t/**\n\t * \n\t * \n\t * @return Returns the String value of the display manager version.\n\t */\n\tpublic String getDisplayManagerVersion() {\n\t\treturn displayManagerVersion;\n\t}\n\n\t/**\n\t * \n\t * @param displayManagerVersion\n\t * The String version of your display manager, as per your\n\t * specification. Ex \"1.0\", \"2.2.1\", etc.\n\t */\n\tpublic void setDisplayManagerVersion(String displayManagerVersion) {\n\t\tif (!InternalUtil.isBlank(displayManagerVersion)) {\n\t\t\tthis.displayManagerVersion = displayManagerVersion;\n\t\t}\n\t}\n\n\t/**\n\t * \n\t * @return The BannerObject, associated with this ImpressionObject instance.\n\t */\n\tpublic Slot getSlot() {\n\t\treturn slot;\n\t}\n\n\t/**\n\t * \n\t * @param bannerObj\n\t * The BannerObject, associated with this instance.\n\t */\n\tpublic void setSlot(Slot slot) {\n\t\tthis.slot = slot;\n\t}\n\n\tpublic Impression(Slot slot) {\n\t\tsetSlot(slot);\n\t}\n\n\tpublic Impression() {\n\n\t}\n\n\t/**\n\t * Use this method to check if this object has all the required parameters\n\t * present, to be used to construct a JSON request. The required parameters\n\t * would be specific to an ad-format.\n\t * \n\t * @param type\n\t * The AdRequestType - one of Banner,Interstitial or Native.\n\t * @return If the mandatory params are present, then true, otherwise false.\n\t */\n\tpublic boolean isValid() {\n\t\tboolean isValid = false;\n\t\t// display manager values are optional, and have a default value\n\t\t// assigned..\n\t\t// check & return if BannerObject is valid.\n\t\tif (slot != null) {\n\t\t\tisValid = slot.isValid();\n\t\t}\n\t\treturn isValid;\n\t}\n\n}",
"public class Property implements Validator {\n\n\tprivate String propertyId = null;\n\n\t/**\n\t * \n\t * @return The String value of the Property ID, as set.\n\t */\n\tpublic String getPropertyId() {\n\t\treturn propertyId;\n\t}\n\n\t/**\n\t * \n\t * @param propertyId\n\t * The Property ID, as obtained from the InMobi UI.\n\t * <p>\n\t * <b>Note:</b>\n\t * </p>\n\t * \n\t * The Property ID is an alphanumeric String.\n\t * \n\t */\n\tpublic void setPropertyId(String propertyId) {\n\t\tif (!InternalUtil.isBlank(propertyId)) {\n\t\t\tthis.propertyId = propertyId;\n\t\t}\n\t}\n\n\t/**\n\t * \n\t * @param propertyId\n\t * Must be the alphanumeric ID as obtained from your InMobi\n\t * dashboard\n\t * @note The paramter must not be null\n\t */\n\tpublic Property(String property) {\n\t\tsetPropertyId(property);\n\t}\n\n\tpublic Property() {\n\n\t}\n\n\t/**\n\t * Use this method to check if this object has all the required parameters\n\t * present, to be used to construct a JSON request. The required parameters\n\t * would be specific to an ad-format.\n\t * \n\t * @return true, if the Property ID set is not empty. False, otherwise.\n\t */\n\tpublic boolean isValid() {\n\t\tboolean isValid = false;\n\t\tif (propertyId != null) {\n\t\t\tisValid = true;\n\t\t} else {\n\t\t\tInternalUtil.Log(\n\t\t\t\t\t\"Please provide a valid Property ID in the request.\",\n\t\t\t\t\tLogLevel.ERROR);\n\t\t}\n\t\treturn isValid;\n\t}\n}",
"public class Request implements Validator {\n\n\tprivate Impression impression;\n\tprivate User user;\n\tprivate Property property;\n\tprivate Device device;\n\tprivate AdRequest requestType = AdRequest.NONE;\n\n\t/**\n\t * \n\t * @return The Impression, as set.\n\t */\n\tpublic Impression getImpression() {\n\t\treturn impression;\n\t}\n\n\t/**\n\t * \n\t * @param impression\n\t * The impression , having the required Banner as well.\n\t */\n\tpublic void setImpression(Impression impression) {\n\t\tthis.impression = impression;\n\t}\n\n\t/**\n\t * \n\t * @return The User, as set.\n\t */\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\t/**\n\t * \n\t * @param user\n\t * The User, with the necessary demographic . This is optional.\n\t */\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\t/**\n\t * \n\t * @return The Property, as set.\n\t */\n\tpublic Property getProperty() {\n\t\treturn property;\n\t}\n\n\t/**\n\t * \n\t * @param property\n\t * sets the Property. Property must have the correct propertyId,\n\t * as obtained from InMobi.\n\t */\n\tpublic void setProperty(Property property) {\n\t\tthis.property = property;\n\t}\n\n\t/**\n\t * \n\t * @return The Device as set.\n\t */\n\tpublic Device getDevice() {\n\t\treturn device;\n\t}\n\n\t/**\n\t * \n\t * @param device\n\t * The Device with the required as obtained from the actual\n\t * device.Please make sure the mandatory (Carrier IP, User Agent)\n\t * is passed correctly. Passing the required Geo would help in\n\t * additional targeting.\n\t */\n\tpublic void setDevice(Device device) {\n\t\tthis.device = device;\n\t}\n\n\tpublic Request(Impression impression, User user, Property property,\n\t\t\tDevice device) {\n\t\tsetImpression(impression);\n\t\tsetUser(user);\n\t\tsetProperty(property);\n\t\tsetDevice(device);\n\t}\n\n\tpublic AdRequest getRequestType() {\n\t\treturn requestType;\n\t}\n\n\tpublic void setRequestType(AdRequest requestType) {\n\t\tthis.requestType = requestType;\n\t}\n\n\tpublic Request() {\n\n\t}\n\n\t/**\n\t * This method basically checks for mandatory parameters, which should not\n\t * be null, and are required in a request:<br/>\n\t * <b>InMobi Property ID:</b> should be valid String, as obtained from\n\t * InMobi, present in Property <br/>\n\t * <b>Carrier IP:</b> should be valid Mobile Country Code, present in device <br/>\n\t * <b>User Agent:</b> should be valid Mobile UA string, present in device <br/>\n\t * <b>gpID/AndroidId/IDA:</b> A valid device ID is <i>strongly\n\t * recommended.</i> Ignore the value if you're developing for Mobile Web.\n\t * \n\t * @param type\n\t * The AdRequest Type, one of Native,Banner or Interstitial\n\t * @note Passing in garbage values for any of mandatory parameters would\n\t * terminate the request from server side. UA is actually\n\t * @return\n\t */\n\tpublic boolean isValid() {\n\t\tboolean isValid = false;\n\t\tif (property != null && property.isValid()) {\n\t\t\tif (device != null && device.isValid()) {\n\n\t\t\t\tif (requestType == AdRequest.NATIVE) {\n\t\t\t\t\t// impression is not mandatory for native ads.\n\t\t\t\t\tif (user != null) {\n\t\t\t\t\t\tisValid = user.isValid();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t}\n\t\t\t\t} else if (requestType == AdRequest.BANNER\n\t\t\t\t\t\t|| requestType == AdRequest.INTERSTITIAL) {\n\t\t\t\t\tif (impression != null && impression.isValid()) {\n\n\t\t\t\t\t\tif (user != null) {\n\t\t\t\t\t\t\tisValid = user.isValid();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tInternalUtil.Log(\"Please provide a valid Impression in the request\",LogLevel.ERROR);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tInternalUtil.Log(\"Valid AdRequest enum not found.\",LogLevel.ERROR);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tInternalUtil.Log(\"Please provide a valid Device in the request\",LogLevel.ERROR);\n\t\t\t}\n\t\t} else {\n\t\t\tInternalUtil.Log(\"Please provide a valid Property in the request\",LogLevel.ERROR);\n\t\t}\n\n\t\treturn isValid;\n\t}\n\n}",
"public class NativeResponse extends AdResponse implements Validator {\n\n\t/**\n\t * The 'namespace' parameter associated with this native ad unit. Use this\n\t * String value in the client side code to trigger javascript function\n\t * callbacks in the WebView.\n\t */\n\tpublic String ns;\n\t/**\n\t * The html/javascript code, which is to be executed in a hidden WebView on\n\t * the client side. Please note that this code doesn't perform any rendering\n\t * of the Native ad itself(<i>that responsibility is yours</i>) but this\n\t * code must be used to track impression/clicks from the html/js. <br/>\n\t * <b>Refer:</b> <br/>\n\t * iOS: https://github.com/InMobi/iOS-Native-Samplecode-InMobi/ <br/>\n\t * Android: https://github.com/InMobi/android-Native-Samplecode-InMobi/ <br/>\n\t * examples to understand triggering of InMobi impression/clicks.\n\t * \n\t * @warning <b>Please do not tamper with this String, and load it as it is\n\t * on the client side. Tampering with the String to scrape out any\n\t * specific html/javascript components may result in incorrect\n\t * results on our portal, or may also lead to your site being\n\t * marked as invalid.</b>\n\t */\n\tpublic String contextCode;\n\n\t/**\n\t * The Base64 encoded String, which contains the native metadata info. This\n\t * info is the same as the \"template\" created on the InMobi dashboard,\n\t * containing the K-V pair info of fields such as \"title\", \"subtitle\",\n\t * \"icon\", \"screenshots\" etc.\n\t */\n\tpublic String pubContent;\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"{\\\"pubContent\\\"\" + \":\" + \"\\\"\" + pubContent + \"\\\"\" + \",\"\n\t\t\t\t+ \"\\\"contextCode\\\"\" + \":\" + \"\\\"\" + contextCode + \"\\\"\" + \",\"\n\t\t\t\t+ \"\\\"namespace\\\"\" + \":\" + \"\\\"\" + ns + \"\\\"\" + \"}\";\n\t}\n\n\t/**\n\t * Use this method to check if this object has all the required parameters\n\t * present. If this method returns false, the object generated after JSON\n\t * parsing would be discarded.\n\t * \n\t * @return True, If the mandatory params are present.False, otherwise.\n\t */\n\tpublic boolean isValid() {\n\t\tboolean isValid = false;\n\t\tif (!InternalUtil.isBlank(contextCode) && !InternalUtil.isBlank(ns)\n\t\t\t\t&& !InternalUtil.isBlank(pubContent)) {\n\t\t\tisValid = true;\n\t\t}\n\t\treturn isValid;\n\t}\n\n\t/**\n\t * Use this method to convert the Base64 encoded pubContent to a JsonObject.\n\t * You may use jsonObject.get(\"<key-name>\") to obtain the required metadata\n\t * value.\n\t * \n\t * @return\n\t */\n\tpublic JsonObject convertPubContentToJsonObject() {\n\t\tJsonObject jsonObject = null;\n\t\tif (pubContent != null) {\n\t\t\tbyte[] bytes = Base64.decodeBase64(pubContent);\n\t\t\tString jsonString = new String(bytes);\n\t\t\tjsonObject = (new Gson()).fromJson(jsonString,\n\t\t\t\t\tnew TypeToken<JsonObject>() {\n\t\t\t\t\t}.getType());\n\t\t}\n\n\t\treturn jsonObject;\n\t}\n\n}"
] | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import main.java.com.inmobi.monetization.ads.Native;
import main.java.com.inmobi.monetization.api.request.ad.Slot;
import main.java.com.inmobi.monetization.api.request.ad.Device;
import main.java.com.inmobi.monetization.api.request.ad.Impression;
import main.java.com.inmobi.monetization.api.request.ad.Property;
import main.java.com.inmobi.monetization.api.request.ad.Request;
import main.java.com.inmobi.monetization.api.response.ad.NativeResponse;
import org.junit.Test; | /**
* Copyright © 2015 InMobi Technologies Pte. Ltd. All rights reserved.
MIT License
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.
InMobi Monetization Library SUBCOMPONENTS:
The InMobi Monetization Library contains subcomponents with separate copyright
notices and license terms. Your use of the source code for the these
subcomponents is subject to the terms and conditions of the following
licenses.
------------------------------------------------------------------------------------------
For commons-codec & commons-lang3:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
------------------------------------------------------------------------------------------
For gson:
Copyright (c) 2008-2009 Google 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 test.java.com.inmobi.monetization.ads;
public class NativeTest {
@Test
public void test() {
Native nativeAd = new Native();
Request request = new Request();
ArrayList<NativeResponse> ads;
ads = nativeAd.loadRequest(request);
assertNull(ads);
nativeAd = new Native();
ads = nativeAd.loadRequest(request);
assertNull(ads);
ads = nativeAd.loadRequest(request);
assertNull(ads);
| Property property = null; | 4 |
LklCBPay/javasdk | src/test/java/QueryCustomAuthTest.java | [
"@Component\r\npublic class CustomAuthClient {\r\n private static final Logger logger=LoggerFactory.getLogger(CustomAuthClient.class);\r\n \r\n @Autowired\r\n private LklCrossPayRestfulClent payRestfulClent;\r\n \r\n /**\r\n * 海关认证请求\r\n * @param customAuthReq\r\n * @param dataHead\r\n * @return\r\n */\r\n public CustomAuthRes customAuth(CustomAuthReq customAuthReq,LklCrossPaySuperReq dataHead){\r\n \t CustomAuthRes customAuthRes=null;\r\n \t LklCrossPayEncryptReq req = LklMsgUtil.encryptMsg(customAuthReq, dataHead);\r\n try {\r\n LklCrossPayEncryptRes encryptRes = payRestfulClent.doPost(LklCrossPayEncryptRes.class, req, \"/gate/customAuth\");\r\n\r\n if (\"0000\".equals(encryptRes.getRetCode())) {\r\n \t customAuthRes = LklMsgUtil.decrypt(encryptRes, CustomAuthRes.class);\r\n } else {\r\n customAuthRes = new CustomAuthRes();\r\n }\r\n customAuthRes.setRetCode(encryptRes.getRetCode());\r\n customAuthRes.setRetMsg(encryptRes.getRetMsg());\r\n customAuthRes.setVer(encryptRes.getVer());\r\n customAuthRes.setPayTypeId(encryptRes.getPayTypeId());\r\n customAuthRes.setReqType(encryptRes.getReqType());\r\n customAuthRes.setTs(encryptRes.getTs());\r\n customAuthRes.setMerId(encryptRes.getMerId());\r\n } catch (Exception e) {\r\n logger.error(\"拉卡拉认证 error\", e);\r\n throw new LklClientException(e.getMessage(), e);\r\n }\r\n return customAuthRes;\r\n }\r\n \r\n /**\r\n * 根据订单号查询海关认证订单\r\n * @param customAuthQueryReq\r\n * @param dataHead\r\n * @return\r\n */\r\n public CustomAuthQueryRes queryCustomAuth(CustomAuthQueryReq customAuthQueryReq,LklCrossPaySuperReq dataHead){\r\n \tCustomAuthQueryRes customAuthQueryRes=null;\r\n \t LklCrossPayEncryptReq req = LklMsgUtil.encryptMsg(customAuthQueryReq, dataHead);\r\n try {\r\n LklCrossPayEncryptRes encryptRes = payRestfulClent.doPost(LklCrossPayEncryptRes.class, req, \"/gate/queryCustomAuth\");\r\n\r\n if (\"0000\".equals(encryptRes.getRetCode())) {\r\n \t customAuthQueryRes = LklMsgUtil.decrypt(encryptRes, CustomAuthQueryRes.class);\r\n } else {\r\n \t customAuthQueryRes = new CustomAuthQueryRes();\r\n }\r\n customAuthQueryRes.setRetCode(encryptRes.getRetCode());\r\n customAuthQueryRes.setRetMsg(encryptRes.getRetMsg());\r\n customAuthQueryRes.setVer(encryptRes.getVer());\r\n customAuthQueryRes.setPayTypeId(encryptRes.getPayTypeId());\r\n customAuthQueryRes.setReqType(encryptRes.getReqType());\r\n customAuthQueryRes.setTs(encryptRes.getTs());\r\n customAuthQueryRes.setMerId(encryptRes.getMerId());\r\n } catch (Exception e) {\r\n logger.error(\"拉卡拉认证 error\", e);\r\n throw new LklClientException(e.getMessage(), e);\r\n }\r\n return customAuthQueryRes;\r\n }\r\n}\r",
"public class LklCrossPaySuperReq implements Serializable {\n private static final long serialVersionUID = 2755358811399044775L;\n\n /**\n * 报文协议版本号,默认为1.0.0\n */\n private String ver = \"1.0.0\";\n /**\n * 商户号\n */\n private String merId;\n /**\n * 1.0.0版本报文-支付类型\n */\n private String payTypeId;\n\n /**\n * 请求业务类型\n */\n private String reqType;\n\n /**\n * 时间戳,yyyyMMddHHmmss+6位不重复随机数或序列\n */\n private String ts;\n\n public String getPayTypeId() {\n return payTypeId;\n }\n\n public void setPayTypeId(String payTypeId) {\n this.payTypeId = payTypeId;\n }\n\n public String getVer() {\n return ver;\n }\n\n public void setVer(String ver) {\n this.ver = ver;\n }\n\n public String getReqType() {\n return reqType;\n }\n\n public void setReqType(String reqType) {\n this.reqType = reqType;\n }\n\n public String getMerId() {\n return merId;\n }\n\n public void setMerId(String merId) {\n this.merId = merId;\n }\n\n public String getTs() {\n return ts;\n }\n\n public void setTs(String ts) {\n this.ts = ts;\n }\n\n @Override\n public String toString() {\n final StringBuffer sb = new StringBuffer(\"LklCrossPaySuperReq{\");\n sb.append(\"ver='\").append(ver).append('\\'');\n sb.append(\", merId='\").append(merId).append('\\'');\n sb.append(\", payTypeId='\").append(payTypeId).append('\\'');\n sb.append(\", reqType='\").append(reqType).append('\\'');\n sb.append(\", ts='\").append(ts).append('\\'');\n sb.append('}');\n return sb.toString();\n }\n}",
"public class CustomAuthQueryReq implements Serializable{\r\n\t\r\n\tprivate static final long serialVersionUID = -3395900389964247218L;\r\n\tprivate String orderNo;\r\n private String payOrderId;\r\n \r\n\tpublic String getPayOrderId() {\r\n\t\treturn payOrderId;\r\n\t}\r\n\r\n\tpublic void setPayOrderId(String payOrderId) {\r\n\t\tthis.payOrderId = payOrderId;\r\n\t}\r\n\r\n\tpublic String getOrderNo() {\r\n\t\treturn orderNo;\r\n\t}\r\n\r\n\tpublic void setOrderNo(String orderNo) {\r\n\t\tthis.orderNo = orderNo;\r\n\t}\r\n \r\n}\r",
"public class CustomAuthQueryRes extends LklCrossPaySuperRes{\r\n\r\n\tprivate static final long serialVersionUID = 1627663082608774833L;\r\n\tprivate String orderNo;\r\n\tprivate String payOrderId;\r\n\tpublic String getPayOrderId() {\r\n\t\treturn payOrderId;\r\n\t}\r\n\tpublic void setPayOrderId(String payOrderId) {\r\n\t\tthis.payOrderId = payOrderId;\r\n\t}\r\n\tprivate String status;\r\n\t\r\n\t\r\n\tpublic String getOrderNo() {\r\n\t\treturn orderNo;\r\n\t}\r\n\tpublic void setOrderNo(String orderNo) {\r\n\t\tthis.orderNo = orderNo;\r\n\t}\r\n\tpublic String getStatus() {\r\n\t\treturn status;\r\n\t}\r\n\tpublic void setStatus(String status) {\r\n\t\tthis.status = status;\r\n\t}\r\n\t\r\n\t\r\n}\r",
"public enum LklEnv {\n\n SANDBOX(\"sandbox\"),\n LIVE(\"live\");\n\n LklEnv(String env) {\n this.env = env;\n }\n\n private String env;\n\n public String getEnv() {\n return env;\n }\n\n public void setEnv(String env) {\n this.env = env;\n }\n}",
"public class LklClientException extends RuntimeException {\n\n public LklClientException(Throwable t) {\n super(t);\n }\n\n public LklClientException(String errorMessage) {\n super(errorMessage);\n }\n\n public LklClientException(String errorMessage, Throwable cause) {\n super(errorMessage, cause);\n }\n}",
"public class DateUtil {\n private static String ymdhms = \"yyyyMMddHHmmssssssss\";\n private static SimpleDateFormat yyyyMMddHHmmssssssss = new SimpleDateFormat(ymdhms);\n\n /**\n * 获得当前时间\n * 格式:yyyyMMddHHmmssssssss\n *\n * @return String\n */\n public static String getCurrentTime() {\n\n return yyyyMMddHHmmssssssss.format(new Date());\n }\n\n /**\n * 返回一个格式化的日期字符串\n *\n * @param pattern 日期格式,若为空则默认为yyyyMMdd\n * @return\n */\n public static String getCurrentDate(String pattern) {\n SimpleDateFormat datePattern = null;\n if (null == pattern || \"\".equals(pattern)) {\n datePattern = new SimpleDateFormat(\"yyyyMMdd\");\n } else {\n datePattern = new SimpleDateFormat(pattern);\n }\n return datePattern.format(new Date());\n }\n}",
"@Component\npublic class LklCrossPayEnv {\n\n @Autowired\n @Qualifier(\"yamlMap\")\n private Map<String, Object> yamlMap;\n\n private static Map<String, Object> YML_MAP;\n\n private static final Map<LklEnv, LklCrossPayClientConfig> ENV_CONFIG = new ConcurrentHashMap<LklEnv, LklCrossPayClientConfig>();\n\n @PostConstruct\n public void afterPropertiesSet() throws Exception {\n// YML_MAP = ctx.getBean(\"yamlMap\", Map.class);\n YML_MAP = (Map<String, Object>) yamlMap.get(\"yamlMap\");\n }\n\n\n /**\n * 获取当前环境的配置信息\n *\n * @return\n */\n public static LklCrossPayClientConfig getEnvConfig() {\n Iterator<Map.Entry<LklEnv, LklCrossPayClientConfig>> it = ENV_CONFIG.entrySet().iterator();\n LklCrossPayClientConfig config = null;\n if (it.hasNext()) {\n config = it.next().getValue();\n }\n return config;\n\n }\n\n /**\n * 注册拉卡拉支付平台环境,一个应用实例只能注册一个环境\n *\n * @param env 拉卡拉环境枚举 {@link LklEnv}\n * @param merId 该环境对应的商户号\n * @param privateKey 该环境对应的私钥\n * @param publicKey 该环境对应的公钥\n */\n public synchronized void registerEnv(LklEnv env, String merId, String privateKey, String publicKey) {\n String envValue = env.getEnv();\n //一个实例只允许注册一个环境\n if (!ENV_CONFIG.isEmpty()) {\n return;\n } else {\n LklCrossPayClientConfig config = new LklCrossPayClientConfig();\n Map<String, String> envObj = (LinkedHashMap<String, String>) YML_MAP.get(envValue);\n config.setPort(String.valueOf(envObj.get(\"port\")));\n config.setPrivateKey(privateKey);\n config.setPublicKey(publicKey);\n config.setServer(String.valueOf(envObj.get(\"server\")));\n config.setMerId(merId);\n ENV_CONFIG.put(env, config);\n\n }\n }\n}"
] | import org.junit.Before;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.lakala.crossborder.client.CustomAuthClient;
import com.lakala.crossborder.client.entities.LklCrossPaySuperReq;
import com.lakala.crossborder.client.entities.query.CustomAuthQueryReq;
import com.lakala.crossborder.client.entities.query.CustomAuthQueryRes;
import com.lakala.crossborder.client.enums.LklEnv;
import com.lakala.crossborder.client.exception.LklClientException;
import com.lakala.crossborder.client.util.DateUtil;
import com.lakala.crossborder.client.util.LklCrossPayEnv;
|
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:client-application.xml")
public class QueryCustomAuthTest {
private static final Logger logger=LoggerFactory.getLogger(QueryCustomAuthTest.class);
@Autowired
private LklCrossPayEnv lklCrossPayEnv;
@Autowired
private CustomAuthClient customAuthClient;
@Before
public void testSetUp() {
//注册应用环境
String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPg0O4rPQJL1O+jqJ4rBjFVNRAuDmBSoii9pYfPQBaescCVY0irkWWoLyfTT65TjvnPpOx+IfNzBTlB13qCEFm7algREoeUHjFgFNHiXJ2LK/R0+VWgXe5+EDFfbrFCPnmLKG3OcKDGQszP0VOf6VVTM1t56CpgaRMm1/+Tzd2TQIDAQAB";
String privKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIbyEihcDZbLfFhVpRU0knOtlzBhuWEjLBN4zd8dVzqAq52zWR04ybgZjjtlw+R9ICeJigmw2Dt3yy8SjpyMu5rYurTg/V0rGwayEuuE7aazi50nhZ/GYFRUVGIG0BoCI+73vsUmCO5EaUIJP/E0ew1bLMV7SMPynoQ8G9jXj8rXAgMBAAECgYAmfpFNcAz0UjGzZSMFbIzGcONrCsV9/zGIkHJxzgXfC2tpPgsSuetZF/kp2nrKCCOPA74by5WzSRXt5KZH5CFzuwwqIBv5cn6AiKiVmro3AnHV+qqNtfGXwLottu0VYcBEY2IPKb7SQ4pP5I0H973hnxR4qRzMAMUmEBVMiuUR+QJBAObLUBTjd7AE4Sls3/vBsYsYLYFfmw/dRHaW6jnuNxPTfVtPTGjY3V/672Vs01/f6QdtHHpMN+2xUk+acErAJTUCQQCVrvakm5R2sQwPycSO4mZW5sHKGbBosAkcY4llISVtxzSjgkPtBPVukCdNSGTuJX7+Ci8KolilrCc2XQCkH21bAkEAlcUAXd3TEL3J5BkMLRLgBTSWaytAtAXR5OdAboGA6nPHGJcYLb31wtBTxEzfyorCbRhIb7DAZpY4pQHCty+DtQJATFwCdPztYxN03MUIof+7R4/WwpwSU4WiUDozCEU9i+A46UT2E/8YmbuuYQ2Sd67nNv/I+brSUEofgus0/YUOywJBAMPu5o9guMsAjVqvXuxbkFpblYGZO/BrwiuLGDWEj4DZFqrIDmqgA6edy3HSoZ7U69BJZLTPb9DeebEiebmJZUI=";
lklCrossPayEnv.registerEnv(LklEnv.SANDBOX, "RZCP161200000", privKey, pubKey);
}
@org.junit.Test
public void testQueryCustomAuth() {
CustomAuthQueryReq queryCustomAuthReq = new CustomAuthQueryReq();
queryCustomAuthReq.setOrderNo("SH20170511175909");
queryCustomAuthReq.setPayOrderId("20170511175909");
LklCrossPaySuperReq head = new LklCrossPaySuperReq();
head.setVer("3.0.0");
head.setTs(DateUtil.getCurrentTime());
head.setMerId(LklCrossPayEnv.getEnvConfig().getMerId());
try {
CustomAuthQueryRes customAuthQueryRes = customAuthClient.queryCustomAuth(queryCustomAuthReq, head);
logger.info("海关认证订单查询结果结果{},msg={}", new String[]{customAuthQueryRes.getRetCode(), customAuthQueryRes.getRetMsg()});
logger.info("海关受理结果:"+customAuthQueryRes.getStatus());
| } catch (LklClientException e) {
| 5 |
Fedict/commons-eid | commons-eid-tests/src/test/java/be/bosa/commons/eid/client/tests/integration/LocaleTest.java | [
"public class BeIDCard implements AutoCloseable {\n\n\tprivate static final String UI_MISSING_LOG_MESSAGE = \"No BeIDCardUI set and can't load DefaultBeIDCardUI\";\n\tprivate static final String UI_DEFAULT_REQUIRES_HEAD = \"No BeIDCardUI set and DefaultBeIDCardUI requires a graphical environment\";\n\tprivate static final String DEFAULT_UI_IMPLEMENTATION = \"be.bosa.commons.eid.dialogs.DefaultBeIDCardUI\";\n\n\tprivate static final byte[] BELPIC_AID = new byte[]{(byte) 0xA0, 0x00, 0x00, 0x01, 0x77, 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35,};\n\tprivate static final byte[] APPLET_AID = new byte[]{(byte) 0xA0, 0x00, 0x00, 0x00, 0x30, 0x29, 0x05, 0x70, 0x00, (byte) 0xAD, 0x13, 0x10, 0x01, 0x01, (byte) 0xFF,};\n\tprivate static final int BLOCK_SIZE = 0xff;\n\n\tprivate final CardChannel cardChannel;\n\tprivate final List<BeIDCardListener> cardListeners;\n\tprivate final CertificateFactory certificateFactory;\n\n\tprivate final Card card;\n\tprivate final CardTerminal cardTerminal;\n\tprivate final Logger logger;\n\n\tprivate CCID ccid;\n\tprivate BeIDCardUI ui;\n\tprivate Locale locale;\n\n\tprivate Thread exclusiveAccessThread;\n\n\t/**\n\t * Instantiate a BeIDCard from an already connected javax.smartcardio.Card,\n\t * with a Logger implementation to receive logging output.\n\t *\n\t * @param card a javax.smartcardio.Card that you have previously determined\n\t * to be a BeID Card\n\t * @param logger the logger instance\n\t * @throws IllegalArgumentException when passed a null logger. to disable logging, call\n\t * BeIDCard(Card) instead.\n\t * @throws RuntimeException when no CertificateFactory capable of producing X509\n\t * Certificates is available.\n\t */\n\tpublic BeIDCard(CardTerminal cardTerminal, Card card, Logger logger) {\n\t\tif (logger == null) {\n\t\t\tthrow new IllegalArgumentException(\"logger expected\");\n\t\t}\n\n\t\tthis.cardTerminal = cardTerminal;\n\t\tthis.card = card;\n\t\tthis.logger = logger;\n\n\t\tthis.cardChannel = card.getBasicChannel();\n\t\tthis.cardListeners = new LinkedList<>();\n\n\t\ttry {\n\t\t\tthis.certificateFactory = CertificateFactory.getInstance(\"X.509\");\n\t\t} catch (CertificateException e) {\n\t\t\tthrow new RuntimeException(\"X.509 algo\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Instantiate a BeIDCard from an already connected javax.smartcardio.Card\n\t * no logging information will be available.\n\t *\n\t * @param card a javax.smartcardio.Card that you have previously determined\n\t * to be a BeID Card\n\t * @throws RuntimeException when no CertificateFactory capable of producing X509\n\t * Certificates is available.\n\t */\n\tpublic BeIDCard(CardTerminal cardTerminal, Card card) {\n\t\tthis(cardTerminal, card, new VoidLogger());\n\t}\n\n\t/**\n\t * Instantiate a BeIDCard from a javax.smartcardio.CardTerminal, with a\n\t * Logger implementation to receive logging output.\n\t *\n\t * @param cardTerminal a javax.smartcardio.CardTerminal that you have previously\n\t * determined to contain a BeID Card\n\t * @param logger the logger instance\n\t * @throws IllegalArgumentException when passed a null logger. to disable logging, call public\n\t * BeIDCard(CardTerminal) instead.\n\t * @throws RuntimeException when no CertificateFactory capable of producing X509\n\t * Certificates is available.\n\t */\n\tpublic BeIDCard(CardTerminal cardTerminal, Logger logger) throws BeIDException {\n\t\tthis(cardTerminal, connect(cardTerminal), logger);\n\t}\n\n\tprivate static Card connect(CardTerminal cardTerminal) throws BeIDException {\n\t\ttry {\n\t\t\treturn cardTerminal.connect(\"T=0\");\n\t\t} catch (CardException e) {\n\t\t\tthrow new BeIDException(e);\n\t\t}\n\t}\n\n\t/**\n\t * close this BeIDCard, when you are done with it, to release any underlying\n\t * resources. All subsequent calls will fail.\n\t */\n\tpublic void close() {\n\t\tlogger.debug(\"closing eID card\");\n\n\t\ttry {\n\t\t\tcard.disconnect(true);\n\t\t} catch (CardException e) {\n\t\t\tlogger.error(\"could not disconnect the card: \" + e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Explicitly set the User Interface to be used for consequent operations.\n\t * All user interaction is handled through this, and possible SPR features\n\t * of CCID-capable CardReaders. This will also modify the Locale setting of\n\t * this beIDCard instance to match the UI's Locale, so the language in any\n\t * SPR messages displayed will be consistent with the UI's language.\n\t *\n\t * @param userInterface an instance of BeIDCardUI\n\t */\n\tpublic void setUI(BeIDCardUI userInterface) {\n\t\tui = userInterface;\n\t\tif (locale == null) {\n\t\t\tsetLocale(userInterface.getLocale());\n\t\t}\n\t}\n\n\t/**\n\t * Register a BeIDCardListener to receive updates on any consequent file\n\t * reading/signature operations executed by this BeIDCard.\n\t *\n\t * @param beIDCardListener a beIDCardListener instance\n\t */\n\tpublic void addCardListener(BeIDCardListener beIDCardListener) {\n\t\tsynchronized (cardListeners) {\n\t\t\tcardListeners.add(beIDCardListener);\n\t\t}\n\t}\n\n\t/**\n\t * Unregister a BeIDCardListener to no longer receive updates on any\n\t * consequent file reading/signature operations executed by this BeIDCard.\n\t *\n\t * @param beIDCardListener a beIDCardListener instance\n\t */\n\tpublic void removeCardListener(BeIDCardListener beIDCardListener) {\n\t\tsynchronized (cardListeners) {\n\t\t\tcardListeners.remove(beIDCardListener);\n\t\t}\n\t}\n\n\t/**\n\t * Reads a certain certificate from the card. Which certificate to read is\n\t * determined by the FileType param. Applicable FileTypes are\n\t * AuthentificationCertificate, NonRepudiationCertificate, CACertificate,\n\t * RootCertificate and RRNCertificate.\n\t *\n\t * @return the certificate requested\n\t */\n\tpublic X509Certificate getCertificate(FileType fileType) throws BeIDException, InterruptedException {\n\t\treturn generateCertificateOfType(fileType);\n\t}\n\n\t/**\n\t * Returns the X509 authentication certificate. This is a convenience method\n\t * for <code>getCertificate(FileType.AuthentificationCertificate)</code>\n\t *\n\t * @return the X509 Authentication Certificate from the card.\n\t */\n\tpublic X509Certificate getAuthenticationCertificate() throws BeIDException, InterruptedException {\n\t\treturn getCertificate(FileType.AuthentificationCertificate);\n\t}\n\n\t/**\n\t * Returns the X509 non-repudiation certificate. This is a convencience\n\t * method for\n\t * <code>getCertificate(FileType.NonRepudiationCertificate)</code>\n\t */\n\tpublic X509Certificate getSigningCertificate() throws BeIDException, InterruptedException {\n\t\treturn getCertificate(FileType.NonRepudiationCertificate);\n\t}\n\n\t/**\n\t * Returns the citizen CA certificate. This is a convenience method for\n\t * <code>getCertificate(FileType.CACertificate)</code>\n\t */\n\tpublic X509Certificate getCACertificate() throws BeIDException, InterruptedException {\n\t\treturn getCertificate(FileType.CACertificate);\n\t}\n\n\t/**\n\t * Returns the Root CA certificate.\n\t *\n\t * @return the Root CA X509 certificate.\n\t */\n\tpublic X509Certificate getRootCACertificate() throws BeIDException, InterruptedException {\n\t\treturn getCertificate(FileType.RootCertificate);\n\t}\n\n\t/**\n\t * Returns the national registration certificate. This is a convencience\n\t * method for <code>getCertificate(FileType.RRNCertificate)</code>\n\t */\n\tpublic X509Certificate getRRNCertificate() throws BeIDException, InterruptedException {\n\t\treturn getCertificate(FileType.RRNCertificate);\n\t}\n\n\t/**\n\t * Returns the entire certificate chain for a given file type. Of course,\n\t * only file types corresponding with a certificate are accepted. Which\n\t * certificate's chain to return is determined by the FileType param.\n\t * Applicable FileTypes are AuthentificationCertificate,\n\t * NonRepudiationCertificate, CACertificate, and RRNCertificate.\n\t *\n\t * @param fileType which certificate's chain to return\n\t * @return the certificate's chain up to and including the Belgian Root Cert\n\t */\n\tpublic List<X509Certificate> getCertificateChain(FileType fileType) throws BeIDException, InterruptedException {\n\t\tList<X509Certificate> chain = new LinkedList<>();\n\t\tchain.add(generateCertificateOfType(fileType));\n\t\tif (fileType.chainIncludesCitizenCA()) {\n\t\t\tchain.add(generateCertificateOfType(FileType.CACertificate));\n\t\t}\n\t\tchain.add(generateCertificateOfType(FileType.RootCertificate));\n\n\t\treturn chain;\n\t}\n\n\t/**\n\t * Returns the X509 authentication certificate chain. (Authentication -\n\t * Citizen CA - Root) This is a convenience method for\n\t * <code>getCertificateChain(FileType.AuthentificationCertificate)</code>\n\t *\n\t * @return the authentication certificate chain\n\t */\n\tpublic List<X509Certificate> getAuthenticationCertificateChain() throws BeIDException, InterruptedException {\n\t\treturn getCertificateChain(FileType.AuthentificationCertificate);\n\t}\n\n\t/**\n\t * Returns the X509 non-repudiation certificate chain. (Non-Repudiation -\n\t * Citizen CA - Root) This is a convenience method for\n\t * <code>getCertificateChain(FileType.NonRepudiationCertificate)</code>\n\t *\n\t * @return the non-repudiation certificate chain\n\t */\n\tpublic List<X509Certificate> getSigningCertificateChain() throws BeIDException, InterruptedException {\n\t\treturn getCertificateChain(FileType.NonRepudiationCertificate);\n\t}\n\n\t/**\n\t * Returns the Citizen CA X509 certificate chain. (Citizen CA - Root) This\n\t * is a convenience method for\n\t * <code>getCertificateChain(FileType.CACertificate)</code>\n\t *\n\t * @return the citizen ca certificate chain\n\t */\n\tpublic List<X509Certificate> getCACertificateChain() throws BeIDException, InterruptedException {\n\t\treturn getCertificateChain(FileType.CACertificate);\n\t}\n\n\t/**\n\t * Returns the national registry X509 certificate chain. (National Registry\n\t * - Root) This is a convenience method for\n\t * <code>getCertificateChain(FileType.RRNCertificate)</code>\n\t *\n\t * @return the national registry certificate chain\n\t */\n\tpublic List<X509Certificate> getRRNCertificateChain() throws BeIDException, InterruptedException {\n\t\treturn getCertificateChain(FileType.RRNCertificate);\n\t}\n\n\t/**\n\t * Create an authentication signature.\n\t *\n\t * @param toBeSigned the data to be signed\n\t * @param requireSecureReader whether to require a secure pinpad reader to obtain the\n\t * citizen's PIN if false, the current BeIDCardUI will be used in\n\t * the absence of a secure pinpad reader. If true, an exception\n\t * will be thrown unless a SPR is available\n\t * @return a SHA-256 digest of the input data signed by the citizen's authentication key\n\t */\n\tpublic byte[] signAuthn(byte[] toBeSigned, boolean requireSecureReader) throws GeneralSecurityException, BeIDException, InterruptedException, CancelledException {\n\t\tMessageDigest messageDigest = BeIDDigest.SHA_256.getMessageDigestInstance();\n\t\tbyte[] digest = messageDigest.digest(toBeSigned);\n\t\treturn sign(digest, BeIDDigest.SHA_256, FileType.AuthentificationCertificate, requireSecureReader);\n\t}\n\n\t/**\n\t * Sign a given digest value.\n\t *\n\t * @param digestValue the digest value to be signed.\n\t * @param digestAlgo the algorithm used to calculate the given digest value.\n\t * @param fileType the certificate's file type.\n\t * @param requireSecureReader <code>true</code> if a secure pinpad reader is required.\n\t */\n\tpublic byte[] sign(byte[] digestValue, BeIDDigest digestAlgo, FileType fileType, boolean requireSecureReader) throws BeIDException, InterruptedException, CancelledException {\n\t\tif (!fileType.isCertificateUserCanSignWith()) {\n\t\t\tthrow new IllegalArgumentException(\"Not a certificate that can be used for signing: \" + fileType.name());\n\t\t}\n\n\t\tif (getCCID().hasFeature(CCID.FEATURE.EID_PIN_PAD_READER)) {\n\t\t\tlogger.debug(\"eID-aware secure PIN pad reader detected\");\n\t\t}\n\n\t\tif (requireSecureReader\n\t\t\t\t&& (!getCCID().hasFeature(CCID.FEATURE.VERIFY_PIN_DIRECT))\n\t\t\t\t&& (getCCID().hasFeature(CCID.FEATURE.VERIFY_PIN_START))) {\n\t\t\tthrow new SecurityException(\"not a secure reader\");\n\t\t}\n\n\t\ttry {\n\t\t\tbeginExclusive();\n\t\t\tnotifySigningBegin(fileType);\n\n\t\t\ttry {\n\t\t\t\t// select the key\n\t\t\t\tlogger.debug(\"selecting key...\");\n\n\t\t\t\tResponseAPDU responseApdu = transmitCommand(\n\t\t\t\t\t\tBeIDCommandAPDU.SELECT_ALGORITHM_AND_PRIVATE_KEY,\n\t\t\t\t\t\tnew byte[]{(byte) 0x04, // length of following data\n\t\t\t\t\t\t\t\t(byte) 0x80, digestAlgo.getAlgorithmReference(), // algorithm reference\n\t\t\t\t\t\t\t\t(byte) 0x84, fileType.getKeyId(),}); // private key reference\n\n\t\t\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\t\t\tthrow new ResponseAPDUException(\"SET (select algorithm and private key) error\", responseApdu);\n\t\t\t\t}\n\n\t\t\t\tif (FileType.NonRepudiationCertificate.getKeyId() == fileType.getKeyId()) {\n\t\t\t\t\tlogger.debug(\"non-repudiation key detected, immediate PIN verify\");\n\t\t\t\t\tverifyPin(PINPurpose.NonRepudiationSignature);\n\t\t\t\t}\n\n\t\t\t\tByteArrayOutputStream digestInfo = new ByteArrayOutputStream();\n\t\t\t\tdigestInfo.write(digestAlgo.getPrefix(digestValue.length));\n\t\t\t\tdigestInfo.write(digestValue);\n\n\t\t\t\tlogger.debug(\"computing digital signature...\");\n\t\t\t\tresponseApdu = transmitCommand(BeIDCommandAPDU.COMPUTE_DIGITAL_SIGNATURE, digestInfo.toByteArray());\n\t\t\t\tif (0x9000 == responseApdu.getSW()) {\n\t\t\t\t\t/*\n\t\t\t\t\t * OK, we could use the card PIN caching feature.\n\t\t\t\t\t *\n\t\t\t\t\t * Notice that the card PIN caching also works when first doing\n\t\t\t\t\t * an authentication after a non-repudiation signature.\n\t\t\t\t\t */\n\t\t\t\t\treturn responseApdu.getData();\n\t\t\t\t}\n\t\t\t\tif (0x6982 != responseApdu.getSW()) {\n\t\t\t\t\tlogger.debug(\"SW: \" + Integer.toHexString(responseApdu.getSW()));\n\t\t\t\t\tthrow new ResponseAPDUException(\"compute digital signature error\", responseApdu);\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * 0x6982 = Security status not satisfied, so we do a PIN\n\t\t\t\t * verification before retrying.\n\t\t\t\t */\n\t\t\t\tlogger.debug(\"PIN verification required...\");\n\t\t\t\tverifyPin(PINPurpose.fromFileType(fileType));\n\n\t\t\t\tlogger.debug(\"computing digital signature (attempt #2 after PIN verification)...\");\n\t\t\t\tresponseApdu = transmitCommand(BeIDCommandAPDU.COMPUTE_DIGITAL_SIGNATURE, digestInfo.toByteArray());\n\t\t\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\t\t\tthrow new ResponseAPDUException(\"compute digital signature error\", responseApdu);\n\t\t\t\t}\n\n\t\t\t\treturn responseApdu.getData();\n\t\t\t} finally {\n\t\t\t\tendExclusive();\n\t\t\t\tnotifySigningEnd(fileType);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new BeIDException(\"Cannot sign\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Verifying PIN Code (without other actions, for testing PIN), using the\n\t * most secure method available. Note that this still has the side effect of\n\t * loading a successfully tests PIN into the PIN cache, so that unless the\n\t * card is removed, a subsequent authentication attempt will not request the\n\t * PIN, but proceed with the PIN given here.\n\t */\n\tpublic void verifyPin() throws BeIDException, InterruptedException, CancelledException {\n\t\tverifyPin(PINPurpose.PINTest);\n\t}\n\n\t/**\n\t * Change PIN code. This method will attempt to change PIN using the most\n\t * secure method available. if requiresSecureReader is true, this will throw\n\t * a SecurityException if no SPR is available, otherwise, this will default\n\t * to changing the PIN via the UI\n\t */\n\tpublic void changePin(boolean requireSecureReader) throws BeIDException, InterruptedException {\n\t\tif (requireSecureReader\n\t\t\t\t&& (!getCCID().hasFeature(CCID.FEATURE.MODIFY_PIN_DIRECT))\n\t\t\t\t&& (!getCCID().hasFeature(CCID.FEATURE.MODIFY_PIN_START))) {\n\t\t\tthrow new SecurityException(\"not a secure reader\");\n\t\t}\n\n\t\tint retriesLeft = -1;\n\t\tResponseAPDU responseApdu;\n\t\tdo {\n\t\t\tif (getCCID().hasFeature(CCID.FEATURE.MODIFY_PIN_START)) {\n\t\t\t\tlogger.debug(\"using modify pin start/finish...\");\n\t\t\t\tresponseApdu = changePINViaCCIDStartFinish(retriesLeft);\n\t\t\t} else if (getCCID().hasFeature(CCID.FEATURE.MODIFY_PIN_DIRECT)) {\n\t\t\t\tlogger.debug(\"could use direct PIN modify here...\");\n\t\t\t\tresponseApdu = changePINViaCCIDDirect(retriesLeft);\n\t\t\t} else {\n\t\t\t\tresponseApdu = changePINViaUI(retriesLeft);\n\t\t\t}\n\n\t\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\t\tlogger.debug(\"CHANGE PIN error\");\n\t\t\t\tlogger.debug(\"SW: \" + Integer.toHexString(responseApdu.getSW()));\n\t\t\t\tif (0x6983 == responseApdu.getSW()) {\n\t\t\t\t\tgetUI().advisePINBlocked();\n\t\t\t\t\tthrow new ResponseAPDUException(\"eID card blocked!\", responseApdu);\n\t\t\t\t}\n\t\t\t\tif (0x63 != responseApdu.getSW1()) {\n\t\t\t\t\tlogger.debug(\"PIN change error. Card blocked?\");\n\t\t\t\t\tthrow new ResponseAPDUException(\"PIN Change Error\", responseApdu);\n\t\t\t\t}\n\t\t\t\tretriesLeft = responseApdu.getSW2() & 0xf;\n\t\t\t\tlogger.debug(\"retries left: \" + retriesLeft);\n\t\t\t}\n\t\t} while (0x9000 != responseApdu.getSW());\n\n\t\tgetUI().advisePINChanged();\n\t}\n\n\t/**\n\t * Returns random data generated by the eID card itself.\n\t *\n\t * @param size the size of the requested random data.\n\t * @return size bytes of random data\n\t */\n\tpublic byte[] getChallenge(int size) throws BeIDException, InterruptedException {\n\t\tResponseAPDU responseApdu = transmitCommand(BeIDCommandAPDU.GET_CHALLENGE, new byte[]{}, 0, 0, size);\n\n\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\tlogger.debug(\"get challenge failure: \" + Integer.toHexString(responseApdu.getSW()));\n\t\t\tthrow new ResponseAPDUException(\"get challenge failure: \" + Integer.toHexString(responseApdu.getSW()), responseApdu);\n\t\t}\n\t\tif (size != responseApdu.getData().length) {\n\t\t\tthrow new IllegalArgumentException(\"challenge size incorrect: \" + responseApdu.getData().length);\n\t\t}\n\n\t\treturn responseApdu.getData();\n\t}\n\n\t/**\n\t * Create a text message transaction signature. The BOSA eID aware secure\n\t * pinpad readers can visualize such type of text message transactions on\n\t * their hardware display.\n\t *\n\t * @param transactionMessage the transaction message to be signed.\n\t */\n\tpublic byte[] signTransactionMessage(String transactionMessage, boolean requireSecureReader) throws BeIDException, InterruptedException, CancelledException {\n\t\tif (getCCID().hasFeature(CCID.FEATURE.EID_PIN_PAD_READER)) {\n\t\t\tgetUI().adviseSecureReaderOperation();\n\t\t}\n\n\t\tbyte[] signature;\n\t\ttry {\n\t\t\tsignature = sign(\n\t\t\t\t\ttransactionMessage.getBytes(), BeIDDigest.PLAIN_TEXT,\n\t\t\t\t\tFileType.AuthentificationCertificate, requireSecureReader\n\t\t\t);\n\t\t} finally {\n\t\t\tif (getCCID().hasFeature(CCID.FEATURE.EID_PIN_PAD_READER)) {\n\t\t\t\tgetUI().adviseSecureReaderOperationEnd();\n\t\t\t}\n\t\t}\n\t\treturn signature;\n\t}\n\n\t/**\n\t * Discard the citizen's PIN code from the PIN cache. Any subsequent\n\t * Authentication signatures will require PIN entry. (non-repudation\n\t * signatures are automatically protected)\n\t */\n\tpublic void logoff() throws BeIDException, InterruptedException {\n\t\tCommandAPDU logoffApdu = new CommandAPDU(0x80, 0xE6, 0x00, 0x00);\n\t\tlogger.debug(\"logoff...\");\n\t\tResponseAPDU responseApdu = transmit(logoffApdu);\n\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\tthrow new RuntimeException(\"logoff failed\");\n\t\t}\n\t}\n\n\t/**\n\t * Unblocking PIN using PUKs. This will choose the most secure method\n\t * available to unblock a blocked PIN. If requireSecureReader is true, will\n\t * throw SecurityException if an SPR is not available\n\t */\n\tpublic void unblockPin(boolean requireSecureReader) throws BeIDException, InterruptedException {\n\t\tif (requireSecureReader && (!getCCID().hasFeature(CCID.FEATURE.VERIFY_PIN_DIRECT))) {\n\t\t\tthrow new SecurityException(\"Not a secure reader\");\n\t\t}\n\n\t\tResponseAPDU responseApdu;\n\t\tint retriesLeft = -1;\n\t\tdo {\n\t\t\tif (getCCID().hasFeature(CCID.FEATURE.VERIFY_PIN_DIRECT)) {\n\t\t\t\tlogger.debug(\"could use direct PIN verify here...\");\n\t\t\t\tresponseApdu = unblockPINViaCCIDVerifyPINDirectOfPUK(retriesLeft);\n\t\t\t} else {\n\t\t\t\tresponseApdu = unblockPINViaUI(retriesLeft);\n\t\t\t}\n\n\t\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\t\tlogger.debug(\"PIN unblock error\");\n\t\t\t\tlogger.debug(\"SW: \" + Integer.toHexString(responseApdu.getSW()));\n\t\t\t\tif (0x6983 == responseApdu.getSW()) {\n\t\t\t\t\tgetUI().advisePINBlocked();\n\t\t\t\t\tthrow new ResponseAPDUException(\"eID card blocked!\", responseApdu);\n\t\t\t\t}\n\t\t\t\tif (0x63 != responseApdu.getSW1()) {\n\t\t\t\t\tlogger.debug(\"PIN unblock error.\");\n\t\t\t\t\tthrow new ResponseAPDUException(\"PIN unblock error\", responseApdu);\n\t\t\t\t}\n\t\t\t\tretriesLeft = responseApdu.getSW2() & 0xf;\n\t\t\t\tlogger.debug(\"retries left: \" + retriesLeft);\n\t\t\t}\n\t\t} while (0x9000 != responseApdu.getSW());\n\n\t\tgetUI().advisePINUnblocked();\n\t}\n\n\t/**\n\t * getATR returns the ATR of the eID Card. If this BeIDCard instance was\n\t * constructed using the CardReader constructor, this is the only way to get\n\t * to the ATR.\n\t */\n\tpublic ATR getATR() {\n\t\treturn card.getATR();\n\t}\n\n\t/**\n\t * @return the current Locale used in CCID SPR operations and UI\n\t */\n\tpublic Locale getLocale() {\n\t\tif (locale != null) {\n\t\t\treturn locale;\n\t\t}\n\t\treturn LocaleManager.getLocale();\n\t}\n\n\t/**\n\t * set the Locale to use for subsequent UI and CCID operations. this will\n\t * modify the Locale of any explicitly set UI, as well. BeIDCard instances,\n\t * while using the global Locale settings made in BeIDCards and/or\n\t * BeIDCardManager by default, may have their own individual Locale settings\n\t * that may override those global settings.\n\t */\n\tpublic void setLocale(Locale newLocale) {\n\t\tlocale = newLocale;\n\t\tif (locale != null && ui != null) {\n\t\t\tui.setLocale(locale);\n\t\t}\n\t}\n\n\t// ===========================================================================================================\n\t// low-level card operations\n\t// not recommended for general use.\n\t// if you find yourself having to call these, we'd very much like to hear\n\t// about it.\n\t// ===========================================================================================================\n\n\t/**\n\t * Select the BELPIC applet on the chip. Since the BELPIC applet is supposed\n\t * to be all alone on the chip, shouldn't be necessary.\n\t */\n\tpublic void selectApplet() throws InterruptedException, BeIDException {\n\t\tResponseAPDU responseApdu;\n\n\t\tresponseApdu = transmitCommand(BeIDCommandAPDU.SELECT_APPLET, BELPIC_AID);\n\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\tlogger.error(\"error selecting BELPIC applet\");\n\t\t\tlogger.debug(\"status word: \" + Integer.toHexString(responseApdu.getSW()));\n\t\t} else {\n\t\t\tlogger.debug(\"BELPIC JavaCard applet selected by BELPIC_AID\");\n\t\t}\n\t}\n\n\t/**\n\t * Begin an exclusive transaction with the card. Once this returns, only the\n\t * calling thread will be able to access the card, until it calls\n\t * endExclusive(). Other threads will receive a CardException. Use this when\n\t * you need to make several calls to the card that depend on each other. for\n\t * example, SELECT FILE and READ BINARY, or SELECT ALGORITHM and COMPUTE\n\t * SIGNATURE, to avoid other threads/processes from interleaving commands\n\t * that would break your transactional logic.\n\t * <p>\n\t * Called automatically by the higher-level methods in this class. If you\n\t * end up calling this directly, this is either something wrong with your\n\t * code, or with this class. Please let us know. You should really only have\n\t * to be calling this when using some of the other low-level methods\n\t * (transmitCommand, etc..) *never* in combination with the high-level\n\t * methods.\n\t */\n\tpublic void beginExclusive() throws BeIDException {\n\t\tif (exclusiveAccessThread != null)\n\t\t\tthrow new IllegalStateException(\"Exclusive access already granted to \" + exclusiveAccessThread.getName());\n\n\t\tlogger.debug(\"---begin exclusive---\");\n\t\ttry {\n\t\t\tcard.beginExclusive();\n\t\t\texclusiveAccessThread = Thread.currentThread();\n\t\t} catch (CardException e) {\n\t\t\tthrow new BeIDException(\"Cannot begin exclusive\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Checks if current thread has exclusive access.\n\t */\n\tpublic boolean hasExclusive() {\n\t\treturn exclusiveAccessThread == Thread.currentThread();\n\t}\n\n\t/**\n\t * Release an exclusive transaction with the card, started by\n\t * beginExclusive().\n\t */\n\tpublic void endExclusive() throws BeIDException {\n\t\tif (Thread.currentThread() != exclusiveAccessThread) return;\n\n\t\tlogger.debug(\"---end exclusive---\");\n\t\ttry {\n\t\t\texclusiveAccessThread = null;\n\t\t\tcard.endExclusive();\n\t\t} catch (CardException e) {\n\t\t\tthrow new BeIDException(\"Cannot begin exclusive\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Read bytes from a previously selected \"File\" on the card. should be\n\t * preceded by a call to selectFile so the card knows what you want to read.\n\t * Consider using one of the higher-level methods, or readFile().\n\t *\n\t * @param fileType the file to read (to allow for notification)\n\t * @param estimatedMaxSize the estimated total size of the file to read (to allow for\n\t * notification)\n\t * @return the data from the file\n\t */\n\tpublic byte[] readBinary(FileType fileType, int estimatedMaxSize) throws BeIDException, InterruptedException {\n\t\tint offset = 0;\n\t\tlogger.debug(\"read binary\");\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\t\tbyte[] data;\n\t\tdo {\n\t\t\tif (Thread.currentThread().isInterrupted()) {\n\t\t\t\tlogger.debug(\"interrupted in readBinary\");\n\t\t\t\tthrow new InterruptedException();\n\t\t\t}\n\n\t\t\tnotifyReadProgress(fileType, offset, estimatedMaxSize);\n\t\t\tResponseAPDU responseApdu = transmitCommand(\n\t\t\t\t\tBeIDCommandAPDU.READ_BINARY, offset >> 8, offset & 0xFF,\n\t\t\t\t\tBLOCK_SIZE);\n\t\t\tint sw = responseApdu.getSW();\n\t\t\tif (0x6B00 == sw) {\n\t\t\t\t/*\n\t\t\t\t * Wrong parameters (offset outside the EF) End of file reached.\n\t\t\t\t * Can happen in case the file size is a multiple of 0xff bytes.\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (0x9000 != sw) {\n\t\t\t\tthrow new BeIDException(\"BeIDCommandAPDU response error: \" + responseApdu.getSW(), new ResponseAPDUException(responseApdu));\n\t\t\t}\n\n\t\t\tdata = responseApdu.getData();\n\t\t\ttry {\n\t\t\t\tbaos.write(data);\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new RuntimeException(e); // should not happen\n\t\t\t}\n\t\t\toffset += data.length;\n\t\t} while (BLOCK_SIZE == data.length);\n\n\t\tnotifyReadProgress(fileType, offset, offset);\n\t\treturn baos.toByteArray();\n\t}\n\n\t/**\n\t * Selects a file to read on the card\n\t *\n\t * @param fileId the file to read\n\t */\n\tpublic void selectFile(byte[] fileId) throws BeIDException, InterruptedException {\n\t\tlogger.debug(\"selecting file\");\n\n\t\tResponseAPDU responseApdu = transmitCommand(BeIDCommandAPDU.SELECT_FILE, fileId);\n\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\tthrow new BeIDException(\"Wrong status word after selecting file: \" + Integer.toHexString(responseApdu.getSW()));\n\t\t}\n\n\t\ttry {\n\t\t\t// SCARD_E_SHARING_VIOLATION fix\n\t\t\tThread.sleep(20);\n\t\t} catch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(\"sleep error: \" + e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Reads a file and converts it to a certificagte.\n\t */\n\tprivate X509Certificate generateCertificateOfType(FileType fileType) throws BeIDException, InterruptedException {\n\t\tByteArrayInputStream certificateInputStream = new ByteArrayInputStream(readFile(fileType));\n\t\ttry {\n\t\t\treturn (X509Certificate) certificateFactory.generateCertificate(certificateInputStream);\n\t\t} catch (CertificateException e) {\n\t\t\tthrow new BeIDException(\"Invalid certificate\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Reads a file from the card.\n\t *\n\t * @param fileType the file to read\n\t * @return the data from the file\n\t */\n\tpublic byte[] readFile(FileType fileType) throws BeIDException, InterruptedException {\n\t\tbeginExclusive();\n\n\t\ttry {\n\t\t\tselectFile(fileType.getFileId());\n\t\t\treturn readBinary(fileType, fileType.getEstimatedMaxSize());\n\t\t} finally {\n\t\t\tendExclusive();\n\t\t}\n\t}\n\n\t/**\n\t * test for CCID Features in the card reader this BeIDCard is inserted into\n\t *\n\t * @param feature the feature to test for (CCID.FEATURE)\n\t * @return true if the given feature is available, false if not\n\t */\n\tpublic boolean cardTerminalHasCCIDFeature(CCID.FEATURE feature) {\n\t\treturn getCCID().hasFeature(feature);\n\t}\n\n\tpublic void removeCard() throws InterruptedException, BeIDException {\n\t\ttry {\n\t\t\twhile (cardTerminal.isCardPresent()) {\n\t\t\t\tThread.sleep(100);\n\t\t\t}\n\t\t} catch (CardException e) {\n\t\t\tthrow new BeIDException(\"Error waiting for card removal\", e);\n\t\t}\n\t}\n\n\t// ===========================================================================================================\n\t// low-level card transmit commands\n\t// not recommended for general use.\n\t// if you find yourself having to call these, we'd very much like to hear\n\t// about it.\n\t// ===========================================================================================================\n\n\tprivate byte[] transmitCCIDControl(boolean usePPDU, CCID.FEATURE feature) throws BeIDException {\n\t\treturn transmitControlCommand(getCCID().getFeature(feature), new byte[0]);\n\t}\n\n\tprivate byte[] transmitCCIDControl(boolean usePPDU, CCID.FEATURE feature, byte[] command) throws BeIDException, InterruptedException {\n\t\treturn usePPDU\n\t\t\t\t? transmitPPDUCommand(feature.getTag(), command)\n\t\t\t\t: transmitControlCommand(getCCID().getFeature(feature), command);\n\t}\n\n\tprivate byte[] transmitControlCommand(int controlCode, byte[] command) throws BeIDException {\n\t\ttry {\n\t\t\treturn card.transmitControlCommand(controlCode, command);\n\t\t} catch (CardException e) {\n\t\t\tthrow new BeIDException(\"Cannot transmit control command\", e);\n\n\t\t}\n\t}\n\n\tprivate byte[] transmitPPDUCommand(int controlCode, byte[] command) throws BeIDException, InterruptedException {\n\t\tResponseAPDU responseAPDU = transmitCommand(BeIDCommandAPDU.PPDU, controlCode, command);\n\t\tif (responseAPDU.getSW() != 0x9000)\n\t\t\tthrow new BeIDException(\"PPDU Command Failed: ResponseAPDU=\" + responseAPDU.getSW());\n\t\tif (responseAPDU.getNr() == 0)\n\t\t\treturn responseAPDU.getBytes();\n\t\treturn responseAPDU.getData();\n\t}\n\n\tprivate ResponseAPDU transmitCommand(BeIDCommandAPDU apdu, int le) throws BeIDException, InterruptedException {\n\t\treturn transmit(new CommandAPDU(apdu.getCla(), apdu.getIns(), apdu.getP1(), apdu.getP2(), le));\n\t}\n\n\tprivate ResponseAPDU transmitCommand(BeIDCommandAPDU apdu, int p2, byte[] data) throws BeIDException, InterruptedException {\n\t\treturn transmit(new CommandAPDU(apdu.getCla(), apdu.getIns(), apdu.getP1(), p2, data));\n\t}\n\n\tprivate ResponseAPDU transmitCommand(BeIDCommandAPDU apdu, int p1, int p2, int le) throws BeIDException, InterruptedException {\n\t\treturn transmit(new CommandAPDU(apdu.getCla(), apdu.getIns(), p1, p2, le));\n\t}\n\n\tprivate ResponseAPDU transmitCommand(BeIDCommandAPDU apdu, byte[] data) throws BeIDException, InterruptedException {\n\t\treturn transmit(new CommandAPDU(apdu.getCla(), apdu.getIns(), apdu.getP1(), apdu.getP2(), data));\n\t}\n\n\tprivate ResponseAPDU transmitCommand(BeIDCommandAPDU apdu, byte[] data, int dataOffset, int dataLength, int ne) throws BeIDException, InterruptedException {\n\t\treturn transmit(new CommandAPDU(apdu.getCla(), apdu.getIns(), apdu.getP1(), apdu.getP2(), data, dataOffset, dataLength, ne));\n\t}\n\n\tprivate ResponseAPDU transmit(CommandAPDU commandApdu) throws BeIDException, InterruptedException {\n\t\ttry {\n\t\t\tResponseAPDU responseApdu = cardChannel.transmit(commandApdu);\n\t\t\tif (0x6c == responseApdu.getSW1()) {\n\t\t\t\t/*\n\t\t\t\t * A minimum delay of 10 msec between the answer ?????????6C\n\t\t\t\t * xx????????? and the next BeIDCommandAPDU is mandatory for eID\n\t\t\t\t * v1.0 and v1.1 cards.\n\t\t\t\t */\n\t\t\t\tlogger.debug(\"sleeping...\");\n\t\t\t\tThread.sleep(10);\n\t\t\t\tresponseApdu = cardChannel.transmit(commandApdu);\n\t\t\t}\n\n\t\t\treturn responseApdu;\n\t\t} catch (CardException e) {\n\t\t\tthrow new BeIDException(\"Cannot transmit data\", e);\n\t\t}\n\t}\n\n\tprivate void notifyReadProgress(FileType fileType, int offset, int estimatedMaxOffset) {\n\t\tif (offset > estimatedMaxOffset) {\n\t\t\testimatedMaxOffset = offset;\n\t\t}\n\n\t\tsynchronized (cardListeners) {\n\t\t\tfor (BeIDCardListener listener : cardListeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener.notifyReadProgress(fileType, offset, estimatedMaxOffset);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tlogger.debug(\"Exception Thrown In BeIDCardListener.notifyReadProgress():\" + ex.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void notifySigningBegin(FileType keyType) {\n\t\tsynchronized (cardListeners) {\n\t\t\tfor (BeIDCardListener listener : cardListeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener.notifySigningBegin(keyType);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tlogger.debug(\"Exception Thrown In BeIDCardListener.notifySigningBegin():\" + ex.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void notifySigningEnd(FileType keyType) {\n\t\tsynchronized (cardListeners) {\n\t\t\tfor (BeIDCardListener listener : cardListeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener.notifySigningEnd(keyType);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tlogger.debug(\"Exception Thrown In BeIDCardListener.notifySigningBegin():\" + ex.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * Verify PIN code for purpose \"purpose\" This method will attempt to verify\n\t * PIN using the most secure method available. If that method turns out to\n\t * be the UI, will pass purpose to the UI.\n\t */\n\n\tprivate void verifyPin(PINPurpose purpose) throws BeIDException, InterruptedException, CancelledException {\n\t\tResponseAPDU responseApdu;\n\t\tint retriesLeft = -1;\n\t\tdo {\n\t\t\tif (getCCID().hasFeature(CCID.FEATURE.VERIFY_PIN_DIRECT)) {\n\t\t\t\tresponseApdu = verifyPINViaCCIDDirect(retriesLeft, purpose);\n\t\t\t} else if (getCCID().hasFeature(CCID.FEATURE.VERIFY_PIN_START)) {\n\t\t\t\tresponseApdu = verifyPINViaCCIDStartFinish(retriesLeft, purpose);\n\t\t\t} else {\n\t\t\t\tresponseApdu = verifyPINViaUI(retriesLeft, purpose);\n\t\t\t}\n\n\t\t\tif (0x9000 != responseApdu.getSW()) {\n\t\t\t\tlogger.debug(\"VERIFY_PIN error\");\n\t\t\t\tlogger.debug(\"SW: \"\n\t\t\t\t\t\t+ Integer.toHexString(responseApdu.getSW()));\n\t\t\t\tif (0x6983 == responseApdu.getSW()) {\n\t\t\t\t\tgetUI().advisePINBlocked();\n\t\t\t\t\tthrow new ResponseAPDUException(\"eID card blocked!\", responseApdu);\n\t\t\t\t}\n\t\t\t\tif (0x63 != responseApdu.getSW1()) {\n\t\t\t\t\tlogger.debug(\"PIN verification error.\");\n\t\t\t\t\tthrow new ResponseAPDUException(\"PIN Verification Error\",\n\t\t\t\t\t\t\tresponseApdu);\n\t\t\t\t}\n\t\t\t\tretriesLeft = responseApdu.getSW2() & 0xf;\n\t\t\t\tlogger.debug(\"retries left: \" + retriesLeft);\n\t\t\t}\n\t\t} while (0x9000 != responseApdu.getSW());\n\t}\n\n\t/*\n\t * Verify PIN code using CCID Direct PIN Verify sequence.\n\t */\n\tprivate ResponseAPDU verifyPINViaCCIDDirect(int retriesLeft, PINPurpose purpose) throws BeIDException, InterruptedException {\n\t\tlogger.debug(\"direct PIN verification...\");\n\t\tgetUI().advisePINPadPINEntry(retriesLeft, purpose);\n\n\t\tbyte[] result;\n\t\ttry {\n\t\t\tresult = transmitCCIDControl(getCCID().usesPPDU(), CCID.FEATURE.VERIFY_PIN_DIRECT, getCCID().createPINVerificationDataStructure(getLocale(), CCID.INS.VERIFY_PIN));\n\t\t} catch (IOException e) {\n\t\t\tthrow new BeIDException(e);\n\t\t} finally {\n\t\t\tgetUI().advisePINPadOperationEnd();\n\t\t}\n\n\t\tResponseAPDU responseApdu = new ResponseAPDU(result);\n\t\tif (0x6401 == responseApdu.getSW()) {\n\t\t\tlogger.debug(\"canceled by user\");\n\t\t\tthrow new SecurityException(\"canceled by user\", new ResponseAPDUException(responseApdu));\n\t\t} else if (0x6400 == responseApdu.getSW()) {\n\t\t\tlogger.debug(\"PIN pad timeout\");\n\t\t}\n\n\t\treturn responseApdu;\n\t}\n\n\t/*\n\t * Verify PIN code using CCID Start/Finish sequence.\n\t */\n\tprivate ResponseAPDU verifyPINViaCCIDStartFinish(int retriesLeft, PINPurpose purpose) throws BeIDException, InterruptedException {\n\t\tlogger.debug(\"CCID verify PIN start/end sequence...\");\n\n\t\tgetUI().advisePINPadPINEntry(retriesLeft, purpose);\n\n\t\ttry {\n\t\t\ttransmitCCIDControl(getCCID().usesPPDU(), CCID.FEATURE.VERIFY_PIN_START, getCCID().createPINVerificationDataStructure(getLocale(), CCID.INS.VERIFY_PIN));\n\t\t\tgetCCID().waitForOK();\n\t\t} catch (IOException e) {\n\t\t\tthrow new BeIDException(\"Cannot verify pin\", e);\n\t\t} finally {\n\t\t\tgetUI().advisePINPadOperationEnd();\n\t\t}\n\n\t\treturn new ResponseAPDU(transmitCCIDControl(getCCID().usesPPDU(), CCID.FEATURE.VERIFY_PIN_FINISH));\n\t}\n\n\tprivate boolean isWindows8Or10() {\n\t\tString osName = System.getProperty(\"os.name\");\n\t\treturn osName.contains(\"Windows 8\") || osName.contains(\"Windows 10\");\n\t}\n\n\t/*\n\t * Verify PIN code by obtaining it from the current UI\n\t */\n\tprivate ResponseAPDU verifyPINViaUI(int retriesLeft, PINPurpose purpose) throws CancelledException, BeIDException, InterruptedException {\n\t\tboolean windows8 = isWindows8Or10();\n\t\tif (windows8) {\n\t\t\tendExclusive();\n\t\t}\n\t\tchar[] pin = getUI().obtainPIN(retriesLeft, purpose);\n\t\tif (windows8) {\n\t\t\tbeginExclusive();\n\t\t}\n\n\t\tbyte[] verifyData = new byte[]{(byte) (0x20 | pin.length), (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};\n\t\tfor (int idx = 0; idx < pin.length; idx += 2) {\n\t\t\tchar digit1 = pin[idx];\n\t\t\tchar digit2;\n\t\t\tif (idx + 1 < pin.length) {\n\t\t\t\tdigit2 = pin[idx + 1];\n\t\t\t} else {\n\t\t\t\tdigit2 = '0' + 0xf;\n\t\t\t}\n\t\t\tbyte value = (byte) (byte) ((digit1 - '0' << 4) + (digit2 - '0'));\n\t\t\tverifyData[idx / 2 + 1] = value;\n\t\t}\n\t\tArrays.fill(pin, (char) 0); // minimize exposure\n\n\t\tlogger.debug(\"verifying PIN...\");\n\t\ttry {\n\t\t\treturn transmitCommand(BeIDCommandAPDU.VERIFY_PIN, verifyData);\n\t\t} finally {\n\t\t\tArrays.fill(verifyData, (byte) 0); // minimize exposure\n\t\t}\n\t}\n\n\t/*\n\t * Modify PIN code using CCID Direct PIN Modify sequence.\n\t */\n\tprivate ResponseAPDU changePINViaCCIDDirect(int retriesLeft) throws BeIDException, InterruptedException {\n\t\tlogger.debug(\"direct PIN modification...\");\n\t\tgetUI().advisePINPadChangePIN(retriesLeft);\n\t\tbyte[] result;\n\n\t\ttry {\n\t\t\tresult = transmitCCIDControl(getCCID().usesPPDU(), CCID.FEATURE.MODIFY_PIN_DIRECT, getCCID().createPINModificationDataStructure(getLocale(), CCID.INS.MODIFY_PIN));\n\t\t} catch (IOException e) {\n\t\t\tthrow new BeIDException(\"Error changing pin\", e);\n\t\t} finally {\n\t\t\tgetUI().advisePINPadOperationEnd();\n\t\t}\n\n\t\tResponseAPDU responseApdu = new ResponseAPDU(result);\n\t\tswitch (responseApdu.getSW()) {\n\t\t\tcase 0x6402:\n\t\t\t\tlogger.debug(\"PINs differ\");\n\t\t\t\tbreak;\n\t\t\tcase 0x6401:\n\t\t\t\tlogger.debug(\"canceled by user\");\n\t\t\t\tthrow new SecurityException(\"canceled by user\", new ResponseAPDUException(responseApdu));\n\t\t\tcase 0x6400:\n\t\t\t\tlogger.debug(\"PIN pad timeout\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn responseApdu;\n\t}\n\n\t/*\n\t * Modify PIN code using CCID Modify PIN Start sequence\n\t */\n\tprivate ResponseAPDU changePINViaCCIDStartFinish(int retriesLeft) throws InterruptedException, BeIDException {\n\t\ttry {\n\t\t\ttransmitCCIDControl(\n\t\t\t\t\tgetCCID().usesPPDU(), CCID.FEATURE.MODIFY_PIN_START,\n\t\t\t\t\tgetCCID().createPINModificationDataStructure(getLocale(), CCID.INS.MODIFY_PIN)\n\t\t\t);\n\n\t\t\tlogger.debug(\"enter old PIN...\");\n\t\t\tgetUI().advisePINPadOldPINEntry(retriesLeft);\n\t\t\tgetCCID().waitForOK();\n\t\t\tgetUI().advisePINPadOperationEnd();\n\n\t\t\tlogger.debug(\"enter new PIN...\");\n\t\t\tgetUI().advisePINPadNewPINEntry(retriesLeft);\n\t\t\tgetCCID().waitForOK();\n\t\t\tgetUI().advisePINPadOperationEnd();\n\n\t\t\tlogger.debug(\"enter new PIN again...\");\n\t\t\tgetUI().advisePINPadNewPINEntryAgain(retriesLeft);\n\t\t\tgetCCID().waitForOK();\n\t\t} catch (IOException e) {\n\t\t\tthrow new BeIDException(\"Error changing pin\", e);\n\t\t} finally {\n\t\t\tgetUI().advisePINPadOperationEnd();\n\t\t}\n\n\t\treturn new ResponseAPDU(transmitCCIDControl(getCCID().usesPPDU(), CCID.FEATURE.MODIFY_PIN_FINISH));\n\t}\n\n\t/*\n\t * Modify PIN via the UI\n\t */\n\tprivate ResponseAPDU changePINViaUI(int retriesLeft) throws BeIDException, InterruptedException {\n\t\tchar[][] pins = getUI().obtainOldAndNewPIN(retriesLeft);\n\t\tchar[] oldPin = pins[0];\n\t\tchar[] newPin = pins[1];\n\n\t\tbyte[] changePinData = new byte[]{(byte) (0x20 | oldPin.length),\n\t\t\t\t(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,\n\t\t\t\t(byte) 0xFF, (byte) 0xFF, (byte) 0xFF,\n\t\t\t\t(byte) (0x20 | newPin.length), (byte) 0xFF, (byte) 0xFF,\n\t\t\t\t(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,\n\t\t\t\t(byte) 0xFF,};\n\n\t\tfor (int idx = 0; idx < oldPin.length; idx += 2) {\n\t\t\tchar digit1 = oldPin[idx];\n\t\t\tchar digit2;\n\t\t\tif (idx + 1 < oldPin.length) {\n\t\t\t\tdigit2 = oldPin[idx + 1];\n\t\t\t} else {\n\t\t\t\tdigit2 = '0' + 0xf;\n\t\t\t}\n\t\t\tbyte value = (byte) (byte) ((digit1 - '0' << 4) + (digit2 - '0'));\n\t\t\tchangePinData[idx / 2 + 1] = value;\n\t\t}\n\t\tArrays.fill(oldPin, (char) 0); // minimize exposure\n\n\t\tfor (int idx = 0; idx < newPin.length; idx += 2) {\n\t\t\tchar digit1 = newPin[idx];\n\t\t\tchar digit2;\n\t\t\tif (idx + 1 < newPin.length) {\n\t\t\t\tdigit2 = newPin[idx + 1];\n\t\t\t} else {\n\t\t\t\tdigit2 = '0' + 0xf;\n\t\t\t}\n\t\t\tbyte value = (byte) (byte) ((digit1 - '0' << 4) + (digit2 - '0'));\n\t\t\tchangePinData[(idx / 2 + 1) + 8] = value;\n\t\t}\n\t\tArrays.fill(newPin, (char) 0); // minimize exposure\n\n\t\ttry {\n\t\t\treturn transmitCommand(BeIDCommandAPDU.CHANGE_PIN, changePinData);\n\t\t} finally {\n\t\t\tArrays.fill(changePinData, (byte) 0);\n\t\t}\n\t}\n\n\t/*\n\t * Unblock PIN using CCID Verify PIN Direct sequence on the PUK\n\t */\n\tprivate ResponseAPDU unblockPINViaCCIDVerifyPINDirectOfPUK(int retriesLeft) throws BeIDException, InterruptedException {\n\t\tlogger.debug(\"direct PUK verification...\");\n\t\tgetUI().advisePINPadPUKEntry(retriesLeft);\n\t\tbyte[] result;\n\t\ttry {\n\t\t\tresult = transmitCCIDControl(getCCID().usesPPDU(), CCID.FEATURE.VERIFY_PIN_DIRECT, getCCID().createPINVerificationDataStructure(getLocale(), CCID.INS.VERIFY_PUK));\n\t\t} catch (IOException e) {\n\t\t\tthrow new BeIDException(e);\n\t\t} finally {\n\t\t\tgetUI().advisePINPadOperationEnd();\n\t\t}\n\n\t\tResponseAPDU responseApdu = new ResponseAPDU(result);\n\t\tif (0x6401 == responseApdu.getSW()) {\n\t\t\tlogger.debug(\"canceled by user\");\n\t\t\tthrow new SecurityException(\"canceled by user\", new ResponseAPDUException(responseApdu));\n\t\t} else if (0x6400 == responseApdu.getSW()) {\n\t\t\tlogger.debug(\"PIN pad timeout\");\n\t\t}\n\n\t\treturn responseApdu;\n\t}\n\n\t/*\n\t * Unblock the PIN by obtaining PUK codes from the UI and calling RESET_PIN\n\t * on the card.\n\t */\n\tprivate ResponseAPDU unblockPINViaUI(int retriesLeft) throws BeIDException, InterruptedException {\n\t\tchar[][] puks = getUI().obtainPUKCodes(retriesLeft);\n\t\tchar[] puk1 = puks[0];\n\t\tchar[] puk2 = puks[1];\n\n\t\tchar[] fullPuk = new char[puk1.length + puk2.length];\n\t\tSystem.arraycopy(puk2, 0, fullPuk, 0, puk2.length);\n\t\tArrays.fill(puk2, (char) 0);\n\t\tSystem.arraycopy(puk1, 0, fullPuk, puk2.length, puk1.length);\n\t\tArrays.fill(puk1, (char) 0);\n\n\t\tbyte[] unblockPinData = new byte[]{\n\t\t\t\t(byte) (0x20 | ((byte) (puk1.length + puk2.length))),\n\t\t\t\t(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,\n\t\t\t\t(byte) 0xFF, (byte) 0xFF, (byte) 0xFF,};\n\n\t\tfor (int idx = 0; idx < fullPuk.length; idx += 2) {\n\t\t\tchar digit1 = fullPuk[idx];\n\t\t\tchar digit2 = fullPuk[idx + 1];\n\t\t\tbyte value = (byte) (byte) ((digit1 - '0' << 4) + (digit2 - '0'));\n\t\t\tunblockPinData[idx / 2 + 1] = value;\n\t\t}\n\t\tArrays.fill(fullPuk, (char) 0); // minimize exposure\n\n\t\ttry {\n\t\t\treturn transmitCommand(BeIDCommandAPDU.RESET_PIN, unblockPinData);\n\t\t} finally {\n\t\t\tArrays.fill(unblockPinData, (byte) 0);\n\t\t}\n\t}\n\n\tprivate CCID getCCID() {\n\t\tif (this.ccid == null) {\n\t\t\tthis.ccid = new CCID(this.card, this.cardTerminal, logger);\n\t\t}\n\t\treturn ccid;\n\t}\n\n\tprivate BeIDCardUI getUI() {\n\t\tif (this.ui == null) {\n\t\t\tif (GraphicsEnvironment.isHeadless()) {\n\t\t\t\tlogger.error(UI_DEFAULT_REQUIRES_HEAD);\n\t\t\t\tthrow new UnsupportedOperationException(UI_DEFAULT_REQUIRES_HEAD);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tClassLoader classLoader = BeIDCard.class.getClassLoader();\n\t\t\t\tClass<?> uiClass = classLoader.loadClass(DEFAULT_UI_IMPLEMENTATION);\n\t\t\t\tthis.ui = (BeIDCardUI) uiClass.newInstance();\n\t\t\t\tif (locale != null) {\n\t\t\t\t\tui.setLocale(locale);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(UI_MISSING_LOG_MESSAGE);\n\t\t\t\tthrow new UnsupportedOperationException(UI_MISSING_LOG_MESSAGE, e);\n\t\t\t}\n\t\t}\n\n\t\treturn ui;\n\t}\n\n\t/**\n\t * Return the CardTerminal that held this BeIdCard when it was detected Will\n\t * return null if the physical Card that we represent was removed.\n\t *\n\t * @return the cardTerminal this BeIDCard was in when detected, or null\n\t */\n\tpublic CardTerminal getCardTerminal() {\n\t\treturn cardTerminal;\n\t}\n\n\t/*\n\t * BeIDCommandAPDU encapsulates values sent in CommandAPDU's, to make these\n\t * more readable in BeIDCard.\n\t */\n\tprivate enum BeIDCommandAPDU {\n\t\tSELECT_APPLET(0x00, 0xA4, 0x04, 0x0C),\n\t\tSELECT_FILE(0x00, 0xA4, 0x08, 0x0C),\n\t\tREAD_BINARY(0x00, 0xB0),\n\t\tVERIFY_PIN(0x00, 0x20, 0x00, 0x01),\n\t\tCHANGE_PIN(0x00, 0x24, 0x00, 0x01), // 0x0024=change reference change\n\t\tSELECT_ALGORITHM_AND_PRIVATE_KEY(0x00, 0x22, 0x41, 0xB6), // ISO 7816-8 SET COMMAND (select algorithm and key for signature)\n\t\tCOMPUTE_DIGITAL_SIGNATURE(0x00, 0x2A, 0x9E, 0x9A), // ISO 7816-8 COMPUTE DIGITAL SIGNATURE COMMAND\n\t\tRESET_PIN(0x00, 0x2C, 0x00, 0x01),\n\t\tGET_CHALLENGE(0x00, 0x84, 0x00, 0x00),\n\t\tGET_CARD_DATA(0x80, 0xE4, 0x00, 0x00),\n\t\tPPDU(0xFF, 0xC2, 0x01);\n\n\t\tprivate final int cla;\n\t\tprivate final int ins;\n\t\tprivate final int p1;\n\t\tprivate final int p2;\n\n\t\tBeIDCommandAPDU(int cla, int ins, int p1, int p2) {\n\t\t\tthis.cla = cla;\n\t\t\tthis.ins = ins;\n\t\t\tthis.p1 = p1;\n\t\t\tthis.p2 = p2;\n\t\t}\n\n\t\tBeIDCommandAPDU(int cla, int ins, int p1) {\n\t\t\tthis.cla = cla;\n\t\t\tthis.ins = ins;\n\t\t\tthis.p1 = p1;\n\t\t\tthis.p2 = -1;\n\t\t}\n\n\t\tBeIDCommandAPDU(int cla, int ins) {\n\t\t\tthis.cla = cla;\n\t\t\tthis.ins = ins;\n\t\t\tthis.p1 = -1;\n\t\t\tthis.p2 = -1;\n\t\t}\n\n\t\tpublic int getCla() {\n\t\t\treturn cla;\n\t\t}\n\n\t\tpublic int getIns() {\n\t\t\treturn ins;\n\t\t}\n\n\t\tpublic int getP1() {\n\t\t\treturn p1;\n\t\t}\n\n\t\tpublic int getP2() {\n\t\t\treturn p2;\n\t\t}\n\t}\n}",
"public class BeIDCards implements AutoCloseable {\n\tprivate static final String UI_MISSING_LOG_MESSAGE = \"No BeIDCardsUI set and can't load DefaultBeIDCardsUI\";\n\tprivate static final String DEFAULT_UI_IMPLEMENTATION = \"be.bosa.commons.eid.dialogs.DefaultBeIDCardsUI\";\n\n\tprivate final Logger logger;\n\tprivate final CardAndTerminalManager cardAndTerminalManager;\n\tprivate final BeIDCardManager cardManager;\n\tprivate final Map<CardTerminal, BeIDCard> beIDTerminalsAndCards;\n\tprivate final Sleeper terminalManagerInitSleeper, cardTerminalSleeper;\n\tprivate final Sleeper cardManagerInitSleeper, beIDSleeper;\n\n\tprivate BeIDCardsUI ui;\n\tprivate int cardTerminalsAttached;\n\tprivate boolean terminalsInitialized, cardsInitialized, uiSelectingCard;\n\n\t/**\n\t * a BeIDCards without logging, using the default BeIDCardsUI\n\t */\n\tpublic BeIDCards() {\n\t\tthis(new VoidLogger(), null);\n\t}\n\n\t/**\n\t * a BeIDCards without logging, using the supplied BeIDCardsUI\n\t *\n\t * @param ui an instance of BeIDCardsUI\n\t * that will be called upon for any user interaction required to\n\t * handle other calls. The UI's Locale will be used globally for\n\t * subsequent UI actions, as if setLocale() was called, except\n\t * where the Locale is explicity set for individual BeIDCard\n\t * instances.\n\t */\n\tpublic BeIDCards(BeIDCardsUI ui) {\n\t\tthis(new VoidLogger(), ui);\n\t}\n\n\t/**\n\t * a BeIDCards logging to supplied logger, using the default BeIDCardsUI\n\t *\n\t * @param logger the logger instance\n\t */\n\tpublic BeIDCards(Logger logger) {\n\t\tthis(logger, null);\n\t}\n\n\t/**\n\t * a BeIDCards logging to logger, using the supplied BeIDCardsUI and locale\n\t *\n\t * @param logger the logger instance\n\t * @param ui an instance of BeIDCardsUI that will be called upon for any\n\t * user interaction required to handle other calls. The UI's\n\t * Locale will be used globally for subsequent UI actions,\n\t * as if setLocale() was called, except where the Locale is\n\t * explicity set for individual BeIDCard instances.\n\t */\n\tpublic BeIDCards(Logger logger, BeIDCardsUI ui) {\n\t\tthis.logger = logger;\n\n\t\tthis.cardAndTerminalManager = new CardAndTerminalManager(logger);\n\t\tthis.cardAndTerminalManager.setProtocol(CardAndTerminalManager.Protocol.T0);\n\t\tthis.cardManager = new BeIDCardManager(logger, cardAndTerminalManager);\n\n\t\tthis.terminalManagerInitSleeper = new Sleeper();\n\t\tthis.cardManagerInitSleeper = new Sleeper();\n\t\tthis.cardTerminalSleeper = new Sleeper();\n\t\tthis.beIDSleeper = new Sleeper();\n\t\tthis.beIDTerminalsAndCards = Collections.synchronizedMap(new HashMap<>());\n\n\t\tthis.terminalsInitialized = false;\n\t\tthis.cardsInitialized = false;\n\t\tthis.uiSelectingCard = false;\n\n\t\tsetUI(ui);\n\n\t\tthis.cardAndTerminalManager.addCardTerminalListener(new DefaultCardTerminalEventsListener());\n\t\tthis.cardManager.addBeIDCardEventListener(new DefaultBeIDCardEventsListener());\n\n\t\tthis.cardAndTerminalManager.start();\n\t}\n\n\t/**\n\t * Return whether any BeID Cards are currently present.\n\t *\n\t * @return true if one or more BeID Cards are inserted in one or more\n\t * connected CardTerminals, false if zero BeID Cards are present\n\t */\n\tpublic boolean hasBeIDCards() {\n\t\treturn hasBeIDCards(null);\n\t}\n\n\t/**\n\t * Return whether any BeID Cards are currently present.\n\t *\n\t * @param terminal if not null, only this terminal will be considered in\n\t * determining whether beID Cards are present.\n\t * @return true if one or more BeID Cards are inserted in one or more\n\t * connected CardTerminals, false if zero BeID Cards are present\n\t */\n\tpublic boolean hasBeIDCards(CardTerminal terminal) {\n\t\twaitUntilCardsInitialized();\n\n\t\tboolean result = terminal != null ? beIDTerminalsAndCards.containsKey(terminal) : !beIDTerminalsAndCards.isEmpty();\n\t\tlogger.debug(\"hasBeIDCards returns \" + result);\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * return Set of all BeID Cards present. Will return empty Set if no BeID\n\t * cards are present at time of call\n\t *\n\t * @return a (possibly empty) set of all BeID Cards inserted at time of call\n\t */\n\tpublic Set<BeIDCard> getAllBeIDCards() {\n\t\twaitUntilCardsInitialized();\n\t\treturn new HashSet<>(beIDTerminalsAndCards.values());\n\t}\n\n\t/**\n\t * return exactly one BeID Card.\n\t * <p>\n\t * This may block when called when no BeID Cards are present, until at least\n\t * one BeID card is inserted, at which point this will be returned. If, at\n\t * time of call, more than one BeID card is present, will request the UI to\n\t * select between those, and return the selected card. If the UI is called\n\t * upon to request the user to select between different cards, or to insert\n\t * one card, and the user declines, CancelledException is thrown.\n\t *\n\t * @return a BeIDCard instance. The only one present, or one chosen out of several by the user\n\t */\n\tpublic BeIDCard getOneBeIDCard() throws CancelledException {\n\t\treturn getOneBeIDCard(null);\n\t}\n\n\t/**\n\t * return a BeID Card inserted into a given CardTerminal\n\t *\n\t * @param terminal if not null, only BeID Cards in this particular CardTerminal\n\t * will be considered.\n\t * <p>\n\t * May block when called when no BeID Cards are present, until at\n\t * least one BeID card is inserted, at which point this will be\n\t * returned. If, at time of call, more than one BeID card is\n\t * present, will request the UI to select between those, and\n\t * return the selected card. If the UI is called upon to request\n\t * the user to select between different cards, or to insert one\n\t * card, and the user declines, CancelledException is thrown.\n\t * @return a BeIDCard instance. The only one present, or one chosen out of several by the user\n\t */\n\tpublic BeIDCard getOneBeIDCard(CardTerminal terminal) throws CancelledException {\n\t\tBeIDCard selectedCard = null;\n\n\t\tdo {\n\t\t\twaitForAtLeastOneCardTerminal();\n\t\t\twaitForAtLeastOneBeIDCard(terminal);\n\n\t\t\t// copy current list of BeID Cards to avoid holding a lock on it\n\t\t\t// during possible selectBeIDCard dialog.\n\t\t\t// (because we'd deadlock when user inserts/removes a card while\n\t\t\t// selectBeIDCard has not returned)\n\t\t\tMap<CardTerminal, BeIDCard> currentBeIDCards = new HashMap<>(beIDTerminalsAndCards);\n\n\t\t\tif (terminal != null) {\n\t\t\t\t// if selecting by terminal and we have a card in the requested one, return that immediately.\n\t\t\t\t// (This will return null if the terminal we want doesn't have a card, and continue the loop).\n\t\t\t\tselectedCard = currentBeIDCards.get(terminal);\n\t\t\t} else if (currentBeIDCards.size() == 1) {\n\t\t\t\t// we have only one BeID card. return it.\n\t\t\t\tselectedCard = currentBeIDCards.values().iterator().next();\n\t\t\t} else {\n\t\t\t\t// more than one, call upon the UI to obtain a selection\n\t\t\t\ttry {\n\t\t\t\t\tlogger.debug(\"selecting\");\n\t\t\t\t\tuiSelectingCard = true;\n\t\t\t\t\tselectedCard = getUI().selectBeIDCard(currentBeIDCards.values());\n\t\t\t\t} catch (OutOfCardsException oocex) {\n\t\t\t\t\t// if we run out of cards, waitForAtLeastOneBeIDCard will ask for one in the next loop\n\t\t\t\t} finally {\n\t\t\t\t\tuiSelectingCard = false;\n\t\t\t\t\tlogger.debug(\"no longer selecting\");\n\t\t\t\t}\n\t\t\t}\n\t\t} while (selectedCard == null);\n\n\t\treturn selectedCard;\n\t}\n\n\t/**\n\t * wait for a particular BeID card to be removed. Note that this only works\n\t * with BeID objects that were acquired using either the\n\t * {@link #getOneBeIDCard()} or {@link #getAllBeIDCards()} methods from the\n\t * same BeIDCards instance. If, at time of call, that particular card is\n\t * present, the UI is called upon to prompt the user to remove that card.\n\t *\n\t * @return this BeIDCards instance to allow for method chaining\n\t */\n\tpublic BeIDCards waitUntilCardRemoved(BeIDCard card) {\n\t\tif (getAllBeIDCards().contains(card)) {\n\t\t\ttry {\n\t\t\t\tlogger.debug(\"waitUntilCardRemoved blocking until card removed\");\n\t\t\t\tgetUI().adviseBeIDCardRemovalRequired();\n\t\t\t\twhile (getAllBeIDCards().contains(card)) {\n\t\t\t\t\tbeIDSleeper.sleepUntilAwakened();\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tgetUI().adviseEnd();\n\t\t\t}\n\t\t}\n\t\tlogger.debug(\"waitUntilCardRemoved returning\");\n\t\treturn this;\n\t}\n\n\tpublic boolean hasCardTerminals() {\n\t\twaitUntilTerminalsInitialized();\n\t\treturn cardTerminalsAttached > 0;\n\t}\n\n\t/**\n\t * Call close() if you no longer need this BeIDCards instance.\n\t */\n\t@Override\n\tpublic void close() throws InterruptedException {\n\t\tthis.cardAndTerminalManager.stop();\n\t}\n\n\t/**\n\t * Set the Locale to use for subsequent UI operations. BeIDCards and\n\t * BeIDCardManager share the same global Locale, so this will impact and and\n\t * all instances of either. BeIDCard instances may have individual,\n\t * per-instance Locale settings, however.\n\t *\n\t * @param newLocale will be used globally for subsequent UI actions, as if\n\t * setLocale() was called, except where the Locale is explicity\n\t * set for individual BeIDCard instances.\n\t * @return this BeIDCards, to allow method chaining\n\t */\n\tpublic BeIDCards setLocale(Locale newLocale) {\n\t\tLocaleManager.setLocale(newLocale);\n\n\t\tfor (BeIDCard card : new HashSet<>(beIDTerminalsAndCards.values())) {\n\t\t\tcard.setLocale(newLocale);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * @return the currently set Locale\n\t */\n\tpublic Locale getLocale() {\n\t\treturn LocaleManager.getLocale();\n\t}\n\n\tprivate void setUI(BeIDCardsUI ui) {\n\t\tthis.ui = ui;\n\t\tif (ui != null) {\n\t\t\tsetLocale(ui.getLocale());\n\t\t}\n\t}\n\n\tprivate BeIDCardsUI getUI() {\n\t\tif (ui == null) {\n\t\t\ttry {\n\t\t\t\tClassLoader classLoader = BeIDCard.class.getClassLoader();\n\t\t\t\tClass<?> uiClass = classLoader.loadClass(DEFAULT_UI_IMPLEMENTATION);\n\t\t\t\tsetUI((BeIDCardsUI) uiClass.newInstance());\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(UI_MISSING_LOG_MESSAGE);\n\t\t\t\tthrow new UnsupportedOperationException(UI_MISSING_LOG_MESSAGE, e);\n\t\t\t}\n\t\t}\n\n\t\treturn ui;\n\t}\n\n\tprivate void waitUntilCardsInitialized() {\n\t\twhile (!cardsInitialized) {\n\t\t\tlogger.debug(\"Waiting for CardAndTerminalManager Cards initialisation\");\n\t\t\tcardManagerInitSleeper.sleepUntilAwakened();\n\t\t\tlogger.debug(\"CardAndTerminalManager now has cards initialized\");\n\t\t}\n\t}\n\n\tprivate void waitUntilTerminalsInitialized() {\n\t\twhile (!terminalsInitialized) {\n\t\t\tlogger.debug(\"Waiting for CardAndTerminalManager Terminals initialisation\");\n\t\t\tterminalManagerInitSleeper.sleepUntilAwakened();\n\t\t\tlogger.debug(\"CardAndTerminalManager now has terminals initialized\");\n\t\t}\n\t}\n\n\tprivate void waitForAtLeastOneBeIDCard(CardTerminal terminal) {\n\t\tif (!hasBeIDCards(terminal)) {\n\t\t\ttry {\n\t\t\t\tgetUI().adviseBeIDCardRequired();\n\t\t\t\twhile (!hasBeIDCards(terminal)) {\n\t\t\t\t\tbeIDSleeper.sleepUntilAwakened();\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tgetUI().adviseEnd();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void waitForAtLeastOneCardTerminal() {\n\t\tif (!hasCardTerminals()) {\n\t\t\ttry {\n\t\t\t\tgetUI().adviseCardTerminalRequired();\n\t\t\t\twhile (!hasCardTerminals()) {\n\t\t\t\t\tcardTerminalSleeper.sleepUntilAwakened();\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tgetUI().adviseEnd();\n\t\t\t}\n\n\t\t\t// If we just found our first CardTerminal, give us 100ms to get notified about any eID cards that may\n\t\t\t// already present in that CardTerminal.\n\t\t\t// We'll get notified about any cards much faster than 100ms, and worst case, 100ms is not noticeable.\n\t\t\t// Better than calling adviseBeIDCardRequired and adviseEnd with a few seconds in between.\n\t\t\tif (!hasBeIDCards()) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(100);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class DefaultCardTerminalEventsListener implements CardTerminalEventsListener {\n\n\t\t@Override\n\t\tpublic void terminalEventsInitialized() {\n\t\t\tterminalsInitialized = true;\n\t\t\tterminalManagerInitSleeper.awaken();\n\t\t}\n\n\t\t@Override\n\t\tpublic void terminalDetached(CardTerminal cardTerminal) {\n\t\t\tcardTerminalsAttached--;\n\t\t\tcardTerminalSleeper.awaken();\n\n\t\t}\n\n\t\t@Override\n\t\tpublic void terminalAttached(CardTerminal cardTerminal) {\n\t\t\tcardTerminalsAttached++;\n\t\t\tcardTerminalSleeper.awaken();\n\t\t}\n\t}\n\n\tprivate class DefaultBeIDCardEventsListener implements BeIDCardEventsListener {\n\t\t@Override\n\t\tpublic void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card) {\n\t\t\tlogger.debug(\"eID Card Insertion Reported\");\n\n\t\t\tif (uiSelectingCard) {\n\t\t\t\ttry {\n\t\t\t\t\tgetUI().eIDCardInsertedDuringSelection(card);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tlogger.error(\"Exception in UI:eIDCardInserted\" + ex.getMessage());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsynchronized (beIDTerminalsAndCards) {\n\t\t\t\tbeIDTerminalsAndCards.put(cardTerminal, card);\n\t\t\t\tbeIDSleeper.awaken();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card) {\n\t\t\tlogger.debug(\"eID Card Removal Reported\");\n\n\t\t\tif (uiSelectingCard) {\n\t\t\t\ttry {\n\t\t\t\t\tgetUI().eIDCardRemovedDuringSelection(card);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tlogger.error(\"Exception in UI:eIDCardRemoved\" + ex.getMessage());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsynchronized (beIDTerminalsAndCards) {\n\t\t\t\tbeIDTerminalsAndCards.remove(cardTerminal);\n\t\t\t\tbeIDSleeper.awaken();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void eIDCardEventsInitialized() {\n\t\t\tlogger.debug(\"eIDCardEventsInitialized\");\n\t\t\tcardsInitialized = true;\n\t\t\tcardManagerInitSleeper.awaken();\n\t\t}\n\t}\n}",
"public enum FileType {\n\tIdentity(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x31}, 179),\n\tIdentitySignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x32}, 128),\n\tAddress(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x33}, 121),\n\tAddressSignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x34}, 128),\n\tPhoto(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x35}, 3064),\n\tAuthentificationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x38}, 1061, 0x82),\n\tNonRepudiationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x39}, 1082, 0x83),\n\tCACertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3A}, 1044),\n\tRootCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3B}, 914),\n\tRRNCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3C}, 820);\n\n\tprivate final byte[] fileId;\n\tprivate final byte keyId;\n\tprivate final int estimatedMaxSize;\n\n\tFileType(byte[] fileId, int estimatedMaxSize) {\n\t\tthis.fileId = fileId;\n\t\tthis.keyId = -1;\n\t\tthis.estimatedMaxSize = estimatedMaxSize;\n\t}\n\n\tFileType(byte[] fileId, int estimatedMaxSize, int keyId) {\n\t\tthis.fileId = fileId;\n\t\tthis.keyId = (byte) keyId;\n\t\tthis.estimatedMaxSize = estimatedMaxSize;\n\t}\n\n\tpublic byte[] getFileId() {\n\t\treturn fileId;\n\t}\n\n\tpublic byte getKeyId() {\n\t\treturn keyId;\n\t}\n\n\tpublic boolean isCertificateUserCanSignWith() {\n\t\treturn keyId != -1;\n\t}\n\n\tpublic boolean chainIncludesCitizenCA() {\n\t\treturn isCertificateUserCanSignWith();\n\t}\n\n\tpublic int getEstimatedMaxSize() {\n\t\treturn estimatedMaxSize;\n\t}\n}",
"public enum BeIDDigest {\n\n\tPLAIN_TEXT(new byte[]{0x30, (byte) 0xff, 0x30, 0x09, 0x06, 0x07, 0x60,\n\t\t\t0x38, 0x01, 0x02, 0x01, 0x03, 0x01, 0x04, (byte) 0xff,}),\n\n\tSHA_1(new byte[]{0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,\n\t\t\t0x02, 0x1a, 0x05, 0x00, 0x04, 0x14,}),\n\n\tSHA_224(new byte[]{0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte) 0x86,\n\t\t\t0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c,}),\n\n\tSHA_256(new byte[]{0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte) 0x86,\n\t\t\t0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20,}),\n\n\tSHA_384(new byte[]{0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte) 0x86,\n\t\t\t0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30,}),\n\n\tSHA_512(new byte[]{0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte) 0x86,\n\t\t\t0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40,}),\n\n\tRIPEMD_128(new byte[]{0x30, 0x1d, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,\n\t\t\t0x02, 0x02, 0x05, 0x00, 0x04, 0x10,}),\n\n\tRIPEMD_160(new byte[]{0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,\n\t\t\t0x02, 0x01, 0x05, 0x00, 0x04, 0x14,}),\n\n\tRIPEMD_256(new byte[]{0x30, 0x2d, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,\n\t\t\t0x02, 0x03, 0x05, 0x00, 0x04, 0x20,}),\n\n\tSHA_1_PSS(new byte[]{}, 0x10),\n\n\tSHA_256_PSS(new byte[]{}, 0x20),\n\n\tNONE(new byte[]{});\n\n\tprivate final byte[] prefix;\n\tprivate final byte algorithmReference;\n\n\tBeIDDigest(byte[] prefix, int algorithmReference) {\n\t\tthis.prefix = prefix;\n\t\tthis.algorithmReference = (byte) algorithmReference;\n\t}\n\n\tBeIDDigest(byte[] prefix) {\n\t\tthis(prefix, 0x01); // default algorithm reference: PKCS#1\n\t}\n\n\tpublic static BeIDDigest getInstance(String name) {\n\t\tname = name.replaceAll(\"-\", \"_\");\n\t\treturn valueOf(name);\n\t}\n\n\tpublic byte[] getPrefix(int valueLength) {\n\t\tif (this.equals(PLAIN_TEXT)) {\n\t\t\tbyte[] digestInfoPrefix = Arrays.copyOf(prefix, prefix.length);\n\t\t\tdigestInfoPrefix[1] = (byte) (valueLength + 13);\n\t\t\tdigestInfoPrefix[14] = (byte) valueLength;\n\t\t\treturn digestInfoPrefix;\n\t\t}\n\n\t\treturn prefix;\n\t}\n\n\tpublic byte getAlgorithmReference() {\n\t\treturn algorithmReference;\n\t}\n\n\tpublic String getStandardName() {\n\t\treturn name().replace('_', '-');\n\t}\n\n\tpublic MessageDigest getMessageDigestInstance()\n\t\t\tthrows NoSuchAlgorithmException {\n\t\treturn MessageDigest.getInstance(getStandardName());\n\t}\n}",
"public interface BeIDCardsUI {\n\t/**\n\t * set Locale for subsequent operations. Implementations MUST ensure that\n\t * after this call, any of the obtainXXX and adviseXXX methods for the same\n\t * instance respect the locale set here. Implementations MAY choose to\n\t * update any interface elements already facing the user at time of call,\n\t * but this is not required.\n\t */\n\tvoid setLocale(Locale newLocale);\n\n\t/**\n\t * get the Locale currently set.\n\t *\n\t * @return the current Locale for this UI\n\t */\n\tLocale getLocale();\n\n\t/**\n\t * The user needs to connect a Card Terminal, since there are none\n\t */\n\tvoid adviseCardTerminalRequired();\n\n\t/**\n\t * The user needs to insert a BeID Card. There are card terminals, but none\n\t * currently holds a BeID card.\n\t */\n\tvoid adviseBeIDCardRequired();\n\n\t/**\n\t * The user needs to remove a BeID Card for security reasons.\n\t */\n\tvoid adviseBeIDCardRemovalRequired();\n\n\t/**\n\t * No more user actions are required, at this point.\n\t */\n\tvoid adviseEnd();\n\n\t/**\n\t * user has multiple eID Cards inserted and needs to choose exactly one.\n\t * throws CancelledException if user cancels throws OutOfCardsException if\n\t * all cards removed before selection could me made.\n\t */\n\tBeIDCard selectBeIDCard(Collection<BeIDCard> availableCards) throws CancelledException, OutOfCardsException;\n\n\t/**\n\t * user added a BeID card while selectBeIDCard() was blocking. An\n\t * implementation should update the list of cards, if possible.\n\t *\n\t * @param card the card just inserted.\n\t */\n\tvoid eIDCardInsertedDuringSelection(BeIDCard card);\n\n\t/**\n\t * user removed a BeID card while selectBeIDCard() was blocking. An\n\t * implementation should update the list of cards, if possible.\n\t *\n\t * @param card the card just removed.\n\t */\n\tvoid eIDCardRemovedDuringSelection(BeIDCard card);\n}",
"public class DefaultBeIDCardsUI implements BeIDCardsUI {\n\n\tprivate final Component parentComponent;\n\tprivate Messages messages;\n\tprivate JFrame adviseFrame;\n\tprivate BeIDSelector selectionDialog;\n\tprivate Locale locale;\n\n\tpublic DefaultBeIDCardsUI() {\n\t\tthis(null);\n\t}\n\n\tpublic DefaultBeIDCardsUI(Component parentComponent) {\n\t\tthis(parentComponent, null);\n\t}\n\n\tpublic DefaultBeIDCardsUI(Component parentComponent, Messages messages) {\n\t\tif (GraphicsEnvironment.isHeadless()) {\n\t\t\tthrow new UnsupportedOperationException(\"DefaultBeIDCardsUI is a GUI and cannot run in a headless environment\");\n\t\t}\n\n\t\tthis.parentComponent = parentComponent;\n\t\tif (messages != null) {\n\t\t\tthis.messages = messages;\n\t\t\tsetLocale(messages.getLocale());\n\t\t} else {\n\t\t\tthis.messages = Messages.getInstance(getLocale());\n\t\t}\n\t}\n\n\t@Override\n\tpublic void adviseCardTerminalRequired() {\n\t\tshowAdvise(\n\t\t\t\tmessages.getMessage(Messages.MESSAGE_ID.CONNECT_READER),\n\t\t\t\tmessages.getMessage(Messages.MESSAGE_ID.CONNECT_READER)\n\t\t);\n\t}\n\n\t@Override\n\tpublic void adviseBeIDCardRequired() {\n\t\tshowAdvise(\n\t\t\t\tmessages.getMessage(Messages.MESSAGE_ID.INSERT_CARD_QUESTION),\n\t\t\t\tmessages.getMessage(Messages.MESSAGE_ID.INSERT_CARD_QUESTION)\n\t\t);\n\t}\n\n\t@Override\n\tpublic void adviseBeIDCardRemovalRequired() {\n\t\tshowAdvise(\n\t\t\t\tmessages.getMessage(Messages.MESSAGE_ID.REMOVE_CARD),\n\t\t\t\tmessages.getMessage(Messages.MESSAGE_ID.REMOVE_CARD)\n\t\t);\n\n\t}\n\n\t@Override\n\tpublic BeIDCard selectBeIDCard(Collection<BeIDCard> availableCards) throws CancelledException, OutOfCardsException {\n\t\ttry {\n\t\t\tselectionDialog = new BeIDSelector(parentComponent, \"Select eID card\", availableCards);\n\t\t\treturn selectionDialog.choose();\n\t\t} finally {\n\t\t\tselectionDialog = null;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void adviseEnd() {\n\t\tif (null != adviseFrame) {\n\t\t\tadviseFrame.dispose();\n\t\t\tadviseFrame = null;\n\t\t}\n\t}\n\n\tprivate void showAdvise(String title, String message) {\n\t\tif (null != adviseFrame) {\n\t\t\tadviseEnd();\n\t\t}\n\n\t\tadviseFrame = new JFrame(title);\n\t\tJPanel panel = new JPanelWithInsets(new Insets(10, 30, 10, 30));\n\t\tBoxLayout boxLayout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);\n\t\tpanel.setLayout(boxLayout);\n\n\t\tpanel.add(new JLabel(message));\n\t\tadviseFrame.getContentPane().add(panel);\n\t\tadviseFrame.pack();\n\n\t\tif (parentComponent != null) {\n\t\t\tadviseFrame.setLocationRelativeTo(parentComponent);\n\t\t} else {\n\t\t\tUtil.centerOnScreen(adviseFrame);\n\t\t}\n\t\tadviseFrame.setAlwaysOnTop(true);\n\t\tadviseFrame.setVisible(true);\n\t}\n\n\t@Override\n\tpublic void eIDCardInsertedDuringSelection(BeIDCard card) {\n\t\tif (selectionDialog != null) {\n\t\t\tselectionDialog.addEIDCard(card);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void eIDCardRemovedDuringSelection(BeIDCard card) {\n\t\tif (selectionDialog != null) {\n\t\t\tselectionDialog.removeEIDCard(card);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setLocale(Locale newLocale) {\n\t\tthis.locale = newLocale;\n\t\tthis.messages = Messages.getInstance(newLocale);\n\t}\n\n\t@Override\n\tpublic Locale getLocale() {\n\t\tif (locale != null) {\n\t\t\treturn locale;\n\t\t}\n\t\treturn LocaleManager.getLocale();\n\t}\n\n}"
] | import be.bosa.commons.eid.client.BeIDCard;
import be.bosa.commons.eid.client.BeIDCards;
import be.bosa.commons.eid.client.FileType;
import be.bosa.commons.eid.client.impl.BeIDDigest;
import be.bosa.commons.eid.client.spi.BeIDCardsUI;
import be.bosa.commons.eid.dialogs.DefaultBeIDCardsUI;
import org.junit.Test;
import java.util.Locale; | /*
* Commons eID Project.
* Copyright (C) 2014 - 2018 BOSA.
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License version 3.0 as published by
* the Free Software Foundation.
*
* 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, see https://www.gnu.org/licenses/.
*/
package be.bosa.commons.eid.client.tests.integration;
public class LocaleTest {
@Test
public void testLocale() throws Exception {
try (BeIDCards cards = new BeIDCards()) {
cards.setLocale(Locale.FRENCH);
try (BeIDCard card = cards.getOneBeIDCard()) { | card.sign(new byte[]{0x00, 0x00, 0x00, 0x00}, BeIDDigest.PLAIN_TEXT, FileType.NonRepudiationCertificate, false); | 3 |
RoboTricker/Transport-Pipes | src/main/java/de/robotricker/transportpipes/inventory/CraftingPipeSettingsInventory.java | [
"public class TransportPipes extends JavaPlugin {\n\n private Injector injector;\n\n private SentryService sentry;\n private ThreadService thread;\n private DiskService diskService;\n\n @Override\n public void onEnable() {\n\n if (Bukkit.getVersion().contains(\"1.13\")) {\n LegacyUtils.setInstance(new LegacyUtils_1_13());\n } else {\n System.err.println(\"------------------------------------------\");\n System.err.println(\"TransportPipes currently only works with Minecraft 1.13.1 and 1.13.2\");\n System.err.println(\"------------------------------------------\");\n Bukkit.getPluginManager().disablePlugin(this);\n return;\n }\n\n try {\n Class.forName(\"org.bukkit.inventory.RecipeChoice\");\n } catch (ClassNotFoundException e) {\n System.err.println(\"------------------------------------------\");\n System.err.println(\"TransportPipes currently only works with Minecraft 1.13.1 and 1.13.2\");\n System.err.println(\"------------------------------------------\");\n Bukkit.getPluginManager().disablePlugin(this);\n return;\n }\n\n if (Files.isRegularFile(Paths.get(getDataFolder().getPath(), \"recipes.yml\"))) {\n System.err.println(\"------------------------------------------\");\n System.err.println(\"Please delete the old plugins/TransportPipes directory so TransportPipes can recreate it with a bunch of new config values\");\n System.err.println(\"------------------------------------------\");\n Bukkit.getPluginManager().disablePlugin(this);\n return;\n }\n\n //Initialize dependency injector\n injector = new InjectorBuilder().addDefaultHandlers(\"de.robotricker.transportpipes\").create();\n injector.register(Logger.class, getLogger());\n injector.register(Plugin.class, this);\n injector.register(JavaPlugin.class, this);\n injector.register(TransportPipes.class, this);\n\n //Initialize logger\n LoggerService logger = injector.getSingleton(LoggerService.class);\n\n //Initialize sentry\n sentry = injector.getSingleton(SentryService.class);\n if (!sentry.init(\"https://[email protected]/1281889?stacktrace.app.packages=de.robotricker&release=\" + getDescription().getVersion())) {\n logger.warning(\"Unable to initialize sentry!\");\n }\n sentry.addTag(\"thread\", Thread.currentThread().getName());\n sentry.injectThread(Thread.currentThread());\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"enabling plugin\");\n\n //Initialize configs\n injector.getSingleton(GeneralConf.class);\n injector.register(LangConf.class, new LangConf(this, injector.getSingleton(GeneralConf.class).getLanguage()));\n\n //Initialize API\n injector.getSingleton(TransportPipesAPI.class);\n\n //Initialize thread\n thread = injector.getSingleton(ThreadService.class);\n thread.start();\n\n //Register pipe\n BaseDuctType<Pipe> baseDuctType = injector.getSingleton(DuctRegister.class).registerBaseDuctType(\"Pipe\", PipeManager.class, PipeFactory.class, PipeItemManager.class);\n baseDuctType.setModelledRenderSystem(injector.newInstance(ModelledPipeRenderSystem.class));\n baseDuctType.setVanillaRenderSystem(injector.newInstance(VanillaPipeRenderSystem.class));\n\n //Register listeners\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(TPContainerListener.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(PlayerListener.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(DuctListener.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(WorldListener.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(PlayerSettingsInventory.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(ResourcepackService.class), this);\n\n //Register commands\n PaperCommandManager commandManager = new PaperCommandManager(this);\n commandManager.enableUnstableAPI(\"help\");\n commandManager.registerCommand(injector.getSingleton(TPCommand.class));\n commandManager.getCommandCompletions().registerCompletion(\"baseDuctType\", c -> injector.getSingleton(DuctRegister.class).baseDuctTypes().stream().map(BaseDuctType::getName).collect(Collectors.toList()));\n\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"enabled plugin\");\n\n diskService = injector.getSingleton(DiskService.class);\n\n TPContainerListener tpContainerListener = injector.getSingleton(TPContainerListener.class);\n runTaskSync(() -> {\n for (World world : Bukkit.getWorlds()) {\n for (Chunk loadedChunk : world.getLoadedChunks()) {\n tpContainerListener.handleChunkLoadSync(loadedChunk, true);\n }\n diskService.loadDuctsSync(world);\n }\n });\n\n if (Bukkit.getPluginManager().isPluginEnabled(\"LWC\")) {\n try {\n com.griefcraft.scripting.Module module = injector.getSingleton(LWCUtils.class);\n com.griefcraft.lwc.LWC.getInstance().getModuleLoader().registerModule(this, module);\n } catch (Exception e) {\n e.printStackTrace();\n sentry.record(e);\n }\n }\n\n }\n\n @Override\n public void onDisable() {\n if (sentry != null && thread != null) {\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"disabling plugin\");\n // Stop tpThread gracefully\n try {\n thread.stopRunning();\n thread.join();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n for (World world : Bukkit.getWorlds()) {\n saveWorld(world);\n }\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"disabled plugin\");\n }\n }\n\n public void saveWorld(World world) {\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"saving world \" + world.getName());\n diskService.saveDuctsSync(world);\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"saved world \" + world.getName());\n }\n\n public void runTaskSync(Runnable task) {\n if (isEnabled()) {\n Bukkit.getScheduler().runTask(this, task);\n }\n }\n\n public void runTaskSyncLater(Runnable task, long delay) {\n if (isEnabled()) {\n Bukkit.getScheduler().runTaskLater(this, task, delay);\n }\n }\n\n public void runTaskAsync(Runnable runnable, long delay) {\n thread.getTasks().put(runnable, delay);\n }\n\n public Injector getInjector() {\n return injector;\n }\n\n public void changeRenderSystem(Player p, String newRenderSystemName) {\n PlayerSettingsConf playerSettingsConf = injector.getSingleton(PlayerSettingsService.class).getOrCreateSettingsConf(p);\n DuctRegister ductRegister = injector.getSingleton(DuctRegister.class);\n GlobalDuctManager globalDuctManager = injector.getSingleton(GlobalDuctManager.class);\n ProtocolService protocolService = injector.getSingleton(ProtocolService.class);\n\n // change render system\n String oldRenderSystemName = playerSettingsConf.getRenderSystemName();\n if (oldRenderSystemName.equalsIgnoreCase(newRenderSystemName)) {\n return;\n }\n playerSettingsConf.setRenderSystemName(newRenderSystemName);\n\n for (BaseDuctType baseDuctType : ductRegister.baseDuctTypes()) {\n RenderSystem oldRenderSystem = RenderSystem.getRenderSystem(oldRenderSystemName, baseDuctType);\n\n // switch render system\n synchronized (globalDuctManager.getPlayerDucts(p)) {\n Iterator<Duct> ductIt = globalDuctManager.getPlayerDucts(p).iterator();\n while (ductIt.hasNext()) {\n Duct nextDuct = ductIt.next();\n protocolService.removeASD(p, oldRenderSystem.getASDForDuct(nextDuct));\n ductIt.remove();\n }\n }\n\n }\n }\n\n public long convertVersionToLong(String version) {\n long versionLong = 0;\n try {\n if (version.contains(\"-\")) {\n for (String subVersion : version.split(\"-\")) {\n if (subVersion.startsWith(\"b\")) {\n int buildNumber = 0;\n String buildNumberString = subVersion.substring(1);\n if (!buildNumberString.equalsIgnoreCase(\"CUSTOM\")) {\n buildNumber = Integer.parseInt(buildNumberString);\n }\n versionLong |= buildNumber;\n } else if (!subVersion.equalsIgnoreCase(\"SNAPSHOT\")) {\n versionLong |= (long) convertMainVersionStringToInt(subVersion) << 32;\n }\n }\n } else {\n versionLong = (long) convertMainVersionStringToInt(version) << 32;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return versionLong;\n }\n\n private int convertMainVersionStringToInt(String mainVersion) {\n int versionInt = 0;\n if (mainVersion.contains(\".\")) {\n // shift for every version number 1 byte to the left\n int leftShift = (mainVersion.split(\"\\\\.\").length - 1) * 8;\n for (String subVersion : mainVersion.split(\"\\\\.\")) {\n byte v = Byte.parseByte(subVersion);\n versionInt |= ((int) v << leftShift);\n leftShift -= 8;\n }\n } else {\n versionInt = Byte.parseByte(mainVersion);\n }\n return versionInt;\n }\n\n}",
"public class LangConf extends Conf {\n\n private static LangConf langConf;\n\n public LangConf(Plugin configPlugin, String language) {\n super(configPlugin, \"lang_\" + language.toLowerCase(Locale.ENGLISH) + \".yml\", \"lang.yml\", true);\n langConf = this;\n }\n\n public enum Key {\n\n PIPES_WHITE(\"pipes.white\"),\n PIPES_YELLOW(\"pipes.yellow\"),\n PIPES_GREEN(\"pipes.green\"),\n PIPES_BLUE(\"pipes.blue\"),\n PIPES_RED(\"pipes.red\"),\n PIPES_BLACK(\"pipes.black\"),\n PIPES_ICE(\"pipes.ice\"),\n PIPES_GOLDEN(\"pipes.golden\"),\n PIPES_IRON(\"pipes.iron\"),\n PIPES_VOID(\"pipes.void\"),\n PIPES_EXTRACTION(\"pipes.extraction\"),\n PIPES_CRAFTING(\"pipes.crafting\"),\n WRENCH(\"wrench\"),\n COLORS_WHITE(\"colors.white\"),\n COLORS_YELLOW(\"colors.yellow\"),\n COLORS_GREEN(\"colors.green\"),\n COLORS_BLUE(\"colors.blue\"),\n COLORS_RED(\"colors.red\"),\n COLORS_BLACK(\"colors.black\"),\n DIRECTIONS_EAST(\"directions.east\"),\n DIRECTIONS_WEST(\"directions.west\"),\n DIRECTIONS_SOUTH(\"directions.south\"),\n DIRECTIONS_NORTH(\"directions.north\"),\n DIRECTIONS_UP(\"directions.up\"),\n DIRECTIONS_DOWN(\"directions.down\"),\n DIRECTIONS_NONE(\"directions.none\"),\n RESOURCEPACK_FAIL(\"resourcepack_fail\"),\n RENDERSYSTEM_BLOCK(\"rendersystem_block\"),\n PROTECTED_BLOCK(\"protected_block\"),\n RENDERSYSTEM_NAME_VANILLA(\"rendersystem_name.vanilla\"),\n RENDERSYSTEM_NAME_MODELLED(\"rendersystem_name.modelled\"),\n PLAYER_SETTINGS_TITLE(\"player_settings.title\"),\n PLAYER_SETTINGS_RENDERDISTANCE(\"player_settings.renderdistance\"),\n PLAYER_SETTINGS_DECREASE_RENDERDISTANCE(\"player_settings.decrease_renderdistance\"),\n PLAYER_SETTINGS_INCREASE_RENDERDISTANCE(\"player_settings.increase_renderdistance\"),\n PLAYER_SETTINGS_RENDERSYSTEM(\"player_settings.rendersystem\"),\n PLAYER_SETTINGS_ITEM_VISIBILITY_SHOW(\"player_settings.item_visibility_show\"),\n PLAYER_SETTINGS_ITEM_VISIBILITY_HIDE(\"player_settings.item_visibility_hide\"),\n DUCT_INVENTORY_TITLE(\"duct_inventory.title\"),\n DUCT_INVENTORY_LEFTARROW(\"duct_inventory.leftarrow\"),\n DUCT_INVENTORY_RIGHTARROW(\"duct_inventory.rightarrow\"),\n DUCT_INVENTORY_FILTER_MODE_AND_STRICTNESS(\"duct_inventory.filter_mode_and_strictness\"),\n DUCT_INVENTORY_GOLDENPIPE_FILTERTITLE(\"duct_inventory.goldenpipe.filtertitle\"),\n DUCT_INVENTORY_EXTRACTIONPIPE_EXTRACTDIRECTION(\"duct_inventory.extractionpipe.extractdirection\"),\n DUCT_INVENTORY_EXTRACTIONPIPE_EXTRACTCONDITION(\"duct_inventory.extractionpipe.extractcondition\"),\n DUCT_INVENTORY_EXTRACTIONPIPE_EXTRACTAMOUNT(\"duct_inventory.extractionpipe.extractamount\"),\n DUCT_INVENTORY_EXTRACTIONPIPE_FILTERTITLE(\"duct_inventory.extractionpipe.filtertitle\"),\n DUCT_INVENTORY_CRAFTINGPIPE_OUTPUTDIRECTION(\"duct_inventory.craftingpipe.outputdirection\"),\n DUCT_INVENTORY_CRAFTINGPIPE_RETRIEVECACHEDITEMS(\"duct_inventory.craftingpipe.retrievecacheditems\"),\n DUCT_INVENTORY_CREATIVE_INVENTORY_TITLE(\"duct_inventory.creative_inventory_title\"),\n FILTER_STRICTNESS_MATERIAL(\"filter_strictness.material\"),\n FILTER_STRICTNESS_MATERIAL_METADATA(\"filter_strictness.material_metadata\"),\n FILTER_MODE_NORMAL(\"filter_mode.normal\"),\n FILTER_MODE_INVERTED(\"filter_mode.inverted\"),\n FILTER_MODE_BLOCKALL(\"filter_mode.blockall\"),\n EXTRACT_CONDITION_NEEDS_REDSTONE(\"extract_condition.needs_redstone\"),\n EXTRACT_CONDITION_ALWAYS_EXTRACT(\"extract_condition.always_extract\"),\n EXTRACT_CONDITION_NEVER_EXTRACT(\"extract_condition.never_extract\"),\n EXTRACT_AMOUNT_EXTRACT_1(\"extract_amount.extract_1\"),\n EXTRACT_AMOUNT_EXTRACT_16(\"extract_amount.extract_16\"),\n SHOW_HIDDEN_DUCTS(\"show_hidden_ducts\");\n\n private String key;\n\n Key(String key) {\n this.key = key;\n }\n\n public String get(Object... replacements) {\n String value = (String) langConf.read(key);\n if (value == null) {\n value = \"&cMissing Language Entry: &4\" + key + \"&r\";\n }\n for (int i = 0; i < replacements.length; i++) {\n value = value.replaceAll(\"%\" + (i + 1) + \"%\", replacements[i].toString());\n }\n return ChatColor.translateAlternateColorCodes('&', value);\n }\n\n public List<String> getLines(Object... replacements) {\n return Arrays.asList(get(replacements).split(\"\\\\\\\\n\"));\n }\n\n public void sendMessage(Player p) {\n for (String line : getLines()) {\n p.sendMessage(line);\n }\n }\n\n }\n\n}",
"public class CraftingPipe extends Pipe {\n\n private ItemData[] recipeItems;\n private Recipe recipe;\n private TPDirection outputDir;\n private List<ItemStack> cachedItems;\n\n public CraftingPipe(DuctType ductType, BlockLocation blockLoc, World world, Chunk chunk, DuctSettingsInventory settingsInv, GlobalDuctManager globalDuctManager, ItemDistributorService itemDistributor) {\n super(ductType, blockLoc, world, chunk, settingsInv, globalDuctManager, itemDistributor);\n recipeItems = new ItemData[9];\n outputDir = null;\n cachedItems = new ArrayList<>();\n }\n\n @Override\n public void tick(boolean bigTick, TransportPipes transportPipes, DuctManager ductManager) {\n super.tick(bigTick, transportPipes, ductManager);\n if (bigTick) {\n performCrafting((PipeManager) ductManager, transportPipes);\n }\n }\n\n @Override\n protected Map<TPDirection, Integer> calculateItemDistribution(PipeItem pipeItem, TPDirection movingDir, List<TPDirection> dirs, TransportPipes transportPipes) {\n ItemStack overflow = addCachedItem(pipeItem.getItem(), transportPipes);\n if (overflow != null) {\n transportPipes.runTaskSync(() -> getWorld().dropItem(getBlockLoc().toLocation(getWorld()), overflow));\n }\n return null;\n }\n\n public void performCrafting(PipeManager pipeManager, TransportPipes transportPipes) {\n if (outputDir != null && recipe != null) {\n ItemStack resultItem = recipe.getResult();\n\n List<RecipeChoice> ingredients = new ArrayList<>();\n if (recipe instanceof ShapelessRecipe) {\n ingredients.addAll(((ShapelessRecipe) recipe).getChoiceList());\n } else if (recipe instanceof ShapedRecipe) {\n Map<Character, Integer> charCounts = new HashMap<>();\n for (String row : ((ShapedRecipe) recipe).getShape()) {\n for (char c : row.toCharArray()) {\n charCounts.put(c, charCounts.getOrDefault(c, 0) + 1);\n }\n }\n for (Character c : charCounts.keySet()) {\n RecipeChoice ingredientChoice = ((ShapedRecipe) recipe).getChoiceMap().get(c);\n if (ingredientChoice != null) {\n ingredients.addAll(Collections.nCopies(charCounts.get(c), ingredientChoice));\n }\n }\n }\n\n List<ItemStack> cachedItems = new ArrayList<>();\n for (ItemStack cachedItem : this.cachedItems) {\n cachedItems.add(cachedItem.clone());\n }\n\n //iterate needed ingredients\n Iterator<RecipeChoice> neededIngredientsIt = ingredients.iterator();\n while (neededIngredientsIt.hasNext()) {\n RecipeChoice neededIngredient = neededIngredientsIt.next();\n\n //iterate cached items\n for (int i = 0; i < cachedItems.size(); i++) {\n if (neededIngredient.test(cachedItems.get(i))) {\n if (cachedItems.get(i).getAmount() > 1) {\n cachedItems.get(i).setAmount(cachedItems.get(i).getAmount() - 1);\n } else {\n cachedItems.remove(i);\n }\n neededIngredientsIt.remove();\n break;\n }\n }\n\n }\n\n if (ingredients.isEmpty()) {\n // update real cachedItems list\n this.cachedItems.clear();\n this.cachedItems.addAll(cachedItems);\n\n transportPipes.runTaskSync(() -> {\n settingsInv.save(null);\n settingsInv.populate();\n });\n\n // output result item\n PipeItem pipeItem = new PipeItem(resultItem.clone(), getWorld(), getBlockLoc(), outputDir);\n pipeItem.getRelativeLocation().set(0.5d, 0.5d, 0.5d);\n pipeItem.resetOldRelativeLocation();\n pipeManager.spawnPipeItem(pipeItem);\n pipeManager.putPipeItemInPipe(pipeItem);\n\n }\n }\n }\n\n public int spaceForItem(ItemData data) {\n int space = 0;\n\n for (int i = 0; i < 9; i++) {\n if (i >= cachedItems.size()) {\n space += data.toItemStack().getMaxStackSize();\n } else {\n ItemStack item = cachedItems.get(i);\n if (item.isSimilar(data.toItemStack()) && item.getAmount() < item.getMaxStackSize()) {\n space += item.getMaxStackSize() - item.getAmount();\n }\n }\n }\n\n return space;\n }\n\n public ItemData[] getRecipeItems() {\n return recipeItems;\n }\n\n public TPDirection getOutputDir() {\n return outputDir;\n }\n\n public void setOutputDir(TPDirection outputDir) {\n this.outputDir = outputDir;\n }\n\n public Recipe getRecipe() {\n return recipe;\n }\n\n public void setRecipe(Recipe recipe) {\n this.recipe = recipe;\n }\n\n public List<ItemStack> getCachedItems() {\n return cachedItems;\n }\n\n public ItemStack addCachedItem(ItemStack item, TransportPipes transportPipes) {\n for (ItemStack cachedItem : cachedItems) {\n if (cachedItem.isSimilar(item)) {\n int cachedItemAmount = cachedItem.getAmount();\n cachedItem.setAmount(Math.min(cachedItem.getMaxStackSize(), cachedItemAmount + item.getAmount()));\n int overflow = cachedItemAmount + item.getAmount() - cachedItem.getMaxStackSize();\n if (overflow > 0) {\n item.setAmount(overflow);\n } else {\n item = null;\n break;\n }\n }\n }\n if (cachedItems.size() < 9 && item != null) {\n cachedItems.add(item);\n item = null;\n }\n\n transportPipes.runTaskSync(() -> {\n settingsInv.save(null);\n settingsInv.populate();\n });\n return item;\n }\n\n public void updateOutputDirection(boolean cycle) {\n TPDirection oldOutputDirection = getOutputDir();\n Set<TPDirection> connections = getAllConnections();\n if (connections.isEmpty()) {\n outputDir = null;\n } else if (cycle || outputDir == null || !connections.contains(outputDir)) {\n do {\n if (outputDir == null) {\n outputDir = TPDirection.NORTH;\n } else {\n outputDir = outputDir.next();\n }\n } while (!connections.contains(outputDir));\n }\n if (oldOutputDirection != outputDir) {\n settingsInv.populate();\n }\n }\n\n @Override\n public void notifyConnectionChange() {\n super.notifyConnectionChange();\n updateOutputDirection(false);\n }\n\n @Override\n public Material getBreakParticleData() {\n return Material.CRAFTING_TABLE;\n }\n\n @Override\n public void saveToNBTTag(CompoundTag compoundTag, ItemService itemService) {\n super.saveToNBTTag(compoundTag, itemService);\n\n compoundTag.putInt(\"outputDir\", outputDir != null ? outputDir.ordinal() : -1);\n\n ListTag<StringTag> recipeItemsListTag = new ListTag<>(StringTag.class);\n for (int i = 0; i < 9; i++) {\n ItemData itemData = recipeItems[i];\n if (itemData == null) {\n recipeItemsListTag.add(new StringTag(null));\n } else {\n recipeItemsListTag.addString(itemService.serializeItemStack(itemData.toItemStack()));\n }\n }\n compoundTag.put(\"recipeItems\", recipeItemsListTag);\n\n ListTag<StringTag> cachedItemsListTag = new ListTag<>(StringTag.class);\n for (int i = 0; i < cachedItems.size(); i++) {\n ItemStack itemStack = cachedItems.get(i);\n cachedItemsListTag.addString(itemService.serializeItemStack(itemStack));\n }\n compoundTag.put(\"cachedItems\", cachedItemsListTag);\n\n }\n\n @Override\n public void loadFromNBTTag(CompoundTag compoundTag, ItemService itemService) {\n super.loadFromNBTTag(compoundTag, itemService);\n\n outputDir = compoundTag.getInt(\"outputDir\") != -1 ? TPDirection.values()[compoundTag.getInt(\"outputDir\")] : null;\n\n ListTag<StringTag> recipeItemsListTag = (ListTag<StringTag>) compoundTag.getListTag(\"recipeItems\");\n for (int i = 0; i < 9; i++) {\n if (i >= recipeItemsListTag.size()) {\n recipeItems[i] = null;\n continue;\n }\n ItemStack deserialized = itemService.deserializeItemStack(recipeItemsListTag.get(i).getValue());\n recipeItems[i] = deserialized != null ? new ItemData(deserialized) : null;\n }\n\n cachedItems.clear();\n ListTag<StringTag> cachedItemsListTag = (ListTag<StringTag>) compoundTag.getListTag(\"cachedItems\");\n for (int i = 0; i < cachedItemsListTag.size(); i++) {\n ItemStack deserialized = itemService.deserializeItemStack(cachedItemsListTag.get(i).getValue());\n if (deserialized != null)\n cachedItems.add(deserialized);\n }\n\n settingsInv.populate();\n settingsInv.save(null);\n }\n\n @Override\n public List<ItemStack> destroyed(TransportPipes transportPipes, DuctManager ductManager, Player destroyer) {\n List<ItemStack> items = super.destroyed(transportPipes, ductManager, destroyer);\n for (int i = 0; i < 9; i++) {\n ItemData id = recipeItems[i];\n if (id != null) {\n items.add(id.toItemStack().clone());\n }\n }\n for (ItemStack cachedItem : cachedItems) {\n items.add(cachedItem.clone());\n }\n return items;\n }\n}",
"public class ItemData {\n\n private ItemStack backedItem;\n\n public ItemData(ItemStack item) {\n this.backedItem = item.clone();\n this.backedItem.setAmount(1);\n }\n\n public ItemStack toItemStack() {\n return backedItem.clone();\n }\n\n @Override\n public int hashCode() {\n int hash = 1;\n\n hash = hash * 31 + backedItem.getType().ordinal();\n hash = hash * 31 + (backedItem.hasItemMeta() ? backedItem.getItemMeta().hashCode() : 0);\n\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n ItemData other = (ItemData) obj;\n if (backedItem == null) {\n return other.backedItem == null;\n } else return backedItem.isSimilar(other.backedItem);\n }\n\n @Override\n public String toString() {\n return backedItem.toString();\n }\n}",
"public enum TPDirection {\n\n EAST(1, 0, 0, BlockFace.EAST, LangConf.Key.DIRECTIONS_EAST.get()),\n WEST(-1, 0, 0, BlockFace.WEST, LangConf.Key.DIRECTIONS_WEST.get()),\n SOUTH(0, 0, 1, BlockFace.SOUTH, LangConf.Key.DIRECTIONS_SOUTH.get()),\n NORTH(0, 0, -1, BlockFace.NORTH, LangConf.Key.DIRECTIONS_NORTH.get()),\n UP(0, 1, 0, BlockFace.UP, LangConf.Key.DIRECTIONS_UP.get()),\n DOWN(0, -1, 0, BlockFace.DOWN, LangConf.Key.DIRECTIONS_DOWN.get());\n\n private Vector vec;\n private BlockFace blockFace;\n private String displayName;\n\n TPDirection(int x, int y, int z, BlockFace blockFace, String displayName) {\n this.vec = new Vector(x, y, z);\n this.blockFace = blockFace;\n this.displayName = displayName;\n }\n\n public Vector getVector() {\n return vec.clone();\n }\n\n public int getX() {\n return vec.getBlockX();\n }\n\n public int getY() {\n return vec.getBlockY();\n }\n\n public int getZ() {\n return vec.getBlockZ();\n }\n\n public BlockFace getBlockFace() {\n return blockFace;\n }\n\n public TPDirection getOpposite() {\n return fromBlockFace(getBlockFace().getOppositeFace());\n }\n\n public boolean isSide() {\n return vec.getBlockY() == 0;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public TPDirection next() {\n int ordinal = ordinal();\n ordinal++;\n ordinal %= values().length;\n return values()[ordinal];\n }\n\n public static TPDirection fromBlockFace(BlockFace blockFace) {\n for (TPDirection tpDir : TPDirection.values()) {\n if (tpDir.getBlockFace().equals(blockFace)) {\n return tpDir;\n }\n }\n return null;\n }\n\n}"
] | import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.attribute.Attribute;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.DragType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.RecipeChoice;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.PressurePlate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import de.robotricker.transportpipes.TransportPipes;
import de.robotricker.transportpipes.config.LangConf;
import de.robotricker.transportpipes.duct.pipe.CraftingPipe;
import de.robotricker.transportpipes.duct.pipe.filter.ItemData;
import de.robotricker.transportpipes.location.TPDirection; | package de.robotricker.transportpipes.inventory;
public class CraftingPipeSettingsInventory extends DuctSettingsInventory {
@Override
public void create() {
inv = Bukkit.createInventory(null, 6 * 9, LangConf.Key.DUCT_INVENTORY_TITLE.get(duct.getDuctType().getFormattedTypeName()));
}
@Override
public void closeForAllPlayers(TransportPipes transportPipes) {
save(null);
super.closeForAllPlayers(transportPipes);
}
@Override
public void populate() {
CraftingPipe pipe = (CraftingPipe) duct; | TPDirection outputDir = pipe.getOutputDir(); | 4 |
underhilllabs/dccsched | src/com/underhilllabs/dccsched/io/RemoteWorksheetsHandler.java | [
"public class ScheduleContract {\n\n /**\n * Special value for {@link SyncColumns#UPDATED} indicating that an entry\n * has never been updated, or doesn't exist yet.\n */\n public static final long UPDATED_NEVER = -2;\n\n /**\n * Special value for {@link SyncColumns#UPDATED} indicating that the last\n * update time is unknown, usually when inserted from a local file source.\n */\n public static final long UPDATED_UNKNOWN = -1;\n\n public interface SyncColumns {\n /** Last time this entry was updated or synchronized. */\n String UPDATED = \"updated\";\n }\n\n interface BlocksColumns {\n /** Unique string identifying this block of time. */\n String BLOCK_ID = \"block_id\";\n /** Title describing this block of time. */\n String BLOCK_TITLE = \"block_title\";\n /** Time when this block starts. */\n String BLOCK_START = \"block_start\";\n /** Time when this block ends. */\n String BLOCK_END = \"block_end\";\n /** Type describing this block. */\n String BLOCK_TYPE = \"block_type\";\n }\n\n interface TracksColumns {\n /** Unique string identifying this track. */\n String TRACK_ID = \"track_id\";\n /** Name describing this track. */\n String TRACK_NAME = \"track_name\";\n /** Color used to identify this track, in {@link Color#argb} format. */\n String TRACK_COLOR = \"track_color\";\n /** Body of text explaining this track in detail. */\n String TRACK_ABSTRACT = \"track_abstract\";\n }\n\n interface RoomsColumns {\n /** Unique string identifying this room. */\n String ROOM_ID = \"room_id\";\n /** Name describing this room. */\n String ROOM_NAME = \"room_name\";\n /** Building floor this room exists on. */\n String ROOM_FLOOR = \"room_floor\";\n }\n\n interface SessionsColumns {\n /** Unique string identifying this session. */\n String SESSION_ID = \"session_id\";\n /** Type of session, such as difficulty level. */\n String TYPE = \"type\";\n /** Title describing this track. */\n String TITLE = \"title\";\n /** Body of text explaining this session in detail. */\n String ABSTRACT = \"abstract\";\n /** Requirements that attendees should meet. */\n String REQUIREMENTS = \"requirements\";\n /** User-specific flag indicating starred status. */\n String STARRED = \"starred\";\n /** Link to Moderator for this session. */\n String MODERATOR_URL = \"moderator_url\";\n /** Link to Wave for this session. */\n String WAVE_URL = \"wave_url\";\n /** Additional keywords that describe this session. */\n String KEYWORDS = \"keywords\";\n /** Hashtag used to identify this session in social media. */\n String HASHTAG = \"hashtag\";\n\n // TODO: moderator, wave, other online links\n }\n\n interface SpeakersColumns {\n /** Unique string identifying this speaker. */\n String SPEAKER_ID = \"speaker_id\";\n /** Name of this speaker. */\n String SPEAKER_NAME = \"speaker_name\";\n /** Company this speaker works for. */\n String SPEAKER_COMPANY = \"speaker_company\";\n /** Body of text describing this speaker in detail. */\n String SPEAKER_ABSTRACT = \"speaker_abstract\";\n }\n\n interface VendorsColumns {\n /** Unique string identifying this vendor. */\n String VENDOR_ID = \"vendor_id\";\n /** Name of this vendor. */\n String NAME = \"name\";\n /** Location or city this vendor is based in. */\n String LOCATION = \"location\";\n /** Body of text describing this vendor. */\n String DESC = \"desc\";\n /** Link to vendor online. */\n String URL = \"url\";\n /** Body of text describing the product of this vendor. */\n String PRODUCT_DESC = \"product_desc\";\n /** Link to vendor logo. */\n String LOGO_URL = \"logo_url\";\n /** {@link #LOGO_URL} stored as local blob, when available. */\n String LOGO = \"logo\";\n /** User-specific flag indicating starred status. */\n String STARRED = \"starred\";\n }\n\n interface NotesColumns {\n /** Time this note was created. */\n String NOTE_TIME = \"note_time\";\n /** User-generated content of note. */\n String NOTE_CONTENT = \"note_content\";\n }\n\n public static final String CONTENT_AUTHORITY = \"com.underhilllabs.dccsched\";\n\n private static final Uri BASE_CONTENT_URI = Uri.parse(\"content://\" + CONTENT_AUTHORITY);\n\n private static final String PATH_BLOCKS = \"blocks\";\n private static final String PATH_AT = \"at\";\n private static final String PATH_BETWEEN = \"between\";\n private static final String PATH_TRACKS = \"tracks\";\n private static final String PATH_ROOMS = \"rooms\";\n private static final String PATH_SESSIONS = \"sessions\";\n private static final String PATH_STARRED = \"starred\";\n private static final String PATH_SPEAKERS = \"speakers\";\n private static final String PATH_VENDORS = \"vendors\";\n private static final String PATH_NOTES = \"notes\";\n private static final String PATH_EXPORT = \"export\";\n private static final String PATH_SEARCH = \"search\";\n private static final String PATH_SEARCH_SUGGEST = \"search_suggest_query\";\n\n /**\n * Blocks are generic timeslots that {@link Sessions} and other related\n * events fall into.\n */\n public static class Blocks implements BlocksColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.block\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.block\";\n\n /** Count of {@link Sessions} inside given block. */\n public static final String SESSIONS_COUNT = \"sessions_count\";\n\n /**\n * Flag indicating that at least one {@link Sessions#SESSION_ID} inside\n * this block has {@link Sessions#STARRED} set.\n */\n public static final String CONTAINS_STARRED = \"contains_starred\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + \" ASC, \"\n + BlocksColumns.BLOCK_END + \" ASC\";\n\n /** Build {@link Uri} for requested {@link #BLOCK_ID}. */\n public static Uri buildBlockUri(String blockId) {\n return CONTENT_URI.buildUpon().appendPath(blockId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #BLOCK_ID}.\n */\n public static Uri buildSessionsUri(String blockId) {\n return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Blocks} that occur\n * between the requested time boundaries.\n */\n public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) {\n return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath(\n String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build();\n }\n\n /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */\n public static String getBlockId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n /**\n * Generate a {@link #BLOCK_ID} that will always match the requested\n * {@link Blocks} details.\n */\n public static String generateBlockId(long startTime, long endTime) {\n startTime /= DateUtils.SECOND_IN_MILLIS;\n endTime /= DateUtils.SECOND_IN_MILLIS;\n return ParserUtils.sanitizeId(startTime + \"-\" + endTime);\n }\n }\n\n /**\n * Tracks are overall categories for {@link Sessions} and {@link Vendors},\n * such as \"Android\" or \"Enterprise.\"\n */\n public static class Tracks implements TracksColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.track\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.track\";\n\n /** Count of {@link Sessions} inside given track. */\n public static final String SESSIONS_COUNT = \"sessions_count\";\n /** Count of {@link Vendors} inside given track. */\n public static final String VENDORS_COUNT = \"vendors_count\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + \" ASC\";\n\n /** Build {@link Uri} for requested {@link #TRACK_ID}. */\n public static Uri buildTrackUri(String trackId) {\n return CONTENT_URI.buildUpon().appendPath(trackId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #TRACK_ID}.\n */\n public static Uri buildSessionsUri(String trackId) {\n return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Vendors} associated with\n * the requested {@link #TRACK_ID}.\n */\n public static Uri buildVendorsUri(String trackId) {\n return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build();\n }\n\n /** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */\n public static String getTrackId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n /**\n * Generate a {@link #TRACK_ID} that will always match the requested\n * {@link Tracks} details.\n */\n public static String generateTrackId(String title) {\n return ParserUtils.sanitizeId(title);\n }\n }\n\n /**\n * Rooms are physical locations at the conference venue.\n */\n public static class Rooms implements RoomsColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.room\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.room\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + \" ASC, \"\n + RoomsColumns.ROOM_NAME + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #ROOM_ID}. */\n public static Uri buildRoomUri(String roomId) {\n return CONTENT_URI.buildUpon().appendPath(roomId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #ROOM_ID}.\n */\n public static Uri buildSessionsDirUri(String roomId) {\n return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build();\n }\n\n /** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */\n public static String getRoomId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n /**\n * Generate a {@link #ROOM_ID} that will always match the requested\n * {@link Rooms} details.\n */\n public static String generateRoomId(String room) {\n return ParserUtils.sanitizeId(room);\n }\n }\n\n /**\n * Each session is a block of time that has a {@link Tracks}, a\n * {@link Rooms}, and zero or more {@link Speakers}.\n */\n public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns,\n SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build();\n public static final Uri CONTENT_STARRED_URI =\n CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.session\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.session\";\n\n public static final String BLOCK_ID = \"block_id\";\n public static final String ROOM_ID = \"room_id\";\n\n public static final String SEARCH_SNIPPET = \"search_snippet\";\n\n // TODO: shortcut primary track to offer sub-sorting here\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + \" ASC,\"\n + SessionsColumns.TITLE + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #SESSION_ID}. */\n public static Uri buildSessionUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Speakers} associated\n * with the requested {@link #SESSION_ID}.\n */\n public static Uri buildSpeakersDirUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Tracks} associated with\n * the requested {@link #SESSION_ID}.\n */\n public static Uri buildTracksDirUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Notes} associated with\n * the requested {@link #SESSION_ID}.\n */\n public static Uri buildNotesDirUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_NOTES).build();\n }\n\n public static Uri buildSessionsAtDirUri(long time) {\n return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time))\n .build();\n }\n\n public static Uri buildSearchUri(String query) {\n return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();\n }\n\n public static boolean isSearchUri(Uri uri) {\n return PATH_SEARCH.equals(uri.getPathSegments().get(1));\n }\n\n /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */\n public static String getSessionId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n public static String getSearchQuery(Uri uri) {\n return uri.getPathSegments().get(2);\n }\n\n /**\n * Generate a {@link #SESSION_ID} that will always match the requested\n * {@link Sessions} details.\n */\n public static String generateSessionId(String title) {\n return ParserUtils.sanitizeId(title);\n }\n }\n\n /**\n * Speakers are individual people that lead {@link Sessions}.\n */\n public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.speaker\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.speaker\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME\n + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */\n public static Uri buildSpeakerUri(String speakerId) {\n return CONTENT_URI.buildUpon().appendPath(speakerId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #SPEAKER_ID}.\n */\n public static Uri buildSessionsDirUri(String speakerId) {\n return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build();\n }\n\n /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */\n public static String getSpeakerId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n /**\n * Generate a {@link #SPEAKER_ID} that will always match the requested\n * {@link Speakers} details.\n */\n public static String generateSpeakerId(String speakerLdap) {\n return ParserUtils.sanitizeId(speakerLdap);\n }\n }\n\n /**\n * Each vendor is a company appearing at the conference that may be\n * associated with a specific {@link Tracks}.\n */\n public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build();\n public static final Uri CONTENT_STARRED_URI =\n CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.vendor\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.vendor\";\n\n /** {@link Tracks#TRACK_ID} that this vendor belongs to. */\n public static final String TRACK_ID = \"track_id\";\n\n public static final String SEARCH_SNIPPET = \"search_snippet\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = VendorsColumns.NAME + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #VENDOR_ID}. */\n public static Uri buildVendorUri(String vendorId) {\n return CONTENT_URI.buildUpon().appendPath(vendorId).build();\n }\n\n public static Uri buildSearchUri(String query) {\n return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();\n }\n\n public static boolean isSearchUri(Uri uri) {\n return PATH_SEARCH.equals(uri.getPathSegments().get(1));\n }\n\n /** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */\n public static String getVendorId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n public static String getSearchQuery(Uri uri) {\n return uri.getPathSegments().get(2);\n }\n\n /**\n * Generate a {@link #VENDOR_ID} that will always match the requested\n * {@link Vendors} details.\n */\n public static String generateVendorId(String companyLogo) {\n return ParserUtils.sanitizeId(companyLogo);\n }\n }\n\n /**\n * Notes are user-generated data related to specific {@link Sessions}.\n */\n public static class Notes implements NotesColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_NOTES).build();\n public static final Uri CONTENT_EXPORT_URI =\n CONTENT_URI.buildUpon().appendPath(PATH_EXPORT).build();\n\n /** {@link Sessions#SESSION_ID} that this note references. */\n public static final String SESSION_ID = \"session_id\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = NotesColumns.NOTE_TIME + \" DESC\";\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.note\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.note\";\n\n public static Uri buildNoteUri(long noteId) {\n return ContentUris.withAppendedId(CONTENT_URI, noteId);\n }\n\n public static long getNoteId(Uri uri) {\n return ContentUris.parseId(uri);\n }\n }\n\n public static class SearchSuggest {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build();\n\n public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1\n + \" COLLATE NOCASE ASC\";\n }\n\n private ScheduleContract() {\n }\n}",
"public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns,\n SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build();\n public static final Uri CONTENT_STARRED_URI =\n CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.session\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.session\";\n\n public static final String BLOCK_ID = \"block_id\";\n public static final String ROOM_ID = \"room_id\";\n\n public static final String SEARCH_SNIPPET = \"search_snippet\";\n\n // TODO: shortcut primary track to offer sub-sorting here\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + \" ASC,\"\n + SessionsColumns.TITLE + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #SESSION_ID}. */\n public static Uri buildSessionUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Speakers} associated\n * with the requested {@link #SESSION_ID}.\n */\n public static Uri buildSpeakersDirUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Tracks} associated with\n * the requested {@link #SESSION_ID}.\n */\n public static Uri buildTracksDirUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Notes} associated with\n * the requested {@link #SESSION_ID}.\n */\n public static Uri buildNotesDirUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_NOTES).build();\n }\n\n public static Uri buildSessionsAtDirUri(long time) {\n return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time))\n .build();\n }\n\n public static Uri buildSearchUri(String query) {\n return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();\n }\n\n public static boolean isSearchUri(Uri uri) {\n return PATH_SEARCH.equals(uri.getPathSegments().get(1));\n }\n\n /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */\n public static String getSessionId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n public static String getSearchQuery(Uri uri) {\n return uri.getPathSegments().get(2);\n }\n\n /**\n * Generate a {@link #SESSION_ID} that will always match the requested\n * {@link Sessions} details.\n */\n public static String generateSessionId(String title) {\n return ParserUtils.sanitizeId(title);\n }\n}",
"public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.speaker\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.speaker\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME\n + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */\n public static Uri buildSpeakerUri(String speakerId) {\n return CONTENT_URI.buildUpon().appendPath(speakerId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #SPEAKER_ID}.\n */\n public static Uri buildSessionsDirUri(String speakerId) {\n return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build();\n }\n\n /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */\n public static String getSpeakerId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n /**\n * Generate a {@link #SPEAKER_ID} that will always match the requested\n * {@link Speakers} details.\n */\n public static String generateSpeakerId(String speakerLdap) {\n return ParserUtils.sanitizeId(speakerLdap);\n }\n}",
"public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build();\n public static final Uri CONTENT_STARRED_URI =\n CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.vendor\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.vendor\";\n\n /** {@link Tracks#TRACK_ID} that this vendor belongs to. */\n public static final String TRACK_ID = \"track_id\";\n\n public static final String SEARCH_SNIPPET = \"search_snippet\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = VendorsColumns.NAME + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #VENDOR_ID}. */\n public static Uri buildVendorUri(String vendorId) {\n return CONTENT_URI.buildUpon().appendPath(vendorId).build();\n }\n\n public static Uri buildSearchUri(String query) {\n return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();\n }\n\n public static boolean isSearchUri(Uri uri) {\n return PATH_SEARCH.equals(uri.getPathSegments().get(1));\n }\n\n /** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */\n public static String getVendorId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n public static String getSearchQuery(Uri uri) {\n return uri.getPathSegments().get(2);\n }\n\n /**\n * Generate a {@link #VENDOR_ID} that will always match the requested\n * {@link Vendors} details.\n */\n public static String generateVendorId(String companyLogo) {\n return ParserUtils.sanitizeId(companyLogo);\n }\n}",
"public class Lists {\n\n /**\n * Creates an empty {@code ArrayList} instance.\n *\n * <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use\n * {@link Collections#emptyList} instead.\n *\n * @return a newly-created, initially-empty {@code ArrayList}\n */\n public static <E> ArrayList<E> newArrayList() {\n return new ArrayList<E>();\n }\n\n /**\n * Creates a resizable {@code ArrayList} instance containing the given\n * elements.\n *\n * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the\n * following:\n *\n * <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);}\n *\n * <p>where {@code sub1} and {@code sub2} are references to subtypes of\n * {@code Base}, not of {@code Base} itself. To get around this, you must\n * use:\n *\n * <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);}\n *\n * @param elements the elements that the list should contain, in order\n * @return a newly-created {@code ArrayList} containing those elements\n */\n public static <E> ArrayList<E> newArrayList(E... elements) {\n int capacity = (elements.length * 110) / 100 + 5;\n ArrayList<E> list = new ArrayList<E>(capacity);\n Collections.addAll(list, elements);\n return list;\n }\n}",
"public class Maps {\n /**\n * Creates a {@code HashMap} instance.\n *\n * @return a newly-created, initially-empty {@code HashMap}\n */\n public static <K, V> HashMap<K, V> newHashMap() {\n return new HashMap<K, V>();\n }\n\n /**\n * Creates a {@code LinkedHashMap} instance.\n *\n * @return a newly-created, initially-empty {@code HashMap}\n */\n public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {\n return new LinkedHashMap<K, V>();\n }\n}",
"public class ParserUtils {\n // TODO: consider refactor to HandlerUtils?\n\n // TODO: localize this string at some point\n public static final String BLOCK_TITLE_BREAKOUT_SESSIONS = \"Breakout sessions\";\n\n public static final String BLOCK_TYPE_FOOD = \"food\";\n public static final String BLOCK_TYPE_SESSION = \"session\";\n public static final String BLOCK_TYPE_OFFICE_HOURS = \"officehours\";\n\n public static final Set<String> LOCAL_TRACK_IDS = Sets.newHashSet(\n\t \"platinum\",\"gold\",\"silver\",\"bronze\", \"business\", \"development\", \"design\", \"community\");\n\n /** Used to sanitize a string to be {@link Uri} safe. */\n private static final Pattern sSanitizePattern = Pattern.compile(\"[^a-z0-9-_]\");\n private static final Pattern sParenPattern = Pattern.compile(\"\\\\(.*?\\\\)\");\n\n /** Used to split a comma-separated string. */\n private static final Pattern sCommaPattern = Pattern.compile(\"\\\\s*,\\\\s*\");\n\n private static Time sTime = new Time();\n private static XmlPullParserFactory sFactory;\n\n /**\n * Sanitize the given string to be {@link Uri} safe for building\n * {@link ContentProvider} paths.\n */\n public static String sanitizeId(String input) {\n return sanitizeId(input, false);\n }\n\n /**\n * Sanitize the given string to be {@link Uri} safe for building\n * {@link ContentProvider} paths.\n */\n public static String sanitizeId(String input, boolean stripParen) {\n if (input == null) return null;\n if (stripParen) {\n // Strip out all parenthetical statements when requested.\n input = sParenPattern.matcher(input).replaceAll(\"\");\n }\n return sSanitizePattern.matcher(input.toLowerCase()).replaceAll(\"\");\n }\n\n /**\n * Split the given comma-separated string, returning all values.\n */\n public static String[] splitComma(CharSequence input) {\n if (input == null) return new String[0];\n return sCommaPattern.split(input);\n }\n\n /**\n * Build and return a new {@link XmlPullParser} with the given\n * {@link InputStream} assigned to it.\n */\n public static XmlPullParser newPullParser(InputStream input) throws XmlPullParserException {\n if (sFactory == null) {\n sFactory = XmlPullParserFactory.newInstance();\n }\n final XmlPullParser parser = sFactory.newPullParser();\n parser.setInput(input, null);\n return parser;\n }\n\n /**\n * Parse the given string as a RFC 3339 timestamp, returning the value as\n * milliseconds since the epoch.\n */\n public static long parseTime(String time) {\n sTime.parse3339(time);\n return sTime.toMillis(false);\n }\n\n /**\n * Return a {@link Blocks#BLOCK_ID} matching the requested arguments.\n */\n public static String findBlock(String title, long startTime, long endTime) {\n // TODO: in future we might check provider if block exists\n return Blocks.generateBlockId(startTime, endTime);\n }\n\n /**\n * Return a {@link Blocks#BLOCK_ID} matching the requested arguments,\n * inserting a new {@link Blocks} entry as a\n * {@link ContentProviderOperation} when none already exists.\n */\n public static String findOrCreateBlock(String title, String type, long startTime, long endTime,\n ArrayList<ContentProviderOperation> batch, ContentResolver resolver) {\n // TODO: check for existence instead of always blindly creating. it's\n // okay for now since the database replaces on conflict.\n final ContentProviderOperation.Builder builder = ContentProviderOperation\n .newInsert(Blocks.CONTENT_URI);\n final String blockId = Blocks.generateBlockId(startTime, endTime);\n builder.withValue(Blocks.BLOCK_ID, blockId);\n builder.withValue(Blocks.BLOCK_TITLE, title);\n builder.withValue(Blocks.BLOCK_START, startTime);\n builder.withValue(Blocks.BLOCK_END, endTime);\n builder.withValue(Blocks.BLOCK_TYPE, type);\n batch.add(builder.build());\n return blockId;\n }\n\n /**\n * Query and return the {@link SyncColumns#UPDATED} time for the requested\n * {@link Uri}. Expects the {@link Uri} to reference a single item.\n */\n public static long queryItemUpdated(Uri uri, ContentResolver resolver) {\n final String[] projection = { SyncColumns.UPDATED };\n final Cursor cursor = resolver.query(uri, projection, null, null, null);\n try {\n if (cursor.moveToFirst()) {\n return cursor.getLong(0);\n } else {\n return ScheduleContract.UPDATED_NEVER;\n }\n } finally {\n cursor.close();\n }\n }\n\n /**\n * Query and return the newest {@link SyncColumns#UPDATED} time for all\n * entries under the requested {@link Uri}. Expects the {@link Uri} to\n * reference a directory of several items.\n */\n public static long queryDirUpdated(Uri uri, ContentResolver resolver) {\n final String[] projection = { \"MAX(\" + SyncColumns.UPDATED + \")\" };\n final Cursor cursor = resolver.query(uri, projection, null, null, null);\n try {\n cursor.moveToFirst();\n return cursor.getLong(0);\n } finally {\n cursor.close();\n }\n }\n\n /**\n * Translate an incoming {@link Tracks#TRACK_ID}, usually passing directly\n * through, but returning a different value when a local alias is defined.\n */\n public static String translateTrackIdAlias(String trackId) {\n if (\"gwt\".equals(trackId)) {\n return \"googlewebtoolkit\";\n } else {\n return trackId;\n }\n }\n\n /**\n * Translate a possibly locally aliased {@link Tracks#TRACK_ID} to its real value;\n * this usually is a pass-through.\n */\n public static String translateTrackIdAliasInverse(String trackId) {\n if (\"googlewebtoolkit\".equals(trackId)) {\n return \"gwt\";\n } else {\n return trackId;\n }\n }\n\n /** XML tag constants used by the Atom standard. */\n public interface AtomTags {\n String ENTRY = \"entry\";\n String UPDATED = \"updated\";\n String TITLE = \"title\";\n String LINK = \"link\";\n String CONTENT = \"content\";\n\n String REL = \"rel\";\n String HREF = \"href\";\n }\n}",
"public class WorksheetEntry {\n private static final String REL_LISTFEED = \"http://schemas.google.com/spreadsheets/2006#listfeed\";\n\n private long mUpdated;\n private String mTitle;\n private String mListFeed;\n\n public long getUpdated() {\n return mUpdated;\n }\n\n public String getTitle() {\n return mTitle;\n }\n\n public String getListFeed() {\n return mListFeed;\n }\n\n @Override\n public String toString() {\n return \"title=\" + mTitle + \", updated=\" + mUpdated + \" (\"\n + DateUtils.getRelativeTimeSpanString(mUpdated) + \")\";\n }\n\n public static WorksheetEntry fromParser(XmlPullParser parser) throws XmlPullParserException,\n IOException {\n final int depth = parser.getDepth();\n final WorksheetEntry entry = new WorksheetEntry();\n\n String tag = null;\n int type;\n while (((type = parser.next()) != END_TAG ||\n parser.getDepth() > depth) && type != END_DOCUMENT) {\n if (type == START_TAG) {\n tag = parser.getName();\n if (LINK.equals(tag)) {\n final String rel = parser.getAttributeValue(null, REL);\n final String href = parser.getAttributeValue(null, HREF);\n if (REL_LISTFEED.equals(rel)) {\n entry.mListFeed = href;\n }\n }\n } else if (type == END_TAG) {\n tag = null;\n } else if (type == TEXT) {\n final String text = parser.getText();\n if (TITLE.equals(tag)) {\n entry.mTitle = text;\n } else if (UPDATED.equals(tag)) {\n entry.mUpdated = ParserUtils.parseTime(text);\n }\n }\n }\n return entry;\n }\n}"
] | import static com.underhilllabs.dccsched.util.ParserUtils.AtomTags.ENTRY;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
import com.underhilllabs.dccsched.provider.ScheduleContract;
import com.underhilllabs.dccsched.provider.ScheduleContract.Sessions;
import com.underhilllabs.dccsched.provider.ScheduleContract.Speakers;
import com.underhilllabs.dccsched.provider.ScheduleContract.Vendors;
import com.underhilllabs.dccsched.util.Lists;
import com.underhilllabs.dccsched.util.Maps;
import com.underhilllabs.dccsched.util.ParserUtils;
import com.underhilllabs.dccsched.util.WorksheetEntry;
import org.apache.http.client.methods.HttpGet;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap; | /*
* Copyright 2010 Google 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.underhilllabs.dccsched.io;
public class RemoteWorksheetsHandler extends XmlHandler {
private static final String TAG = "WorksheetsHandler";
private RemoteExecutor mExecutor;
public RemoteWorksheetsHandler(RemoteExecutor executor) {
super(ScheduleContract.CONTENT_AUTHORITY);
mExecutor = executor;
}
@Override
public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver)
throws XmlPullParserException, IOException { | final HashMap<String, WorksheetEntry> sheets = Maps.newHashMap(); | 5 |
anyremote/anyremote-android-client | java/anyremote/client/android/SearchForm.java | [
"public class About extends Dialog {\n\n\tprivate static Context mContext = null;\n\n\tpublic About(Context context) {\n\t\tsuper(context);\n\t\tmContext = context;\n\t}\n\n\t@Override\n\tpublic void onCreate(Bundle savedInstanceState) {\n\t\t\n\t\tsetContentView(anyremote.client.android.R.layout.about);\n\t\t\n\t\tTextView tv = (TextView) findViewById(anyremote.client.android.R.id.legal_text);\n\t\t\n\t\ttv.setText(Html.fromHtml(readRawTextFile(anyremote.client.android.R.raw.legal)));\n\t\ttv = (TextView) findViewById(anyremote.client.android.R.id.info_text);\n\t\ttv.setText(Html.fromHtml(readRawTextFile(anyremote.client.android.R.raw.info)));\n\t\ttv.setLinkTextColor(Color.WHITE);\n\t\t\n\t\tLinkify.addLinks(tv, Linkify.ALL);\n\t}\n\n\tpublic static String readRawTextFile(int id) {\n\t\t\n\t\tInputStream inputStream = mContext.getResources().openRawResource(id);\n\t\t\n\t\tInputStreamReader in = new InputStreamReader(inputStream);\n\t\t\n\t\tBufferedReader buf = new BufferedReader(in);\n\t\t\n\t\tString line;\n\t\tStringBuilder text = new StringBuilder();\n\t\t\n\t\ttry {\n\t\t\twhile ((line = buf.readLine()) != null)\n\t\t\t\ttext.append(line);\n\t\t} catch (IOException e) {\n\t\t\treturn null;\n\t\t}\n\t\treturn text.toString();\n\t}\n}",
"public class Address {\n\tpublic String name;\n\tpublic String URL;\n\tpublic String pass;\t\n\tpublic boolean autoconnect;\t\n}",
"public class AddressAdapter extends ArrayAdapter<Address> {\n\n\tprivate Vector<Address> items;\n\tContext context;\n\n\tpublic AddressAdapter(Context context, int textViewResourceId, Vector<Address> items) {\n\t\tsuper(context, textViewResourceId, items);\n\t\tthis.context = context;\n\t\tthis.items = items;\n\t\tanyRemote._log(\"AddressAdapter\", \"got # \"+this.items.size());\n\t}\n\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\t\tfinal View v;\n\t\tif (convertView == null) {\n\t\t\tLayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tv = vi.inflate(R.layout.search_list_item, null);\n\t\t} else {\n\t\t\tv = convertView;\n\t\t}\n\t\t\n\t\tAddress a = items.get(position);\n\t\t\n\t\tImageView type = (ImageView) v.findViewById(R.id.peer_type_icon);\n\t\tImageView secu = (ImageView) v.findViewById(R.id.peer_security_icon);\n\t\tImageView auto = (ImageView) v.findViewById(R.id.peer_autoconnect_icon);\n\t\t\n\t\tTextView name = (TextView) v.findViewById(R.id.peer_list_item);\n\t\tTextView addr = (TextView) v.findViewById(R.id.peer_list_address);\n\t\t\n\t\tif (a.URL.startsWith(\"btspp:\")) {\n\t\t type.setImageResource(R.drawable.bluetooth);\n\t\t} else{\n\t\t\ttype.setImageResource(R.drawable.wifi);\t\n\t\t}\n\t\tif (a.pass.length() == 0) {\n\t\t secu.setImageResource(R.drawable.decrypted);\n\t\t} else{\n\t\t\tsecu.setImageResource(R.drawable.encrypted);\t\n\t\t}\n\t\t\n auto.setVisibility((a.autoconnect ? View.VISIBLE : View.GONE));\n\t\t\n\t\tname.setText(a.name);\n\t\taddr.setText(a.URL);\n\n\t\treturn v;\n\t}\n\t\n\tpublic int size() {\n\t\treturn items.size();\n\t}\n\t\n\tpublic Address getItem(String name) {\n\t\tfor (int i=0;i<items.size();i++) {\n\t\t\tAddress a = items.get(i);\n\t\t\tif (name.compareTo(a.name) == 0) {\n\t\t\t\treturn a;\n\t\t\t}\n\t\t}\n\t\treturn null;\n \t}\n\t\n\tpublic Address getAutoconnectItem() {\n\t\tfor (int i=0;i<items.size();i++) {\n\t\t\tAddress a = items.get(i);\n\t\t\tif (a.autoconnect) {\n\t\t\t\treturn a;\n\t\t\t}\n\t\t}\n\t\treturn null;\n \t}\n\t\n\tpublic void remove(String name) {\n\t\tfor (int i=0;i<items.size();i++) {\n\t\t\tAddress a = items.get(i);\n\t\t\tif (name.compareTo(a.name) == 0) {\n\t\t\t\tremove(a);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n }\n\n\tpublic boolean addIfNew(String name, String host, String pass, boolean autoconnect) {\n\t\tif (name == null || host == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int i=0;i<items.size();i++) {\n\t\t\tAddress a = items.get(i);\n\t\t\tif (name.compareTo(a.name) == 0) {\n\t\t\t\tboolean update = false;\n\t\t\t\tif (host != null) {\n\t\t\t\t\tif (host.compareTo(a.URL) != 0) {\n\t\t\t\t\t\ta.URL = host;\n\t\t\t\t\t\tupdate = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pass != null) {\n\t\t\t\t\tif (pass.compareTo(a.pass) != 0) {\n\t\t\t\t\t\ta.pass = pass;\n\t\t\t\t\t\tupdate = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (autoconnect != a.autoconnect) {\n\t\t\t\t\ta.autoconnect = autoconnect;\n\t\t\t\t\tupdate = true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//anyRemote._log(\"AddressAdapter\", \"addIfNew \"+update+\" \"+name+\"/\"+host+\"/\"+pass);\n\t\t\t\tif (update) {\n\t\t\t\t\tnotifyDataSetChanged();\n\t\t\t\t}\n\t\t\t\t \n\t\t\t\treturn update;\n\t\t\t}\n\t\t}\n\t\t\n\t\tAddress a = new Address();\n\t\ta.name = name;\n\t\ta.URL = host;\n\t\ta.pass = pass;\t\t\n\t\ta.autoconnect = autoconnect;\t\t\n\t\tadd(a);\n\t\t\n\t\tif (autoconnect) { // only single auto connect item is allowed\n\t\t\tfor (int i=0;i<items.size();i++) {\n\t\t\t\tAddress p = items.get(i);\n\t\t\t\tif (name.compareTo(p.name) != 0) {\n\t\t\t\t\tp.autoconnect = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//anyRemote._log(\"AddressAdapter\", \"addIfNew 1 \"+name+\"/\"+host+\"/\"+pass);\n\t\tnotifyDataSetChanged();\n\t\treturn true;\n\t}\n}",
"public class BTScanner implements IScanner {\t\n\n Handler searchFormHandler;\n SearchForm calledFrom;\n \n boolean deregStateRcv = false;\n\n\tprivate BluetoothAdapter mBtAdapter;\n\n\tpublic BTScanner(Handler hdl, SearchForm sf) {\n searchFormHandler = hdl;\n calledFrom = sf;\n }\n\n public void startScan() {\n\n\t\t// Register for broadcasts when a device is discovered\n\t\tIntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);\n\t\tcalledFrom.registerReceiver(mReceiver, filter);\n\n\t\t// Register for broadcasts when discovery has finished\n\t\tfilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);\n\t\tcalledFrom.registerReceiver(mReceiver, filter);\n\n // Get the local Bluetooth adapter\n\t\tmBtAdapter = BluetoothAdapter.getDefaultAdapter();\n \n doDiscovery();\n }\n\n public void stopScan () {\n \n\t\tif (mBtAdapter != null && mBtAdapter.isDiscovering()) {\n\t\t\tanyRemote._log(\"BTScanner\", \"stopScan\");\n\t\t\tmBtAdapter.cancelDiscovery();\t\t\n\t\t}\n \n // Make sure we're not doing discovery anymore\n calledFrom.unregisterReceiver(mReceiver);\n\t\tif (deregStateRcv) {\n\t\t calledFrom.unregisterReceiver(mBTStateReceiver);\n\t\t}\n }\n\n private void informDiscoveryResult(int res) {\n Message msg = searchFormHandler.obtainMessage(res);\n\t\tmsg.sendToTarget();\n }\n\n private void informDiscoveryResult(String v) {\n \n ScanMessage sm = new ScanMessage();\n sm.name = v;\n\n Message msg = searchFormHandler.obtainMessage(SCAN_PROGRESS, sm);\n\t\tmsg.sendToTarget();\n }\n \n\tprivate void doDiscovery() {\n \n\t\tif (mBtAdapter == null) {\n informDiscoveryResult(SCAN_FAILED);\n stopScan();\n\t\t\treturn;\n\t\t}\n\t\tif (!mBtAdapter.isEnabled()) {\n\t\t\tswitchBluetoothOn();\n\t\t} else { \n\t\t\tdoRealDiscovery();\n\t\t}\n\t}\n\n\tprivate void doRealDiscovery() {\n \n\t\tanyRemote._log(\"BTScanner\", \"doRealDiscovery\");\n\n\t\t// Indicate scanning in the title\n informDiscoveryResult(SCAN_STARTED);\n\n\t\t// Request discover from BluetoothAdapter\n\t\tmBtAdapter.startDiscovery();\n\t}\n \n\tpublic void switchBluetoothOn() {\n \n\t\tanyRemote._log(\"BTScanner\", \"switchBluetoothOn\");\n\t\t\n String actionStateChanged = BluetoothAdapter.ACTION_STATE_CHANGED;\n\t\tString actionRequestEnable = BluetoothAdapter.ACTION_REQUEST_ENABLE;\n\t\t\n deregStateRcv = true;\n\t\t\n calledFrom.registerReceiver(mBTStateReceiver, new IntentFilter(actionStateChanged));\n\t\t\n calledFrom.startActivityForResult(new Intent(actionRequestEnable), 0);\n\t}\n \n\t// The BroadcastReceiver that listens for discovered devices and\n\t// changes the title when discovery is finished\n\tprivate final BroadcastReceiver mReceiver = new BroadcastReceiver() {\n\t\t\n @Override\n\t\tpublic void onReceive(Context context, Intent intent) {\n\t\t\tanyRemote._log(\"BTScanner\", \"BroadcastReceiver.onReceive discovery \");\n\n\t\t\tString action = intent.getAction();\n\n\t\t\t// When discovery finds a device\n\t\t\tif (BluetoothDevice.ACTION_FOUND.equals(action)) {\n\n\t\t\t\t// Get the BluetoothDevice object from the Intent\n\t\t\t\tBluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);\n\t\t\t\tanyRemote._log(\"BTScanner\", \"BroadcastReceiver::onReceive discovery GOT ONE \"+device.getName()+\" \"+device.getAddress());\n\n\t\t\t\t// If it's already paired, skip it, because it's been listed already\n\t\t\t\t//if (device.getBondState() != BluetoothDevice.BOND_BONDED) {\n ScanMessage sm = new ScanMessage();\n sm.name = device.getName();\n sm.address = \"btspp://\"+device.getAddress();\n \n Message msg = searchFormHandler.obtainMessage(SCAN_FOUND, sm);\n\t\t msg.sendToTarget();\n\t\t\t\t//}\n\n\t\t\t// When discovery is finished, change the Activity title\n\t\t\t} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {\n\n\t\t\t\tanyRemote._log(\"BTScanner\", \"BroadcastReceiver::onReceive discovery FINISHED\");\n\t\t\t\tinformDiscoveryResult(SCAN_FINISHED);\n\t\t\t}\n\t\t}\n\t};\n\n\t// The BroadcastReceiver that handles BT state\n\tprivate final BroadcastReceiver mBTStateReceiver = new BroadcastReceiver() {\n\t\t\n @Override\n\t\tpublic void onReceive(Context context, Intent intent) {\n\t\t\tanyRemote._log(\"BTScanner\", \"BroadcastReceiver::onReceive state\");\n\n\t\t\tString stateExtra = BluetoothAdapter.EXTRA_STATE;\n\t\t\tint state = intent.getIntExtra(stateExtra, -1);\n\t\t\t\n switch (state) {\n\t\t\t\t\n case (BluetoothAdapter.STATE_TURNING_ON) : {\n\t\t\t\t\tinformDiscoveryResult(R.string.bt_on);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n case (BluetoothAdapter.STATE_ON) : {\n\t\t\t\t\tanyRemote._log(\"BTScanner\", \"BroadcastReceiver::onReceive state ON\");\n \n informDiscoveryResult(R.string.bt_on);\n \n\t\t\t\t\tcalledFrom.unregisterReceiver(this);\n\t\t\t\t\tderegStateRcv = false;\n\t\n\t\t\t\t\tdoRealDiscovery();\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n case (BluetoothAdapter.STATE_TURNING_OFF) : {\n\t\t\t\t\tinformDiscoveryResult(R.string.bt_on);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n case (BluetoothAdapter.STATE_OFF) : {\n\t\t\t\t\tanyRemote._log(\"BTScanner\", \"BroadcastReceiver::onReceive state OFF\");\n\t\t\t\t\tinformDiscoveryResult(R.string.bt_on);\n\t\t\t\t\t\n calledFrom.unregisterReceiver(this);\n\t\t\t\t\tderegStateRcv = false;\n\t\t\t\t\t\n break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}",
"public class IPScanner implements IScanner {\t\n\n\tstatic final String DEFAULT_IP_PORT = \"5197\";\n\tstatic final int MAX_PING_TASKS = 16;\n\tstatic final int MAX_SUBNET_ADDR = 254;\n\n Handler searchFormHandler;\n\n\tvolatile Integer asyncNum = new Integer(-1);\n\tArrayList<String> hosts = new ArrayList<String>();\n\tPingTask ipSearchTask = null;\n\n\tpublic IPScanner(Handler hdl) {\n searchFormHandler = hdl;\n }\n\n public void startScan() {\n\n if (ipSearchTask != null) {\n anyRemote._log(\"IPScanner\", \"startScan: already scanning\");\n return;\n }\n\n String ip = anyRemote.getLocalIpAddress();\n if (ip == null) {\n Message msg = searchFormHandler.obtainMessage(SCAN_FAILED);\n msg.sendToTarget();\n return;\n }\n\t\tanyRemote._log(\"IPScanner\", \"startScan \"+ip);\n\t\n\t\tscanSubNet(ip.substring(0,ip.lastIndexOf('.')+1));\n\t\t//scanSubNet(\"172.16.32.\");\n }\n\n public void stopScan () {\n \n\t\tsynchronized (asyncNum) {\n\t\t\tasyncNum = -1;\n\t\t}\n \n\t\tif (ipSearchTask != null) { \n\t\t\tanyRemote._log(\"IPScanner\", \"stopScan\");\n\t\t\tipSearchTask.cancel(true);\n\t\t}\n }\n\t\n\tprivate void scanSubNet(String subnet){\n\t\t\n\t\tanyRemote._log(\"IPScanner\", \"scanSubNet \"+subnet);\n\t\t\t\t\n\t hosts.clear();\n\t asyncNum = 0; \n\t \n Message msg = searchFormHandler.obtainMessage(SCAN_STARTED);\n\t\tmsg.sendToTarget();\n\t\t\n\t ipSearchTask = new PingTask();\n\t ipSearchTask.execute(subnet); \n\t}\n\t\n\tclass PingTask extends AsyncTask<String, Integer, Void> {\n\n @Override\n\t\tprotected Void doInBackground(String... params) {\n\t\t\t\n\t\t for (int i=1; i<MAX_SUBNET_ADDR; i++){\n\t\t anyRemote._log(\"IPScanner\", \"PingTask.doInBackground Trying: \" + params[0] + String.valueOf(i));\n\t\t \n\t\t synchronized (asyncNum) {\n\t\t \tif (asyncNum < 0) {\n\t\t \t\t// cancel search\n\t\t \t\tanyRemote._log(\"IPScanner\", \"PingTask.doInBackground Search cancelled\");\n\t\t \t\ti = 255;\n\t\t \t} else {\n\t\t \t asyncNum++;\n\t\t \t}\n\t\t }\n \n if (i < MAX_SUBNET_ADDR) {\n\t\t PingHostTask mTask = new PingHostTask();\n \n int apiVersion = Integer.valueOf(android.os.Build.VERSION.SDK);\n\t\t \n if (apiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) { // API 11\n \t\t mTask.executeOnExecutor(THREAD_POOL_EXECUTOR, params[0] + String.valueOf(i));\n } else {\n mTask.execute(params[0] + String.valueOf(i));\n }\n\n\t\t while (asyncNum > MAX_PING_TASKS) {\n\t\t \t anyRemote._log(\"IPScanner\", \"PingTask.doInBackground Waiting to run : \" + asyncNum);\n\t\t \t\t try {\n\t\t \t\t\t Thread.sleep(300);\n\t\t \t\t } catch (InterruptedException e) {\n\t\t \t\t }\n\t\t }\n }\n\t\t\t \n\t\t\t publishProgress(i);\n\t\t }\n\t\t \n\t\t while (asyncNum > 0) {\n\t \t\ttry {\n\t \t\t\tThread.sleep(300);\n\t \t\t} catch (InterruptedException e) {\n\t \t\t}\n\t\t }\n\n\t\t\treturn null;\n\t\t}\n\t\t\n @Override\n protected void onProgressUpdate(Integer... progress) {\n \t\n \tanyRemote._log(\"IPScanner\", \"PingTask.onProgressUpdate \"+progress[0]);\n \t\n \t// dynamically add discovered hosts\n\t\t synchronized (hosts) {\n\t\t\t for (int h = 0;h<hosts.size();h++) {\n \n ScanMessage sm = new ScanMessage();\n sm.name = \"socket://\"+hosts.get(h);\n sm.address = \"socket://\"+hosts.get(h) + \":\" + DEFAULT_IP_PORT;\n \n Message msg = searchFormHandler.obtainMessage(SCAN_FOUND, sm);\n\t\t msg.sendToTarget();\n\t\t\t }\n\t\t\t hosts.clear();\n\t\t }\n\t\t \n\t\t synchronized (asyncNum) {\n\t\t \tif (asyncNum > 0) {\n\t\t\t\t anyRemote._log(\"IPScanner\", \"PingTask.onProgressUpdate \" + asyncNum);\n \n ScanMessage sm = new ScanMessage();\n sm.name = progress[0]+\"/255\";\n\n Message msg = searchFormHandler.obtainMessage(SCAN_PROGRESS, sm);\n\t\t msg.sendToTarget();\n\t\t \t}\n\t\t }\n }\n \n @Override\n protected void onPostExecute(Void unused) {\n Message msg = searchFormHandler.obtainMessage(SCAN_FINISHED);\n\t\t msg.sendToTarget();\n\t\t asyncNum = -1;\n\t\t ipSearchTask = null;\n }\n \n @Override\n protected void onCancelled() {\n Message msg = searchFormHandler.obtainMessage(SCAN_FINISHED);\n\t\t msg.sendToTarget();\n\t\t asyncNum = -1;\n\t\t ipSearchTask = null;\n }\n\t}\n\t\n\tclass PingHostTask extends AsyncTask<String, Void, Void> {\n\t\t\n /*PipedOutputStream mPOut;\n PipedInputStream mPIn;\n LineNumberReader mReader;\n Process mProcess;*/\n \n\t\t/*\n\t\t@Override\n protected void onPreExecute() {\n /*mPOut = new PipedOutputStream();\n try {\n mPIn = new PipedInputStream(mPOut);\n mReader = new LineNumberReader(new InputStreamReader(mPIn));\n } catch (IOException e) {\n cancel(true);\n }\n }*/\n\n /*public void stop() {\n\t\t\tProcess p = mProcess;\n\t\t\tif (p != null) {\n\t\t\t\tp.destroy();\n\t\t\t}\n\t\t\tcancel(true);\n\t\t}*/\n\n\t\t@Override\n\t\tprotected Void doInBackground(String... params) {\n\n\t\t\tanyRemote._log(\"IPScanner\", \"PingHostTask.doInBackground START\");\n \n try {\n\t\t\t\tInetAddress inetAddress = InetAddress.getByName(params[0]);\n\t\t\t\t\n anyRemote._log(\"IPScanner\", \"PingHostTask.doInBackground # \" + inetAddress);\n \n if (inetAddress.isReachable(1000)) {\n\t\t\t\t\t\n\t\t\t\t\tsynchronized (asyncNum) {\n\t\t\t\t\t\tif (asyncNum < 0) {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tanyRemote._log(\"IPScanner\", \"PingHostTask.doInBackground reachable # \" + params[0]);\n\t\t\t\t\tString host = inetAddress.getHostName();\n\n\t\t\t\t\tsynchronized (hosts) {\n\t\t\t\t\t\thosts.add(host);\n\t\t\t\t\t}\n\n\t\t\t\t\tsynchronized (asyncNum) {\n\t\t\t\t\t\tasyncNum--;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t} catch (UnknownHostException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t\t/*try {\n\t\t\t\tlog(\"start # \" + params[0]);\n\t\t\t\tString cmd = \"/system/bin/ping -q -n -w 1 -c 1 \" + params[0];\n\t\t\t\tProcess mProcess = new ProcessBuilder()\n\t\t\t\t\t\t.command(cmd)\n\t\t\t\t\t\t.redirectErrorStream(true).start();\n\t\t\t\tlog(\"started # \" + params[0]);\n\n\t\t\t\ttry {\n\t\t\t\t\tInputStream in = mProcess.getInputStream();\n\t\t\t\t\tOutputStream out = mProcess.getOutputStream();\n\t\t\t\t\tbyte[] buffer = new byte[1024];\n\t\t\t\t\tint count;\n\t\t\t\t\tlog(\"AA \" + params[0]);\n\t\t\t\t\t\n\t\t\t\t\t// in -> buffer -> mPOut -> mReader -> 1 line of ping\n\t\t\t\t\t// information to parse\n\t\t\t\t\twhile ((count = in.read(buffer)) != -1) {\n\t\t\t\t\t\tmPOut.write(buffer, 0, count);\n\t\t\t\t\t\t// publishProgress();\n\t\t\t\t\t}\n\t\t\t\t\tlog(\"done for # \" + params[0] + \" \" + buffer);\n\t\t\t\t\tout.close();\n\t\t\t\t\tin.close();\n\t\t\t\t\tmPOut.close();\n\t\t\t\t\tmPIn.close();\n\t\t\t\t} finally {\n\t\t\t\t\tmProcess.destroy();\n\t\t\t\t\tmProcess = null;\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\tlog(\"IOException for # \" + params[0] + \" \" + e.getMessage());\n\t\t\t}*/\n\n\t\t\tsynchronized (asyncNum) {\n\t\t\t\tasyncNum--;\n\t\t\t}\n\n\t\t\tanyRemote._log(\"IPScanner\", \"PingHostTask.doInBackground Down # \" + params[0]);\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\t/*\n @Override\n protected void onProgressUpdate(Void... values) {\n try {\n // Is a line ready to read from the \"ping\" command?\n while (mReader.ready()) {\n // This just displays the output, you should typically parse it I guess.\n \tlog(\"Got \"+mReader.readLine());\n }\n } catch (IOException t) {\n }\n }*/\n \t}\n}",
"@TargetApi(android.os.Build.VERSION_CODES.JELLY_BEAN) // API 16\npublic class ZCScanner implements IScanner {\t\n\n static final String ZEROCONF_TCP_SERVICE_TYPE = \"_anyremote._tcp\";\n static final String ZEROCONF_WEB_SERVICE_TYPE = \"_anyremote-http._tcp\";\n \n static final String ZEROCONF_SERVICE_NAME = \"anyRemote\";\n\n private NsdManager mNsdManager = null;\n private ArDiscoveryListener mDiscoveryListenerTCP = null;\n private ArDiscoveryListener mDiscoveryListenerWEB = null;\n private NsdManager.ResolveListener resolver = null;\n boolean resolving = false; \n \n ArrayList<NsdServiceInfo> toResolve = new ArrayList<NsdServiceInfo>();\n Handler searchFormHandler;\n Context context;\n \n\n\tpublic ZCScanner(Handler hdl, Context ctx) {\n searchFormHandler = hdl;\n context = ctx;\n }\n\n @TargetApi(android.os.Build.VERSION_CODES.JELLY_BEAN)\n public void resolveNext() {\n \n\t\ttry {\n\t\t\tThread.sleep(100);\n\t\t} catch (InterruptedException e) {\n\t\t}\n \n synchronized (toResolve) {\n if (toResolve.size() > 0 && !resolving) {\n NsdServiceInfo srvInfo = toResolve.remove(0);\n anyRemote._log(\"ZCScanner\",\"resolveNext (remains #\" + toResolve.size() + \") \" + srvInfo);\n resolving = true;\n mNsdManager.resolveService(srvInfo, resolver);\n }\n }\n }\n\n @TargetApi(android.os.Build.VERSION_CODES.JELLY_BEAN)\n public void startScan() {\n \n if (mNsdManager == null) {\n mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);\n }\n \n\t\ttry {\n\t\t\tThread.sleep(100);\n\t\t} catch (InterruptedException e) {\n\t\t}\n \n if (resolver == null) {\n \n resolver = new NsdManager.ResolveListener() {\n\n @Override\n public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {\n anyRemote._log(\"ZCScanner\", \"resolve failed \" + errorCode);\n synchronized (toResolve) {\n resolving = false;\n }\n resolveNext(); \n }\n\n @Override\n public void onServiceResolved(NsdServiceInfo serviceInfo) {\n\n String service = serviceInfo.getServiceName();\n String type = serviceInfo.getServiceType();\n String host = serviceInfo.getHost().getHostAddress();\n String port = String.valueOf(serviceInfo.getPort());\n\n anyRemote._log(\"ZCScanner\", \"resolve succeeded \" + service +\"/\" + type);\n\n ScanMessage sm = new ScanMessage();\n\n if (type.contains(ZEROCONF_TCP_SERVICE_TYPE)) {\n\n sm.name = service + \"://\" + host;\n sm.address = \"socket://\" + host + \":\" + port;\n\n } else if (type.contains(ZEROCONF_WEB_SERVICE_TYPE)) {\n\n sm.name = \"web://\" + host;\n sm.address = \"web://\" + host + \":\" + port;\n\n } else {\n\n anyRemote._log(\"ZCScanner\", \"resolver: improper service type \" + type);\n return;\n }\n\n Message msg = searchFormHandler.obtainMessage(SCAN_FOUND, sm);\n\t\t msg.sendToTarget();\n\t\t \n\t\t synchronized (toResolve) {\n resolving = false;\n }\n resolveNext(); \n }\n };\n }\n \n if (mDiscoveryListenerTCP == null) {\n anyRemote._log(\"ZCScanner\", \"startScan TCP\");\n mDiscoveryListenerTCP = new ArDiscoveryListener(ZEROCONF_TCP_SERVICE_TYPE);\n }\n \n if (mDiscoveryListenerWEB == null) {\n anyRemote._log(\"ZCScanner\", \"startScan WEB\");\n mDiscoveryListenerWEB = new ArDiscoveryListener(ZEROCONF_WEB_SERVICE_TYPE);\n }\n \n anyRemote._log(\"ZCScanner\", \"startScan discoverServices\");\n \n \t\t\t\n\t\ttry {\n\t\t\tThread.sleep(100);\n\t\t} catch (InterruptedException e) {\n\t\t}\n \n\t\tMainLoop.schedule(new TimerTask() {\n public void run() {\n stopScan();\n }\n }, 15000); // stop discovery after 15 seconds\n \n mNsdManager.discoverServices(ZEROCONF_TCP_SERVICE_TYPE, \n NsdManager.PROTOCOL_DNS_SD, \n (NsdManager.DiscoveryListener) mDiscoveryListenerTCP);\n\n\t\ttry {\n\t\t\tThread.sleep(100);\n\t\t} catch (InterruptedException e) {\n\t\t}\n \n mNsdManager.discoverServices(ZEROCONF_WEB_SERVICE_TYPE, \n NsdManager.PROTOCOL_DNS_SD, \n (NsdManager.DiscoveryListener) mDiscoveryListenerWEB);\n }\n \n @TargetApi(android.os.Build.VERSION_CODES.JELLY_BEAN)\n public void stopScan () {\n \ttry {\n \t\tmNsdManager.stopServiceDiscovery((NsdManager.DiscoveryListener) mDiscoveryListenerTCP);\n \t} catch (IllegalArgumentException e) { \n \t}\n \ttry {\n \t\tmNsdManager.stopServiceDiscovery((NsdManager.DiscoveryListener) mDiscoveryListenerWEB);\n \t} catch (IllegalArgumentException e) {\n \t}\n }\n \n private void informDiscoveryResult(int res) {\n Message msg = searchFormHandler.obtainMessage(res);\n\t\tmsg.sendToTarget();\n }\n \n @TargetApi(android.os.Build.VERSION_CODES.JELLY_BEAN)\n public class ArDiscoveryListener implements NsdManager.DiscoveryListener {\n\n private String serviceType;\n \n public ArDiscoveryListener(String sType) {\n \n serviceType = sType; \n\n anyRemote._log(\"ZCScanner\", \"ArDiscoveryListener \"+serviceType);\n }\n \n // Called as soon as service discovery begins.\n @Override\n public void onDiscoveryStarted(String regType) {\n anyRemote._log(\"ZCScanner\", \"service discovery started \"+serviceType);\n }\n\n @Override\n public void onServiceFound(NsdServiceInfo service) {\n \n anyRemote._log(\"ZCScanner\",\"service discovery success \" + service.getServiceName() + \" \" + service.getServiceType());\n if (!service.getServiceName().contains(ZEROCONF_SERVICE_NAME)) {\n return;\n }\n \n if (service.getServiceType().contains(serviceType)) {\n synchronized (toResolve) {\n toResolve.add(service);\n anyRemote._log(\"ZCScanner\",\"resolve queue #\" + toResolve.size());\n }\n resolveNext();\n } else {\n // Service type is the string containing the protocol and transport layer for this service\n anyRemote._log(\"ZCScanner\",\"unknown service type \" + service.getServiceType());\n }\n }\n \n @Override\n public void onServiceLost(NsdServiceInfo service) {\n // When the network service is no longer available.\n // Internal bookkeeping code goes here.\n anyRemote._log(\"ZCScanner\", \"service lost \" + service.getServiceName());\n informDiscoveryResult(SCAN_FAILED);\n }\n\n @Override\n public void onDiscoveryStopped(String serviceType) {\n anyRemote._log(\"ZCScanner\",\"discovery stopped \" + serviceType);\n informDiscoveryResult(SCAN_FINISHED);\n }\n\n @Override\n public void onStartDiscoveryFailed(String serviceType, int errorCode) {\n anyRemote._log(\"ZCScanner\", \"discovery failed: error code \" + errorCode);\n mNsdManager.stopServiceDiscovery((NsdManager.DiscoveryListener) this);\n informDiscoveryResult(SCAN_FAILED);\n }\n\n @Override\n public void onStopDiscoveryFailed(String serviceType, int errorCode) {\n anyRemote._log(\"ZCScanner\",\"discovery failed: error code \" + errorCode);\n mNsdManager.stopServiceDiscovery((NsdManager.DiscoveryListener) this);\n informDiscoveryResult(SCAN_FAILED);\n }\n }\n}",
"public interface IScanner {\n\t\n static final int SCAN_STARTED = 0;\n static final int SCAN_FAILED = 1;\n static final int SCAN_FINISHED = 2;\n static final int SCAN_PROGRESS = 3;\n static final int SCAN_FOUND = 4;\n\n void startScan();\n void stopScan ();\n\n}",
"public class ScanMessage {\n\tpublic String name;\n\tpublic String address;\n}"
] | import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.Toast;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import anyremote.client.android.R;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import anyremote.client.android.util.About;
import anyremote.client.android.util.Address;
import anyremote.client.android.util.AddressAdapter;
import anyremote.client.android.util.BTScanner;
import anyremote.client.android.util.IPScanner;
import anyremote.client.android.util.ZCScanner;
import anyremote.client.android.util.IScanner;
import anyremote.client.android.util.ScanMessage; | //
// anyRemote android client
// a bluetooth/wi-fi remote control for Linux.
//
// Copyright (C) 2011-2016 Mikhail Fedotov <[email protected]>
//
// 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 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 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 anyremote.client.android;
public class SearchForm extends arActivity
implements OnItemClickListener,
//DialogInterface.OnDismissListener,
//DialogInterface.OnCancelListener,
AdapterView.OnItemSelectedListener {
ListView searchList;
AddressAdapter dataSource;
int selected = 0;
Handler handler = null;
IScanner scanner = null;
// BT stuff
private BluetoothAdapter mBtAdapter;
String connectTo = "";
String connectName = "";
String connectPass = "";
boolean connectAuto = false;
boolean skipDismissDialog = false;
boolean deregStateRcv = false;
String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefix = "SearchForm"; // log stuff
Intent intent = getIntent();
id = intent.getStringExtra("SUBID");
log("onCreate " + id);
//requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.search_dialog);
setResult(Activity.RESULT_CANCELED);
setTitle(R.string.searchFormUnconnected);
searchList = (ListView) findViewById(R.id.search_list);
searchList.setOnItemClickListener(this);
registerForContextMenu(searchList);
dataSource = new AddressAdapter(this, R.layout.search_list_item, anyRemote.protocol.loadPrefs());
searchList.setAdapter(dataSource);
searchList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
searchList.setOnItemSelectedListener(this);
//searchList.setItemChecked(selected, true);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if (dataSource.size() == 0) { // first-time run
Toast.makeText(this, "Press Menu ...", Toast.LENGTH_SHORT).show();
} else {
if (anyRemote.firstConnect) {
anyRemote.firstConnect = false; | final Address auto = dataSource.getAutoconnectItem(); | 1 |
pmarques/SocketIO-Server | SocketIO-Netty/src/test/java/eu/k2c/socket/io/ci/usecases/UC17Handler.java | [
"public abstract class AbstractHandler extends AbstractSocketIOHandler {\n\t@Override\n\tpublic boolean validate(String URI) {\n\t\t// This isn't belongs to socketIO Spec AFAIK\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void onConnect(final SocketIOOutbound outbound, final SocketIOSessionEventRegister eventRegister,\n\t\t\tfinal SocketIOSessionNSRegister NSRegister) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic void onDisconnect(final DisconnectReason reason, final String errorMessage) {\n\t}\n\n\t@Override\n\tpublic void onMessage(final long messageID, final String message) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic void onJSONMessage(final long messageID, final String message) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic void onAck(final long messageID, final String data) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic void onError(final String reason, final String advice) {\n\t}\n}",
"public interface SocketIOOutbound {\n\t/**\n\t * Terminate the connection. This method may return before the connection\n\t * disconnect completes. The onDisconnect() method of the associated\n\t * SocketInbound will be called when the disconnect is completed. The\n\t * onDisconnect() method may be called during the invocation of this method.\n\t */\n\tvoid disconnect();\n\n\t/**\n\t * Initiate an orderly close of the connection. The state will be changed to\n\t * CLOSING so no new messages can be sent, but messages may still arrive\n\t * until the distant end has acknowledged the close.\n\t */\n\tvoid close();\n\n\tConnectionState getConnectionState();\n\n\t/**\n\t * Send a text message to the client. This method will block if the message\n\t * will not fit in the outbound buffer. If the socket is closed, becomes\n\t * closed, or times out, while trying to send the message, the\n\t * SocketClosedException will be thrown.\n\t * \n\t * @param message\n\t * The message to send\n\t * @param endPoint\n\t * The message endPoint\n\t * \n\t * @throws SocketIOException\n\t */\n\tvoid sendMessage(final String message, final String endPoint) throws SocketIOException;\n\n\t/**\n\t * Send a JSON message to the client. This method will block if the message\n\t * will not fit in the outbound buffer. If the socket is closed, becomes\n\t * closed, or times out, while trying to send the message, the\n\t * SocketClosedException will be thrown.\n\t * \n\t * @param message\n\t * The JSON message to send\n\t * @param endPoint\n\t * The message endPoint\n\t * \n\t * @throws IllegalStateException\n\t * if the socket is not CONNECTED.\n\t * @throws SocketIOException\n\t */\n\tvoid sendJSONMessage(final String message, final String endPoint) throws SocketIOException;\n\n\t/**\n\t * Send a event message to a client.\n\t * \n\t * @param eventName\n\t * Event name\n\t * @param message\n\t * The JSON message to send\n\t * @param endPoint\n\t * The message endPoint\n\t * @throws SocketIOException\n\t */\n\tvoid sendEventMessage(final String eventName, final String message, final String endPoint) throws SocketIOException;\n\n\t/**\n\t * Force to send an acknowledge for a received message.\n\t * This is necessary when a package is sent with '+' on message id.\n\t * NOTE: This methode could disappear due to the implications in the\n\t * correctness in terms of SocketIO flow\n\t * \n\t * @param message\n\t * The JSON message to send\n\t * @param endPoint\n\t * The message endPoint\n\t * @param handler\n\t * A method to be executed by the acknowledge of this packet\n\t * \n\t * @throws SocketIOException\n\t */\n\tvoid sendJSONMessage(String string, final String endPoint, AckHandler ackHandler) throws SocketIOException;\n\n\t/**\n\t * Force to send an acknowledge for a received message.\n\t * This is necessary when a package is sent with '+' on message id.\n\t * NOTE: This methode could disappear due to the implications in the\n\t * correctness in terms of SocketIO flow\n\t * \n\t * @param message\n\t * The message to send\n\t * @param endPoint\n\t * The message endPoint\n\t * @param handler\n\t * A method to be executed by the acknowledge of this packet\n\t * \n\t * @throws SocketIOException\n\t */\n\tvoid sendMessage(String string, final String endPoint, AckHandler ackHandler) throws SocketIOException;\n\n\t/**\n\t * Send a event message to a client.\n\t * \n\t * @param eventName\n\t * Event name\n\t * @param message\n\t * The JSON message to send\n\t * @param endPoint\n\t * The message endPoint\n\t * @param handler\n\t * A method to be executed by the acknowledge of this packet\n\t * \n\t * @throws SocketIOException\n\t */\n\tvoid sendEventMessage(final String eventName, final String message, final String endPoint, final AckHandler handler)\n\t\t\tthrows SocketIOException;\n\n\t/**\n\t * Force to send an acknowledge for a received message.\n\t * This is necessary when a package is sent with '+' on message id.\n\t * NOTE: This method could disappear due to the implications in the\n\t * correctness in terms of SocketIO flow\n\t * \n\t * @param messageID\n\t * Event name\n\t * @param message\n\t * The message to send\n\t * \n\t * @throws SocketIOException\n\t */\n\tvoid sendAck(final long messageID, final String message) throws SocketIOException;\n}",
"public interface SocketIOSessionEventRegister {\n\t/**\n\t * Register a event listener for client session. When a event with a\n\t * {@link evenName} is received, this is send to the {@link handler}. If\n\t * there is no event listener for the coming event this is will be sent\n\t * to the {@link SocketIOSession#onEvent}\n\t * \n\t * @param eventName\n\t * Event name to be added.\n\t * @param handler\n\t * Event listener.\n\t */\n\tvoid registerEventListeners(final String eventName, final SocketIOEventHandler handler);\n\n\t/**\n\t * Remove event listener from client session\n\t * \n\t * @param eventName\n\t * Event Name to be removed.\n\t */\n\tvoid unRegisterEventListeners(final String eventName);\n\n\t/**\n\t * Remove all event listeners from the client session.\n\t */\n\tvoid removeEventListeners();\n\n\t// TODO: This shall not be available to client\n\tSocketIOEventHandler getHandler(final String eventName);\n}",
"public interface SocketIOSessionNSRegister {\n\t/**\n\t * Register a event listener for client session. When a event with a\n\t * {@link evenName} is received, this is send to the {@link handler}. If\n\t * there is no event listener for the coming event this is will be sent\n\t * to the {@link SocketIOSession#onEvent}\n\t * \n\t * @param eventName\n\t * Event name to be added.\n\t * @param handler\n\t * Event listener.\n\t */\n\tvoid registerNSListeners(final String eventName, final SocketIONSHandler handler);\n\n\t/**\n\t * Remove event listener from client session\n\t * \n\t * @param eventName\n\t * Event Name to be removed.\n\t */\n\tvoid unRegisterNSListeners(final String eventName);\n\n\t/**\n\t * Remove all event listeners from the client session.\n\t */\n\tvoid removeNS();\n\n\tpublic SocketIONSHandler getHandler(final String eventName);\n}",
"public class SocketIOException extends IOException {\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic SocketIOException() {\n\t\tsuper();\n\t}\n\n\tpublic SocketIOException(final String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic SocketIOException(final Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n\tpublic SocketIOException(final String message, final Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n}"
] | import eu.k2c.socket.io.ci.AbstractHandler;
import eu.k2c.socket.io.server.api.SocketIOOutbound;
import eu.k2c.socket.io.server.api.SocketIOSessionEventRegister;
import eu.k2c.socket.io.server.api.SocketIOSessionNSRegister;
import eu.k2c.socket.io.server.exceptions.SocketIOException;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.jboss.netty.handler.codec.http.QueryStringDecoder; | /**
* Copyright (C) 2011 K2C @ Patrick Marques <[email protected]>
*
* 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.
*
* Except as contained in this notice, the name(s) of the above copyright holders
* shall not be used in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization.
*/
package eu.k2c.socket.io.ci.usecases;
public class UC17Handler extends AbstractHandler {
private static final Logger LOGGER = Logger.getLogger(UC17Handler.class);
// 'test sending query strings to the server'
private String URI;
@Override
public boolean validate(final String URI) {
this.URI = URI;
return true;
}
@Override | public void onConnect(final SocketIOOutbound outbound, final SocketIOSessionEventRegister eventRegister, | 2 |
bencvt/LibShapeDraw | projects/main/src/main/java/libshapedraw/shape/WireframeLinesBlendIterable.java | [
"public interface MinecraftAccess {\n /** Tessellator.instance.startDrawing */\n public MinecraftAccess startDrawing(int mode);\n\n /** Tessellator.instance.addVertex */\n public MinecraftAccess addVertex(double x, double y, double z);\n\n /** Tessellator.instance.addVertex */\n public MinecraftAccess addVertex(ReadonlyVector3 coords);\n\n /** Tessellator.instance.draw */\n public MinecraftAccess finishDrawing();\n\n /** RenderHelper.enableStandardItemLighting */\n public MinecraftAccess enableStandardItemLighting();\n\n /** Minecraft.ingameGUI.getChatGUI().printChatMessage */\n public MinecraftAccess sendChatMessage(String message);\n\n /** Minecraft.ingameGUI.getChatGUI() */\n public boolean chatWindowExists();\n\n /** Minecraft.timer.renderPartialTicks */\n public float getPartialTick();\n\n /** Minecraft.mcProfiler.startSection */\n public MinecraftAccess profilerStartSection(String sectionName);\n\n /** Minecraft.mcProfiler.endSection */\n public MinecraftAccess profilerEndSection();\n\n /** Minecraft.mcProfiler.endStartSection */\n public MinecraftAccess profilerEndStartSection(String sectionName);\n}",
"public class Color implements ReadonlyColor, Animates<ReadonlyColor> {\n private static final long serialVersionUID = 1L;\n\n private double red;\n private double green;\n private double blue;\n private double alpha;\n\n /** @see Vector3#timeline */\n private transient Timeline timeline;\n\n public Color(double red, double green, double blue, double alpha) {\n set(red, green, blue, alpha);\n }\n\n public Color(double red, double green, double blue) {\n set(red, green, blue, 1.0);\n }\n\n /**\n * Construct this color using a 32-bit integer packed with each of the\n * color's components, one per byte. The order, from most significant to\n * least, is red, green, blue, alpha.\n * @see #convertARGBtoRGBA\n */\n public Color(int rgba) {\n setRGBA(rgba);\n }\n\n public Color(ReadonlyColor other) {\n set(other.getRed(), other.getGreen(), other.getBlue(), other.getAlpha());\n }\n\n @Override\n public Color copy() {\n return new Color(red, green, blue, alpha);\n }\n\n @Override\n public double getRed() {\n return red;\n }\n\n @Override\n public double getGreen() {\n return green;\n }\n\n @Override\n public double getBlue() {\n return blue;\n }\n\n @Override\n public double getAlpha() {\n return alpha;\n }\n\n @Override\n public int getRGBA() {\n return ((((int) (getRed() * 255.0)) & 0xff) << 24) |\n ((((int) (getGreen() * 255.0)) & 0xff) << 16) |\n ((((int) (getBlue() * 255.0)) & 0xff) << 8) |\n (((int) (getAlpha() * 255.0)) & 0xff);\n }\n\n @Override\n public int getARGB() {\n return ((((int) (getAlpha() * 255.0)) & 0xff) << 24) |\n ((((int) (getRed() * 255.0)) & 0xff) << 16) |\n ((((int) (getGreen() * 255.0)) & 0xff) << 8) |\n (((int) (getBlue() * 255.0)) & 0xff);\n }\n\n @Override\n public void glApply() {\n GL11.glColor4d(red, green, blue, alpha);\n }\n\n @Override\n public void glApply(double alphaScale) {\n GL11.glColor4d(red, green, blue, clamp(alpha * alphaScale));\n }\n\n /** @return true if two colors are equal, rounding each component. */\n @Override\n public boolean equals(Object other) {\n return other instanceof ReadonlyColor && hashCode() == other.hashCode();\n }\n\n @Override\n public int hashCode() {\n return getRGBA();\n }\n\n @Override\n public String toString() {\n return String.format(\"0x%08x\", getRGBA());\n }\n\n // ========\n // Mutators\n // ========\n\n /**\n * Set this color's red component, clamped to [0.0, 1.0].\n * @return the same color object, modified in-place.\n */\n public Color setRed(double red) {\n this.red = clamp(red);\n return this;\n }\n\n /**\n * Set this color's green component, clamped to [0.0, 1.0].\n * @return the same color object, modified in-place.\n */\n public Color setGreen(double green) {\n this.green = clamp(green);\n return this;\n }\n\n /**\n * Set this color's blue component, clamped to [0.0, 1.0].\n * @return the same color object, modified in-place.\n */\n public Color setBlue(double blue) {\n this.blue = clamp(blue);\n return this;\n }\n\n /**\n * Set this color's alpha component, clamped to [0.0, 1.0].\n * @return the same color object, modified in-place.\n */\n public Color setAlpha(double alpha) {\n this.alpha = clamp(alpha);\n return this;\n }\n\n /**\n * Set all of this color's components, clamped to [0.0, 1.0].\n * @return the same color object, modified in-place.\n */\n public Color set(double red, double green, double blue, double alpha) {\n this.red = clamp(red);\n this.green = clamp(green);\n this.blue = clamp(blue);\n this.alpha = clamp(alpha);\n return this;\n }\n\n /**\n * Set all of this color components to match another color's.\n * @return the same color object, modified in-place.\n */\n public Color set(ReadonlyColor other) {\n red = clamp(other.getRed());\n green = clamp(other.getGreen());\n blue = clamp(other.getBlue());\n alpha = clamp(other.getAlpha());\n return this;\n }\n\n /**\n * Multiply each of the red/green/blue color components by the given\n * factor, clamping the results to [0.0, 1.0].\n * @return the same color object, modified in-place.\n */\n public Color scaleRGB(double factor) {\n red = clamp(red*factor);\n green = clamp(green*factor);\n blue = clamp(blue*factor);\n return this;\n }\n\n /**\n * Multiply the alpha color component by the given factor, clamping the\n * result to [0.0, 1.0].\n * @return the same color object, modified in-place.\n */\n public Color scaleAlpha(double factor) {\n alpha = clamp(alpha*factor);\n return this;\n }\n\n /**\n * Blend all color components with another color's.\n * @return the same color object, modified in-place.\n */\n public Color blend(ReadonlyColor other, double percent) {\n setRed(blend(getRed(), other.getRed(), percent));\n setGreen(blend(getGreen(), other.getGreen(), percent));\n setBlue(blend(getBlue(), other.getBlue(), percent));\n setAlpha(blend(getAlpha(), other.getAlpha(), percent));\n return this;\n }\n\n /**\n * Set all color components from a packed 32-bit integer.\n * This is the reverse of {@link #getRGBA()}.\n * @return the same color object, modified in-place.\n */\n public Color setRGBA(int rgba) {\n setRed(((rgba & 0xff000000) >>> 24) / 255.0);\n setGreen(((rgba & 0xff0000) >>> 16) / 255.0);\n setBlue(((rgba & 0xff00) >>> 8) / 255.0);\n setAlpha((rgba & 0xff) / 255.0);\n return this;\n }\n\n /**\n * Set each of this color's components to a random value in [0.0, 1.0).\n * @return the same color object, modified in-place.\n */\n public Color setRandom() {\n red = Math.random();\n green = Math.random();\n blue = Math.random();\n alpha = Math.random();\n return this;\n }\n\n /**\n * Set this color's red, green, and blue (excluding alpha) components to a\n * random value in [0.0, 1.0).\n * @return the same color object, modified in-place.\n */\n public Color setRandomRGB() {\n red = Math.random();\n green = Math.random();\n blue = Math.random();\n return this;\n }\n\n private static double clamp(double x) {\n if (x < 0.0) {\n return 0.0;\n } else if (x > 1.0) {\n return 1.0;\n } else {\n return x;\n }\n }\n\n private static double blend(double fromValue, double toValue, double percent) {\n return fromValue + (toValue - fromValue)*percent;\n }\n\n // ========\n // Animates interface\n // ========\n\n @Override\n public boolean isAnimating() {\n return timeline != null && !timeline.isDone();\n }\n\n @Override\n public Color animateStop() {\n if (timeline != null && !timeline.isDone()) {\n timeline.abort();\n }\n timeline = null;\n return this;\n }\n\n @Override\n public Color animateStart(ReadonlyColor toColor, long durationMs) {\n if (toColor == null) {\n throw new IllegalArgumentException(\"toColor cannot be null\");\n }\n newTimeline(toColor.getRed(), toColor.getGreen(), toColor.getBlue(), toColor.getAlpha(), durationMs);\n timeline.play();\n return this;\n }\n /**\n * Convenience method, equivalent to\n * <code>animateStart(new Color(toRed, toGreen, toBlue, toAlpha), durationMs)</code>\n */\n public Color animateStart(double toRed, double toGreen, double toBlue, double toAlpha, long durationMs) {\n newTimeline(toRed, toGreen, toBlue, toAlpha, durationMs);\n timeline.play();\n return this;\n }\n\n @Override\n public Color animateStartLoop(ReadonlyColor toColor, boolean reverse, long durationMs) {\n if (toColor == null) {\n throw new IllegalArgumentException(\"toColor cannot be null\");\n }\n newTimeline(toColor.getRed(), toColor.getGreen(), toColor.getBlue(), toColor.getAlpha(), durationMs);\n timeline.playLoop(reverse);\n return this;\n }\n /**\n * Convenience method, equivalent to\n * </code>animateStartLoop(new Color(toRed, toGreen, toBlue, toAlpha), reverse, durationMs)</code>\n */\n public Color animateStartLoop(double toRed, double toGreen, double toBlue, double toAlpha, boolean reverse, long durationMs) {\n newTimeline(toRed, toGreen, toBlue, toAlpha, durationMs);\n timeline.playLoop(reverse);\n return this;\n }\n\n private void newTimeline(double toRed, double toGreen, double toBlue, double toAlpha, long durationMs) {\n animateStop();\n timeline = new Timeline(this);\n timeline.addPropertyToInterpolate(\"red\", red, toRed);\n timeline.addPropertyToInterpolate(\"green\", green, toGreen);\n timeline.addPropertyToInterpolate(\"blue\", blue, toBlue);\n timeline.addPropertyToInterpolate(\"alpha\", alpha, toAlpha);\n timeline.setDuration(durationMs);\n }\n\n // ========\n // Named colors and other static methods\n // ========\n\n // Define all extended web colors (W3C)\n /** <div style=\"background:#f0f8ff\">#f0f8ff</div> */\n public static final ReadonlyColor ALICE_BLUE = new Color(0xf0f8ffff);\n /** <div style=\"background:#faebd7\">#faebd7</div> */\n public static final ReadonlyColor ANTIQUE_WHITE = new Color(0xfaebd7ff);\n /** <div style=\"background:#00ffff\">#00ffff</div> */\n public static final ReadonlyColor AQUA = new Color(0x00ffffff);\n /** <div style=\"background:#7fffd4\">#7fffd4</div> */\n public static final ReadonlyColor AQUAMARINE = new Color(0x7fffd4ff);\n /** <div style=\"background:#f0ffff\">#f0ffff</div> */\n public static final ReadonlyColor AZURE = new Color(0xf0ffffff);\n /** <div style=\"background:#f5f5dc\">#f5f5dc</div> */\n public static final ReadonlyColor BEIGE = new Color(0xf5f5dcff);\n /** <div style=\"background:#ffe4c4\">#ffe4c4</div> */\n public static final ReadonlyColor BISQUE = new Color(0xffe4c4ff);\n /** <div style=\"background:#000000\">#000000</div> */\n public static final ReadonlyColor BLACK = new Color(0x000000ff);\n /** <div style=\"background:#ffebcd\">#ffebcd</div> */\n public static final ReadonlyColor BLANCHED_ALMOND = new Color(0xffebcdff);\n /** <div style=\"background:#0000ff\">#0000ff</div> */\n public static final ReadonlyColor BLUE = new Color(0x0000ffff);\n /** <div style=\"background:#8a2be2\">#8a2be2</div> */\n public static final ReadonlyColor BLUE_VIOLET = new Color(0x8a2be2ff);\n /** <div style=\"background:#a52a2a\">#a52a2a</div> */\n public static final ReadonlyColor BROWN = new Color(0xa52a2aff);\n /** <div style=\"background:#deb887\">#deb887</div> */\n public static final ReadonlyColor BURLY_WOOD = new Color(0xdeb887ff);\n /** <div style=\"background:#5f9ea0\">#5f9ea0</div> */\n public static final ReadonlyColor CADET_BLUE = new Color(0x5f9ea0ff);\n /** <div style=\"background:#7fff00\">#7fff00</div> */\n public static final ReadonlyColor CHARTREUSE = new Color(0x7fff00ff);\n /** <div style=\"background:#d2691e\">#d2691e</div> */\n public static final ReadonlyColor CHOCOLATE = new Color(0xd2691eff);\n /** <div style=\"background:#ff7f50\">#ff7f50</div> */\n public static final ReadonlyColor CORAL = new Color(0xff7f50ff);\n /** <div style=\"background:#6495ed\">#6495ed</div> */\n public static final ReadonlyColor CORNFLOWER_BLUE = new Color(0x6495edff);\n /** <div style=\"background:#fff8dc\">#fff8dc</div> */\n public static final ReadonlyColor CORNSILK = new Color(0xfff8dcff);\n /** <div style=\"background:#dc143c\">#dc143c</div> */\n public static final ReadonlyColor CRIMSON = new Color(0xdc143cff);\n public static final ReadonlyColor CYAN = AQUA;\n /** <div style=\"background:#00008b\">#00008b</div> */\n public static final ReadonlyColor DARK_BLUE = new Color(0x00008bff);\n /** <div style=\"background:#008b8b\">#008b8b</div> */\n public static final ReadonlyColor DARK_CYAN = new Color(0x008b8bff);\n /** <div style=\"background:#b8860b\">#b8860b</div> */\n public static final ReadonlyColor DARK_GOLDENROD = new Color(0xb8860bff);\n /** <div style=\"background:#a9a9a9\">#a9a9a9</div> */\n public static final ReadonlyColor DARK_GRAY = new Color(0xa9a9a9ff);\n /** <div style=\"background:#006400\">#006400</div> */\n public static final ReadonlyColor DARK_GREEN = new Color(0x006400ff);\n /** <div style=\"background:#a9a9a9\">#a9a9a9</div> */\n public static final ReadonlyColor DARK_GREY = DARK_GRAY;\n /** <div style=\"background:#bdb76b\">#bdb76b</div> */\n public static final ReadonlyColor DARK_KHAKI = new Color(0xbdb76bff);\n /** <div style=\"background:#8b008b\">#8b008b</div> */\n public static final ReadonlyColor DARK_MAGENTA = new Color(0x8b008bff);\n /** <div style=\"background:#556b2f\">#556b2f</div> */\n public static final ReadonlyColor DARK_OLIVE_GREEN = new Color(0x556b2fff);\n /** <div style=\"background:#ff8c00\">#ff8c00</div> */\n public static final ReadonlyColor DARK_ORANGE = new Color(0xff8c00ff);\n /** <div style=\"background:#9932cc\">#9932cc</div> */\n public static final ReadonlyColor DARK_ORCHID = new Color(0x9932ccff);\n /** <div style=\"background:#8b0000\">#8b0000</div> */\n public static final ReadonlyColor DARK_RED = new Color(0x8b0000ff);\n /** <div style=\"background:#e9967a\">#e9967a</div> */\n public static final ReadonlyColor DARK_SALMON = new Color(0xe9967aff);\n /** <div style=\"background:#8fbc8f\">#8fbc8f</div> */\n public static final ReadonlyColor DARK_SEA_GREEN = new Color(0x8fbc8fff);\n /** <div style=\"background:#483d8b\">#483d8b</div> */\n public static final ReadonlyColor DARK_SLATE_BLUE = new Color(0x483d8bff);\n /** <div style=\"background:#2f4f4f\">#2f4f4f</div> */\n public static final ReadonlyColor DARK_SLATE_GRAY = new Color(0x2f4f4fff);\n /** <div style=\"background:#2f4f4f\">#2f4f4f</div> */\n public static final ReadonlyColor DARK_SLATE_GREY = DARK_SLATE_GRAY;\n /** <div style=\"background:#00ced1\">#00ced1</div> */\n public static final ReadonlyColor DARK_TURQUOISE = new Color(0x00ced1ff);\n /** <div style=\"background:#9400d3\">#9400d3</div> */\n public static final ReadonlyColor DARK_VIOLET = new Color(0x9400d3ff);\n /** <div style=\"background:#ff1493\">#ff1493</div> */\n public static final ReadonlyColor DEEP_PINK = new Color(0xff1493ff);\n /** <div style=\"background:#00bfff\">#00bfff</div> */\n public static final ReadonlyColor DEEP_SKY_BLUE = new Color(0x00bfffff);\n /** <div style=\"background:#696969\">#696969</div> */\n public static final ReadonlyColor DIM_GRAY = new Color(0x696969ff);\n /** <div style=\"background:#696969\">#696969</div> */\n public static final ReadonlyColor DIM_GREY = DIM_GRAY;\n /** <div style=\"background:#1e90ff\">#1e90ff</div> */\n public static final ReadonlyColor DODGER_BLUE = new Color(0x1e90ffff);\n /** <div style=\"background:#b22222\">#b22222</div> */\n public static final ReadonlyColor FIRE_BRICK = new Color(0xb22222ff);\n /** <div style=\"background:#fffaf0\">#fffaf0</div> */\n public static final ReadonlyColor FLORAL_WHITE = new Color(0xfffaf0ff);\n /** <div style=\"background:#228b22\">#228b22</div> */\n public static final ReadonlyColor FOREST_GREEN = new Color(0x228b22ff);\n /** <div style=\"background:#ff00ff\">#ff00ff</div> */\n public static final ReadonlyColor FUCHSIA = new Color(0xff00ffff);\n /** <div style=\"background:#dcdcdc\">#dcdcdc</div> */\n public static final ReadonlyColor GAINSBORO = new Color(0xdcdcdcff);\n /** <div style=\"background:#f8f8ff\">#f8f8ff</div> */\n public static final ReadonlyColor GHOST_WHITE = new Color(0xf8f8ffff);\n /** <div style=\"background:#ffd700\">#ffd700</div> */\n public static final ReadonlyColor GOLD = new Color(0xffd700ff);\n /** <div style=\"background:#daa520\">#daa520</div> */\n public static final ReadonlyColor GOLDENROD = new Color(0xdaa520ff);\n /** <div style=\"background:#808080\">#808080</div> */\n public static final ReadonlyColor GRAY = new Color(0x808080ff);\n /** <div style=\"background:#008000\">#008000</div> */\n public static final ReadonlyColor GREEN = new Color(0x008000ff);\n /** <div style=\"background:#adff2f\">#adff2f</div> */\n public static final ReadonlyColor GREEN_YELLOW = new Color(0xadff2fff);\n /** <div style=\"background:#808080\">#808080</div> */\n public static final ReadonlyColor GREY = GRAY;\n /** <div style=\"background:#f0fff0\">#f0fff0</div> */\n public static final ReadonlyColor HONEYDEW = new Color(0xf0fff0ff);\n /** <div style=\"background:#ff69b4\">#ff69b4</div> */\n public static final ReadonlyColor HOT_PINK = new Color(0xff69b4ff);\n /** <div style=\"background:#cd5c5c\">#cd5c5c</div> */\n public static final ReadonlyColor INDIAN_RED = new Color(0xcd5c5cff);\n /** <div style=\"background:#4b0082\">#4b0082</div> */\n public static final ReadonlyColor INDIGO = new Color(0x4b0082ff);\n /** <div style=\"background:#fffff0\">#fffff0</div> */\n public static final ReadonlyColor IVORY = new Color(0xfffff0ff);\n /** <div style=\"background:#f0e68c\">#f0e68c</div> */\n public static final ReadonlyColor KHAKI = new Color(0xf0e68cff);\n /** <div style=\"background:#e6e6fa\">#e6e6fa</div> */\n public static final ReadonlyColor LAVENDER = new Color(0xe6e6faff);\n /** <div style=\"background:#fff0f5\">#fff0f5</div> */\n public static final ReadonlyColor LAVENDER_BLUSH = new Color(0xfff0f5ff);\n /** <div style=\"background:#7cfc00\">#7cfc00</div> */\n public static final ReadonlyColor LAWN_GREEN = new Color(0x7cfc00ff);\n /** <div style=\"background:#fffacd\">#fffacd</div> */\n public static final ReadonlyColor LEMON_CHIFFON = new Color(0xfffacdff);\n /** <div style=\"background:#add8e6\">#add8e6</div> */\n public static final ReadonlyColor LIGHT_BLUE = new Color(0xadd8e6ff);\n /** <div style=\"background:#f08080\">#f08080</div> */\n public static final ReadonlyColor LIGHT_CORAL = new Color(0xf08080ff);\n /** <div style=\"background:#e0ffff\">#e0ffff</div> */\n public static final ReadonlyColor LIGHT_CYAN = new Color(0xe0ffffff);\n /** <div style=\"background:#fafad2\">#fafad2</div> */\n public static final ReadonlyColor LIGHT_GOLDENROD_YELLOW = new Color(0xfafad2ff);\n /** <div style=\"background:#d3d3d3\">#d3d3d3</div> */\n public static final ReadonlyColor LIGHT_GRAY = new Color(0xd3d3d3ff);\n /** <div style=\"background:#90ee90\">#90ee90</div> */\n public static final ReadonlyColor LIGHT_GREEN = new Color(0x90ee90ff);\n /** <div style=\"background:#d3d3d3\">#d3d3d3</div> */\n public static final ReadonlyColor LIGHT_GREY = LIGHT_GRAY;\n /** <div style=\"background:#ffb6c1\">#ffb6c1</div> */\n public static final ReadonlyColor LIGHT_PINK = new Color(0xffb6c1ff);\n /** <div style=\"background:#ffa07a\">#ffa07a</div> */\n public static final ReadonlyColor LIGHT_SALMON = new Color(0xffa07aff);\n /** <div style=\"background:#20b2aa\">#20b2aa</div> */\n public static final ReadonlyColor LIGHT_SEA_GREEN = new Color(0x20b2aaff);\n /** <div style=\"background:#87cefa\">#87cefa</div> */\n public static final ReadonlyColor LIGHT_SKY_BLUE = new Color(0x87cefaff);\n /** <div style=\"background:#778899\">#778899</div> */\n public static final ReadonlyColor LIGHT_SLATE_GRAY = new Color(0x778899ff);\n /** <div style=\"background:#778899\">#778899</div> */\n public static final ReadonlyColor LIGHT_SLATE_GREY = LIGHT_SLATE_GRAY;\n /** <div style=\"background:#b0c4de\">#b0c4de</div> */\n public static final ReadonlyColor LIGHT_STEEL_BLUE = new Color(0xb0c4deff);\n /** <div style=\"background:#ffffe0\">#ffffe0</div> */\n public static final ReadonlyColor LIGHT_YELLOW = new Color(0xffffe0ff);\n /** <div style=\"background:#00ff00\">#00ff00</div> */\n public static final ReadonlyColor LIME = new Color(0x00ff00ff);\n /** <div style=\"background:#32cd32\">#32cd32</div> */\n public static final ReadonlyColor LIME_GREEN = new Color(0x32cd32ff);\n /** <div style=\"background:#faf0e6\">#faf0e6</div> */\n public static final ReadonlyColor LINEN = new Color(0xfaf0e6ff);\n /** <div style=\"background:#ff00ff\">#ff00ff</div> */\n public static final ReadonlyColor MAGENTA = FUCHSIA;\n /** <div style=\"background:#800000\">#800000</div> */\n public static final ReadonlyColor MAROON = new Color(0x800000ff);\n /** <div style=\"background:#66cdaa\">#66cdaa</div> */\n public static final ReadonlyColor MEDIUM_AQUAMARINE = new Color(0x66cdaaff);\n /** <div style=\"background:#0000cd\">#0000cd</div> */\n public static final ReadonlyColor MEDIUM_BLUE = new Color(0x0000cdff);\n /** <div style=\"background:#ba55d3\">#ba55d3</div> */\n public static final ReadonlyColor MEDIUM_ORCHID = new Color(0xba55d3ff);\n /** <div style=\"background:#9370db\">#9370db</div> */\n public static final ReadonlyColor MEDIUM_PURPLE = new Color(0x9370dbff);\n /** <div style=\"background:#3cb371\">#3cb371</div> */\n public static final ReadonlyColor MEDIUM_SEA_GREEN = new Color(0x3cb371ff);\n /** <div style=\"background:#7b68ee\">#7b68ee</div> */\n public static final ReadonlyColor MEDIUM_SLATE_BLUE = new Color(0x7b68eeff);\n /** <div style=\"background:#00fa9a\">#00fa9a</div> */\n public static final ReadonlyColor MEDIUM_SPRING_GREEN = new Color(0x00fa9aff);\n /** <div style=\"background:#48d1cc\">#48d1cc</div> */\n public static final ReadonlyColor MEDIUM_TURQUOISE = new Color(0x48d1ccff);\n /** <div style=\"background:#c71585\">#c71585</div> */\n public static final ReadonlyColor MEDIUM_VIOLET_RED = new Color(0xc71585ff);\n /** <div style=\"background:#191970\">#191970</div> */\n public static final ReadonlyColor MIDNIGHT_BLUE = new Color(0x191970ff);\n /** <div style=\"background:#f5fffa\">#f5fffa</div> */\n public static final ReadonlyColor MINT_CREAM = new Color(0xf5fffaff);\n /** <div style=\"background:#ffe4e1\">#ffe4e1</div> */\n public static final ReadonlyColor MISTY_ROSE = new Color(0xffe4e1ff);\n /** <div style=\"background:#ffe4b5\">#ffe4b5</div> */\n public static final ReadonlyColor MOCCASIN = new Color(0xffe4b5ff);\n /** <div style=\"background:#ffdead\">#ffdead</div> */\n public static final ReadonlyColor NAVAJO_WHITE = new Color(0xffdeadff);\n /** <div style=\"background:#000080\">#000080</div> */\n public static final ReadonlyColor NAVY = new Color(0x000080ff);\n /** <div style=\"background:#fdf5e6\">#fdf5e6</div> */\n public static final ReadonlyColor OLD_LACE = new Color(0xfdf5e6ff);\n /** <div style=\"background:#808000\">#808000</div> */\n public static final ReadonlyColor OLIVE = new Color(0x808000ff);\n /** <div style=\"background:#6b8e23\">#6b8e23</div> */\n public static final ReadonlyColor OLIVE_DRAB = new Color(0x6b8e23ff);\n /** <div style=\"background:#ffa500\">#ffa500</div> */\n public static final ReadonlyColor ORANGE = new Color(0xffa500ff);\n /** <div style=\"background:#ff4500\">#ff4500</div> */\n public static final ReadonlyColor ORANGE_RED = new Color(0xff4500ff);\n /** <div style=\"background:#da70d6\">#da70d6</div> */\n public static final ReadonlyColor ORCHID = new Color(0xda70d6ff);\n /** <div style=\"background:#eee8aa\">#eee8aa</div> */\n public static final ReadonlyColor PALE_GOLDENROD = new Color(0xeee8aaff);\n /** <div style=\"background:#98fb98\">#98fb98</div> */\n public static final ReadonlyColor PALE_GREEN = new Color(0x98fb98ff);\n /** <div style=\"background:#afeeee\">#afeeee</div> */\n public static final ReadonlyColor PALE_TURQUOISE = new Color(0xafeeeeff);\n /** <div style=\"background:#db7093\">#db7093</div> */\n public static final ReadonlyColor PALE_VIOLET_RED = new Color(0xdb7093ff);\n /** <div style=\"background:#ffefd5\">#ffefd5</div> */\n public static final ReadonlyColor PAPAYA_WHIP = new Color(0xffefd5ff);\n /** <div style=\"background:#ffdab9\">#ffdab9</div> */\n public static final ReadonlyColor PEACH_PUFF = new Color(0xffdab9ff);\n /** <div style=\"background:#cd853f\">#cd853f</div> */\n public static final ReadonlyColor PERU = new Color(0xcd853fff);\n /** <div style=\"background:#ffc0cb\">#ffc0cb</div> */\n public static final ReadonlyColor PINK = new Color(0xffc0cbff);\n /** <div style=\"background:#dda0dd\">#dda0dd</div> */\n public static final ReadonlyColor PLUM = new Color(0xdda0ddff);\n /** <div style=\"background:#b0e0e6\">#b0e0e6</div> */\n public static final ReadonlyColor POWDER_BLUE = new Color(0xb0e0e6ff);\n /** <div style=\"background:#800080\">#800080</div> */\n public static final ReadonlyColor PURPLE = new Color(0x800080ff);\n /** <div style=\"background:#ff0000\">#ff0000</div> */\n public static final ReadonlyColor RED = new Color(0xff0000ff);\n /** <div style=\"background:#bc8f8f\">#bc8f8f</div> */\n public static final ReadonlyColor ROSY_BROWN = new Color(0xbc8f8fff);\n /** <div style=\"background:#4169e1\">#4169e1</div> */\n public static final ReadonlyColor ROYAL_BLUE = new Color(0x4169e1ff);\n /** <div style=\"background:#8b4513\">#8b4513</div> */\n public static final ReadonlyColor SADDLE_BROWN = new Color(0x8b4513ff);\n /** <div style=\"background:#fa8072\">#fa8072</div> */\n public static final ReadonlyColor SALMON = new Color(0xfa8072ff);\n /** <div style=\"background:#f4a460\">#f4a460</div> */\n public static final ReadonlyColor SANDY_BROWN = new Color(0xf4a460ff);\n /** <div style=\"background:#2e8b57\">#2e8b57</div> */\n public static final ReadonlyColor SEA_GREEN = new Color(0x2e8b57ff);\n /** <div style=\"background:#fff5ee\">#fff5ee</div> */\n public static final ReadonlyColor SEASHELL = new Color(0xfff5eeff);\n /** <div style=\"background:#a0522d\">#a0522d</div> */\n public static final ReadonlyColor SIENNA = new Color(0xa0522dff);\n /** <div style=\"background:#c0c0c0\">#c0c0c0</div> */\n public static final ReadonlyColor SILVER = new Color(0xc0c0c0ff);\n /** <div style=\"background:#87ceeb\">#87ceeb</div> */\n public static final ReadonlyColor SKY_BLUE = new Color(0x87ceebff);\n /** <div style=\"background:#6a5acd\">#6a5acd</div> */\n public static final ReadonlyColor SLATE_BLUE = new Color(0x6a5acdff);\n /** <div style=\"background:#708090\">#708090</div> */\n public static final ReadonlyColor SLATE_GRAY = new Color(0x708090ff);\n /** <div style=\"background:#708090\">#708090</div> */\n public static final ReadonlyColor SLATE_GREY = SLATE_GRAY;\n /** <div style=\"background:#fffafa\">#fffafa</div> */\n public static final ReadonlyColor SNOW = new Color(0xfffafaff);\n /** <div style=\"background:#00ff7f\">#00ff7f</div> */\n public static final ReadonlyColor SPRING_GREEN = new Color(0x00ff7fff);\n /** <div style=\"background:#4682b4\">#4682b4</div> */\n public static final ReadonlyColor STEEL_BLUE = new Color(0x4682b4ff);\n /** <div style=\"background:#d2b48c\">#d2b48c</div> */\n public static final ReadonlyColor TAN = new Color(0xd2b48cff);\n /** <div style=\"background:#008080\">#008080</div> */\n public static final ReadonlyColor TEAL = new Color(0x008080ff);\n /** <div style=\"background:#d8bfd8\">#d8bfd8</div> */\n public static final ReadonlyColor THISTLE = new Color(0xd8bfd8ff);\n /** <div style=\"background:#ff6347\">#ff6347</div> */\n public static final ReadonlyColor TOMATO = new Color(0xff6347ff);\n /** <div style=\"background:#40e0d0\">#40e0d0</div> */\n public static final ReadonlyColor TURQUOISE = new Color(0x40e0d0ff);\n /** <div style=\"background:#ee82ee\">#ee82ee</div> */\n public static final ReadonlyColor VIOLET = new Color(0xee82eeff);\n /** <div style=\"background:#f5deb3\">#f5deb3</div> */\n public static final ReadonlyColor WHEAT = new Color(0xf5deb3ff);\n /** <div style=\"background:#ffffff\">#ffffff</div> */\n public static final ReadonlyColor WHITE = new Color(0xffffffff);\n /** <div style=\"background:#f5f5f5\">#f5f5f5</div> */\n public static final ReadonlyColor WHITE_SMOKE = new Color(0xf5f5f5ff);\n /** <div style=\"background:#ffff00\">#ffff00</div> */\n public static final ReadonlyColor YELLOW = new Color(0xffff00ff);\n /** <div style=\"background:#9acd32\">#9acd32</div> */\n public static final ReadonlyColor YELLOW_GREEN = new Color(0x9acd32ff);\n // Bob Ross approves\n\n // Other useful named colors\n public static final ReadonlyColor TRANSPARENT_BLACK = new Color(0x00000000);\n public static final ReadonlyColor TRANSPARENT_WHITE = new Color(0xffffff00);\n\n private static HashMap<String, ReadonlyColor> namedColors;\n /**\n * @return the ReadonlyColor matching the name parameter, or null if there\n * is no such named color. Insensitive to case, whitespace, and\n * underscores.\n * <p>\n * All <a href=\"http://en.wikipedia.org/wiki/Web_colors\">W3C/X11\n * named colors</a> are included.\n */\n public static ReadonlyColor getNamedColor(String name) {\n if (name == null) {\n return null;\n }\n if (namedColors == null) {\n // lazily instantiate\n namedColors = new HashMap<String, ReadonlyColor>();\n try {\n for (Field field : Color.class.getDeclaredFields()) {\n if (field.getType() == ReadonlyColor.class) {\n namedColors.put(field.getName().replaceAll(\"_\", \"\"), (ReadonlyColor) field.get(null));\n }\n }\n } catch (Exception e) {\n throw new LSDInternalReflectionException(\"unable to reflect named colors\", e);\n }\n }\n return namedColors.get(name.toUpperCase().replaceAll(\"[_\\\\s]\", \"\"));\n }\n\n /**\n * Change the byte order of a 32-bit integer packed with color components.\n */\n public static int convertARGBtoRGBA(int argb) {\n return (argb << 8) | ((argb & 0xff000000) >>> 24);\n }\n\n /**\n * Change the byte order of a 32-bit integer packed with color components.\n */\n public static int convertRGBAtoARGB(int rgba) {\n return (rgba >>> 8) | ((rgba & 0x000000ff) << 24);\n }\n}",
"public class LineStyle implements ReadonlyLineStyle {\n private static final long serialVersionUID = 1L;\n public static final ReadonlyLineStyle DEFAULT = new LineStyle(\n Color.MAGENTA.copy().setAlpha(0.8), 3.0F, true);\n\n private Color mainColor;\n private float mainWidth;\n private Color secondaryColor;\n private float secondaryWidth;\n\n public LineStyle(Color color, float width, boolean hasSecondaryColor) {\n set(color, width, hasSecondaryColor);\n }\n\n public LineStyle(Color mainColor, float mainWidth, Color secondaryColor, float secondaryWidth) {\n set(mainColor, mainWidth, secondaryColor, secondaryWidth);\n }\n\n public LineStyle(ReadonlyLineStyle other) {\n setMainColor(other.getMainReadonlyColor().copy());\n setMainWidth(other.getMainWidth());\n setSecondaryColor(other.getSecondaryReadonlyColor() == null ? null : other.getSecondaryReadonlyColor().copy());\n setSecondaryWidth(other.getSecondaryWidth());\n }\n\n @Override\n public LineStyle copy() {\n return new LineStyle(this);\n }\n\n @Override\n public ReadonlyColor getMainReadonlyColor() {\n return mainColor;\n }\n\n @Override\n public ReadonlyColor getSecondaryReadonlyColor() {\n return secondaryColor;\n }\n\n @Override\n public float getMainWidth() {\n return mainWidth;\n }\n\n @Override\n public float getSecondaryWidth() {\n return secondaryWidth;\n }\n\n @Override\n public boolean hasSecondaryColor() {\n return secondaryColor != null;\n }\n\n @Override\n public boolean glApply(boolean useSecondary) {\n if (useSecondary) {\n if (secondaryColor == null) {\n return false;\n }\n GL11.glDepthFunc(GL11.GL_GREATER);\n secondaryColor.glApply();\n GL11.glLineWidth(secondaryWidth);\n } else {\n GL11.glDepthFunc(GL11.GL_LEQUAL);\n mainColor.glApply();\n GL11.glLineWidth(mainWidth);\n }\n return true;\n }\n\n @Override\n public boolean isAnimating() {\n return mainColor.isAnimating() ||\n (secondaryColor != null && secondaryColor.isAnimating());\n }\n\n /** @return true if two line styles are equal. */\n @Override\n public boolean equals(Object other) {\n return other instanceof LineStyle && toString().equals(other.toString());\n }\n\n @Override\n public int hashCode() {\n return toString().hashCode();\n }\n\n @Override\n public String toString() {\n StringBuilder b = new StringBuilder(\"(\");\n b.append(getMainColor()).append(',').append(getMainWidth());\n if (hasSecondaryColor()) {\n b.append('|').append(getSecondaryColor()).append(',').append(getSecondaryWidth());\n }\n return b.append(')').toString();\n }\n\n // ========\n // Accessors for mutable properties\n // ========\n\n /** @return the main line color, mutable. */\n public Color getMainColor() {\n return mainColor;\n }\n\n /** @return the secondary line color, mutable. May be null. */\n public Color getSecondaryColor() {\n return secondaryColor;\n }\n\n // ========\n // Mutators\n // ========\n\n /**\n * Convenience method to set mainColor, mainWidth, secondaryColor, and\n * secondaryWidth at once.\n * @param color sets mainColor\n * @param width sets both mainWidth and secondaryWidth\n * @param hasSecondaryColor if true, secondaryColor will be a\n * semi-transparent version of mainColor. If false, secondaryColor\n * is null.\n * @return the same line style object, modified in-place.\n */\n public LineStyle set(Color color, float width, boolean hasSecondaryColor) {\n setMainColor(color);\n setMainWidth(width);\n if (hasSecondaryColor) {\n setSecondaryColorFromMain();\n } else {\n setSecondaryColor(null);\n }\n setSecondaryWidth(width);\n return this;\n }\n\n /**\n * Set all components of this line style.\n * @return the same line style object, modified in-place.\n */\n public LineStyle set(Color mainColor, float mainWidth, Color secondaryColor, float secondaryWidth) {\n setMainColor(mainColor);\n setMainWidth(mainWidth);\n setSecondaryColor(secondaryColor);\n setSecondaryWidth(secondaryWidth);\n return this;\n }\n\n /**\n * Set the line style's main color, which cannot be null.\n * @return the same line style object, modified in-place.\n */\n public LineStyle setMainColor(Color mainColor) {\n if (mainColor == null) {\n throw new IllegalArgumentException(\"main color cannot be null\");\n }\n this.mainColor = mainColor;\n return this;\n }\n\n /**\n * Set the line style's main width.\n * @return the same line style object, modified in-place.\n */\n public LineStyle setMainWidth(float mainWidth) {\n if (mainWidth < 0) {\n throw new IllegalArgumentException(\"line width must be positive\");\n }\n this.mainWidth = mainWidth;\n return this;\n }\n\n /**\n * Set the line style's secondary color, which can be null.\n * @return the same line style object, modified in-place.\n */\n public LineStyle setSecondaryColor(Color secondaryColor) {\n // null allowed\n this.secondaryColor = secondaryColor;\n return this;\n }\n\n /**\n * Set the line style's secondary color to a semi-transparent version of\n * the main line color.\n * @return the same line style object, modified in-place.\n */\n public LineStyle setSecondaryColorFromMain() {\n secondaryColor = mainColor.copy().scaleAlpha(XrayShape.SECONDARY_ALPHA);\n return this;\n }\n\n /**\n * Set the line style's secondary width.\n * @return the same line style object, modified in-place.\n */\n public LineStyle setSecondaryWidth(float secondaryWidth) {\n if (secondaryWidth < 0) {\n throw new IllegalArgumentException(\"line width must be positive\");\n }\n this.secondaryWidth = secondaryWidth;\n return this;\n }\n}",
"public interface ReadonlyColor extends Serializable {\n /**\n * @return a new deep-copied mutable Color. Does not copy animations.\n * <p>\n * Same concept as Object.clone(), minus the tedious/clunky checked\n * exception, CloneNotSupportedException.\n */\n public Color copy();\n\n /** @return this color's red component, in the range [0.0, 1.0]. */\n public double getRed();\n\n /** @return this color's green component, in the range [0.0, 1.0]. */\n public double getGreen();\n\n /** @return this color's blue component, in the range [0.0, 1.0]. */\n public double getBlue();\n\n /**\n * @return this color's alpha component, in the range [0.0, 1.0].\n * 0.0 is fully transparent; 1.0 is fully opaque.\n */\n public double getAlpha();\n\n /**\n * @return a 32-bit integer packed with each of the color's components, one\n * per byte. The order, from most significant to least, is\n * red, green, blue, alpha.\n */\n public int getRGBA();\n\n /**\n * @return a 32-bit integer packed with each of the color's components, one\n * per byte. The order, from most significant to least, is\n * alpha, red, green, blue.\n */\n public int getARGB();\n\n /**\n * Convenience method to update the OpenGL state to use this color.\n * <p>\n * Equivalent to\n * <code>GL11.glColor4d(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha())</code>\n */\n public void glApply();\n\n /**\n * Convenience method to update the OpenGL state to use this color, with\n * the alpha value scaled by a specified factor. The Color instance remains\n * unchanged by the factor. The final alpha value passed to OpenGL is\n * clamped to [0.0, 1.0]. \n * <p>\n * Equivalent to <code>c.copy().scaleAlpha(alphaScale).glApply()</code>,\n * without the extra Color instance creation.\n */\n public void glApply(double alphaScale);\n\n /** @return true if this color is being updated by an active animation. */\n public boolean isAnimating();\n\n @Override\n public boolean equals(Object other);\n\n @Override\n public int hashCode();\n\n @Override\n public String toString();\n}",
"public interface ReadonlyLineStyle extends Serializable {\n /**\n * @return a new deep-copied mutable LineStyle.\n * <p>\n * Same concept as Object.clone(), minus the tedious/clunky checked\n * exception, CloneNotSupportedException.\n */\n public LineStyle copy();\n\n /** @return a read-only view of the main line color. */\n public ReadonlyColor getMainReadonlyColor();\n\n /** @return the main line width. */\n public float getMainWidth();\n\n /** @return a read-only view of the secondary line color. May be null. */\n public ReadonlyColor getSecondaryReadonlyColor();\n\n /**\n * @return the secondary line width, which is unused if the secondary line\n * color is null.\n */\n public float getSecondaryWidth();\n\n /** @return true if the secondary line color is null. */\n public boolean hasSecondaryColor();\n\n /**\n * Convenience method that sets the OpenGL state to match this line style.\n * I.e., call glColor4d, glLineWidth, and glDepthFunc.\n * @return false if the OpenGL state was not set due to the secondary color\n * not being set for this line style.\n */\n public boolean glApply(boolean useSecondary);\n\n /**\n * @return true if either of this line style's colors is being updated by\n * an active animation.\n * <p>\n * The line widths can be animated by a Timeline too, but not an\n * internal one: LineStyle does not implement the full\n * {@link libshapedraw.animation.Animates} interface.\n */\n public boolean isAnimating();\n\n @Override\n public boolean equals(Object other);\n\n @Override\n public int hashCode();\n\n @Override\n public String toString();\n}",
"public interface ReadonlyVector3 extends Serializable {\n /**\n * @return a new deep-copied mutable Vector3. Does not copy animations.\n * <p>\n * Same concept as Object.clone(), minus the tedious/clunky checked\n * exception, CloneNotSupportedException.\n */\n public Vector3 copy();\n\n /** @return the vector's x component. */\n public double getX();\n\n /** @return the vector's y component. */\n public double getY();\n\n /** @return the vector's z component. */\n public double getZ();\n\n /** @return the vector's component for the given axis. */\n public double getComponent(Axis axis);\n\n /**\n * @return true if the specified vector component matches a value within a\n * a margin of error (epsilon).\n * @see #EPSILON\n */\n public boolean componentEquals(Axis axis, double value, double epsilon);\n\n /** @return true if the vector components match the other's exactly. */\n public boolean equalsExact(ReadonlyVector3 other);\n\n /** @return true if the vector components match the other's exactly. */\n public boolean equalsExact(double otherX, double otherY, double otherZ);\n\n /**\n * @return true if the vector components match the other's within a margin\n * of error (epsilon).\n * @see #EPSILON\n */\n public boolean equals(ReadonlyVector3 other, double epsilon);\n\n /**\n * @return true if the vector components match the other's within a margin\n * of error (epsilon).\n * @see #EPSILON\n */\n public boolean equals(double otherX, double otherY, double otherZ, double epsilon);\n\n /**\n * A recommended margin of error to use with\n * {@link #equals(ReadonlyVector3, double)}.\n */\n public static final double EPSILON = 1E-6;\n\n /**\n * Equivalent to {@link #equalsExact(ReadonlyVector3)}.\n * <p>\n * This method is marked as deprecated because it's better practice to\n * explicitly state margins of error for floating-point comparisons. For a\n * non-zero margin of error, use {@link #equals(ReadonlyVector3, double)}.\n * @deprecated\n */\n @Override\n @Deprecated\n public boolean equals(Object other);\n\n @Override\n public int hashCode();\n\n @Override\n public String toString();\n\n /** @return true if all of this vector's components are exactly zero. */\n public boolean isZero();\n\n /**\n * Equivalent to <code>distanceSquared(Vector3.ZEROS)</code>.\n * @return the vector's length (aka magnitude) squared. To compare two\n * two vectors' lengths, use this method instead of\n * {@link #length()} as it avoids the relatively expensive sqrt\n * call.\n */\n public double lengthSquared();\n\n /**\n * Equivalent to <code>distance(Vector3.ZEROS)</code>.\n * @return the vector's length (aka magnitude). This uses the relatively\n * expensive sqrt function, so avoid calling it repeatedly.\n */\n public double length();\n\n /**\n * @return the distance between two points, squared. If you're trying to\n * compare two distances, use this method instead of\n * {@link #distance} as it avoids the relatively expensive sqrt\n * call.\n */\n public double distanceSquared(ReadonlyVector3 other);\n\n /** @deprecated as of release 1.1 replaced by {@link #distanceSquared} */\n @Deprecated public double getDistanceSquared(ReadonlyVector3 other);\n\n /**\n * @return the distance between two points. This uses the relatively\n * expensive sqrt function, so avoid calling it repeatedly.\n */\n public double distance(ReadonlyVector3 other);\n\n /** @deprecated as of release 1.1 replaced by {@link #distance} */\n @Deprecated public double getDistance(ReadonlyVector3 other);\n\n /** @return the dot product between two vectors: x0*x1 + y0*y1 + z0*z1. */\n public double dot(ReadonlyVector3 other);\n\n /**\n * @return the angle, in radians [0, pi], between two vectors. If either\n * vector is all zeros, 0 is returned.\n */\n public double angle(ReadonlyVector3 other);\n\n /**\n * @return the angle, in degrees [0, 180], between two vectors. If either\n * vector is all zeros, 0 is returned.\n */\n public double angleDegrees(ReadonlyVector3 other);\n\n /**\n * @return the angle, in radians (-pi/2, pi/2] of the vector direction's\n * heading, relative to the z axis.\n */\n public double yaw();\n\n /**\n * @return the angle, in degrees (-180, 180] of the vector direction's\n * heading, relative to the z axis.\n */\n public double yawDegrees();\n\n /**\n * @return the angle, in radians [-pi/2, pi/2] of the vector direction's\n * elevation.\n */\n public double pitch();\n\n /**\n * @return the angle, in degrees [-90, 90] of the vector direction's\n * elevation.\n */\n public double pitchDegrees();\n\n /**\n * @return true if the point is inside the axis-aligned bounding box\n * specified by the two corner parameters.\n */\n public boolean isInAABB(ReadonlyVector3 lowerCorner, ReadonlyVector3 upperColor);\n\n /** @return true if the point is inside the sphere. */\n public boolean isInSphere(ReadonlyVector3 origin, double radius);\n\n /**\n * Convenience method to update the OpenGL state with this vector.\n * <p>\n * Equivalent to\n * <code>GL11.glRotated(angleDegrees, v.getX(), v.getY(), v.getZ())</code>.\n * <p>\n * Calling this method on a zero vector is a no-op.\n * <p>\n * \"Un-applying\" the rotation (e.g., glPushMatrix and glPopMatrix)\n * is the responsibility of the caller.\n * <p>\n * All of these operations are actually\n * <a href=\"http://www.opengl.org/wiki/Legacy_OpenGL\">deprecated in OpenGL\n * 3.0</a>, but Minecraft is just old school like that.\n */\n public void glApplyRotateDegrees(double angleDegrees);\n\n /**\n * Convenience method to update the OpenGL state with this vector.\n * <p>\n * Equivalent to\n * <code>GL11.glRotated(angleRadians*180.0/Math.PI, v.getX(), v.getY(), v.getZ())</code>.\n * <p>\n * Calling this method on a zero vector is a no-op.\n * <p>\n * \"Un-applying\" the rotation (e.g., glPushMatrix and glPopMatrix)\n * is the responsibility of the caller.\n * <p>\n * All of these operations are actually\n * <a href=\"http://www.opengl.org/wiki/Legacy_OpenGL\">deprecated in OpenGL\n * 3.0</a>, but Minecraft is just old school like that.\n */\n public void glApplyRotateRadians(double angleRadians);\n\n /**\n * Convenience method to update the OpenGL state with this vector.\n * <p>\n * Equivalent to\n * <code>GL11.glScaled(v.getX(), v.getY(), v.getZ())</code>.\n * <p>\n * \"Un-applying\" the scaling (e.g., glPushMatrix and glPopMatrix)\n * is the responsibility of the caller.\n * <p>\n * All of these operations are actually\n * <a href=\"http://www.opengl.org/wiki/Legacy_OpenGL\">deprecated in OpenGL\n * 3.0</a>, but Minecraft is just old school like that.\n */\n public void glApplyScale();\n\n /**\n * Convenience method to update the OpenGL state with this vector.\n * <p>\n * Equivalent to\n * <code>GL11.glTranslated(v.getX(), v.getY(), v.getZ())</code>.\n * <p>\n * \"Un-applying\" the translation (e.g., glPushMatrix and glPopMatrix)\n * is the responsibility of the caller.\n * <p>\n * All of these operations are actually\n * <a href=\"http://www.opengl.org/wiki/Legacy_OpenGL\">deprecated in OpenGL\n * 3.0</a>, but Minecraft is just old school like that.\n */\n public void glApplyTranslate();\n\n /** @return true if this vector is being updated by an active animation. */\n public boolean isAnimating();\n}",
"public class Vector3 implements ReadonlyVector3, Animates<ReadonlyVector3>, Serializable {\n private static final long serialVersionUID = 1L;\n public static final ReadonlyVector3 ZEROS = new Vector3();\n\n private static final double R2D = 180.0 / Math.PI;\n private static final double D2R = Math.PI / 180.0;\n\n private double x;\n private double y;\n private double z;\n\n /**\n * It is perhaps a bit wasteful to have a Timeline field on every Vector3\n * instance just to support those few Vector3s that need to be animated,\n * even if it is lazily instantiated. However, developer convenience wins\n * over premature optimization.\n * <p>\n * In any case, java.nio.FloatBuffer is a more appropriate data container\n * for a large number of vertices in a memory-constrained environment.\n */\n private transient Timeline timeline;\n\n /** Create a new vector with all components set to zero. */\n public Vector3() {\n // do nothing; 0.0 is the default double value already\n }\n\n public Vector3(double x, double y, double z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n public Vector3(ReadonlyVector3 other) {\n this(other.getX(), other.getY(), other.getZ());\n }\n\n @Override\n public Vector3 copy() {\n return new Vector3(x, y, z);\n }\n\n @Override\n public double getX() {\n return x;\n }\n\n @Override\n public double getY() {\n return y;\n }\n\n @Override\n public double getZ() {\n return z;\n }\n\n @Override\n public double getComponent(Axis axis) {\n if (axis == null) {\n throw new IllegalArgumentException(\"axis cannot be null\");\n } else if (axis == Axis.X) {\n return x;\n } else if (axis == Axis.Y) {\n return y;\n } else {\n return z;\n }\n }\n\n @Override\n public boolean componentEquals(Axis axis, double value, double epsilon) {\n // A negative epsilon is pointless (causing this check to always\n // return false), but still valid.\n return Math.abs(getComponent(axis) - value) <= epsilon;\n }\n\n @Override\n public boolean equalsExact(ReadonlyVector3 other) {\n return other != null && equalsExact(other.getX(), other.getY(), other.getZ());\n }\n\n @Override\n public boolean equalsExact(double otherX, double otherY, double otherZ) {\n return x == otherX && y == otherY && z == otherZ;\n }\n\n @Override\n public boolean equals(ReadonlyVector3 other, double epsilon) {\n return other != null && equals(other.getX(), other.getY(), other.getZ(), epsilon);\n }\n\n @Override\n public boolean equals(double otherX, double otherY, double otherZ, double epsilon) {\n // A negative epsilon is pointless (causing this check to always\n // return false), but still valid.\n return (Math.abs(x - otherX) <= epsilon &&\n Math.abs(y - otherY) <= epsilon &&\n Math.abs(z - otherZ) <= epsilon);\n }\n\n @Deprecated\n @Override\n public boolean equals(Object other) {\n return other instanceof ReadonlyVector3 && equalsExact((ReadonlyVector3) other);\n }\n\n @Override\n public int hashCode() {\n // Equivalent to java.util.Arrays.hashCode(new double[] {x, y, z})\n // without the extra object allocation.\n long bits;\n int hash = 1;\n bits = Double.doubleToLongBits(x);\n hash = 31*hash + (int) (bits ^ (bits >>> 32));\n bits = Double.doubleToLongBits(y);\n hash = 31*hash + (int) (bits ^ (bits >>> 32));\n bits = Double.doubleToLongBits(z);\n hash = 31*hash + (int) (bits ^ (bits >>> 32));\n return hash;\n }\n\n @Override\n public String toString() {\n return \"(\" + x + \",\" + y + \",\" + z + \")\";\n }\n\n @Override\n public boolean isZero() {\n return x == 0.0 && y == 0.0 && z == 0.0;\n }\n\n @Override\n public double lengthSquared() {\n return Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2);\n }\n\n @Override\n public double length() {\n return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));\n }\n\n @Override\n public double distanceSquared(ReadonlyVector3 other) {\n return Math.pow(x - other.getX(), 2) + Math.pow(y - other.getY(), 2) + Math.pow(z - other.getZ(), 2);\n }\n\n @Override\n @Deprecated public double getDistanceSquared(ReadonlyVector3 other) {\n return Math.pow(x - other.getX(), 2) + Math.pow(y - other.getY(), 2) + Math.pow(z - other.getZ(), 2);\n }\n\n @Override\n public double distance(ReadonlyVector3 other) {\n return Math.sqrt(Math.pow(x - other.getX(), 2) + Math.pow(y - other.getY(), 2) + Math.pow(z - other.getZ(), 2));\n }\n\n @Override\n @Deprecated public double getDistance(ReadonlyVector3 other) {\n return Math.sqrt(Math.pow(x - other.getX(), 2) + Math.pow(y - other.getY(), 2) + Math.pow(z - other.getZ(), 2));\n }\n\n @Override\n public double dot(ReadonlyVector3 other) {\n return x*other.getX() + y*other.getY() + z*other.getZ();\n }\n\n @Override\n public double angle(ReadonlyVector3 other) {\n double angle = Math.acos(dot(other) / (length() * other.length()));\n if (Double.isNaN(angle)) {\n if (x != 0.0 && Math.signum(x) == -Math.signum(other.getX())) {\n // vectors point in exact opposite directions\n return Math.PI;\n } else {\n // same direction or at least one of the vectors is all zeros\n return 0.0;\n }\n } else {\n return angle;\n }\n }\n\n @Override\n public double angleDegrees(ReadonlyVector3 other) {\n return angle(other) * R2D;\n }\n\n @Override\n public double yaw() {\n return Math.atan2(x, z);\n }\n\n @Override\n public double yawDegrees() {\n return Math.atan2(x, z) * R2D;\n }\n\n @Override\n public double pitch() {\n double m = Math.pow(x, 2) + Math.pow(z, 2);\n if (m > 0.0) {\n return Math.asin(y / Math.sqrt(m));\n } else if (y < 0.0) {\n // straight up\n return -Math.PI / 2.0;\n } else if (y > 0.0) {\n // straight down\n return Math.PI / 2.0;\n } else {\n // vector is all zeros\n return 0.0;\n }\n }\n\n @Override\n public double pitchDegrees() {\n return pitch() * R2D;\n }\n\n @Override\n public boolean isInAABB(ReadonlyVector3 lowerCorner, ReadonlyVector3 upperCorner) {\n if (lowerCorner.getX() > upperCorner.getX() ||\n lowerCorner.getY() > upperCorner.getY() ||\n lowerCorner.getZ() > upperCorner.getZ()) {\n return (x >= Math.min(lowerCorner.getX(), upperCorner.getX()) &&\n x <= Math.max(lowerCorner.getX(), upperCorner.getX()) &&\n y >= Math.min(lowerCorner.getY(), upperCorner.getY()) &&\n y <= Math.max(lowerCorner.getY(), upperCorner.getY()) &&\n z >= Math.min(lowerCorner.getZ(), upperCorner.getZ()) &&\n z <= Math.max(lowerCorner.getZ(), upperCorner.getZ()));\n }\n return (x >= lowerCorner.getX() &&\n x <= upperCorner.getX() &&\n y >= lowerCorner.getY() &&\n y <= upperCorner.getY() &&\n z >= lowerCorner.getZ() &&\n z <= upperCorner.getZ());\n }\n\n @Override\n public boolean isInSphere(ReadonlyVector3 origin, double radius) {\n return Math.pow(x - origin.getX(), 2) +\n Math.pow(y - origin.getY(), 2) +\n Math.pow(z - origin.getZ(), 2)\n <= Math.pow(radius, 2);\n }\n\n @Override\n public void glApplyRotateDegrees(double angleDegrees) {\n if (!isZero()) {\n // We have to use glRotatef because glRotated is missing from LWJGL\n // 2.4.2, the version Minecraft ships with. LWJGL did fix this several\n // releases ago though: http://lwjgl.org/forum/index.php?topic=4128.0\n GL11.glRotatef((float) angleDegrees, (float) x, (float) y, (float) z);\n }\n }\n\n @Override\n public void glApplyRotateRadians(double angleRadians) {\n if (!isZero()) {\n // see above\n GL11.glRotatef((float) (angleRadians*R2D), (float) x, (float) y, (float) z);\n }\n }\n\n @Override\n public void glApplyScale() {\n GL11.glScaled(x, y, z);\n }\n\n @Override\n public void glApplyTranslate() {\n GL11.glTranslated(x, y, z);\n }\n\n // ========\n // Mutators\n // ========\n\n /**\n * Set all of this vector's components to match another vector's.\n * @return the same vector object, modified in-place.\n */\n public Vector3 set(double x, double y, double z) {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n }\n\n /**\n * Set all of this vector's components to match another vector's.\n * @return the same vector object, modified in-place.\n */\n public Vector3 set(ReadonlyVector3 other) {\n x = other.getX();\n y = other.getY();\n z = other.getZ();\n return this;\n }\n\n /**\n * Set this vector's x component.\n * @return the same vector object, modified in-place.\n */\n public Vector3 setX(double x) {\n this.x = x;\n return this;\n }\n\n /**\n * Set this vector's y component.\n * @return the same vector object, modified in-place.\n */\n public Vector3 setY(double y) {\n this.y = y;\n return this;\n }\n\n /**\n * Set this vector's z component.\n * @return the same vector object, modified in-place.\n */\n public Vector3 setZ(double z) {\n this.z = z;\n return this;\n }\n\n /**\n * Set one of this vector's components, specified by the axis, to the\n * specified value.\n * @return the same vector object, modified in-place.\n */\n public Vector3 setComponent(Axis axis, double value) {\n if (axis == null) {\n throw new IllegalArgumentException(\"axis cannot be null\");\n } else if (axis == Axis.X) {\n x = value;\n } else if (axis == Axis.Y) {\n y = value;\n } else {\n z = value;\n }\n return this;\n }\n\n /**\n * Swap the components of this vector: set y to the previous x value,\n * z to y, and x to z. To swap in the other direction, simply call this\n * method twice.\n * @return the same vector object, modified in-place.\n */\n public Vector3 swapComponents() {\n double tmp = z;\n z = y;\n y = x;\n x = tmp;\n return this;\n }\n\n /**\n * Add to this vector's x component.\n * @return the same vector object, modified in-place.\n */\n public Vector3 addX(double xAmount) {\n x += xAmount;\n return this;\n }\n\n /**\n * Add to this vector's y component.\n * @return the same vector object, modified in-place.\n */\n public Vector3 addY(double yAmount) {\n y += yAmount;\n return this;\n }\n\n /**\n * Add to this vector's z component.\n * @return the same vector object, modified in-place.\n */\n public Vector3 addZ(double zAmount) {\n z += zAmount;\n return this;\n }\n\n /**\n * Add to one of this vector's components, specified by the axis.\n * @return the same vector object, modified in-place.\n */\n public Vector3 addComponent(Axis axis, double amount) {\n return setComponent(axis, getComponent(axis) + amount);\n }\n\n /**\n * Add a vector to this vector.\n * @return the same vector object, modified in-place.\n */\n public Vector3 add(double xAmount, double yAmount, double zAmount) {\n x += xAmount;\n y += yAmount;\n z += zAmount;\n return this;\n }\n\n /**\n * Add a vector to this vector.\n * @return the same vector object, modified in-place.\n */\n public Vector3 add(ReadonlyVector3 other) {\n x += other.getX();\n y += other.getY();\n z += other.getZ();\n return this;\n }\n\n /**\n * Subtract a vector from this vector.\n * Equivalent to <code>addX(-other.getX()).addY(-other.getY()).addZ(-other.getZ())</code>.\n * @return the same vector object, modified in-place.\n */\n public Vector3 subtract(ReadonlyVector3 other) {\n x -= other.getX();\n y -= other.getY();\n z -= other.getZ();\n return this;\n }\n\n /**\n * Set all of this vector's components to 0.\n * Equivalent to <code>set(Vector3.ZEROS)</code>.\n * @return the same vector object, modified in-place.\n */\n public Vector3 zero() {\n x = 0.0;\n y = 0.0;\n z = 0.0;\n return this;\n }\n\n /**\n * Set all of this vector's components to random values in [0.0, 1.0).\n * @return the same vector object, modified in-place.\n */\n public Vector3 setRandom() {\n x = Math.random();\n y = Math.random();\n z = Math.random();\n return this;\n }\n\n /**\n * Given two other vectors, pick the lowest x, y, and z values and set this\n * vector's components to those values.\n * @return the same vector object, modified in-place.\n */\n public Vector3 setMinimum(ReadonlyVector3 a, ReadonlyVector3 b) {\n x = Math.min(a.getX(), b.getX());\n y = Math.min(a.getY(), b.getY());\n z = Math.min(a.getZ(), b.getZ());\n return this;\n }\n\n /**\n * Given two other vectors, pick the highest x, y, and z values and set this\n * vector's components to those values.\n * @return the same vector object, modified in-place.\n */\n public Vector3 setMaximum(ReadonlyVector3 a, ReadonlyVector3 b) {\n x = Math.max(a.getX(), b.getX());\n y = Math.max(a.getY(), b.getY());\n z = Math.max(a.getZ(), b.getZ());\n return this;\n }\n\n /**\n * Set this vector to a unit vector (i.e. length=1) facing the direction\n * specified by yaw and pitch angles, both in radians.\n * @return the same vector object, modified in-place.\n */\n public Vector3 setFromYawPitch(double yaw, double pitch) {\n x = Math.sin(yaw)*Math.cos(pitch);\n y = Math.sin(pitch);\n z = Math.cos(yaw)*Math.cos(pitch);\n return this;\n }\n\n /**\n * Set this vector to a unit vector (i.e. length=1) facing the direction\n * specified by yaw and pitch angles, both in degrees.\n * @return the same vector object, modified in-place.\n */\n public Vector3 setFromYawPitchDegrees(double yawDegrees, double pitchDegrees) {\n return setFromYawPitch(yawDegrees*D2R, pitchDegrees*D2R);\n }\n\n /**\n * Multiply each component of this vector by a given factor.\n * @return the same vector object, modified in-place.\n */\n public Vector3 scale(double factor) {\n x *= factor;\n y *= factor;\n z *= factor;\n return this;\n }\n\n /**\n * Multiply the x component of this vector by a given factor.\n * @return the same vector object, modified in-place.\n */\n public Vector3 scaleX(double factor) {\n x *= factor;\n return this;\n }\n\n /**\n * Multiply the y component of this vector by a given factor.\n * @return the same vector object, modified in-place.\n */\n public Vector3 scaleY(double factor) {\n y *= factor;\n return this;\n }\n\n /**\n * Multiply the z component of this vector by a given factor.\n * @return the same vector object, modified in-place.\n */\n public Vector3 scaleZ(double factor) {\n z *= factor;\n return this;\n }\n\n /**\n * Multiply one of this vector's components, specified by the axis, by a\n * given factor.\n * @return the same vector object, modified in-place.\n */\n public Vector3 scaleComponent(Axis axis, double factor) {\n return setComponent(axis, getComponent(axis) * factor);\n }\n\n /**\n * Set each component of this vector to its negative value.\n * Equivalent to <code>scale(-1)</code>.\n * @return the same vector object, modified in-place.\n */\n public Vector3 negate() {\n x = -x;\n y = -y;\n z = -z;\n return this;\n }\n\n /**\n * Set each component of this vector to its absolute value.\n * @return the same vector object, modified in-place.\n */\n public Vector3 absolute() {\n x = Math.abs(x);\n y = Math.abs(y);\n z = Math.abs(z);\n return this;\n }\n\n /**\n * Ensure that each component of this vector is in the specified range.\n * @return the same vector object, modified in-place.\n */\n public Vector3 clamp(double min, double max) {\n x = Math.min(max, Math.max(min, x));\n y = Math.min(max, Math.max(min, y));\n z = Math.min(max, Math.max(min, z));\n return this;\n }\n\n /**\n * Ensure that the x component of this vector is in the specified range.\n * @return the same vector object, modified in-place.\n */\n public Vector3 clampX(double min, double max) {\n x = Math.min(max, Math.max(min, x));\n return this;\n }\n\n /**\n * Ensure that the y component of this vector is in the specified range.\n * @return the same vector object, modified in-place.\n */\n public Vector3 clampY(double min, double max) {\n y = Math.min(max, Math.max(min, y));\n return this;\n }\n\n /**\n * Ensure that the z component of this vector is in the specified range.\n * @return the same vector object, modified in-place.\n */\n public Vector3 clampZ(double min, double max) {\n z = Math.min(max, Math.max(min, z));\n return this;\n }\n\n /**\n * Ensure that one of this vector's components, specified by the axis, is\n * in the specified range.\n * @return the same vector object, modified in-place.\n */\n public Vector3 clampComponent(Axis axis, double min, double max) {\n return setComponent(axis, Math.min(max, Math.max(min, getComponent(axis))));\n }\n\n /**\n * Drop the fractional portion of each component by casting each to an int,\n * then back to a double. Values move closer to zero.\n * <p>E.g.: -3.25 to -3.0; -0.6 to 0.0; 0.4 to 0.0; 5.3 to 5.0.\n * @return the same vector object, modified in-place.\n */\n public Vector3 truncate() {\n x = (int) x;\n y = (int) y;\n z = (int) z;\n return this;\n }\n\n /**\n * Drop the fractional portion of each component using {@link Math#floor}.\n * Values move closer to negative infinity.\n * <p>E.g.: -3.25 to -4.0; -0.6 to -1.0; 0.4 to 0.0; 5.3 to 5.0. \n * @return the same vector object, modified in-place.\n */\n public Vector3 floor() {\n x = Math.floor(x);\n y = Math.floor(y);\n z = Math.floor(z);\n return this;\n }\n\n /**\n * Drop the fractional portion of each component using {@link Math#ceil}.\n * Values move closer to positive infinity.\n * <p>E.g.: -3.25 to -3.0; -0.6 to 0.0; 0.4 to 1.0; 5.3 to 6.0. \n * @return the same vector object, modified in-place.\n */\n public Vector3 ceiling() {\n x = Math.ceil(x);\n y = Math.ceil(y);\n z = Math.ceil(z);\n return this;\n }\n\n /**\n * Drop the fractional portion of each component using {@link Math#round}.\n * Values move to the closest whole number.\n * <p>E.g.: -3.25 to -3.0; -0.6 to -1.0; 0.4 to 0.0; 5.3 to 5.0. \n * @return the same vector object, modified in-place.\n */\n public Vector3 round() {\n x = Math.round(x);\n y = Math.round(y);\n z = Math.round(z);\n return this;\n }\n\n /**\n * Set this vector to the midpoint in between it and another vector.\n * Equivalent to <code>interpolate(other, 0.5)</code>.\n * @return the same vector object, modified in-place.\n */\n public Vector3 midpoint(ReadonlyVector3 other) {\n x = x/2.0 + other.getX()/2.0;\n y = y/2.0 + other.getY()/2.0;\n z = z/2.0 + other.getZ()/2.0;\n return this;\n }\n\n /**\n * Set this vector to a point along the line between it and another vector.\n * E.g., 0.0 is this vector; 0.5 is halfway between this vector and the\n * other; 1.0 is the other vector.\n * @return the same vector object, modified in-place.\n */\n public Vector3 interpolate(ReadonlyVector3 other, double alpha) {\n x = (1.0 - alpha)*x + alpha*other.getX();\n y = (1.0 - alpha)*y + alpha*other.getY();\n z = (1.0 - alpha)*z + alpha*other.getZ();\n return this;\n }\n\n /**\n * Set this vector to the cross product between this vector and another.\n * @return the same vector object, modified in-place.\n */\n public Vector3 cross(ReadonlyVector3 other) {\n double tmpX = y*other.getZ() - z*other.getY();\n double tmpY = z*other.getX() - x*other.getZ();\n z = x*other.getY() - y*other.getX();\n x = tmpX;\n y = tmpY;\n return this;\n }\n\n /**\n * Convert this vector to a unit vector. I.e., a length of 1 but still\n * facing in the same direction. If the vector is all zeros, it is left\n * unchanged.\n * @return the same vector object, modified in-place.\n */\n public Vector3 normalize() {\n double length = length();\n if (length == 0.0) {\n return this;\n }\n x /= length;\n y /= length;\n z /= length;\n return this;\n }\n\n // ========\n // Animates interface\n // ========\n\n @Override\n public boolean isAnimating() {\n return timeline != null && !timeline.isDone();\n }\n\n @Override\n public Vector3 animateStop() {\n if (timeline != null && !timeline.isDone()) {\n timeline.abort();\n }\n timeline = null;\n return this;\n }\n\n @Override\n public Vector3 animateStart(ReadonlyVector3 toVector, long durationMs) {\n if (toVector == null) {\n throw new IllegalArgumentException(\"toVector cannot be null\");\n }\n newTimeline(toVector.getX(), toVector.getY(), toVector.getZ(), durationMs);\n timeline.play();\n return this;\n }\n /**\n * Convenience method, equivalent to\n * <code>animateStart(new Vector3(toX, toY, toZ), durationMs)</code>\n */\n public Vector3 animateStart(double toX, double toY, double toZ, long durationMs) {\n newTimeline(toX, toY, toZ, durationMs);\n timeline.play();\n return this;\n }\n\n @Override\n public Vector3 animateStartLoop(ReadonlyVector3 toVector, boolean reverse, long durationMs) {\n if (toVector == null) {\n throw new IllegalArgumentException(\"toVector cannot be null\");\n }\n newTimeline(toVector.getX(), toVector.getY(), toVector.getZ(), durationMs);\n timeline.playLoop(reverse);\n return this;\n }\n /**\n * Convenience method, equivalent to\n * <code>animateStartLoop(new Vector3(toX, toY, toZ), reverse, durationMs)</code>\n */\n public Vector3 animateStartLoop(double toX, double toY, double toZ, boolean reverse, long durationMs) {\n newTimeline(toX, toY, toZ, durationMs);\n timeline.playLoop(reverse);\n return this;\n }\n\n private void newTimeline(double toX, double toY, double toZ, long durationMs) {\n animateStop();\n timeline = new Timeline(this);\n timeline.addPropertyToInterpolate(\"x\", x, toX);\n timeline.addPropertyToInterpolate(\"y\", y, toY);\n timeline.addPropertyToInterpolate(\"z\", z, toZ);\n timeline.setDuration(durationMs);\n }\n}"
] | import java.util.Iterator;
import libshapedraw.MinecraftAccess;
import libshapedraw.primitive.Color;
import libshapedraw.primitive.LineStyle;
import libshapedraw.primitive.ReadonlyColor;
import libshapedraw.primitive.ReadonlyLineStyle;
import libshapedraw.primitive.ReadonlyVector3;
import libshapedraw.primitive.Vector3;
import org.lwjgl.opengl.GL11; | package libshapedraw.shape;
/**
* A series of connected line segments that smoothly blends from one line style
* to another along the segments.
* <p>
* For most use cases you'll want to use WireframeLinesBlend instead, which
* takes a Collection of ReadonlyVector3s rather than an Iterable. Only use
* this class if you want to blend based solely on the render cap, not on the
* number of points.
*/
public class WireframeLinesBlendIterable extends WireframeLines {
private LineStyle blendToLineStyle;
public WireframeLinesBlendIterable(Vector3 origin, Iterable<ReadonlyVector3> relativePoints) {
super(origin, relativePoints);
}
public WireframeLinesBlendIterable(Iterable<ReadonlyVector3> absolutePoints) {
super(absolutePoints);
}
public LineStyle getBlendToLineStyle() {
return blendToLineStyle;
}
public WireframeLinesBlendIterable setBlendToLineStyle(LineStyle blendToLineStyle) {
this.blendToLineStyle = blendToLineStyle;
return this;
}
/**
* Convenience method.
* @see LineStyle#set
*/
public WireframeLinesBlendIterable setBlendToLineStyle(Color color, float width, boolean visibleThroughTerrain) {
if (blendToLineStyle == null) {
blendToLineStyle = new LineStyle(color, width, visibleThroughTerrain);
} else {
blendToLineStyle.set(color, width, visibleThroughTerrain);
}
return this;
}
/**
* The "blend endpoint" refers to the last line to be rendered, which
* should be 100% getBlendToLineStyle().
*/
protected int getBlendEndpoint() {
return getRenderCap() - 1;
}
@Override
protected void renderLines(MinecraftAccess mc, boolean isSecondary) { | final ReadonlyLineStyle fromStyle = getEffectiveLineStyle(); | 4 |
bmelnychuk/outlay | outlay/app/src/main/java/app/outlay/view/Navigator.java | [
"public class MainActivity extends DrawerActivity {\n\n private MainFragment mainFragment;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(app.outlay.R.layout.activity_single_fragment);\n\n Bundle b = getIntent().getExtras();\n mainFragment = new MainFragment();\n mainFragment.setArguments(b);\n addFragment(app.outlay.R.id.fragment, mainFragment);\n }\n\n @Override\n protected void signOut() {\n getApp().releaseUserComponent();\n FirebaseAuth.getInstance().signOut();\n Navigator.goToLoginScreen(this);\n finish();\n }\n\n @Override\n public void onBackPressed() {\n if(mainFragment.onBackPressed()) {\n super.onBackPressed();\n }\n }\n\n @Override\n protected void createUser() {\n Navigator.goToSyncGuestActivity(this);\n }\n}",
"public class AnalysisFragment extends BaseMvpFragment<AnalysisView, AnalysisPresenter> implements AnalysisView {\n private static final int REF_TIMESTAMP = 1451660400;\n\n @Bind(app.outlay.R.id.categoryTitle)\n MaterialAutoCompleteTextView categoryTitle;\n\n @Bind(app.outlay.R.id.barChart)\n BarChart barChart;\n\n @Bind(app.outlay.R.id.toolbar)\n Toolbar toolbar;\n\n @Bind(app.outlay.R.id.categoryIcon)\n ImageView categoryIcon;\n\n @Bind(app.outlay.R.id.startDate)\n EditText startDateEdit;\n\n @Bind(app.outlay.R.id.endDate)\n EditText endDateEdit;\n\n @Inject\n AnalysisPresenter presenter;\n\n private CategoryAutoCompleteAdapter autoCompleteAdapter;\n private DayAxisValueFormatter dayAxisValueFormatter;\n\n private Date startDate;\n private Date endDate;\n private Category selectedCategory;\n\n @Override\n public AnalysisPresenter createPresenter() {\n return presenter;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getApp().getUserComponent().inject(this);\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(app.outlay.R.layout.fragment_analysis, null, false);\n return view;\n }\n\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n setToolbar(toolbar);\n setTitle(getResources().getString(app.outlay.R.string.menu_item_analysis));\n setDisplayHomeAsUpEnabled(true);\n\n Drawable noCategoryIcon = IconUtils.getIconMaterialIcon(\n getContext(),\n MaterialDesignIconic.Icon.gmi_label,\n getOutlayTheme().inactiveIconColor,\n app.outlay.R.dimen.report_category_icon,\n 4\n );\n categoryIcon.setImageDrawable(noCategoryIcon);\n startDateEdit.setOnClickListener(v -> showDatePickerDialog(0));\n endDateEdit.setOnClickListener(v -> showDatePickerDialog(1));\n\n autoCompleteAdapter = new CategoryAutoCompleteAdapter();\n categoryTitle.setAdapter(autoCompleteAdapter);\n categoryTitle.setOnItemClickListener((parent, view1, position, id) -> {\n DeviceUtils.hideKeyboard(getActivity());\n Category category = autoCompleteAdapter.getItem(position);\n selectedCategory = category;\n loadCategoryIcon(category);\n onDataChanged();\n });\n\n initChart();\n\n getPresenter().getCategories();\n }\n\n private void loadCategoryIcon(Category category) {\n int iconCodeRes = getResourceHelper().getIntegerResource(category.getIcon());\n Drawable categoryIconDrawable = IconUtils.getCategoryIcon(getContext(),\n iconCodeRes,\n category.getColor(),\n app.outlay.R.dimen.report_category_icon\n );\n categoryIcon.setImageDrawable(categoryIconDrawable);\n }\n\n private void onDataChanged() {\n if (selectedCategory == null) {\n return;\n }\n if (startDate == null || endDate == null) {\n return;\n }\n DateTime startDateTime = new DateTime(startDate);\n DateTime endDateTime = new DateTime(endDate);\n\n if (startDateTime.isAfter(endDateTime)) {\n return;\n }\n\n analytics().trackAnalysisPerformed(startDate, endDate);\n getPresenter().getExpenses(startDate, endDate, selectedCategory);\n }\n\n private void initChart() {\n barChart.setDrawBarShadow(false);\n barChart.setDrawValueAboveBar(true);\n barChart.getDescription().setEnabled(false);\n barChart.setPinchZoom(false);\n barChart.setMaxVisibleValueCount(60);\n barChart.getLegend().setEnabled(false);\n barChart.setDrawGridBackground(false);\n barChart.getAxisRight().setEnabled(false);\n barChart.setScaleYEnabled(false);\n\n dayAxisValueFormatter = new DayAxisValueFormatter();\n XAxis xAxis = barChart.getXAxis();\n xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);\n xAxis.setLabelRotationAngle(270);\n xAxis.setDrawGridLines(false);\n xAxis.setGranularity(1f);\n xAxis.setTextColor(getOutlayTheme().secondaryTextColor);\n xAxis.setValueFormatter(dayAxisValueFormatter);\n\n\n YAxis leftAxis = barChart.getAxisLeft();\n leftAxis.setValueFormatter(new AmountValueFormatter());\n leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);\n leftAxis.setTextColor(getOutlayTheme().secondaryTextColor);\n leftAxis.setSpaceTop(15f);\n leftAxis.setAxisMinimum(0f);\n }\n\n private void showDatePickerDialog(int dateType) {\n DatePickerFragment datePickerFragment = new DatePickerFragment();\n datePickerFragment.setOnDateSetListener((parent, year, monthOfYear, dayOfMonth) -> {\n Calendar c = Calendar.getInstance();\n c.set(year, monthOfYear, dayOfMonth);\n Date selected = c.getTime();\n if (dateType == 0) {\n startDate = selected;\n startDateEdit.setText(DateUtils.toLongString(selected));\n } else {\n endDate = selected;\n endDateEdit.setText(DateUtils.toLongString(selected));\n }\n onDataChanged();\n });\n datePickerFragment.show(getChildFragmentManager(), \"datePicker\");\n }\n\n @Override\n public void showAnalysis(Report report) {\n List<BarEntry> barEntries = new ArrayList<>();\n List<Expense> expenses = report.getExpenses();\n\n for (int i = 0; i < expenses.size(); i++) {\n Expense expense = expenses.get(i);\n barEntries.add(new BarEntry(\n i,\n expense.getAmount().floatValue())\n );\n }\n BarDataSet barSet = new BarDataSet(barEntries, \"\");\n barSet.setColor(selectedCategory.getColor());\n\n List<IBarDataSet> dataSets = new ArrayList<>();\n dataSets.add(barSet);\n\n BarData data = new BarData(dataSets);\n data.setValueTextSize(10f);\n data.setValueTextColor(getOutlayTheme().secondaryTextColor);\n data.setBarWidth(0.9f);\n\n dayAxisValueFormatter.setExpenses(expenses);\n barChart.setData(data);\n barChart.invalidate();\n barChart.animateY(500);\n }\n\n @Override\n public void setCategories(List<Category> categories) {\n autoCompleteAdapter.setItems(categories);\n }\n\n public static class DayAxisValueFormatter implements IAxisValueFormatter {\n private List<Expense> expenses;\n\n public DayAxisValueFormatter setExpenses(List<Expense> expenses) {\n this.expenses = expenses;\n return this;\n }\n\n @Override\n public String getFormattedValue(float value, AxisBase axis) {\n if (expenses != null && value < expenses.size()) {\n Expense expense = expenses.get((int) value);\n return DateUtils.toShortString(expense.getReportedWhen());\n } else {\n return null;\n }\n }\n }\n\n public static class AmountValueFormatter implements IAxisValueFormatter {\n private DecimalFormat mFormat;\n\n public AmountValueFormatter() {\n mFormat = new DecimalFormat(\"###,###,###,##0.0\");\n }\n\n @Override\n public String getFormattedValue(float value, AxisBase axis) {\n return mFormat.format(value);\n }\n\n }\n}",
"public class CategoriesFragment extends BaseMvpFragment<CategoriesView, CategoriesPresenter> implements OnDragListener, CategoriesView {\n\n @Bind(app.outlay.R.id.toolbar)\n Toolbar toolbar;\n\n @Bind(app.outlay.R.id.categoriesGrid)\n RecyclerView categoriesGrid;\n\n @Bind(app.outlay.R.id.noContent)\n View noContent;\n\n @Bind(app.outlay.R.id.noContentImage)\n ImageView noContentImage;\n\n @Bind(app.outlay.R.id.fab)\n FloatingActionButton fab;\n\n @Inject\n CategoriesPresenter presenter;\n\n private ItemTouchHelper mItemTouchHelper;\n private CategoriesDraggableGridAdapter adapter;\n\n @Override\n public CategoriesPresenter createPresenter() {\n return presenter;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getApp().getUserComponent().inject(this);\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(app.outlay.R.layout.fragment_categories, null, false);\n return view;\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n ButterKnife.bind(this, view);\n\n setToolbar(toolbar);\n setDisplayHomeAsUpEnabled(true);\n getActivity().setTitle(getString(app.outlay.R.string.caption_categories));\n\n GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 4);\n categoriesGrid.setLayoutManager(gridLayoutManager);\n\n adapter = new CategoriesDraggableGridAdapter(getOutlayTheme());\n adapter.setDragListener(this);\n adapter.setOnCategoryClickListener(c -> Navigator.goToCategoryDetails(getActivity(), c.getId()));\n categoriesGrid.setAdapter(adapter);\n\n ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter);\n mItemTouchHelper = new ItemTouchHelper(callback);\n mItemTouchHelper.attachToRecyclerView(categoriesGrid);\n\n fab.setImageDrawable(getResourceHelper().getFabIcon(app.outlay.R.string.ic_material_add));\n fab.setOnClickListener(v -> Navigator.goToCategoryDetails(getActivity(), null));\n\n Drawable noCategoryIcon = IconUtils.getIconMaterialIcon(\n getContext(),\n MaterialDesignIconic.Icon.gmi_label,\n getOutlayTheme().inactiveIconColor,\n app.outlay.R.dimen.icon_no_results,\n 16\n );\n noContentImage.setImageDrawable(noCategoryIcon);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n presenter.getCategories();\n }\n\n @Override\n public void onStartDrag(RecyclerView.ViewHolder viewHolder) {\n analytics().trackCategoryDragEvent();\n mItemTouchHelper.startDrag(viewHolder);\n }\n\n @Override\n public void onEndDrag(RecyclerView.ViewHolder viewHolder) {\n List<Category> items = adapter.getItems();\n for (int i = 0; i < items.size(); i++) {\n items.get(i).setOrder(i);\n }\n presenter.updateOrder(items);\n }\n\n @Override\n public void showCategories(List<Category> categoryList) {\n adapter.setItems(categoryList);\n noContent.setVisibility(categoryList.isEmpty() ? View.VISIBLE : View.GONE);\n }\n}",
"public class CategoryDetailsFragment extends BaseMvpFragment<CategoryDetailsView, CategoryDetailsPresenter> implements CategoryDetailsView {\n public static final String ARG_CATEGORY_PARAM = \"_argCategoryId\";\n\n @Bind(app.outlay.R.id.toolbar)\n Toolbar toolbar;\n\n @Bind(app.outlay.R.id.iconsGrid)\n RecyclerView iconsGrid;\n\n @Bind(app.outlay.R.id.colorPicker)\n LineColorPicker colorPicker;\n\n @Bind(app.outlay.R.id.categoryName)\n EditText categoryName;\n\n @Bind(app.outlay.R.id.categoryInputLayout)\n TextInputLayout categoryInputLayout;\n\n @Inject\n CategoryDetailsPresenter presenter;\n\n private IconsGridAdapter adapter;\n private Category category;\n\n @Override\n public CategoryDetailsPresenter createPresenter() {\n return presenter;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getApp().getUserComponent().inject(this);\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(app.outlay.R.layout.fragment_category_details, null, false);\n return view;\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n inflater.inflate(app.outlay.R.menu.menu_category_details, menu);\n MenuItem saveItem = menu.findItem(app.outlay.R.id.action_save);\n saveItem.setIcon(getResourceHelper().getMaterialToolbarIcon(app.outlay.R.string.ic_material_done));\n if (category != null && category.getId() == null) {\n MenuItem deleteItem = menu.findItem(app.outlay.R.id.action_delete);\n deleteItem.setVisible(false);\n }\n super.onCreateOptionsMenu(menu, inflater);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case app.outlay.R.id.action_save:\n Category category = getCategory();\n if (validateCategory(category)) {\n if (TextUtils.isEmpty(category.getId())) {\n analytics().trackCategoryCreated(category);\n } else {\n analytics().trackCategoryUpdated(category);\n }\n presenter.updateCategory(getCategory());\n }\n break;\n case app.outlay.R.id.action_delete:\n category = getCategory();\n analytics().trackCategoryDeleted(category);\n presenter.deleteCategory(category);\n break;\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n setToolbar(toolbar);\n setDisplayHomeAsUpEnabled(true);\n\n GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 4);\n iconsGrid.setLayoutManager(gridLayoutManager);\n adapter = new IconsGridAdapter(IconUtils.getAll(), getOutlayTheme());\n iconsGrid.setAdapter(adapter);\n colorPicker.setOnColorChangedListener(i -> adapter.setActiveColor(i));\n\n if (getArguments().containsKey(ARG_CATEGORY_PARAM)) {\n String categoryId = getArguments().getString(ARG_CATEGORY_PARAM);\n getActivity().setTitle(getString(app.outlay.R.string.caption_edit_category));\n presenter.getCategory(categoryId);\n } else {\n getActivity().setTitle(getString(app.outlay.R.string.caption_edit_category));\n showCategory(new Category());\n }\n\n categoryName.addTextChangedListener(new TextWatcherAdapter() {\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n categoryInputLayout.setErrorEnabled(false);\n }\n });\n }\n\n @Override\n public void showCategory(Category category) {\n this.category = category;\n\n if (category.getId() == null) {\n int colorsCount = colorPicker.getColors().length;\n int randomPosition = new Random().nextInt(colorsCount);\n colorPicker.setSelectedColorPosition(randomPosition);\n adapter.setActiveColor(colorPicker.getColor());\n } else {\n colorPicker.setSelectedColor(category.getColor());\n adapter.setActiveItem(category.getIcon(), category.getColor());\n categoryName.setText(category.getTitle());\n }\n }\n\n @Override\n public void finish() {\n getActivity().onBackPressed();\n }\n\n public Category getCategory() {\n category.setTitle(categoryName.getText().toString());\n category.setColor(colorPicker.getColor());\n category.setIcon(adapter.getSelectedIcon());\n return category;\n }\n\n private boolean validateCategory(Category category) {\n boolean result = true;\n if (TextUtils.isEmpty(category.getTitle())) {\n categoryInputLayout.setErrorEnabled(true);\n categoryInputLayout.setError(getString(app.outlay.R.string.error_category_name_empty));\n categoryName.requestFocus();\n result = false;\n } else if (TextUtils.isEmpty(category.getIcon())) {\n Alert.error(getBaseActivity().getRootView(), getString(app.outlay.R.string.error_category_icon));\n result = false;\n }\n\n return result;\n }\n}",
"public class ExpensesDetailsFragment extends BaseMvpFragment<ExpenseDetailsView, ExpenseDetailsPresenter> implements ExpenseDetailsView {\n\n public static final String ARG_EXPENSE_ID = \"_argExpenseId\";\n public static final String ARG_DATE = \"_argDate\";\n\n @Bind(app.outlay.R.id.toolbar)\n Toolbar toolbar;\n\n @Bind(app.outlay.R.id.categoryTitle)\n MaterialAutoCompleteTextView categoryTitle;\n\n @Bind(app.outlay.R.id.categoryIcon)\n ImageView categoryIcon;\n\n @Bind(app.outlay.R.id.amount)\n EditText amount;\n\n @Bind(app.outlay.R.id.note)\n EditText note;\n\n @Bind(app.outlay.R.id.date)\n EditText dateEdit;\n\n @Bind(app.outlay.R.id.amountInputLayout)\n TextInputLayout amountInputLayout;\n\n @Inject\n ExpenseDetailsPresenter presenter;\n private CategoryAutoCompleteAdapter autoCompleteAdapter;\n private Expense expense;\n private Category selectedCategory;\n private Date defaultDate;\n\n @Override\n public ExpenseDetailsPresenter createPresenter() {\n return presenter;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getApp().getUserComponent().inject(this);\n defaultDate = new Date(getArguments().getLong(ARG_DATE, new Date().getTime()));\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(app.outlay.R.layout.fragment_expense_details, null, false);\n ButterKnife.bind(this, view);\n setToolbar(toolbar);\n setDisplayHomeAsUpEnabled(true);\n\n Drawable noCategoryIcon = IconUtils.getIconMaterialIcon(\n getContext(),\n MaterialDesignIconic.Icon.gmi_label,\n ContextCompat.getColor(getActivity(), app.outlay.R.color.icon_inactive),\n app.outlay.R.dimen.report_category_icon,\n 4\n );\n categoryIcon.setImageDrawable(noCategoryIcon);\n\n\n return view;\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n inflater.inflate(app.outlay.R.menu.menu_category_details, menu);\n MenuItem saveItem = menu.findItem(app.outlay.R.id.action_save);\n saveItem.setIcon(getResourceHelper().getMaterialToolbarIcon(app.outlay.R.string.ic_material_done));\n if (expense != null && expense.getId() == null) {\n MenuItem deleteItem = menu.findItem(app.outlay.R.id.action_delete);\n deleteItem.setVisible(false);\n }\n super.onCreateOptionsMenu(menu, inflater);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case app.outlay.R.id.action_save:\n if (validateInput()) {\n Expense expense = getExpense();\n if (TextUtils.isEmpty(expense.getId())) {\n analytics().trackExpenseCreated(expense);\n } else {\n analytics().trackExpenseUpdated(expense);\n }\n presenter.updateExpense(expense);\n getActivity().onBackPressed();\n }\n break;\n case app.outlay.R.id.action_delete:\n Expense expense = getExpense();\n analytics().trackExpenseDeleted(expense);\n presenter.deleteExpense(expense);\n getActivity().onBackPressed();\n break;\n }\n return super.onOptionsItemSelected(item);\n }\n\n private void loadCategoryIcon(Category category) {\n int iconCodeRes = getResourceHelper().getIntegerResource(category.getIcon());\n Drawable categoryIconDrawable = IconUtils.getCategoryIcon(getContext(),\n iconCodeRes,\n category.getColor(),\n app.outlay.R.dimen.report_category_icon\n );\n categoryIcon.setImageDrawable(categoryIconDrawable);\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n autoCompleteAdapter = new CategoryAutoCompleteAdapter();\n categoryTitle.setAdapter(autoCompleteAdapter);\n categoryTitle.setOnItemClickListener((parent, view1, position, id) -> {\n\n Category category = autoCompleteAdapter.getItem(position);\n selectedCategory = category;\n loadCategoryIcon(category);\n\n });\n presenter.getCategories();\n dateEdit.setOnFocusChangeListener((v, hasFocus) -> {\n if (hasFocus) {\n showDatePickerDialog();\n }\n });\n dateEdit.setOnClickListener(v -> showDatePickerDialog());\n\n if (getArguments().containsKey(ARG_EXPENSE_ID)) {\n String expenseId = getArguments().getString(ARG_EXPENSE_ID);\n getActivity().setTitle(getString(app.outlay.R.string.caption_edit_expense));\n presenter.findExpense(expenseId, defaultDate);\n } else {\n getActivity().setTitle(getString(app.outlay.R.string.caption_new_expense));\n showExpense(new Expense());\n }\n amount.addTextChangedListener(new TextWatcherAdapter() {\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n amountInputLayout.setErrorEnabled(false);\n }\n });\n }\n\n private void showDatePickerDialog() {\n DatePickerFragment datePickerFragment = new DatePickerFragment();\n datePickerFragment.setOnDateSetListener((parent, year, monthOfYear, dayOfMonth) -> {\n Calendar c = Calendar.getInstance();\n c.set(year, monthOfYear, dayOfMonth);\n Date selected = c.getTime();\n setDateStr(selected);\n expense.setReportedWhen(selected);\n });\n datePickerFragment.show(getChildFragmentManager(), \"datePicker\");\n }\n\n @Override\n public void showCategories(List<Category> categories) {\n autoCompleteAdapter.setItems(categories);\n }\n\n @Override\n public void showExpense(Expense e) {\n this.expense = e;\n if (e.getId() != null) {\n selectedCategory = e.getCategory();\n loadCategoryIcon(selectedCategory);\n\n categoryTitle.setText(e.getCategory().getTitle());\n amount.setText(NumberUtils.formatAmount(e.getAmount()));\n note.setText(e.getNote());\n setDateStr(expense.getReportedWhen());\n } else {\n this.expense.setReportedWhen(defaultDate);\n setDateStr(expense.getReportedWhen());\n }\n }\n\n public Expense getExpense() {\n if (selectedCategory != null) {\n expense.setCategory(selectedCategory);\n }\n String amountStr = amount.getText().toString().replaceAll(\",\", \".\");\n expense.setAmount(new BigDecimal(amountStr));\n expense.setNote(note.getText().toString());\n return expense;\n }\n\n private void setDateStr(Date date) {\n dateEdit.setText(DateUtils.toLongString(date));\n }\n\n private boolean validateInput() {\n boolean result = true;\n if (selectedCategory == null) {\n categoryTitle.setError(getString(app.outlay.R.string.error_category_name_empty));\n categoryTitle.requestFocus();\n result = false;\n } else if (!selectedCategory.getTitle().equals(categoryTitle.getText().toString())) {\n categoryTitle.setError(getString(app.outlay.R.string.error_category_name_invalid));\n categoryTitle.requestFocus();\n result = false;\n }\n\n if (TextUtils.isEmpty(amount.getText())) {\n //TODO validate number\n amountInputLayout.setError(getString(app.outlay.R.string.error_amount_invalid));\n amountInputLayout.requestFocus();\n result = false;\n } else {\n String amountStr = amount.getText().toString().replaceAll(\",\", \".\");\n BigDecimal number = new BigDecimal(amountStr);\n if (number.compareTo(BigDecimal.ZERO) <= 0) {\n amountInputLayout.setError(getString(app.outlay.R.string.error_amount_invalid));\n amountInputLayout.requestFocus();\n result = false;\n }\n }\n\n return result;\n }\n}",
"public class ExpensesListFragment extends BaseMvpFragment<ExpensesView, ExpensesListPresenter> implements ExpensesView {\n public static final String ARG_CATEGORY_ID = \"_argCategoryId\";\n public static final String ARG_DATE_FROM = \"_argDateFrom\";\n public static final String ARG_DATE_TO = \"_argDateTo\";\n\n private static final int MODE_LIST = 0;\n private static final int MODE_GRID = 1;\n\n @Bind(app.outlay.R.id.recyclerView)\n RecyclerView recyclerView;\n\n @Bind(app.outlay.R.id.toolbar)\n Toolbar toolbar;\n\n @Bind(app.outlay.R.id.fab)\n FloatingActionButton fab;\n\n @Bind(app.outlay.R.id.noResults)\n View noResults;\n\n @Bind(app.outlay.R.id.filterCategoryIcon)\n PrintView filterCategoryIcon;\n\n @Bind(app.outlay.R.id.filterCategoryName)\n TextView filterCategoryName;\n\n @Bind(app.outlay.R.id.filterDateLabel)\n TextView filterDateLabel;\n\n @Inject\n ExpensesListPresenter presenter;\n\n private ExpenseAdapter adapter;\n private Date dateFrom;\n private Date dateTo;\n private String categoryId;\n\n private int mode = MODE_LIST;\n\n @Override\n public ExpensesListPresenter createPresenter() {\n return presenter;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getApp().getUserComponent().inject(this);\n\n long dateFromMillis = getArguments().getLong(ARG_DATE_FROM);\n long dateToMillis = getArguments().getLong(ARG_DATE_TO);\n\n dateFrom = new Date(dateFromMillis);\n dateTo = new Date(dateToMillis);\n if (getArguments().containsKey(ARG_CATEGORY_ID)) {\n categoryId = getArguments().getString(ARG_CATEGORY_ID);\n }\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(app.outlay.R.layout.fragment_expenses_list, null, false);\n return view;\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n setToolbar(toolbar);\n setDisplayHomeAsUpEnabled(true);\n setTitle(getString(app.outlay.R.string.caption_expenses));\n\n filterDateLabel.setText(getDateLabel());\n fab.setImageDrawable(getResourceHelper().getFabIcon(app.outlay.R.string.ic_material_add));\n fab.setOnClickListener(v -> Navigator.goToExpenseDetails(getActivity(), null));\n recyclerView.setHasFixedSize(true);\n\n// adapter = new GridExpensesAdapter();\n// StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);\n// recyclerView.setLayoutManager(staggeredGridLayoutManager);\n \n adapter = new ListExpensesAdapter();\n LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());\n recyclerView.setLayoutManager(linearLayoutManager);\n recyclerView.setAdapter(adapter);\n adapter.setOnExpenseClickListener(expense -> Navigator.goToExpenseDetails(getActivity(), expense));\n }\n\n @Override\n public void onResume() {\n super.onResume();\n presenter.findExpenses(dateFrom, dateTo, categoryId);\n }\n\n private void displayExpenses(List<Expense> expenses) {\n if (expenses.isEmpty()) {\n noResults.setVisibility(View.VISIBLE);\n } else {\n noResults.setVisibility(View.GONE);\n adapter.setItems(expenses);\n }\n }\n\n private void displayCategory(Category category) {\n if (category != null) {\n IconUtils.loadCategoryIcon(category, filterCategoryIcon);\n filterCategoryName.setText(category.getTitle());\n } else {\n filterCategoryName.setVisibility(View.GONE);\n filterCategoryIcon.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void showReport(Report report) {\n displayExpenses(report.getExpenses());\n Map<Category, Report> grouped = report.groupByCategory();\n if (grouped.size() == 1) {\n displayCategory(report.getExpenses().get(0).getCategory());\n }\n }\n\n private String getDateLabel() {\n String dateFromStr = DateUtils.toShortString(dateFrom);\n String dateToStr = DateUtils.toShortString(dateTo);\n String result = dateFromStr;\n if (!dateFromStr.equals(dateToStr)) {\n result += \" - \" + dateToStr;\n }\n return result;\n }\n}",
"public class ReportFragment extends BaseMvpFragment<StatisticView, ReportPresenter> implements StatisticView {\n public static final String ARG_DATE = \"_argDate\";\n\n public static final int PERIOD_DAY = 0;\n public static final int PERIOD_WEEK = 1;\n public static final int PERIOD_MONTH = 2;\n\n @Bind(app.outlay.R.id.recyclerView)\n RecyclerView recyclerView;\n\n @Bind(app.outlay.R.id.tabs)\n TabLayout tabLayout;\n\n @Bind(app.outlay.R.id.toolbar)\n Toolbar toolbar;\n\n @Bind(app.outlay.R.id.noResults)\n View noResults;\n\n @Inject\n ReportPresenter presenter;\n\n private int selectedPeriod;\n private Date selectedDate;\n private ReportAdapter adapter;\n\n @Override\n public ReportPresenter createPresenter() {\n return presenter;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getApp().getUserComponent().inject(this);\n selectedDate = new Date(getArguments().getLong(ARG_DATE, new Date().getTime()));\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(app.outlay.R.layout.fragment_report, null, false);\n return view;\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n super.onCreateOptionsMenu(menu, inflater);\n\n inflater.inflate(app.outlay.R.menu.menu_report, menu);\n MenuItem dateItem = menu.findItem(app.outlay.R.id.action_date);\n dateItem.setIcon(getResourceHelper().getMaterialToolbarIcon(app.outlay.R.string.ic_material_today));\n\n MenuItem listItem = menu.findItem(app.outlay.R.id.action_list);\n listItem.setIcon(getResourceHelper().getMaterialToolbarIcon(app.outlay.R.string.ic_material_list));\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case app.outlay.R.id.action_date:\n DatePickerFragment datePickerFragment = new DatePickerFragment();\n datePickerFragment.setOnDateSetListener((view, year, monthOfYear, dayOfMonth) -> {\n Calendar c = Calendar.getInstance();\n c.set(year, monthOfYear, dayOfMonth);\n Date selected = c.getTime();\n analytics().trackExpensesViewDateChange(selectedDate, selected);\n selectedDate = selected;\n ReportFragment.this.setTitle(DateUtils.toShortString(selected));\n updateTitle();\n presenter.getExpenses(selectedDate, selectedPeriod);\n });\n datePickerFragment.show(getChildFragmentManager(), \"datePicker\");\n break;\n case app.outlay.R.id.action_list:\n analytics().trackViewExpensesList();\n goToExpensesList(selectedDate, selectedPeriod);\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n setToolbar(toolbar);\n setDisplayHomeAsUpEnabled(true);\n updateTitle();\n\n LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());\n\n tabLayout.addTab(tabLayout.newTab().setText(app.outlay.R.string.label_day));\n tabLayout.addTab(tabLayout.newTab().setText(app.outlay.R.string.label_week));\n tabLayout.addTab(tabLayout.newTab().setText(app.outlay.R.string.label_month));\n tabLayout.getTabAt(selectedPeriod).select();\n tabLayout.addOnTabSelectedListener(new OnTabSelectedListenerAdapter() {\n @Override\n public void onTabSelected(TabLayout.Tab tab) {\n selectedPeriod = tab.getPosition();\n switch (selectedPeriod) {\n case ReportFragment.PERIOD_DAY:\n analytics().trackViewDailyExpenses();\n break;\n case ReportFragment.PERIOD_WEEK:\n analytics().trackViewWeeklyExpenses();\n break;\n case ReportFragment.PERIOD_MONTH:\n analytics().trackViewMonthlyExpenses();\n break;\n }\n updateTitle();\n presenter.getExpenses(selectedDate, selectedPeriod);\n }\n });\n\n recyclerView.setLayoutManager(layoutManager);\n adapter = new ReportAdapter();\n recyclerView.setAdapter(adapter);\n presenter.getExpenses(selectedDate, selectedPeriod);\n\n adapter.setOnItemClickListener((category, report) -> goToExpensesList(selectedDate, selectedPeriod, category.getId()));\n }\n\n @Override\n public void showReport(Report report) {\n if (report.isEmpty()) {\n noResults.setVisibility(View.VISIBLE);\n } else {\n noResults.setVisibility(View.GONE);\n adapter.setItems(new CategorizedExpenses(report));\n }\n }\n\n private void updateTitle() {\n switch (selectedPeriod) {\n case PERIOD_DAY:\n setTitle(DateUtils.toShortString(selectedDate));\n break;\n case PERIOD_WEEK:\n Date startDate = DateUtils.getWeekStart(selectedDate);\n Date endDate = DateUtils.getWeekEnd(selectedDate);\n setTitle(DateUtils.toShortString(startDate) + \" - \" + DateUtils.toShortString(endDate));\n break;\n case PERIOD_MONTH:\n startDate = DateUtils.getMonthStart(selectedDate);\n endDate = DateUtils.getMonthEnd(selectedDate);\n setTitle(DateUtils.toShortString(startDate) + \" - \" + DateUtils.toShortString(endDate));\n break;\n }\n }\n\n public void goToExpensesList(Date date, int selectedPeriod) {\n this.goToExpensesList(date, selectedPeriod, null);\n }\n\n public void goToExpensesList(Date date, int selectedPeriod, String category) {\n date = DateUtils.fillCurrentTime(date);\n Date startDate = date;\n Date endDate = date;\n\n switch (selectedPeriod) {\n case ReportFragment.PERIOD_DAY:\n startDate = DateUtils.getDayStart(date);\n endDate = DateUtils.getDayEnd(date);\n break;\n case ReportFragment.PERIOD_WEEK:\n startDate = DateUtils.getWeekStart(date);\n endDate = DateUtils.getWeekEnd(date);\n break;\n case ReportFragment.PERIOD_MONTH:\n startDate = DateUtils.getMonthStart(date);\n endDate = DateUtils.getMonthEnd(date);\n break;\n }\n Navigator.goToExpensesList(getActivity(), startDate, endDate, category);\n }\n}"
] | import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import app.outlay.domain.model.Expense;
import app.outlay.view.activity.LoginActivity;
import app.outlay.view.activity.MainActivity;
import app.outlay.view.activity.SingleFragmentActivity;
import app.outlay.view.activity.SyncGuestActivity;
import app.outlay.view.fragment.AnalysisFragment;
import app.outlay.view.fragment.CategoriesFragment;
import app.outlay.view.fragment.CategoryDetailsFragment;
import app.outlay.view.fragment.ExpensesDetailsFragment;
import app.outlay.view.fragment.ExpensesListFragment;
import app.outlay.view.fragment.ReportFragment;
import java.util.Date; | package app.outlay.view;
/**
* Created by Bogdan Melnychuk on 1/24/16.
*/
public final class Navigator {
public static void goToCategoryDetails(FragmentActivity activityFrom, String categoryId) {
Bundle b = new Bundle();
if (categoryId != null) {
b.putString(CategoryDetailsFragment.ARG_CATEGORY_PARAM, categoryId);
}
changeFragment(activityFrom, CategoryDetailsFragment.class, b);
}
public static void goToCategoriesList(FragmentActivity from) { | SingleFragmentActivity.start(from, CategoriesFragment.class); | 2 |
padster/Muse-EEG-Toolkit | sampleApp/src/main/java/eeg/useit/today/eegtoolkit/sampleapp/MoreDeviceDetailsActivity.java | [
"public class Constants {\n public static final String TAG = \"EEGToolkit\";\n public static final String RECORDING_PREFIX = \"data\";\n\n // HACK: Should configure these elsewhere, perhaps attributes to renderers.\n public static final double VOLTAGE_MAX = 1000.0;\n public static final double VOLTAGE_MIN = 700.0;\n}",
"public class FrequencyBands {\n /** Which band we're looking at. */\n public enum Band {\n // Frequency cutoff values taken from Muse documentation:\n // http://developer.choosemuse.com/research-tools/available-data\n DELTA( 1, 4),\n THETA( 4, 8),\n ALPHA(7.5, 13),\n BETA( 13, 30),\n GAMMA( 30, 44);\n\n public double minHz;\n public double maxHz;\n\n Band(double minHz, double maxHz) {\n this.minHz = minHz;\n this.maxHz = maxHz;\n }\n }\n\n // What type of aggregation is done to the frequency value.\n public enum ValueType {\n // Log of the sum of the Power Spectral Density of the data over the frequency range.\n ABSOLUTE,\n // Relative = divide the absolute linear-scale power in one band\n // over the sum of the absolute linear-scale powers in all bands. [0, 1]\n RELATIVE,\n // Compares current value to range of values seen in short history. [0, 1]\n SCORE,\n }\n\n /** Given a Band and ValueType, return the muse type that corresponds. */\n public static MuseDataPacketType toMuseType(Band band, ValueType type) {\n switch(band) {\n case ALPHA:\n switch(type) {\n case RELATIVE: return MuseDataPacketType.ALPHA_RELATIVE;\n case ABSOLUTE: return MuseDataPacketType.ALPHA_ABSOLUTE;\n case SCORE: return MuseDataPacketType.ALPHA_SCORE;\n }\n break;\n case BETA:\n switch(type) {\n case RELATIVE: return MuseDataPacketType.BETA_RELATIVE;\n case ABSOLUTE: return MuseDataPacketType.BETA_ABSOLUTE;\n case SCORE: return MuseDataPacketType.BETA_SCORE;\n }\n break;\n case GAMMA:\n switch(type) {\n case RELATIVE: return MuseDataPacketType.GAMMA_RELATIVE;\n case ABSOLUTE: return MuseDataPacketType.GAMMA_ABSOLUTE;\n case SCORE: return MuseDataPacketType.GAMMA_SCORE;\n }\n break;\n case DELTA:\n switch(type) {\n case RELATIVE: return MuseDataPacketType.DELTA_RELATIVE;\n case ABSOLUTE: return MuseDataPacketType.DELTA_ABSOLUTE;\n case SCORE: return MuseDataPacketType.DELTA_SCORE;\n }\n break;\n case THETA:\n switch(type) {\n case RELATIVE: return MuseDataPacketType.THETA_RELATIVE;\n case ABSOLUTE: return MuseDataPacketType.THETA_ABSOLUTE;\n case SCORE: return MuseDataPacketType.THETA_SCORE;\n }\n }\n throw new IllegalArgumentException(\"Bad band / value type combination.\");\n }\n}",
"public class MuseManagerUtil {\n /** Called when a muse is discovered. */\n public interface MuseCallback {\n void museFound(Muse muse);\n }\n\n /** @return Muse device matching this address, or null. */\n public static void getByMacAddress(final String macAddress, final MuseCallback callback) {\n if (macAddress == null) {\n throw new IllegalArgumentException(\"Mac address can't be null.\");\n }\n // See if already found:\n for (Muse muse : MuseManagerAndroid.getInstance().getMuses()) {\n if (macAddress.equals(muse.getMacAddress())) {\n callback.museFound(muse);\n return;\n }\n }\n // If not, schedule finding:\n MuseManagerAndroid.getInstance().setMuseListener(new MuseListener() {\n @Override\n public void museListChanged() {\n for (Muse muse : MuseManagerAndroid.getInstance().getMuses()) {\n if (macAddress.equals(muse.getMacAddress())) {\n callback.museFound(muse);\n MuseManagerAndroid.getInstance().stopListening();\n return;\n }\n }\n }\n });\n MuseManagerAndroid.getInstance().startListening();\n }\n}",
"public class EpochCollector extends BaseObservable {\n /** History of epochs taken. */\n private final List<Map<String, TimeSeriesSnapshot<Double>>> epochs = new ArrayList<>();\n\n /** Live sources of the time series data. */\n private final Map<String, TimeSeries<Double>> timeSeries = new HashMap<>();\n\n /** Track another named source. */\n public void addSource(String name, TimeSeries<Double> series) {\n timeSeries.put(name, series);\n }\n\n /** For all the tracked sources, take a snapshot and save that epoch internally. */\n public void collectEpoch() {\n Map<String, TimeSeriesSnapshot<Double>> epoch = new HashMap<>();\n for (Map.Entry<String, TimeSeries<Double>> entry : timeSeries.entrySet()) {\n epoch.put(entry.getKey(), entry.getValue().getRecentSnapshot(Double.class));\n }\n epochs.add(epoch);\n notifyChange();\n }\n\n /** @return All the previously stored epochs. */\n public List<Map<String, TimeSeriesSnapshot<Double>>> getEpochs() {\n return epochs;\n }\n\n /** Resets epoch data history. */\n public void clear() {\n epochs.clear();\n }\n}",
"public class MergedSeries implements LiveSeries<Double[]> {\n private static final long NO_TIMESTAMP = -1L;\n\n private final List<Listener<Double[]>> listeners = new ArrayList<>();\n\n private final long[] lastTimestamp;\n private final Double[] lastValue;\n\n /** Create a merged series, listening to a list of 1D double series. */\n public MergedSeries(LiveSeries<Double> ...series) {\n int n = series.length;\n this.lastTimestamp = new long[n];\n this.lastValue = new Double[n];\n\n for (int i = 0; i < n; i++) {\n this.lastTimestamp[i] = NO_TIMESTAMP;\n this.lastValue[i] = 0.0;\n\n final int idx = i;\n series[i].addListener(new LiveSeries.Listener<Double>() {\n @Override public void valueAdded(long timestamp, Double value) {\n MergedSeries.this.handleNewValue(idx, timestamp, value);\n }\n });\n }\n }\n\n /**\n * Handle a value coming in, by storing it and firing the merged value if it's the last to arrive.\n */\n private void handleNewValue(int index, long timestamp, double value) {\n this.lastTimestamp[index] = timestamp;\n this.lastValue[index] = value;\n if (allHaveValues()) {\n Double[] valueCopy = Arrays.copyOf(this.lastValue, this.lastValue.length);\n for (Listener<Double[]> listener : this.listeners) {\n listener.valueAdded(timestamp, valueCopy);\n }\n // Clear all after fire, so we know when everything has arrived later.\n for (int i = 0; i < this.lastTimestamp.length; i++) {\n this.lastTimestamp[i] = NO_TIMESTAMP;\n this.lastValue[i] = 0.0;\n }\n }\n }\n\n /** @return Whether all wrapped series have recent values. */\n private boolean allHaveValues() {\n for (int i = 1; i < this.lastTimestamp.length; i++) {\n if (this.lastTimestamp[i] == NO_TIMESTAMP) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public void addListener(Listener<Double[]> listener) {\n this.listeners.add(listener);\n }\n}",
"public class TimeSeries<T> extends BaseObservable implements LiveSeries<T> {\n public static <T> TimeSeries<T> fromMaxAgeMS(long maxAgeMS) {\n return new TimeSeries<T>(maxAgeMS, -1);\n }\n public static <T> TimeSeries<T> fromMaxLength(int maxSampleCount) {\n return new TimeSeries<T>(-1, maxSampleCount);\n }\n\n /** Values within the timeseries. */\n private final CircularArray<T> values = new CircularArray<>();\n\n /** Times at which the values were taken. */\n private final CircularArray<Long> timestampsMicro = new CircularArray<>();\n\n /** Values older than this will be removed. */\n private final long maxAgeMicro;\n\n /** Only store this many values. */\n private final int maxSampleCount;\n\n /** Things interested on when this series changes. */\n private final List<Listener<T>> listeners = new ArrayList<>();\n\n /** Create a timeseries, giving it a maximum age (in ms) length to contain. */\n public TimeSeries(long maxAgeMS) {\n this(maxAgeMS, -1);\n }\n\n /** Create a timeseries, giving either maximum age (in ms) or maximum sample count. */\n public TimeSeries(long maxAgeMS, int maxSampleCount) {\n this.maxAgeMicro = maxAgeMS == -1 ? -1 : maxAgeMS * 1000L;\n this.maxSampleCount = maxSampleCount;\n assert this.maxAgeMicro == -1 ^ this.maxSampleCount == -1;\n }\n\n /** @return Whether the time series has any data. */\n public boolean isEmpty() {\n return values.isEmpty();\n }\n\n /** Pushes a value to the end of the array. */\n public void pushValue(long timestampMicro, T value) {\n synchronized (this) {\n timestampsMicro.addLast(timestampMicro);\n values.addLast(value);\n for (Listener<T> listener : listeners) {\n listener.valueAdded(timestampMicro, value);\n }\n notifyChange();\n }\n }\n\n /**\n * Take a snapshot of the current values, first culling any that are too old.\n */\n public TimeSeriesSnapshot<T> getRecentSnapshot(Class<T> clazz) {\n synchronized (this) {\n if (this.isEmpty()) {\n return TimeSeriesSnapshot.EMPTY;\n }\n\n // First, remove all the old values.\n long finalSnapshot = timestampsMicro.getLast();\n if (maxSampleCount == -1) {\n while (timestampsMicro.getFirst() + maxAgeMicro < finalSnapshot) {\n timestampsMicro.popFirst();\n values.popFirst();\n }\n } else {\n while (timestampsMicro.size() > maxSampleCount) {\n timestampsMicro.popFirst();\n values.popFirst();\n }\n }\n\n // Next, snapshot into arrays and return:\n int n = this.values.size();\n long[] timestamps = new long[n];\n T[] values = (T[]) Array.newInstance(clazz, n);\n for (int i = 0; i < n; i++) {\n timestamps[i] = this.timestampsMicro.get(i);\n values[i] = this.values.get(i);\n }\n return new TimeSeriesSnapshot(timestamps, values);\n }\n }\n\n /**\n * Given a live series, and duration, convert into a TimeSeries with history.\n */\n public static <V> TimeSeries<V> fromLiveSeries(LiveSeries<V> liveSeries, long maxAgeMS) {\n final TimeSeries<V> result = TimeSeries.fromMaxAgeMS(maxAgeMS);\n liveSeries.addListener(new LiveSeries.Listener<V>() {\n @Override public void valueAdded(long timestampMicro, V data) {\n result.pushValue(timestampMicro, data);\n }\n });\n return result;\n }\n\n /**\n * Given a live series, and a smaple count, convert into a TimeSeries with history.\n */\n public static <V> TimeSeries<V> fromLiveSeriesWithCount(LiveSeries<V> liveSeries, int maxLength) {\n final TimeSeries<V> result = TimeSeries.fromMaxLength(maxLength);\n liveSeries.addListener(new LiveSeries.Listener<V>() {\n @Override public void valueAdded(long timestampMicro, V data) {\n result.pushValue(timestampMicro, data);\n }\n });\n return result;\n }\n\n @Override\n public void addListener(Listener<T> listener) {\n this.listeners.add(listener);\n }\n}",
"public class Plot2DView extends SurfaceView {\n private final static float DOT_RADIUS = 0.05f;\n\n private TimeSeries<Double[]> timeSeries;\n\n /** Creates a Plot2D graph by parsing attributes. */\n public Plot2DView(Context context, AttributeSet attrs) {\n super(context, attrs);\n setWillNotDraw(false);\n }\n\n /** Connect the view to a viewmodel. */\n public void setTimeSeries(TimeSeries<Double[]> ts) {\n assert this.timeSeries == null;\n this.timeSeries = ts;\n this.timeSeries.addListener(new LiveSeries.Listener<Double[]>() {\n @Override public void valueAdded(long timestampMicro, Double[] data) {\n invalidate();\n }\n });\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Paint background = new Paint();\n background.setColor(Color.WHITE);\n background.setStyle(Paint.Style.FILL_AND_STROKE);\n canvas.drawPaint(background);\n\n if (timeSeries == null || timeSeries.isEmpty()) {\n return; // No points, so skip.\n }\n\n // Calculate bounds for the X axis.\n TimeSeriesSnapshot<Double[]> snapshot = timeSeries.getRecentSnapshot(Double[].class);\n long timeEndMicro = snapshot.timestamps[snapshot.length - 1];\n long timeStartMicro = snapshot.timestamps[0];\n double timeDeltaInv = 1.0 / (double)(timeEndMicro - timeStartMicro);\n\n for (int i = 0; i < snapshot.length; i++) {\n double x = snapshot.values[i][0]; // Relative Theta\n double y = snapshot.values[i][1]; // Relative Beta\n float fX = (float)(x * canvas.getWidth());\n float fY = (float)((1 - y) * canvas.getHeight());\n float fR = DOT_RADIUS * canvas.getWidth();\n double age = Math.min(1, Math.max(0,\n (timeEndMicro - snapshot.timestamps[i]) * timeDeltaInv));\n canvas.drawCircle(fX, fY, fR, paintForAge(age));\n }\n }\n\n // Convert age (0 = new, 1 = old) into a paint, using red-green scale.\n private static Paint paintForAge(double age) {\n Paint paint = new Paint();\n int r = (int)(255 * (1 - age));\n int g = (int)(255 * age);\n paint.setARGB(255, r, g, 0);\n paint.setStyle(Paint.Style.FILL_AND_STROKE);\n return paint;\n }\n}",
"public class FrequencyBandViewModel extends BaseObservable implements LiveSeries<Double> {\n /** Most recent frequency values. */\n private final double[] frequencyState = new double[4];\n\n /** Muse packet type for this frequency band. */\n private final MuseDataPacketType museType;\n\n /** Listeners for new values that come in. */\n private List<Listener<Double>> listeners = new ArrayList<>();\n\n public FrequencyBandViewModel(StreamingDeviceViewModel device, Band band, ValueType type) {\n museType = FrequencyBands.toMuseType(band, type);\n\n // Add listener to streaming device, use new values to update timeseries.\n // TODO: Unregister when device stops, or on disposal.\n device.registerDataListenerWhenConnected(new BaseDataPacketListener() {\n @Override public void receiveMuseDataPacket(MuseDataPacket museDataPacket, Muse muse) {\n FrequencyBandViewModel.this.updateValues(\n museDataPacket.timestamp(),\n museDataPacket.getEegChannelValue(Eeg.EEG1),\n museDataPacket.getEegChannelValue(Eeg.EEG2),\n museDataPacket.getEegChannelValue(Eeg.EEG3),\n museDataPacket.getEegChannelValue(Eeg.EEG4)\n );\n }\n }, museType);\n }\n\n\n @Bindable\n public double[] getFrequencyValues() {\n return this.frequencyState;\n }\n\n @Bindable\n public double getAverage() {\n // Cross-sensor averaging, done by the VM.\n double sum = 0.0;\n for (int i = 0; i < frequencyState.length; i++) {\n sum += frequencyState[i];\n }\n return sum / frequencyState.length;\n }\n\n // Updates the new values given the most recent data packet.\n private void updateValues(long timestamp, double... newState) {\n assert newState.length <= 4;\n for (int i = 0; i < newState.length; i++) {\n frequencyState[i] = newState[i];\n }\n\n // A bit of a hack, that it is a live series of the average.\n double average = getAverage();\n for (Listener<Double> listener : listeners) {\n listener.valueAdded(timestamp, average);\n }\n notifyChange();\n }\n\n @Override\n public void addListener(Listener<Double> listener) {\n this.listeners.add(listener);\n }\n}",
"public class StreamingDeviceViewModel extends BaseObservable {\n /** Muse that this device is backed by. */\n private Muse muse = null;\n\n /** All things to be run on connection. */\n private final List<Runnable> connectionCallbacks = new ArrayList<>();\n\n /** Current status of connection. */\n private ConnectionState connectionState = ConnectionState.DISCONNECTED;\n\n /** Set the muse that is backing this device. If needed, try to connect straight away. */\n public void setMuse(Muse muse) {\n assert this.muse == null;\n assert this.connectionState == ConnectionState.DISCONNECTED;\n this.muse = muse;\n this.connectionState = this.muse.getConnectionState();\n if (!this.connectionCallbacks.isEmpty()) {\n this.connectToMuse();\n }\n notifyChange();\n }\n\n @Bindable\n public ConnectionState getConnectionState() {\n return this.connectionState;\n }\n\n /** @return Bluetooth device name, or default if not yet connected. */\n public String getName() {\n return this.muse == null ? \"No device\" : this.muse.getName();\n }\n\n /** @return Bluetooth mac address, or null if not yet connected. */\n public String getMacAddress() {\n return this.muse == null ? null : this.muse.getMacAddress();\n }\n\n /** @return A new live VM for a single time series from a raw data channel. */\n public RawChannelViewModel createRawTimeSeries(final Eeg channel, int durationSec) {\n int samples = (int)(durationSec * 220.0); // Muse sample rate.\n return new RawChannelViewModel(this, channel, -1, samples);\n }\n\n /** @return A new live VM for each sensor's frequency value for a given band/type combo. */\n public FrequencyBandViewModel createFrequencyLiveValue(Band band, ValueType type) {\n return new FrequencyBandViewModel(this, band, type);\n }\n\n /** @return A new live VM for the frequency band powers. */\n public PSDViewModel createPSDLiveValue() {\n return new PSDViewModel(this);\n }\n\n /**\n * Register a data listener to the device.\n * - If already connected, registers it directly.\n * - Otherwise, sets it up to register when conncted, and tries to connect if possible.\n */\n public void registerDataListenerWhenConnected(\n final MuseDataListener listener, final MuseDataPacketType type) {\n Log.i(Constants.TAG, \"Connecting to \" + type.name() + \" in state \" + connectionState.name());\n if (this.connectionState == ConnectionState.CONNECTED) {\n // Already connected, go for launch.\n this.muse.registerDataListener(listener, type);\n } else {\n Log.i(Constants.TAG, \"Adding connection callback...\");\n this.connectionCallbacks.add(new Runnable() {\n @Override\n public void run() {\n Log.i(Constants.TAG, \"Connected! running callback...\");\n StreamingDeviceViewModel.this.muse.registerDataListener(listener, type);\n }\n });\n if (this.muse != null && this.connectionState == ConnectionState.DISCONNECTED) {\n // We want a connection, we have a device, may as well connect.\n this.connectToMuse();\n }\n }\n }\n\n /** Remove all listeners that have been added. */\n public void removeAllListeners() {\n this.muse.unregisterAllListeners();\n }\n\n /** Call to force connection to the Muse device. */\n private void connectToMuse() {\n if (this.muse.getConnectionState() == ConnectionState.CONNECTED) {\n // Already connected:\n Log.i(Constants.TAG, \"Have connection, triggering callbacks.\");\n this.handleConnection();\n } else {\n assert this.connectionState == ConnectionState.DISCONNECTED;\n Log.i(Constants.TAG, \"Need connection, running async\");\n this.connectionState = connectionState.CONNECTING;\n this.muse.registerConnectionListener(new MuseConnectionListener() {\n @Override\n public void receiveMuseConnectionPacket(MuseConnectionPacket packet, Muse muse) {\n connectionState = packet.getCurrentConnectionState();\n if (connectionState == ConnectionState.CONNECTED) {\n StreamingDeviceViewModel.this.handleConnection();\n }\n }\n });\n this.muse.runAsynchronously();\n }\n }\n\n /** Handle connection change to the muse device. */\n private void handleConnection() {\n Log.i(Constants.TAG, \"Connected!\");\n this.connectionState = ConnectionState.CONNECTED;\n // Connected, update everything that was waiting for this...\n for(Runnable callback : this.connectionCallbacks) {\n callback.run();\n }\n this.connectionCallbacks.clear();\n notifyChange();\n }\n}"
] | import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.choosemuse.libmuse.Eeg;
import com.choosemuse.libmuse.Muse;
import com.choosemuse.libmuse.MuseManagerAndroid;
import eeg.useit.today.eegtoolkit.Constants;
import eeg.useit.today.eegtoolkit.common.FrequencyBands;
import eeg.useit.today.eegtoolkit.common.MuseManagerUtil;
import eeg.useit.today.eegtoolkit.model.EpochCollector;
import eeg.useit.today.eegtoolkit.model.MergedSeries;
import eeg.useit.today.eegtoolkit.model.TimeSeries;
import eeg.useit.today.eegtoolkit.sampleapp.databinding.ActivityMoreDeviceDetailsBinding;
import eeg.useit.today.eegtoolkit.view.Plot2DView;
import eeg.useit.today.eegtoolkit.vm.FrequencyBandViewModel;
import eeg.useit.today.eegtoolkit.vm.StreamingDeviceViewModel; | package eeg.useit.today.eegtoolkit.sampleapp;
/**
* Activity containing more example views provided by the toolkit.
*/
public class MoreDeviceDetailsActivity extends AppCompatActivity {
public static int DURATION_SEC = 4;
/** The live device VM backing this view. */
private final StreamingDeviceViewModel deviceVM = new StreamingDeviceViewModel();
/** Epoch Model */ | private final EpochCollector epochCollector = new EpochCollector(); | 3 |
jentrata/jentrata | ebms-msh-api/src/main/java/org/jentrata/ebms/cpa/PartnerAgreement.java | [
"public class EbmsConstants {\n\n public static final String JENTRATA_VERSION = \"JentrataVersion\";\n\n //Jentrata Message Header keys\n public static final String SOAP_VERSION = \"JentrataSOAPVersion\";\n public static final String EBMS_VERSION = \"JentrataEBMSVersion\";\n public static final String VALID_PARTNER_AGREEMENT = \"JentrataIsValidPartnerAgreement\";\n public static final String EBMS_MESSAGE_MEP = \"JentrataMEP\";\n\n public static final String SOAP_VERSION_1_1 = \"1.1\";\n public static final String SOAP_VERSION_1_2 = \"1.2\";\n\n public static final String SOAP_1_1_NAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\";\n\n public static final String SOAP_1_2_NAMESPACE = \"http://www.w3.org/2003/05/soap-envelope\";\n public static final String EBXML_V2_NAMESPACE = \"http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd\";\n\n public static final String EBXML_V3_NAMESPACE = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/\";\n\n public static final String EBMS_V2 = \"ebMSV2\";\n public static final String EBMS_V3 = \"ebMSV3\";\n\n public static final String EBMS_V3_MEP_ONE_WAY = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/oneWay\";\n public static final String EBMS_V3_MEP_TWO_WAY = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/twoWay\";\n\n public static final String EBMS_V3_MEP_BINDING_PUSH = \"ttp://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/push\";\n\n public static final String EBMS_RECEIPT_REQUIRED = \"JentrataReceiptRequired\";\n\n public static final String CONTENT_ID = \"Content-ID\";\n public static final String CONTENT_LENGTH = Exchange.CONTENT_LENGTH;\n public static final String CONTENT_TRANSFER_ENCODING = \"Content-Transfer-Encoding\";\n public static final String CONTENT_DISPOSITION = \"Content-Disposition\";\n public static final String CONTENT_TYPE = Exchange.CONTENT_TYPE;\n\n public static final String SOAP_XML_CONTENT_TYPE = \"application/soap+xml\";\n public static final String TEXT_XML_CONTENT_TYPE = \"text/xml\";\n public static final String MESSAGE_ID = \"JentrataMessageID\";\n public static final String REF_TO_MESSAGE_ID = \"JentrataRefMessageID\";\n public static final String MESSAGE_FROM = \"JentrataFrom\";\n public static final String MESSAGE_FROM_TYPE = \"JentrataFromPartyIdType\";\n public static final String MESSAGE_FROM_ROLE = \"JentrataPartyFromRole\";\n public static final String MESSAGE_TO = \"JentrataTo\";\n public static final String MESSAGE_TO_TYPE = \"JentrataToPartyIdType\";\n public static final String MESSAGE_TO_ROLE = \"JentrataPartyToRole\";\n public static final String MESSAGE_AGREEMENT_REF = \"JentrataAgreementRef\";\n public static final String MESSAGE_PART_PROPERTIES = \"JentraraPartProperties\";\n public static final String MESSAGE_PAYLOAD_SCHEMA = \"JentrataPayloadSchema\";\n public static final String MESSAGE_DIRECTION = \"JentrataMessageDirection\";\n public static final String MESSAGE_DIRECTION_INBOUND = \"inbox\";\n public static final String MESSAGE_DIRECTION_OUTBOUND = \"outbox\";\n public static final String MESSAGE_STATUS = \"JentrataMessageStatus\";\n public static final String MESSAGE_STATUS_DESCRIPTION = \"JentrataMessageStatusDesc\";\n public static final String MESSAGE_TYPE = \"JentrataMessageType\";\n public static final String MESSAGE_SERVICE = \"JentrataService\";\n public static final String MESSAGE_ACTION = \"JentrataAction\";\n public static final String MESSAGE_CONVERSATION_ID = \"JentrataConversationId\";\n public static final String CPA = \"JentrataCPA\";\n public static final String CPA_ID = \"JentrataCPAId\";\n public static final String PAYLOAD_ID = \"JentrataPayloadId\";\n public static final String PAYLOAD_FILENAME = \"JentrataPayloadFilename\";\n public static final String PAYLOAD_COMPRESSION = \"JentrataPayloadCompression\";\n public static final String CPA_ID_UNKNOWN = \"UNKNOWN\";\n public static final String CONTENT_CHAR_SET = \"JentrataCharSet\";\n public static final String SOAP_BODY_PAYLOAD_ID = \"soapbodypart\";\n public static final String SECURITY_CHECK = \"JentrataSecurityCheck\";\n public static final String SECURITY_RESULTS = \"JentrataSecurityResults\";\n\n public static final String SECURITY_ERROR_CODE = \"JentrataSecurityErrorCode\";\n public static final String EBMS_ERROR = \"JentrataEbmsError\";\n public static final String EBMS_ERROR_CODE = \"JentrataEbmsErrorCode\";\n public static final String EBMS_ERROR_DESCRIPTION = \"JentrataEbmsErrorDesc\";\n public static final String MESSAGE_PAYLOADS = \"JentrataPayloads\";\n public static final String COMPRESSION_TYPE = \"CompressionType\";\n public static final String GZIP = \"application/gzip\";\n public static final String MESSAGE_DATE = \"JentrataMessageDate\";\n public static final String MESSAGE_RECEIPT_PATTERN = \"JentrataMessageReceipt\";\n public static final String MESSAGE_DUP_DETECTION = \"JentrataDupDetection\";\n public static final String DUPLICATE_MESSAGE = \"JentrataIsDuplicateMessage\";\n public static final String DUPLICATE_MESSAGE_ID = \"JentrataDuplicateMessageId\";\n public static final String VALIDATION_ERROR_DESC = \"JentrataValidationErrorDesc\";\n public static final String EBMS_VALIDATION_ERROR = \"JentrataValidationError\";\n\n public static final String DEFAULT_CPA_ID = \"JentrataDefaultCPAId\";\n public static final String DELIVERY_ERROR = \"JentrataDeliveryError\";\n}",
"public enum MessageType {\n\n USER_MESSAGE,\n SIGNAL_MESSAGE,\n SIGNAL_MESSAGE_WITH_USER_MESSAGE,\n SIGNAL_MESSAGE_ERROR,\n UNKNOWN\n\n}",
"public class BusinessInfo {\n\n public static final BusinessInfo DEFAULT = new BusinessInfo();\n static {\n DEFAULT.setServices(Collections.EMPTY_LIST);\n DEFAULT.setPayloadProfile(Collections.EMPTY_LIST);\n DEFAULT.setProperties(Collections.EMPTY_LIST);\n }\n\n private List<Service> services;\n private List<PayloadService> payloadProfile;\n private String mpc;\n private List<MessageProperty> properties;\n\n public List<Service> getServices() {\n return services;\n }\n\n public void setServices(List<Service> services) {\n this.services = services;\n }\n\n public List<PayloadService> getPayloadProfile() {\n return payloadProfile;\n }\n\n public void setPayloadProfile(List<PayloadService> payloadProfile) {\n this.payloadProfile = payloadProfile;\n }\n\n public String getMpc() {\n return mpc;\n }\n\n public void setMpc(String mpc) {\n this.mpc = mpc;\n }\n\n public List<MessageProperty> getProperties() {\n return properties;\n }\n\n public void setProperties(List<MessageProperty> properties) {\n this.properties = properties;\n }\n}",
"public class Party {\n\n private String partyId;\n private String partyIdType;\n private String role;\n private SecurityToken authorization;\n\n public String getPartyId() {\n return partyId;\n }\n\n public void setPartyId(String partyId) {\n this.partyId = partyId;\n }\n\n public String getPartyIdType() {\n return partyIdType;\n }\n\n public void setPartyIdType(String partyIdType) {\n this.partyIdType = partyIdType;\n }\n\n public String getRole() {\n return role;\n }\n\n public void setRole(String role) {\n this.role = role;\n }\n\n public SecurityToken getAuthorization() {\n return authorization;\n }\n\n public void setAuthorization(SecurityToken authorization) {\n this.authorization = authorization;\n }\n}",
"public class PayloadService {\n\n public static final PayloadService DEFAULT_PAYLOAD_SERVICE = new PayloadService(\"[email protected]\",\"text/xml\");\n\n\n public enum CompressionType {\n NONE(\"\"),\n GZIP(\"application/gzip\");\n\n private String type;\n\n CompressionType(String type) {\n this.type=type;\n }\n\n public String getType() {\n return type;\n }\n }\n\n private CompressionType compressionType = CompressionType.NONE;\n private String payloadId;\n private String contentType;\n\n\n public PayloadService() {}\n\n public PayloadService(String payloadId) {\n this.payloadId = payloadId;\n }\n\n public PayloadService(String payloadId, String contentType) {\n this.payloadId = payloadId;\n this.contentType = contentType;\n }\n\n public CompressionType getCompressionType() {\n return compressionType;\n }\n\n public void setCompressionType(CompressionType compressionType) {\n this.compressionType = compressionType;\n }\n\n public String getPayloadId() {\n return payloadId;\n }\n\n public void setPayloadId(String payloadId) {\n this.payloadId = payloadId;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public void setContentType(String contentType) {\n this.contentType = contentType;\n }\n}",
"public class Protocol {\n\n private String address;\n private String soapVersion = EbmsConstants.SOAP_VERSION_1_2;\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getSoapVersion() {\n return soapVersion;\n }\n\n public void setSoapVersion(String soapVersion) {\n this.soapVersion = soapVersion;\n }\n}",
"public class ReceptionAwareness {\n\n public static final ReceptionAwareness DEFAULT = new ReceptionAwareness();\n\n private static final Map<String,Object> DEFAULT_RETRY = new HashMap<>();\n private static final Map<String,Object> DEFAULT_DUP_DETECTION = new HashMap<>();\n\n static {\n DEFAULT_RETRY.put(\"enabled\",false);\n DEFAULT_DUP_DETECTION.put(\"enabled\",true);\n }\n\n private Map<String,Object> retry = DEFAULT_RETRY;\n private Map<String,Object> duplicateDetection = DEFAULT_DUP_DETECTION;\n\n public boolean isRetryEnabled() {\n return retry != null && (boolean)retry.get(\"enabled\");\n }\n\n public boolean isDuplicateDetectionEnabled() {\n return duplicateDetection != null && (boolean)duplicateDetection.get(\"enabled\");\n }\n\n public Map<String, Object> getRetry() {\n return retry;\n }\n\n public void setRetry(Map<String, Object> retry) {\n this.retry = retry;\n }\n\n public Map<String, Object> getDuplicateDetection() {\n return duplicateDetection;\n }\n\n public void setDuplicateDetection(Map<String, Object> duplicateDetection) {\n this.duplicateDetection = duplicateDetection;\n }\n}",
"public class Security {\n\n public static final Security DEFAULT_SECURITY = new Security();\n\n public enum ReplyPatternType {\n Callback,\n Response\n }\n\n private boolean sendReceipt = true;\n private ReplyPatternType sendReceiptReplyPattern = ReplyPatternType.Callback;\n private boolean sendReceiptNonRepudiation = false;\n private boolean disableBSPEnforcement = false;\n private boolean inclusiveNamespacesEnabled = true;\n private Signature signature = null;\n\n public boolean isSendReceipt() {\n return sendReceipt;\n }\n\n public void setSendReceipt(boolean sendReceipt) {\n this.sendReceipt = sendReceipt;\n }\n\n public ReplyPatternType getSendReceiptReplyPattern() {\n return sendReceiptReplyPattern;\n }\n\n public void setSendReceiptReplyPattern(ReplyPatternType sendReceiptReplyPattern) {\n this.sendReceiptReplyPattern = sendReceiptReplyPattern;\n }\n\n public boolean isSendReceiptNonRepudiation() {\n return sendReceiptNonRepudiation;\n }\n\n public void setSendReceiptNonRepudiation(boolean sendReceiptNonRepudiation) {\n this.sendReceiptNonRepudiation = sendReceiptNonRepudiation;\n }\n\n public Signature getSignature() {\n return signature;\n }\n\n public void setSignature(Signature signature) {\n this.signature = signature;\n }\n\n public boolean isDisableBSPEnforcement() {\n return disableBSPEnforcement;\n }\n\n public void setDisableBSPEnforcement(boolean disableBSPEnforcement) {\n this.disableBSPEnforcement = disableBSPEnforcement;\n }\n\n public boolean isInclusiveNamespacesEnabled() {\n return inclusiveNamespacesEnabled;\n }\n\n public void setInclusiveNamespacesEnabled(boolean inclusiveNamespacesEnabled) {\n this.inclusiveNamespacesEnabled = inclusiveNamespacesEnabled;\n }\n}",
"public class Service {\n\n private String service;\n private String action;\n private ServiceIdentifier identifier = null;\n private List<ValidationPredicate> validations;\n\n public Service() {}\n\n public Service(String service, String action) {\n this.service = service;\n this.action = action;\n }\n\n public String getService() {\n return service;\n }\n\n public void setService(String service) {\n this.service = service;\n }\n\n public String getAction() {\n return action;\n }\n\n public void setAction(String action) {\n this.action = action;\n }\n\n\n public ServiceIdentifier getIdentifier() {\n return identifier;\n }\n\n public void setIdentifier(ServiceIdentifier identifier) {\n this.identifier = identifier;\n }\n\n public List<ValidationPredicate> getValidations() {\n return validations;\n }\n\n public void setValidations(List<ValidationPredicate> validations) {\n this.validations = validations;\n }\n}"
] | import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import org.jentrata.ebms.EbmsConstants;
import org.jentrata.ebms.MessageType;
import org.jentrata.ebms.cpa.pmode.BusinessInfo;
import org.jentrata.ebms.cpa.pmode.Party;
import org.jentrata.ebms.cpa.pmode.PayloadService;
import org.jentrata.ebms.cpa.pmode.Protocol;
import org.jentrata.ebms.cpa.pmode.ReceptionAwareness;
import org.jentrata.ebms.cpa.pmode.Security;
import org.jentrata.ebms.cpa.pmode.Service; | package org.jentrata.ebms.cpa;
/**
* A Agreement between 2 trading partners
*
* @author aaronwalker
*/
public class PartnerAgreement {
private String cpaId;
private boolean active = true;
private String agreementRef;
private String mep = EbmsConstants.EBMS_V3_MEP_ONE_WAY;
private String mepBinding = EbmsConstants.EBMS_V3_MEP_BINDING_PUSH;
private Party initiator;
private Party responder; | private Protocol protocol; | 5 |
ls1intum/jReto | Source/test/jReto/integration/TransferCancellationTest.java | [
"public class PeerConfiguration {\n\tpublic final RunLoop runloop;\n\tpublic final LocalPeer peer1;\n\tpublic final LocalPeer peer2;\n\tpublic final List<LocalPeer> participatingPeers;\n\tpublic final List<LocalPeer> reachablePeers;\n\tpublic final List<LocalPeer> destinations;\n\n\tpublic static List<LocalPeer> destinationPeerList(LocalPeer peer1, List<LocalPeer> participatingPeers) {\n\t\tList<LocalPeer> result = new ArrayList<>(participatingPeers);\n\t\tresult.remove(peer1);\n\t\treturn result;\n\t}\n\t\n\tpublic PeerConfiguration(RunLoop runloop, LocalPeer peer1, LocalPeer peer2, List<LocalPeer> participatingPeers) {\n\t\tthis(runloop, peer1, peer2, participatingPeers, participatingPeers);\n\t}\n\tpublic PeerConfiguration(RunLoop runloop, LocalPeer peer1, LocalPeer peer2, List<LocalPeer> participatingPeers, List<LocalPeer> reachablePeers) {\n\t\tthis(runloop, peer1, peer2, participatingPeers, reachablePeers, Arrays.asList(peer2));\n\t}\n\tpublic PeerConfiguration(RunLoop runloop, LocalPeer peer1, LocalPeer peer2, List<LocalPeer> participatingPeers, List<LocalPeer> reachablePeers, List<LocalPeer> destinations) {\n\t\tthis.runloop = runloop;\n\t\tthis.peer1 = peer1;\n\t\tthis.peer2 = peer2;\n\t\tthis.participatingPeers = participatingPeers;\n\t\tthis.reachablePeers = reachablePeers;\n\t\tthis.destinations = destinations;\n\t}\n\t\n\tpublic Set<UUID> getMulticastDestinationIdentifiers() {\n\t\tSet<UUID> results = new HashSet<>();\n\t\tfor (LocalPeer peer : this.destinations) results.add(peer.getUniqueIdentifier());\n\t\treturn results;\n\t}\n\tpublic Set<UUID> getReachablePeerIdentifiers() {\n\t\tSet<UUID> results = new HashSet<>();\n\t\tfor (LocalPeer peer : this.reachablePeers) results.add(peer.getUniqueIdentifier());\n\t\treturn results;\n\t}\n\tpublic Set<RemotePeer> getMulticastDestinations(LocalPeer peer) {\n\t\tHashSet<RemotePeer> destinations = new HashSet<>();\n\t\tSet<UUID> multicastIdentifiers = this.getMulticastDestinationIdentifiers();\n\t\t\n\t\tfor (RemotePeer remotePeer : peer.getPeers()) {\n\t\t\tif (multicastIdentifiers.contains(remotePeer.getUniqueIdentifier())) destinations.add(remotePeer);\n\t\t}\n\t\t\n\t\treturn destinations;\n\t}\n\tpublic void startAndExecuteAfterDiscovery(final Runnable onDiscoveryComplete) {\n\t\tfinal Map<LocalPeer, Set<UUID>> discoveredPeersByPeer = new HashMap<>();\n\t\t\n\t\tfor (final LocalPeer reachablePeer : reachablePeers) {\n\t\t\tdiscoveredPeersByPeer.put(reachablePeer, new HashSet<UUID>());\n\t\t\tdiscoveredPeersByPeer.get(reachablePeer).add(reachablePeer.getUniqueIdentifier());\n\t\t}\n\t\tfor (LocalPeer participatingPeer : participatingPeers) {\n\t\t\tif (reachablePeers.contains(participatingPeer)) {\n\t\t\t\tparticipatingPeer.start(peer -> {\n\t\t\t\t\tSystem.err.println(\"Discovered peer: \"+peer.getUniqueIdentifier());\n\t\t\t\t\t\n\t\t\t\t\tdiscoveredPeersByPeer.get(participatingPeer).add(peer.getUniqueIdentifier());\n\t\t\t\t\t\n\t\t\t\t\tboolean allDiscovered = true;\n\t\t\t\t\tSet<UUID> allReachablePeers = getReachablePeerIdentifiers();\n\t\t\t\t\tfor (Set<UUID> identifiers : discoveredPeersByPeer.values()) {\n\t\t\t\t\t\tif (!identifiers.equals(new HashSet<>(allReachablePeers))) {\n\t\t\t\t\t\t\tallDiscovered = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (allDiscovered) onDiscoveryComplete.run();\n\t\t\t\t}, peer -> {});\n\t\t\t} else {\n\t\t\t\tparticipatingPeer.start(peer -> {}, peer -> {});\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis.runloop.start();\n\t}\n\t\n\tpublic static LocalPeer createLocalPeer(RunLoop runloop, Module... modules) {\n\t\treturn new LocalPeer(UUID.randomUUID(), Arrays.asList(modules), runloop, new Router.BroadcastDelaySettings(0.2, 0.1));\n\t}\n\t\n\t/**\n\t * A simple peer configuration that allows direct communication.\n\t * */\n\tpublic static PeerConfiguration directNeighborConfiguration() {\n\t\tfinal RunLoop runloop = new RunLoop(false);\n\n\t\tDummyNetworkInterface manager = new DummyNetworkInterface(\"test\", runloop, 1024, 1);\n\t\tfinal LocalPeer localPeer1 = createLocalPeer(runloop, new DummyModule(manager, runloop));\n\t\tfinal LocalPeer localPeer2 = createLocalPeer(runloop, new DummyModule(manager, runloop));\n\t\treturn new PeerConfiguration(runloop, localPeer1, localPeer2, Arrays.asList(localPeer1, localPeer2));\n\t}\n\t\n\t/**\n\t * A peer configuration that allows communication via 2 hops.\n\t * */\n\tpublic static PeerConfiguration twoHopRoutedConfiguration() {\n\t\tfinal RunLoop runloop = new RunLoop(false);\n\n\t\tDummyNetworkInterface manager1 = new DummyNetworkInterface(\"test1\", runloop, 1024, 1);\n\t\tDummyNetworkInterface manager2 = new DummyNetworkInterface(\"test2\", runloop, 1024, 1);\n\t\t\n\t\tfinal LocalPeer localPeer1 = createLocalPeer(runloop, new DummyModule(manager1, runloop));\n\t\tfinal LocalPeer localPeer2 = createLocalPeer(runloop, new DummyModule(manager2, runloop));\n\t\tfinal LocalPeer localPeer3 = createLocalPeer(runloop, new DummyModule(manager1, runloop), new DummyModule(manager2, runloop));\n\t\treturn new PeerConfiguration(runloop, localPeer1, localPeer2, Arrays.asList(localPeer1, localPeer2, localPeer3));\n\t}\n\n\t/**\n\t * A peer configuration that allows communication via 2 hops and multicasts to both peers.\n\t * */\n\tpublic static PeerConfiguration twoHopRoutedMulticastConfiguration() {\n\t\tPeerConfiguration config = PeerConfiguration.twoHopRoutedConfiguration();\n\t\t\n\t\treturn new PeerConfiguration(config.runloop, config.peer1, config.peer2, config.participatingPeers, config.reachablePeers, destinationPeerList(config.peer1, config.participatingPeers));\n\t}\n\t\n\t/**\n\t * A peer configuration that allows communication via 4 hops.\n\t * */\n\tpublic static PeerConfiguration fourHopRoutedConfiguration() {\n\t\tfinal RunLoop runloop = new RunLoop(false);\n\n\t\tDummyNetworkInterface manager1 = new DummyNetworkInterface(\"test1\", runloop, 1024, 1);\n\t\tDummyNetworkInterface manager2 = new DummyNetworkInterface(\"test2\", runloop, 1024, 1);\n\t\tDummyNetworkInterface manager3 = new DummyNetworkInterface(\"test3\", runloop, 1024, 1);\n\t\tDummyNetworkInterface manager4 = new DummyNetworkInterface(\"test4\", runloop, 1024, 1);\n\t\t\n\t\tfinal LocalPeer localPeer1 = createLocalPeer(runloop, new DummyModule(manager1, runloop));\n\t\tfinal LocalPeer localPeer4 = createLocalPeer(runloop, new DummyModule(manager4, runloop));\n\t\tfinal LocalPeer localPeer12 = createLocalPeer(runloop, new DummyModule(manager1, runloop), new DummyModule(manager2, runloop));\n\t\tfinal LocalPeer localPeer23 = createLocalPeer(runloop, new DummyModule(manager2, runloop), new DummyModule(manager3, runloop));\n\t\tfinal LocalPeer localPeer34 = createLocalPeer(runloop, new DummyModule(manager3, runloop), new DummyModule(manager4, runloop));\n\t\treturn new PeerConfiguration(runloop, localPeer1, localPeer4, Arrays.asList(localPeer1, localPeer4, localPeer12, localPeer23, localPeer34));\n\t}\n\t\n\t/**\n\t * A peer configuration that allows communication via 4 hops and multicasts to all peers.\n\t * */\n\tpublic static PeerConfiguration fourHopRoutedMulticastConfiguration() {\n\t\tPeerConfiguration config = PeerConfiguration.fourHopRoutedConfiguration();\n\t\t\n\t\treturn new PeerConfiguration(config.runloop, config.peer1, config.peer2, config.participatingPeers, config.reachablePeers, destinationPeerList(config.peer1, config.participatingPeers));\n\t}\n\t\n\t/**\n\t * A peer configuration that contains a direct route, but a cheaper route via another peer (cost: 10 vs. 2). \n\t * */\n\tpublic static PeerConfiguration nontrivial2HopNetworkConfiguration() {\n\t\tfinal RunLoop runloop = new RunLoop(false);\n\n\t\tDummyNetworkInterface manager1 = new DummyNetworkInterface(\"test1\", runloop, 1024, 1);\n\t\tDummyNetworkInterface manager2 = new DummyNetworkInterface(\"test2\", runloop, 1024, 1);\n\t\tDummyNetworkInterface manager3 = new DummyNetworkInterface(\"test3\", runloop, 1024, 10);\n\t\tDummyNetworkInterface manager4 = new DummyNetworkInterface(\"test4\", runloop, 1024, 15);\n\t\t\n\t\tfinal LocalPeer localPeer1 = createLocalPeer(runloop, new DummyModule(manager1, runloop), new DummyModule(manager3, runloop));\n\t\tfinal LocalPeer localPeer2 = createLocalPeer(runloop, new DummyModule(manager2, runloop), new DummyModule(manager3, runloop));\n\t\tfinal LocalPeer localPeer3 = createLocalPeer(runloop, new DummyModule(manager1, runloop), new DummyModule(manager2, runloop), new DummyModule(manager4, runloop));\n\t\tfinal LocalPeer localPeer4 = createLocalPeer(runloop, new DummyModule(manager4, runloop));\n\t\treturn new PeerConfiguration(runloop, localPeer1, localPeer2, Arrays.asList(localPeer1, localPeer2, localPeer3, localPeer4));\n\t}\n\t\n\t/**\n\t * A peer configuration that contains a direct route, but a cheaper route via another peer (cost: 10 vs. 2). \n\t * */\n\tpublic static PeerConfiguration nontrivial2HopNetworkMulticastConfiguration() {\n\t\tPeerConfiguration config = PeerConfiguration.fourHopRoutedConfiguration();\n\t\t\n\t\treturn new PeerConfiguration(config.runloop, config.peer1, config.peer2, config.participatingPeers, config.reachablePeers, destinationPeerList(config.peer1, config.participatingPeers));\n\t}\n\t\n\t/**\n\t * A peer configuration that includes two peers that cannot connect to peer1 and peer2.\n\t * */\n\tpublic static PeerConfiguration configurationWithDisconnectedPeers() {\n\t\tfinal RunLoop runloop = new RunLoop(false);\n\n\t\tDummyNetworkInterface manager1 = new DummyNetworkInterface(\"test1\", runloop, 1024, 1);\n\t\tDummyNetworkInterface manager2 = new DummyNetworkInterface(\"test2\", runloop, 1024, 1);\n\t\tDummyNetworkInterface manager3 = new DummyNetworkInterface(\"test3\", runloop, 1024, 10);\n\t\tDummyNetworkInterface manager4 = new DummyNetworkInterface(\"test4\", runloop, 1024, 15);\n\t\t\n\t\tfinal LocalPeer localPeer1 = createLocalPeer(runloop, new DummyModule(manager1, runloop), new DummyModule(manager2, runloop));\n\t\tfinal LocalPeer localPeer2 = createLocalPeer(runloop, new DummyModule(manager1, runloop), new DummyModule(manager2, runloop));\n\t\tfinal LocalPeer localPeer3 = createLocalPeer(runloop, new DummyModule(manager3, runloop), new DummyModule(manager4, runloop));\n\t\tfinal LocalPeer localPeer4 = createLocalPeer(runloop, new DummyModule(manager3, runloop));\n\t\treturn new PeerConfiguration(runloop, localPeer1, localPeer2, Arrays.asList(localPeer1, localPeer2, localPeer3, localPeer4), Arrays.asList(localPeer1, localPeer2));\n\t}\n\t\n\t/**\n\t * A peer configuration that contains a direct route, but a cheaper route via another peer (cost: 10 vs. 2). \n\t * */\n\tpublic static PeerConfiguration multicastConfigurationWithDisconnectedPeers() {\n\t\tPeerConfiguration config = PeerConfiguration.configurationWithDisconnectedPeers();\n\t\t\n\t\treturn new PeerConfiguration(config.runloop, config.peer1, config.peer2, config.participatingPeers, config.reachablePeers, destinationPeerList(config.peer1, config.reachablePeers));\n\t}\n\t\n}",
"public class TestData {\n\tpublic static ByteBuffer generate(int length) {\n\t\tByteBuffer buffer = ByteBuffer.allocate(length);\n\t\tfor (int i=0; i<length; i++) {\n\t\t\tbuffer.put((byte)(i%127));\n\t\t}\n\t\tbuffer.rewind();\n\t\treturn buffer;\n\t}\n\t\n\tpublic static void verify(ByteBuffer buffer, int length) {\n\t\tint count = buffer.remaining();\n\t\tif (count != length) throw new IllegalArgumentException(\"Test data needs to have the correct length\");\n\t\t\n\t\tfor (int i=0; i<count; i++) {\n\t\t\tbyte value = buffer.get();\n\t\t\t\n\t\t\tif (value != i%127) throw new IllegalArgumentException(\"Buffer has incorrect value: \"+value+\", should be: \"+i%127);\n\t\t}\n\t}\n}",
"public class Connection {\n\tpublic static interface ConnectHandler {\n\t\tvoid onConnect(Connection connection);\n\t}\n\tpublic static interface IncomingTransferHandler {\n\t\tvoid onTransferAvailable(Connection connection, InTransfer transfer);\n\t}\n\tpublic static interface ConnectionDataHandler {\n\t\tvoid onData(Connection connection, ByteBuffer data);\n\t}\n\tpublic static interface CloseHandler {\n\t\tvoid onClose(Connection connection);\n\t}\n\tpublic static interface ErrorHandler {\n\t\tvoid onError(Connection connection, String error);\n\t}\n\t\n\tprivate ConnectHandler connectHandler;\n\tprivate IncomingTransferHandler incomingTransferStartedHandler;\n\tprivate ConnectionDataHandler dataHandler;\n\tprivate CloseHandler closeHandler;\n\tprivate ErrorHandler errorHandler;\n\t\n /** The trasfer manager, which is responsible for data transmissions. */\n\tprivate TransferProcessor transferProcessor;\n /** The reliability manager, which is responsible for cleanly closing connections and providing automatic reconnect functionality. */\n\tprivate ReliablitiyManager reliabilityManager;\n /** Whether this connection is currently connected. */\n\tprivate boolean isConnected = false;\n\t\n\t/** Implements the TransferProcessor's Handler protocol and calls methods appropriately */\n\tprivate TransferProcessorHandler transferProcessorHandler = new TransferProcessorHandler() {\n\t\t@Override\n\t\tpublic void notifyTransferStarted(InTransfer transfer) {\n\t\t\tConnection.this.notifyTransferStarted(transfer);\n\t\t}\n\t}; \n\t/** Implements the ReliabilityManager's Handler protocol and calls methods appropriately */\n\tprivate ReliabilityManagerHandler reliablityHandler = new ReliabilityManagerHandler() {\t\n\t\t@Override\n\t\tpublic void onUnexpectedFinalConnectionClose() {\n\t\t\tnotifyError();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void onExpectedConnectionClose() {\n\t\t\tnotifyClose();\n\t\t}\n\n\t\t@Override\n\t\tpublic void onConnectionConnected() {\n\t\t\tnotifyConnect();\n\t\t}\n\t};\n\t\n /**\n * Constructs a Connection. Users should use RemotePeer and LocalPeer's connect() methods to establish connections.\n *\n * @param packetConnection The packet connection used by this connection.\n * @param localIdentifier: The local peer's identifier\n * @param executor The Executor delegate methods and events are dispatched on\n * @param isConnectionEstablisher: A boolean indicating whether the connection was established on this peer. If the connection closes unexpectedly, the \n * connection establisher is responsible for any reconnect attempts.\n * @param connectionManager The connection's manager. If a reconnect is required, it is responsible to establish a new underlying connection.\n */\n\tConnection(PacketConnection packetConnection, UUID localIdentifier, Executor executor, boolean isConnectionEstablisher, PacketConnectionManager connectionManager) {\t\n\t\tthis.transferProcessor = new TransferProcessor(packetConnection);\n\t\n\t\tSet<UUID> destinationIdentifiers = new HashSet<>();\n\t\tfor (Node destination : packetConnection.getDestinations()) destinationIdentifiers.add(destination.getIdentifier());\n\t\tthis.reliabilityManager = new ReliablitiyManager(packetConnection, connectionManager, localIdentifier, destinationIdentifiers, isConnectionEstablisher, executor);\n\t\t\n\t\tthis.transferProcessor.setHandler(this.transferProcessorHandler);\n\t\tthis.reliabilityManager.setHandler(this.reliablityHandler);\n\t}\n\n\tvoid setTransferProcessor(TransferProcessor transferProcessor) {\n\t\tthis.transferProcessor = transferProcessor;\n\t}\n\tvoid setReliablitiyManager(ReliablitiyManager reliabilityManager) {\n\t\tthis.reliabilityManager = reliabilityManager;\n\t}\n /** Whether this connection is currently connected. */\n\tpublic boolean isConnected() {\n\t\treturn this.isConnected;\n\t}\n\t\n\t/**\n\t * Closes this connection.\n\t * */\n\tpublic void close() {\n\t\tthis.isConnected = false;\n\t\tConnection.this.reliabilityManager.closeConnection();\n\t}\n\t/**\n\t * Attempts to reconnect this connection. You can call this method when the connection was closed explicitly (i.e. by calling close()) or when it was closed by a network fault.\n\t * */\n\tpublic void attemptReconnect() {\n\t\tConnection.this.reliabilityManager.attemptConnect();\n\t}\n\n\t/**\n\t * Sends data.\n\t * \n\t * @param data The data to be sent.\n\t */\n\tpublic OutTransfer send(ByteBuffer data) {\n\t\tDefaultDataSource dataSource = new DefaultDataSource(data);\n\t\t\n\t\treturn this.send(dataSource.getDataLength(), (offset, length) -> dataSource.getData(offset, length));\n\t}\n\tpublic static interface DataProvider {\n\t\tByteBuffer getData(int offset, int length);\n\t}\n\t/**\n\t * Sends data. Use this if you don't want to store the full data in memory at once. A dataProvider is used that lets you load data piece by piece.\n\t * \n\t * @param dataLength The total length of this transfer.\n\t * @param dataProvider Called when another chunk of data is needed.\n\t */\n\tpublic OutTransfer send(int dataLength, DataProvider dataProvider) {\n\t\treturn this.transferProcessor.startTransfer(dataLength, dataProvider);\n\t}\n\t\n\tprivate void notifyTransferStarted(InTransfer transfer) {\n\t\tif (this.incomingTransferStartedHandler != null) {\n\t\t\tthis.incomingTransferStartedHandler.onTransferAvailable(this, transfer);\n\t\t} else if (this.dataHandler != null) {\n\t\t\ttransfer.setOnCompleteData((t, data) -> this.dataHandler.onData(this, data));\n\t\t} else {\n\t\t\tSystem.err.println(\"You need to set either onTransfer or onData on connection \"+this);\n\t\t}\n\t}\n\tprivate void notifyConnect() {\n\t\tthis.isConnected = true;\n\t\tif (this.connectHandler != null) this.connectHandler.onConnect(this);\n\t}\n\tprivate void notifyClose() {\n\t\tthis.isConnected = false;\n\t\tif (this.closeHandler != null) this.closeHandler.onClose(this);\n\t}\n\tprivate void notifyError() {\n\t\tthis.isConnected = false;\n\t\tif (this.errorHandler != null) this.errorHandler.onError(this, \"The connection was closed unexpectedly and could not be reestablished.\");\n\t}\n\tpublic ConnectHandler getOnConnect() {\n\t\treturn connectHandler;\n\t}\n\tpublic void setOnConnect(ConnectHandler connectHandler) {\n\t\tif (this.isConnected) { this.connectHandler.onConnect(this); }\n\t\tthis.connectHandler = connectHandler;\n\t}\n\tpublic IncomingTransferHandler getOnTransfer() {\n\t\treturn incomingTransferStartedHandler;\n\t}\n\tpublic void setOnTransfer(IncomingTransferHandler incomingTransferStartedHandler) {\n\t\tthis.incomingTransferStartedHandler = incomingTransferStartedHandler;\n\t}\n\tpublic ConnectionDataHandler getOnData() {\n\t\treturn this.dataHandler;\n\t}\n\tpublic void setOnData(ConnectionDataHandler dataHandler) {\n\t\tthis.dataHandler = dataHandler;\n\t}\n\tpublic CloseHandler getOnClose() {\n\t\treturn closeHandler;\n\t}\n\tpublic void setOnClose(CloseHandler closeHandler) {\n\t\tthis.closeHandler = closeHandler;\n\t}\n\tpublic ErrorHandler getOnError() {\n\t\treturn errorHandler;\n\t}\n\tpublic void setOnError(ErrorHandler errorHandler) {\n\t\tthis.errorHandler = errorHandler;\n\t}\n}",
"public class RemotePeer {\n\tpublic static interface ConnectionCreatedCallback {\n\t\tvoid onConnectionCreated(Connection connection);\n\t}\n\t\n /** The LocalPeer that created this peer */\n\tprivate final LocalPeer localPeer;\n /** The node representing this peer on the routing level */\n\tprivate Node node;\n\tprivate IncomingConnectionHandler incomingConnectionHandler;\n \n\t/**\n * Internal initializer. See the class documentation about how to obtain RemotePeer instances.\n * @param node The node representing the the peer on the routing level.\n * @param localPeer The local peer that created this peer\n */\n\tRemotePeer(LocalPeer localPeer, Node node) {\n\t\tthis.localPeer = localPeer;\n\t\tthis.node = node;\n\t}\n\t\n /** Returns this peer's unique identifier. */\n\tpublic UUID getUniqueIdentifier() {\n\t\treturn RemotePeer.this.node.getIdentifier();\n\t}\n\t\n /**\n * Establishes a connection to this peer. The connection can only be used to send data, not to receive data.\n * @return A Connection object. It can be used to send data immediately (the transfers will be started once the connection was successfully established).\n * */\n\tpublic Connection connect() {\n\t\treturn this.localPeer.connect(new HashSet<>(Arrays.asList(this)));\n\t}\n\t\n\t/**\n\t * Sets the incomingConnectionHandler. When you set it, it will be called when any incoming connections from this peer are received.\n\t * The LocalPeer will not report incoming connections from this peer once this property is set.\n\t * */\n\tpublic void setIncomingConnectionHandler(IncomingConnectionHandler incomingConnectionHandler) {\n\t\tthis.incomingConnectionHandler = incomingConnectionHandler;\n\t}\n\tpublic IncomingConnectionHandler getIncomingConnectionHandler() {\n\t\treturn this.incomingConnectionHandler;\n\t}\n\tNode getNode() {\n\t\treturn this.node;\n\t}\n}",
"public abstract class Transfer {\n\tpublic static interface StartHandler {\n\t\tvoid onStart(Transfer transfer);\n\t}\n\tpublic static interface ProgressHandler {\n\t\tvoid onProgress(Transfer transfer);\n\t}\n\tpublic static interface CompletionHandler {\n\t\tvoid onComplete(Transfer transfer);\n\t}\n\tpublic static interface CancellationHandler {\n\t\tvoid onCancel(Transfer transfer);\n\t}\n\tpublic static interface EndHandler {\n\t\tvoid onEnd(Transfer transfer);\n\t}\n\t\n // Called when the transfer starts. If this property is set when the transfer is already started, the closure is called immediately.\n\tprivate StartHandler startHandler;\n // Called whenever the transfer makes progress.\n\tprivate ProgressHandler progressHandler;\n // Called when the transfer completes successfully. To receive the data from an incoming transfer, use onCompleteData or onPartialData of InTransfer.\n\tprivate CompletionHandler completionHandler;\n // Called when the transfer is cancelled.\n\tprivate CancellationHandler cancellationHandler;\n // Called when the transfer ends, either by cancellation or completion.\n\tprivate EndHandler endHandler;\n\t\n\tpublic StartHandler getOnStart() {\n\t\treturn startHandler;\n\t}\n\t/** Sets the onStart event handler. */\n\tpublic void setOnStart(StartHandler startHandler) {\n\t\tthis.startHandler = startHandler;\n\t\t\n\t\tif (this.isStarted) startHandler.onStart(this);\n\t}\n\tpublic ProgressHandler getOnProgress() {\n\t\treturn progressHandler;\n\t}\n\t/** Sets the onProgress event handler. */\n\tpublic void setOnProgress(ProgressHandler progressHandler) {\n\t\tthis.progressHandler = progressHandler;\n\t}\n\tpublic CompletionHandler getOnComplete() {\n\t\treturn completionHandler;\n\t}\n\t/** Sets the onComplete event handler. */\n\tpublic void setOnComplete(CompletionHandler completionHandler) {\n\t\tthis.completionHandler = completionHandler;\n\t}\n\tpublic CancellationHandler getOnCancel() {\n\t\treturn cancellationHandler;\n\t}\n\t/** Sets the onCancel event handler. */\n\tpublic void setOnCancel(CancellationHandler cancellationHandler) {\n\t\tthis.cancellationHandler = cancellationHandler;\n\t}\n\tpublic EndHandler getOnEnd() {\n\t\treturn endHandler;\n\t}\n\t/** Sets the onEnd event handler. */\n\tpublic void setOnEnd(EndHandler endHandler) {\n\t\tthis.endHandler = endHandler;\n\t}\n\t\n /** Whether the transfer was been started */\n\tprivate boolean isStarted;\n /** Whether the transfer was completed successfully */\n\tprivate boolean isCompleted;\n /** Whether the transfer was cancelled */\n\tprivate boolean isCancelled;\n /** The transfer's length in bytes*/\n\tprivate final int length;\n /** The transfer's current progress in bytes */\n\tprivate int progress;\n /** Indicates if the transfer is currently interrupted. This occurs, for example, when a connection closes unexpectedly. The transfer is resumed automatically on reconnect. */\n\tprivate boolean isInterrupted;\n /** The transfer's identifier */\n\tprivate final UUID identifier;\n /** The transfer's manager. */\n\tprivate final TransferManager transferManager;\n\n /** \n * Constructs a Transfer.\n * @param manager The TransferManager responsible for this transfer.\n * @param length The total length of the transfer in bytes.\n * @param identifier The transfer's identifier.\n */\n\tpublic Transfer(TransferManager transferManager, int length, UUID identifier) {\n\t\tthis.length = length;\n\t\tthis.identifier = identifier;\n\t\tthis.transferManager = transferManager;\n\t}\n\t\n /** Whether all data was sent. */\n\tpublic boolean getIsAllDataTransmitted() {\n\t\treturn this.progress == this.length;\n\t}\n\t\n /** The transfer's current progress in bytes */\n\tpublic int getProgress() {\n\t\treturn this.progress;\n\t}\n\t\n /** The transfer's identifier */\n\tpublic UUID getIdentifier() {\n\t\treturn this.identifier;\n\t}\n\t\n /** The transfer's length in bytes*/\n\tpublic int getLength() {\n\t\treturn this.length;\n\t}\n\t\n\t/** Cancels the transfer. */\n\tpublic abstract void cancel();\n\t\n /** Updates the transfer's progress. */\n\tvoid updateProgress(int numberOfBytes) {\n\t\tif (this.length < this.progress+numberOfBytes) throw new IllegalArgumentException(\"You may not update the progress beyond the Transfer's length.\");\n\t\t\n\t\tthis.progress += numberOfBytes;\n\t\t\n\t\tthis.confirmProgress();\n\t\tif (this.getIsAllDataTransmitted()) this.confirmCompletion();\n\t}\n\t\n\tvoid setInterrupted(boolean interrupted) {\n\t\tthis.isInterrupted = interrupted;\n\t}\n\t\n\tpublic boolean getIsInterrupted() {\n\t\treturn this.isInterrupted;\n\t}\n /** Whether the transfer was been started */\n\tpublic boolean getIsStarted() {\n\t\treturn this.isStarted;\n\t}\n /** Whether the transfer was completed successfully */\n\tpublic boolean getIsCompleted() {\n\t\treturn this.isCompleted;\n\t}\n /** Whether the transfer was cancelled */\n\tpublic boolean getIsCancelled() {\n\t\treturn this.isCancelled;\n\t}\n\t\n /** Call to change the transfer's state to started and dispatch the associated events. */\n\tvoid confirmStart() {\n\t\tthis.isStarted = true;\n\t\tif (this.startHandler != null) this.startHandler.onStart(this);\n\t}\n /** Call to confirm updated progress and dispatch the associated events. */\n\tvoid confirmProgress() {\n\t\tif (this.progressHandler != null) this.progressHandler.onProgress(this);\n\t}\n /** Call to change thet transfer's state to cancelled and dispatch the associated events. */\n\tvoid confirmCancel() {\n\t\tthis.isCancelled = true;\n\t\tif (this.cancellationHandler != null) this.cancellationHandler.onCancel(this);\n\t\tthis.confirmEnd();\n\t}\n /** Call to change thet transfer's state to completed and dispatch the associated events. */\n\tvoid confirmCompletion() {\n\t\tthis.isCompleted = true;\n\t\tif (this.completionHandler != null) this.completionHandler.onComplete(this);\n\t\tthis.confirmEnd();\n\t}\n /** Call to change thet transfer's state to ended, dispatch the associated events, and clean up events. */\n\tvoid confirmEnd() {\n\t\tif (this.endHandler != null) this.endHandler.onEnd(this);\n\t}\n\n\t/** Sets the transfer's progress. */\n\tvoid setProgress(int progress) {\n\t\tthis.progress = progress;\n\t}\n\tTransferManager getTransferManager() {\n\t\treturn this.transferManager;\n\t}\n}",
"public class CountDown {\n\tprivate int counter;\n\tprivate Runnable runnable;\n\t\n\tpublic CountDown(int target, Runnable runnable) {\n\t\tthis.counter = target;\n\t\tthis.runnable = runnable;\n\t}\n\t\n\tpublic void countDown() {\n\t\tif (this.counter == 0) throw new IllegalStateException(\"Tried to count down below 0\");\n\t\t\n\t\tthis.counter--;\n\t\t\n\t\tif (this.counter == 0) this.runnable.run();\n\t}\n}"
] | import static org.junit.Assert.*;
import jReto.meta.PeerConfiguration;
import jReto.util.TestData;
import org.junit.Test;
import de.tum.in.www1.jReto.Connection;
import de.tum.in.www1.jReto.RemotePeer;
import de.tum.in.www1.jReto.connectivity.Transfer;
import de.tum.in.www1.jReto.util.CountDown; | package jReto.integration;
public class TransferCancellationTest {
@Test(timeout=1000)
public void testTransferDataIntegrityDirect() {
new TransferCancellationTest().testTransferCancellation(PeerConfiguration.directNeighborConfiguration());
}
@Test(timeout=1000)
public void testTransferDataIntegrity2Hop() {
new TransferCancellationTest().testTransferCancellation(PeerConfiguration.twoHopRoutedConfiguration());
}
@Test(timeout=1000)
public void testTransferDataIntegrity4Hop() {
new TransferCancellationTest().testTransferCancellation(PeerConfiguration.fourHopRoutedConfiguration());
}
@Test(timeout=1000)
public void testTransferDataIntegrityNontrivial() {
new TransferCancellationTest().testTransferCancellation(PeerConfiguration.nontrivial2HopNetworkConfiguration());
}
@Test(timeout=1000)
public void testTransferDataIntegrityDisconnectedPeers() {
new TransferCancellationTest().testTransferCancellation(PeerConfiguration.configurationWithDisconnectedPeers());
}
int dataLength = 1000000;
boolean didCancel = false;
public void testTransferCancellation(final PeerConfiguration peerConfiguration) {
CountDown cancellationCountDown = new CountDown(2, () -> peerConfiguration.runloop.stop());
peerConfiguration.startAndExecuteAfterDiscovery(() -> {
peerConfiguration.peer2.setIncomingConnectionHandler((connectingPeer, connection) -> {
connection.setOnTransfer((c, transfer) -> {
transfer.setOnCompleteData((t, data) -> {}); // We don't care about the data, but need to set a data handler to keep the transfer from complaining
transfer.setOnComplete(t -> fail("Transfer should not complete."));
transfer.setOnCancel(t -> {
assertTrue("transfer should have cancelled state", t.getIsCancelled());
assertFalse("transfer should not be completed", t.getIsCompleted());
cancellationCountDown.countDown();
});
transfer.setOnProgress(t -> {
// When we get the first progress update, we cancel the transfer.
if (!didCancel) {
didCancel = true;
peerConfiguration.runloop.execute(() -> {
transfer.cancel();
});
}
});
});
});
RemotePeer destination = peerConfiguration.peer1.getPeers().stream().filter(p -> p.getUniqueIdentifier().equals(peerConfiguration.peer2.getUniqueIdentifier())).findFirst().get();
Connection connection = destination.connect(); | Transfer outTransfer = connection.send(TestData.generate(dataLength)); | 1 |
jjoe64/GraphView-Demos | app/src/main/java/com/jjoe64/graphview_demos/categories/StylingExamplesFragment.java | [
"public enum FullscreenExample {\n HELLO_WORLD(R.layout.fullscreen_example_simple, HelloWorld.class),\n SCALING_XY(R.layout.fullscreen_example_simple, ScalingXY.class),\n SCALING_X(R.layout.fullscreen_example_simple, ScalingX.class),\n SCROLLING_X(R.layout.fullscreen_example_simple, ScrollingX.class),\n FIXED_FRAME(R.layout.fullscreen_example_simple, FixedFrame.class),\n REALTIME_SCROLLING(R.layout.fullscreen_example_simple, RealtimeScrolling.class),\n DATES(R.layout.fullscreen_example_simple, Dates.class),\n SIMPLE_LINE_GRAPH(R.layout.fullscreen_example_simple, SimpleLineGraph.class),\n ADVANCED_LINE_GRAPH(R.layout.fullscreen_example_simple, AdvancedLineGraph.class),\n UNIQUE_LEGEND_LINE_GRAPH(R.layout.fullscreen_example_simple, UniqueLegendLineGraph.class),\n SIMPLE_BAR_GRAPH(R.layout.fullscreen_example_simple, SimpleBarGraph.class),\n ADVANCED_BAR_GRAPH(R.layout.fullscreen_example_simple, AdvancedBarGraph.class),\n MULTIPLE_BAR_GRAPH(R.layout.fullscreen_example_simple, MultipleBarGraph.class),\n SIMPLE_POINTS_GRAPH(R.layout.fullscreen_example_simple, SimplePointsGraph.class),\n SECOND_SCALE_GRAPH(R.layout.fullscreen_example_simple, SecondScaleGraph.class),\n CUSTOM_LABELS(R.layout.fullscreen_example_simple, CustomLabelsGraph.class),\n NO_LABELS(R.layout.fullscreen_example_simple, NoLabelsGraph.class),\n STATIC_LABELS(R.layout.fullscreen_example_simple, StaticLabelsGraph.class),\n TAP_LISTENER(R.layout.fullscreen_example_simple, TapListenerGraph.class),\n STYLING_LABELS(R.layout.fullscreen_example_simple, StylingLabels.class),\n STYLING_COLORS(R.layout.fullscreen_example_simple, StylingColors.class),\n ADD_SERIES(R.layout.fullscreen_example_add_series, AddSeriesAtRuntime.class),\n TITLES_EXAMPLE(R.layout.fullscreen_example_simple, TitlesExample.class),\n SNAPSHOT_SHARE(R.layout.fullscreen_example_add_series, SnapshotShareGraph.class),\n ;\n\n public static final String ARG_ID = \"FEID\";\n static final String URL_PREFIX = \"https://github.com/jjoe64/GraphView-Demos/blob/master/app/src/main/java/com/jjoe64/graphview_demos/examples/\";\n\n public final @LayoutRes int contentView;\n public final Class<? extends BaseExample> exampleClass;\n public final String url;\n\n FullscreenExample(@LayoutRes int contentView, Class<? extends BaseExample> exampleClass) {\n this.contentView = contentView;\n this.exampleClass = exampleClass;\n this.url = URL_PREFIX+exampleClass.getSimpleName()+\".java\";\n }\n}",
"public abstract class ItemDetailFragment extends Fragment {\n /**\n * The fragment argument representing the item ID that this fragment\n * represents.\n */\n public static final String ARG_ITEM_ID = \"item_id\";\n\n /**\n * The dummy content this fragment is presenting.\n */\n private MenuContent.MenuItem mItem;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public ItemDetailFragment() {\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (getArguments().containsKey(ARG_ITEM_ID)) {\n // Load the dummy content specified by the fragment\n // arguments. In a real-world scenario, use a Loader\n // to load content from a content provider.\n mItem = MenuContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));\n\n Activity activity = this.getActivity();\n CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);\n if (appBarLayout != null) {\n appBarLayout.setTitle(mItem.content);\n //appBarLayout.setBackgroundResource(mItem.background);\n }\n }\n }\n\n protected void openFullscreen(FullscreenExample helloWorld) {\n Intent intent = new Intent(getActivity(), FullscreenActivity.class);\n intent.putExtra(FullscreenExample.ARG_ID, helloWorld.name());\n startActivity(intent);\n }\n\n protected void openSource(FullscreenExample helloWorld) {\n Intent i = new Intent(\"android.intent.action.VIEW\");\n i.setData(Uri.parse(helloWorld.url));\n startActivity(i);\n }\n}",
"public class StylingColors extends BaseExample {\n @Override\n public void onCreate(FullscreenActivity activity) {\n GraphView graph = (GraphView) activity.findViewById(R.id.graph);\n initGraph(graph);\n }\n\n @Override\n public void initGraph(GraphView graph) {\n DataPoint[] points = new DataPoint[30];\n for (int i = 0; i < 30; i++) {\n points[i] = new DataPoint(i, Math.sin(i*0.5) * 20*(Math.random()*10+1));\n }\n LineGraphSeries<DataPoint> series = new LineGraphSeries<>(points);\n\n points = new DataPoint[15];\n for (int i = 0; i < 15; i++) {\n points[i] = new DataPoint(i*2, Math.sin(i*0.5) * 20*(Math.random()*10+1));\n }\n LineGraphSeries<DataPoint> series2 = new LineGraphSeries<>(points);\n\n // styling grid/labels\n graph.getGridLabelRenderer().setGridColor(Color.RED);\n graph.getGridLabelRenderer().setHighlightZeroLines(false);\n graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.GREEN);\n graph.getGridLabelRenderer().setVerticalLabelsColor(Color.RED);\n graph.getGridLabelRenderer().setVerticalLabelsVAlign(GridLabelRenderer.VerticalLabelsVAlign.ABOVE);\n graph.getGridLabelRenderer().setGridStyle(GridLabelRenderer.GridStyle.HORIZONTAL);\n graph.getGridLabelRenderer().reloadStyles();\n\n\n // styling viewport\n graph.getViewport().setBackgroundColor(Color.argb(255, 222, 222, 222));\n graph.getViewport().setDrawBorder(true);\n graph.getViewport().setBorderColor(Color.BLUE);\n\n // styling series\n series.setTitle(\"Random Curve 1\");\n series.setColor(Color.GREEN);\n series.setDrawDataPoints(true);\n series.setDataPointsRadius(10);\n series.setThickness(8);\n\n series2.setTitle(\"Random Curve 2\");\n series2.setDrawBackground(true);\n series2.setBackgroundColor(Color.argb(100, 255, 255, 0));\n Paint paint = new Paint();\n paint.setStyle(Paint.Style.STROKE);\n paint.setStrokeWidth(10);\n paint.setPathEffect(new DashPathEffect(new float[]{8, 5}, 0));\n series2.setDrawAsPath(true);\n series2.setCustomPaint(paint);\n\n // styling legend\n graph.getLegendRenderer().setVisible(true);\n graph.getLegendRenderer().setTextSize(25);\n graph.getLegendRenderer().setBackgroundColor(Color.argb(150, 50, 0, 0));\n graph.getLegendRenderer().setTextColor(Color.WHITE);\n //graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);\n //graph.getLegendRenderer().setMargin(30);\n graph.getLegendRenderer().setFixedPosition(150, 0);\n\n graph.addSeries(series);\n graph.addSeries(series2);\n }\n}",
"public class StylingLabels extends BaseExample {\n @Override\n public void onCreate(FullscreenActivity activity) {\n GraphView graph = (GraphView) activity.findViewById(R.id.graph);\n initGraph(graph);\n }\n\n @Override\n public void initGraph(GraphView graph) {\n DataPoint[] points = new DataPoint[30];\n for (int i = 0; i < 30; i++) {\n points[i] = new DataPoint(i, Math.sin(i*0.5) * 20*(Math.random()*10+1));\n }\n LineGraphSeries<DataPoint> series = new LineGraphSeries<>(points);\n\n points = new DataPoint[15];\n for (int i = 0; i < 15; i++) {\n points[i] = new DataPoint(i*2, Math.sin(i*0.5) * 20*(Math.random()*10+1));\n }\n LineGraphSeries<DataPoint> series2 = new LineGraphSeries<>(points);\n\n // styling grid/labels\n graph.getGridLabelRenderer().setHighlightZeroLines(false);\n graph.getGridLabelRenderer().setVerticalLabelsAlign(Paint.Align.LEFT);\n graph.getGridLabelRenderer().setLabelVerticalWidth(100);\n graph.getGridLabelRenderer().setTextSize(20);\n graph.getGridLabelRenderer().setGridStyle(GridLabelRenderer.GridStyle.HORIZONTAL);\n graph.getGridLabelRenderer().setHorizontalLabelsAngle(120);\n graph.getGridLabelRenderer().reloadStyles();\n\n // styling series\n series.setTitle(\"Random Curve 1\");\n series.setColor(Color.GREEN);\n series.setDrawDataPoints(true);\n series.setDataPointsRadius(10);\n series.setThickness(8);\n\n graph.addSeries(series);\n graph.addSeries(series2);\n }\n}",
"public class TitlesExample extends BaseExample {\n @Override\n public void onCreate(FullscreenActivity activity) {\n GraphView graph = (GraphView) activity.findViewById(R.id.graph);\n initGraph(graph);\n }\n\n @Override\n public void initGraph(GraphView graph) {\n LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {\n new DataPoint(0, 1),\n new DataPoint(1, 5),\n new DataPoint(2, 3),\n new DataPoint(3, 2),\n new DataPoint(4, 6)\n });\n graph.addSeries(series);\n\n // titles\n graph.setTitle(\"Chart Title\");\n graph.getGridLabelRenderer().setVerticalAxisTitle(\"Vertical Axis\");\n graph.getGridLabelRenderer().setHorizontalAxisTitle(\"Horizontal Axis\");\n\n // optional styles\n //graph.setTitleTextSize(40);\n //graph.setTitleColor(Color.BLUE);\n //graph.getGridLabelRenderer().setVerticalAxisTitleTextSize(40);\n graph.getGridLabelRenderer().setVerticalAxisTitleColor(Color.BLUE);\n //graph.getGridLabelRenderer().setHorizontalAxisTitleTextSize(40);\n graph.getGridLabelRenderer().setHorizontalAxisTitleColor(Color.BLUE);\n }\n}"
] | import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview_demos.FullscreenExample;
import com.jjoe64.graphview_demos.ItemDetailFragment;
import com.jjoe64.graphview_demos.R;
import com.jjoe64.graphview_demos.examples.StylingColors;
import com.jjoe64.graphview_demos.examples.StylingLabels;
import com.jjoe64.graphview_demos.examples.TitlesExample; | package com.jjoe64.graphview_demos.categories;
/**
* Created by jonas on 07.09.16.
*/
public class StylingExamplesFragment extends ItemDetailFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.styling_examples_content, container, false);
GraphView graph = (GraphView) rootView.findViewById(R.id.graph);
new StylingLabels().initGraph(graph);
rootView.findViewById(R.id.cardStylingLabelsGraph).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openFullscreen(FullscreenExample.STYLING_LABELS);
}
});
rootView.findViewById(R.id.imgFullscreen).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openFullscreen(FullscreenExample.STYLING_LABELS);
}
});
rootView.findViewById(R.id.imgSource).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openSource(FullscreenExample.STYLING_LABELS);
}
});
graph = (GraphView) rootView.findViewById(R.id.graph2); | new StylingColors().initGraph(graph); | 2 |
d-plaindoux/suitcase | src/main/java/org/smallibs/suitcase/match/Matcher.java | [
"public interface Case<T, R> {\n\n Optional<R> unapply(T t);\n\n interface WithoutCapture<T, R> extends Case<T, Result.WithoutCapture<R>> {\n static <T, R> WithoutCapture<T, R> adapt(Case<T, Result.WithoutCapture<R>> aCase) {\n return aCase::unapply;\n }\n }\n\n interface WithCapture<T, R> extends Case<T, Result.WithCapture<R>> {\n static <T, R> WithCapture<T, R> adapt(Case<T, Result.WithCapture<R>> aCase) {\n return aCase::unapply;\n }\n }\n\n}",
"public abstract class Result<R> {\n\n public static <R> WithoutCapture<R> success(R term) {\n return new WithoutCapture<>(term);\n }\n\n public static <C> WithCapture<C> successWithCapture(C result) {\n return new WithCapture<>(result);\n }\n\n private final R capturedObject;\n\n public Result(R capturedObject) {\n this.capturedObject = capturedObject;\n }\n\n public R resultValue() {\n return capturedObject;\n }\n\n public static class WithCapture<C> extends Result<C> {\n public WithCapture(C capturedObject) {\n super(capturedObject);\n }\n }\n\n public static class WithoutCapture<T> extends Result<T> {\n public WithoutCapture(T capturedObject) {\n super(capturedObject);\n }\n }\n\n}",
"public final class Functions {\n\n public static <R> Supplier<R> constant(final R object) {\n return () -> object;\n }\n\n public static <C1, C2, R> Function<Pair<C1, C2>, R> function(Function2<C1, C2, R> function) {\n return params -> function.apply(params._1, params._2);\n }\n\n public static <C1, C2, C3, R> Function<Pair<C1, Pair<C2, C3>>, R> function(Function3<C1, C2, C3, R> function) {\n return params -> function.apply(params._1, params._2._1, params._2._2);\n }\n\n public static <C1, C2, C3, C4, R> Function<Pair<C1, Pair<C2, Pair<C3, C4>>>, R> function(Function4<C1, C2, C3, C4, R> function) {\n return params -> function.apply(params._1, params._2._1, params._2._2._1, params._2._2._2);\n }\n\n public static <C1, C2, C3, C4, C5, R> Function<Pair<C1, Pair<C2, Pair<C3, Pair<C4, C5>>>>, R> function(Function5<C1, C2, C3, C4, C5, R> function) {\n return params -> function.apply(params._1, params._2._1, params._2._2._1, params._2._2._2._1, params._2._2._2._2);\n }\n\n public static <C1, C2, C3, C4, C5, C6, R> Function<Pair<C1, Pair<C2, Pair<C3, Pair<C4, Pair<C5, C6>>>>>, R> function(Function6<C1, C2, C3, C4, C5, C6, R> function) {\n return params -> function.apply(params._1, params._2._1, params._2._2._1, params._2._2._2._1, params._2._2._2._2._1, params._2._2._2._2._2);\n }\n\n //\n // Interfaces\n //\n\n public interface Function2<A, B, R> {\n R apply(A a, B b);\n }\n\n public interface Function3<A, B, C, R> {\n R apply(A a, B b, C c);\n }\n\n public interface Function4<A, B, C, D, R> {\n R apply(A a, B b, C c, D d);\n }\n\n public interface Function5<A, B, C, D, E, R> {\n R apply(A a, B b, C c, D d, E e);\n }\n\n public interface Function6<A, B, C, D, E, F, R> {\n R apply(A a, B b, C c, D d, E e, F f);\n }\n}",
"static <T> Case.WithoutCapture<T, T> Constant(T value) {\n return new Case0<T, T>(p -> Objects.deepEquals(p, value) ? Optional.of(p) : Optional.empty()).$();\n}",
"static <T> Case.WithoutCapture<T, T> typeOf(Class<T> type) {\n return new Case0<T, T>(p -> p.getClass().isAssignableFrom(type) ? Optional.of(type.cast(p)) : Optional.empty()).$();\n}"
] | import org.smallibs.suitcase.cases.Case;
import org.smallibs.suitcase.cases.Result;
import org.smallibs.suitcase.utils.Functions;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import static org.smallibs.suitcase.cases.core.Cases.Constant;
import static org.smallibs.suitcase.cases.core.Cases.typeOf; | /*
* Copyright (C)2015 D. Plaindoux.
*
* This program 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, 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.smallibs.suitcase.match;
/**
* The Matcher defines a pattern matching rule set.
*
* @param <T> The matched object type
* @param <R> The matching result type
*/
public class Matcher<T, R> implements Case.WithoutCapture<T, R> {
/**
* The rule set
*/
private final List<Rule<?>> rules;
/**
* The constructor
*/
protected Matcher() {
this.rules = new LinkedList<>();
}
/**
* Factory
*
* @param <T> The matched object type
* @param <R> The matching result type
* @return a fresh pattern matching rule set
*/
public static <T, R> Matcher<T, R> create() {
return new Matcher<>();
}
/**
* Method called in order to create a new rule. The returns a When
* object able to capture a conditional or a termination.
*
* @param <C> The type of the capture
* @param object The pattern
* @return a
*/
public <C> WhenRuleWithoutCapture caseOf(WithoutCapture<? extends T, C> object) {
return new WhenRuleWithoutCapture<>(object);
}
/**
* Method called in order to create a new rule. The returns a When
* object able to capture a conditional or a termination.
*
* @param <C> The type of the capture
* @param object The pattern
* @return a
*/
public <C> WhenRuleWithCapture<C> caseOf(WithCapture<? extends T, C> object) {
return new WhenRuleWithCapture<>(object);
}
/**
* Method called in order to create a new rule. The returns a When
* object able to capture a conditional or a termination.
*
* @param <E> The class type to be matched
* @param object The pattern
* @return a
*/
public <E extends T> WhenRuleWithoutCapture<E> caseOf(Class<E> object) { | return new WhenRuleWithoutCapture<>(typeOf(object)); | 4 |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/ui/fragments/ManageSourcesFragment.java | [
"public class SourceItem {\n private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;\n private int sourceCategoryImgId;\n\n public int getSourceCategoryImgId() {\n return sourceCategoryImgId;\n }\n\n public void setSourceCategoryImgId(int sourceCategoryImgId) {\n this.sourceCategoryImgId = sourceCategoryImgId;\n }\n\n public String getSourceName() {\n return sourceName;\n }\n\n public void setSourceName(String sourceName) {\n this.sourceName = sourceName;\n }\n\n public String getSourceUrl() {\n return sourceUrl;\n }\n\n public void setSourceUrl(String sourceUrl) {\n this.sourceUrl = sourceUrl;\n }\n\n public String getSourceDateAdded() {\n return sourceDateAdded;\n }\n\n public void setSourceDateAdded(String sourceDateAdded) {\n this.sourceDateAdded = sourceDateAdded;\n }\n\n public String getSourceCategoryName() {\n return sourceCategoryName;\n }\n\n public void setSourceCategoryName(String sourceCategoryName) {\n this.sourceCategoryName = sourceCategoryName;\n }\n}",
"public interface ISourceView {\n void dataSourceSaved(String message);\n\n void dataSourceSaveFailed(String message);\n\n void dataSourceLoaded(List<String> sourceNames);\n\n void dataSourceItemsLoaded(List<SourceItem> sourceItems);\n\n void dataSourceLoadingFailed(String message);\n\n void sourceItemModified(SourceItem sourceItem, String oldName);\n\n void sourceItemModificationFailed(String message);\n\n void sourceItemDeleted(SourceItem sourceItem);\n\n void sourceItemDeletionFailed(String message);\n}",
"public class SourcesPresenter implements ISourcePresenter, OnSourceSavedListener, OnSourcesLoadedListener, OnSourcesModifyListener {\n\n private ISourceView mISourceView;\n private SourceInteractor mSourceInteractor;\n private EditText mETxtSourceName, mETxtSourceUrl;\n private TextView mTxtCategory;\n private ImageView mImgCategory;\n private FrameLayout mFrameCategory;\n\n public SourcesPresenter(ISourceView mISourceView, Context mContext) {\n this.mISourceView = mISourceView;\n this.mSourceInteractor = new SourceInteractor(mContext);\n }\n\n public void addSource(SourceItem sourceItem) {\n mSourceInteractor.addSourceToDb(this, sourceItem);\n }\n\n public void getSources() {\n mSourceInteractor.getSourcesFromDb(this);\n }\n\n public void getSourceItems() {\n mSourceInteractor.getSourceItemsFromDb(this);\n }\n\n public void modifySources(final Context context, final SourceItem sourceItem) {\n final MaterialDialog modifyDialog = new MaterialDialog.Builder(context)\n .title(R.string.modify_source)\n .customView(R.layout.dialog_modify_source, true)\n .positiveText(R.string.modify)\n .negativeText(R.string.cancel)\n .neutralText(R.string.delete)\n .onPositive(new MaterialDialog.SingleButtonCallback() {\n @Override\n public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {\n String sourceName = mETxtSourceName.getText().toString();\n String sourceUrl = mETxtSourceUrl.getText().toString();\n String sourceCategory = mTxtCategory.getText().toString();\n int sourceCategoryImgId = new Categories(context).getDrawableId(sourceCategory);\n\n SourceItem sourceItemNew = new SourceItem();\n sourceItemNew.setSourceName(sourceName);\n sourceItemNew.setSourceUrl(sourceUrl);\n sourceItemNew.setSourceCategoryName(sourceCategory);\n sourceItemNew.setSourceCategoryImgId(sourceCategoryImgId);\n\n mSourceInteractor.editSourceItemInDb(SourcesPresenter.this, sourceItemNew, sourceItem.getSourceName());\n }\n })\n .onNeutral(new MaterialDialog.SingleButtonCallback() {\n @Override\n public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {\n mSourceInteractor.deleteSourceItemFromDb(SourcesPresenter.this, sourceItem);\n }\n })\n .build();\n\n mETxtSourceName = (EditText) modifyDialog.getView().findViewById(R.id.edit_text_source_name);\n mETxtSourceUrl = (EditText) modifyDialog.getView().findViewById(R.id.edit_text_source_url);\n mFrameCategory = (FrameLayout) modifyDialog.getView().findViewById(R.id.frame_layout_category);\n mTxtCategory = (TextView) modifyDialog.getView().findViewById(R.id.text_view_category);\n mImgCategory = (ImageView) modifyDialog.getView().findViewById(R.id.image_view_category);\n\n mETxtSourceName.setText(sourceItem.getSourceName());\n mETxtSourceUrl.setText(sourceItem.getSourceUrl());\n mTxtCategory.setText(sourceItem.getSourceCategoryName());\n mImgCategory.setImageResource(new Categories(context).getDrawableId(sourceItem.getSourceCategoryName()));\n\n //add a white color filter to the images if dark theme is selected\n if (!SettingsPreferences.THEME) {\n mImgCategory.setColorFilter(ContextCompat.getColor(context, R.color.md_grey_100));\n }\n\n mFrameCategory.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n final List<CategoryItem> categoryItems = new Categories(context).getCategoryItems();\n\n final MaterialDialog categoryDialog = new MaterialDialog.Builder(context)\n .title(R.string.add_category)\n .adapter(new CategoryListAdapter(context, categoryItems),\n new MaterialDialog.ListCallback() {\n @Override\n public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {\n //Toast.makeText(HomeActivity.this, \"Clicked item \" + which, Toast.LENGTH_SHORT).show();\n mImgCategory.setImageDrawable(categoryItems.get(which).getCategoryImg());\n mTxtCategory.setText(categoryItems.get(which).getCategoryName());\n dialog.dismiss();\n }\n })\n .build();\n categoryDialog.show();\n }\n });\n\n modifyDialog.show();\n }\n\n public void deleteSource(SourceItem sourceItem) {\n mSourceInteractor.deleteSourceItemFromDb(SourcesPresenter.this, sourceItem);\n }\n\n @Override\n public void onSuccess(String message) {\n mISourceView.dataSourceSaved(message);\n\n }\n\n @Override\n public void onFailure(String message) {\n mISourceView.dataSourceSaveFailed(message);\n }\n\n @Override\n public void onSourceLoaded(List<String> sourceNames) {\n mISourceView.dataSourceLoaded(sourceNames);\n }\n\n @Override\n public void onSourceItemsLoaded(List<SourceItem> sourceItems) {\n mISourceView.dataSourceItemsLoaded(sourceItems);\n }\n\n @Override\n public void onSourceLoadingFailed(String message) {\n mISourceView.dataSourceLoadingFailed(message);\n }\n\n @Override\n public void onSourceModified(SourceItem sourceItem, String oldName) {\n mISourceView.sourceItemModified(sourceItem, oldName);\n }\n\n @Override\n public void onSourceModifiedFailed(String message) {\n mISourceView.sourceItemModificationFailed(message);\n }\n\n @Override\n public void onSourceDeleted(SourceItem sourceItem) {\n mISourceView.sourceItemDeleted(sourceItem);\n }\n\n @Override\n public void onSourceDeletionFailed(String message) {\n mISourceView.sourceItemDeletionFailed(message);\n }\n}",
"public class SourcesRecyclerViewAdapter extends RecyclerView.Adapter<SourcesRecyclerViewAdapter.SourcesViewHolder> {\n private Context mContext;\n private List<SourceItem> mSourceItems;\n private SourcesPresenter mSourcesPresenter;\n private int mLastPosition = -1;\n\n public SourcesRecyclerViewAdapter(Context mContext, List<SourceItem> mSourceItems) {\n this.mContext = mContext;\n this.mSourceItems = mSourceItems;\n }\n\n @Override\n public SourcesRecyclerViewAdapter.SourcesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.source_item, parent, false);\n SourcesViewHolder sourcesViewHolder = new SourcesViewHolder(view);\n return sourcesViewHolder;\n }\n\n @Override\n public void onBindViewHolder(SourcesRecyclerViewAdapter.SourcesViewHolder holder, int position) {\n holder.mTxtSource.setText(mSourceItems.get(position).getSourceName());\n holder.mTxtSourceUrl.setText(UrlUtil.getWebsiteName(mSourceItems.get(position).getSourceUrl()));\n holder.mTxtCategory.setText(mSourceItems.get(position).getSourceCategoryName());\n //holder.mImgCategory.setImageResource(mSourceItems.get(position).getSourceCategoryImgId());\n holder.mImgCategory.setImageResource(new Categories(mContext).getDrawableId(mSourceItems.get(position).getSourceCategoryName()));\n\n //add fading animation as the items start loading\n if (SettingsPreferences.SOURCES_RECYCLER_VIEW_ANIMATION) {\n setAnimation(holder.mItemView, position);\n }\n\n //set card background color and other things according to dark theme\n if (!SettingsPreferences.THEME) {\n holder.mCardSource.setCardBackgroundColor(ContextCompat.getColor(mContext, R.color.darkColorAccent));\n holder.mImgCategory.setColorFilter(ContextCompat.getColor(mContext, R.color.md_grey_300));\n } else {\n //looks ugly\n //holder.mCardSource.setCardBackgroundColor(ContextCompat.getColor(mContext, new ColorsUtil().getRandomColor()));\n }\n }\n\n private void setAnimation(View view, int position) {\n if (position > mLastPosition) {\n FadeAnimationUtil fadeAnimationUtil = new FadeAnimationUtil(mContext);\n fadeAnimationUtil.fadeInAlpha(view, 500);\n mLastPosition = position;\n }\n }\n\n //use to remove the sticky animation\n @Override\n public void onViewDetachedFromWindow(SourcesViewHolder holder) {\n super.onViewDetachedFromWindow(holder);\n holder.mItemView.clearAnimation();\n }\n\n @Override\n public int getItemCount() {\n return mSourceItems.size();\n }\n\n public int getSourceItemPosition(SourceItem sourceItem) {\n for (int i = 0; i < mSourceItems.size(); i++) {\n if (sourceItem.getSourceName().equals(mSourceItems.get(i).getSourceName())) {\n return i;\n }\n }\n return 0;\n }\n\n public void removeAt(int position) {\n mSourceItems.remove(position);\n notifyItemRemoved(position);\n notifyItemRangeChanged(position, mSourceItems.size());\n }\n\n public void modifyAt(int position, SourceItem sourceItem) {\n mSourceItems.set(position, sourceItem);\n notifyItemChanged(position);\n }\n\n public class SourcesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, ISourceView {\n private TextView mTxtSource;\n private TextView mTxtSourceUrl;\n private TextView mTxtCategory;\n private ImageView mImgCategory;\n private CardView mCardSource;\n private View mItemView;\n\n public SourcesViewHolder(View itemView) {\n super(itemView);\n mTxtSource = (TextView) itemView.findViewById(R.id.text_view_source);\n mTxtSourceUrl = (TextView) itemView.findViewById(R.id.text_view_source_url);\n mTxtCategory = (TextView) itemView.findViewById(R.id.text_view_category);\n mImgCategory = (ImageView) itemView.findViewById(R.id.image_view_category);\n mCardSource = (CardView) itemView.findViewById(R.id.card_view_source);\n mItemView = itemView;\n mCardSource.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View view) {\n if (mSourcesPresenter == null) {\n mSourcesPresenter = new SourcesPresenter(this, mContext);\n }\n mSourcesPresenter.modifySources(mContext, mSourceItems.get(getAdapterPosition()));\n }\n\n //No use\n @Override\n public void dataSourceSaved(String message) {\n\n }\n\n //No use\n @Override\n public void dataSourceSaveFailed(String message) {\n\n }\n\n //No use\n @Override\n public void dataSourceLoaded(List<String> sourceNames) {\n\n }\n\n //No use\n @Override\n public void dataSourceItemsLoaded(List<SourceItem> sourceItems) {\n\n }\n\n //No use\n @Override\n public void dataSourceLoadingFailed(String message) {\n\n }\n\n @Override\n public void sourceItemModified(SourceItem sourceItem, String oldName) {\n SourceItem sourceItemOld = new SourceItem();\n sourceItemOld.setSourceName(oldName);\n modifyAt(getSourceItemPosition(sourceItemOld), sourceItem);\n }\n\n @Override\n public void sourceItemModificationFailed(String message) {\n Toast.makeText(mContext, \"Error:\\n\" + message, Toast.LENGTH_SHORT).show();\n }\n\n @Override\n public void sourceItemDeleted(SourceItem sourceItem) {\n removeAt(getSourceItemPosition(sourceItem));\n }\n\n @Override\n public void sourceItemDeletionFailed(String message) {\n Toast.makeText(mContext, \"Error:\\n\" + message, Toast.LENGTH_SHORT).show();\n }\n }\n}",
"public class ItemDecorationUtil extends RecyclerView.ItemDecoration {\n private int mSpanCount;\n private int mSpacing;\n private boolean mIncludeEdge;\n\n public ItemDecorationUtil(int mSpanCount, int mSpacing, boolean mIncludeEdge) {\n this.mSpanCount = mSpanCount;\n this.mSpacing = mSpacing;\n this.mIncludeEdge = mIncludeEdge;\n }\n\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {\n int position = parent.getChildAdapterPosition(view); // item position\n int column = position % mSpanCount; // item column\n\n if (mIncludeEdge) {\n outRect.left = mSpacing - column * mSpacing / mSpanCount; // spacing - column * ((1f / spanCount) * spacing)\n outRect.right = (column + 1) * mSpacing / mSpanCount; // (column + 1) * ((1f / spanCount) * spacing)\n\n if (position < mSpanCount) { // top edge\n outRect.top = mSpacing;\n }\n outRect.bottom = mSpacing; // item bottom\n } else {\n outRect.left = column * mSpacing / mSpanCount; // column * ((1f / spanCount) * spacing)\n outRect.right = mSpacing - (column + 1) * mSpacing / mSpanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)\n if (position >= mSpanCount) {\n outRect.top = mSpacing; // item top\n }\n }\n }\n}"
] | import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.sources.ISourceView;
import com.crazyhitty.chdev.ks.munch.sources.SourcesPresenter;
import com.crazyhitty.chdev.ks.munch.ui.adapters.SourcesRecyclerViewAdapter;
import com.crazyhitty.chdev.ks.munch.utils.ItemDecorationUtil;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife; | package com.crazyhitty.chdev.ks.munch.ui.fragments;
/**
* Created by Kartik_ch on 12/6/2015.
*/
public class ManageSourcesFragment extends Fragment implements ISourceView {
@Bind(R.id.recycler_view_sources)
RecyclerView recyclerViewSources;
private SourcesRecyclerViewAdapter mSourcesRecyclerViewAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private SourcesPresenter mSourcesPresenter;
private RecyclerView.ItemDecoration mItemDecoration;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_manage_sources, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mSourcesPresenter == null) {
mSourcesPresenter = new SourcesPresenter(this, getActivity());
}
//mLayoutManager=new LinearLayoutManager(getActivity());
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerViewSources.setLayoutManager(mLayoutManager);
mItemDecoration = new ItemDecorationUtil(2, 8, false);
recyclerViewSources.addItemDecoration(mItemDecoration);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mSourcesPresenter.getSourceItems();
}
}, 500);
}
//no use
@Override
public void dataSourceSaved(String message) {
}
//no use
@Override
public void dataSourceSaveFailed(String message) {
}
//no use
@Override
public void dataSourceLoaded(List<String> sourceNames) {
}
@Override | public void dataSourceItemsLoaded(List<SourceItem> sourceItems) { | 0 |
iChun/Hats | src/main/java/me/ichun/mods/hats/client/gui/window/WindowAllHats.java | [
"public class WorkspaceHats extends Workspace\n implements IHatSetter\n{\n public static final DecimalFormat FORMATTER = new DecimalFormat(\"#,###,###\");\n\n public final boolean fallback;\n public final @Nonnull LivingEntity hatEntity;\n public final HatsSavedData.HatPart hatDetails;\n public final ItemStack hatLauncher;\n\n public int age;\n\n public WindowInputReceiver windowInput;\n public WindowHatsList windowHatsList;\n public WindowSidebar windowSidebar;\n\n public ArrayList<HatsSavedData.HatPart> changedHats = new ArrayList<>();\n\n public WorkspaceHats(Screen lastScreen, boolean fallback, @Nonnull LivingEntity hatEntity, @Nullable ItemStack hatLauncher)\n {\n super(lastScreen, new TranslationTextComponent(\"hats.gui.selection.title\"), Hats.configClient.guiMinecraftStyle);\n windows.add(windowInput = new WindowInputReceiver(this));\n\n this.fallback = fallback || hatEntity != Minecraft.getInstance().player || hatLauncher != null;\n this.hatEntity = hatEntity;\n this.hatLauncher = hatLauncher;\n\n if(hatLauncher != null)\n {\n this.hatDetails = HatHandler.getHatPart(hatLauncher).createCopy();\n }\n else\n {\n this.hatDetails = HatHandler.getHatPart(hatEntity).createCopy();\n }\n\n addWindow(windowHatsList = new WindowHatsList(this));\n addWindow(windowSidebar = new WindowSidebar(this));\n }\n\n @Override\n protected void init()\n {\n int padding = 10;\n windowHatsList.constraints().right(this, Constraint.Property.Type.RIGHT, padding + 22).top(this, Constraint.Property.Type.TOP, padding).bottom(this, Constraint.Property.Type.BOTTOM, padding);\n windowHatsList.setWidth((int)Math.floor((getWidth() / 2F)) - (padding + 22));\n windowHatsList.constraint.apply();\n\n //space from the list = 2 px\n windowSidebar.constraints().left(windowHatsList, Constraint.Property.Type.RIGHT, 2).top(windowHatsList, Constraint.Property.Type.TOP, 0).bottom(windowHatsList, Constraint.Property.Type.BOTTOM, 0);\n windowSidebar.setWidth(20);\n windowSidebar.constraint.apply();\n\n super.init();\n }\n\n @Override\n public void resize(Minecraft mc, int width, int height)\n {\n int padding = 10;\n windowHatsList.setWidth((int)Math.floor((width / 2F)) - (padding + 22));\n super.resize(mc, width, height);\n windowSidebar.resize(mc, width, height);\n }\n\n @Override\n public void renderWindows(MatrixStack stack, int mouseX, int mouseY, float partialTick)\n {\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n\n RenderHelper.setupGuiFlatDiffuseLighting();\n\n boolean invisibleEnt = hatEntity.isInvisible();\n if(invisibleEnt)\n {\n hatEntity.setInvisible(false);\n }\n if(fallback)\n {\n RenderSystem.enableDepthTest();\n RenderSystem.depthMask(true);\n\n RenderSystem.pushMatrix();\n\n float zoom = (windowInput.camDist * 40);\n int x = (int)((windowHatsList.getLeft() / 2F) - windowInput.x * 40);\n int y = (int)((getHeight() / 4 * 3F + windowInput.y * 40) + (hatEntity.getHeight() / 2) * 50F - zoom);\n if(hatLauncher != null)\n {\n stack.push();\n\n y = (int)((getHeight() / 2F + windowInput.y * 40) - zoom);\n\n stack.translate(x, y, 0F);\n\n float scale = -160F;\n stack.translate(0F, 0F, 200F);\n stack.scale(scale, scale, scale);\n stack.rotate(Vector3f.YP.rotationDegrees((iChunUtil.eventHandlerClient.ticks + partialTick + (windowInput.driftYaw * 2)) * 0.5F));\n\n IRenderTypeBuffer.Impl bufferSource = minecraft.getRenderTypeBuffers().getBufferSource();\n minecraft.getItemRenderer().renderItem(hatLauncher, ItemCameraTransforms.TransformType.GUI, 0xF000F0, OverlayTexture.NO_OVERLAY, stack, bufferSource);\n\n bufferSource.finish();\n stack.pop();\n }\n else\n {\n RenderSystem.translatef(0F, 0F, 200F);\n InventoryScreen.drawEntityOnScreen(x, y, Math.max(80 - (int)(hatEntity.getWidth() * 20 + zoom), 10), x - mouseX, (getHeight() / 2F) - mouseY, hatEntity);\n }\n RenderSystem.popMatrix();\n\n RenderSystem.depthMask(false);\n RenderSystem.disableDepthTest();\n }\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n\n RenderSystem.pushMatrix();\n super.renderWindows(stack, mouseX, mouseY, partialTick);\n RenderSystem.popMatrix();\n\n if(invisibleEnt)\n {\n hatEntity.setInvisible(true);\n }\n }\n\n public boolean usePlayerInventory()\n {\n return HatHandler.useInventory(Minecraft.getInstance().player);\n }\n\n public ArrayList<HatsSavedData.HatPart> getHatPartSource() //Also used in the Hat render\n {\n ArrayList<HatsSavedData.HatPart> source = HatHandler.getHatSource(Minecraft.getInstance().player);\n HatResourceHandler.combineLists(source, changedHats);\n return source;\n }\n\n @Override\n public boolean canDockWindows()\n {\n return false;\n }\n\n @Override\n public boolean mouseDragged(double mouseX, double mouseY, int button, double distX, double distY)\n {\n return (this.getListener() != null && this.isDragging()) && this.getListener().mouseDragged(mouseX, mouseY, button, distX, distY);\n }\n\n public void addWindowWithHalfGreyout(Window<?> window)\n {\n WindowHalfGreyout greyout = new WindowHalfGreyout(this, window);\n addWindow(greyout);\n greyout.init();\n\n addWindow(window);\n }\n\n @Override\n public void renderBackground(MatrixStack stack)\n {\n if(fallback)\n {\n this.renderBackground(stack, 0);\n }\n else\n {\n //taken from AbstractGui.fillGradient\n RenderSystem.disableTexture();\n RenderSystem.enableBlend();\n RenderSystem.disableAlphaTest();\n RenderSystem.defaultBlendFunc();\n RenderSystem.shadeModel(7425);\n Tessellator tessellator = Tessellator.getInstance();\n Matrix4f matrix = stack.getLast().getMatrix();\n BufferBuilder builder = tessellator.getBuffer();\n builder.begin(7, DefaultVertexFormats.POSITION_COLOR);\n //draw the original bits\n int z = getBlitOffset();\n fillGradient(matrix, builder, windowHatsList.getRight() - (int)(windowHatsList.getWidth() / 2F), 0, width, height, z, 0xc0101010, 0xd0101010);\n\n float x1 = windowHatsList.getLeft() - 20;\n float x2 = windowHatsList.getRight() - (int)(windowHatsList.getWidth() / 2F);\n float y1 = 0;\n float y2 = height;\n\n int colorA = 0xc0101010;\n int colorB = 0xd0101010;\n float f = (float)(colorA >> 24 & 255) / 255.0F;\n float f1 = (float)(colorA >> 16 & 255) / 255.0F;\n float f2 = (float)(colorA >> 8 & 255) / 255.0F;\n float f3 = (float)(colorA & 255) / 255.0F;\n float f4 = (float)(colorB >> 24 & 255) / 255.0F;\n float f5 = (float)(colorB >> 16 & 255) / 255.0F;\n float f6 = (float)(colorB >> 8 & 255) / 255.0F;\n float f7 = (float)(colorB & 255) / 255.0F;\n builder.pos(matrix, x2, y1, (float)z).color(f1, f2, f3, f).endVertex();\n builder.pos(matrix, x1, y1, (float)z).color(f1, f2, f3, 0).endVertex();\n builder.pos(matrix, x1, y2, (float)z).color(f5, f6, f7, 0).endVertex();\n builder.pos(matrix, x2, y2, (float)z).color(f5, f6, f7, f4).endVertex();\n\n tessellator.draw();\n RenderSystem.shadeModel(7424);\n RenderSystem.enableAlphaTest();\n RenderSystem.enableTexture();\n }\n\n RenderSystem.pushMatrix();\n\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n }\n\n @Override\n public void resetBackground()\n {\n RenderSystem.popMatrix();\n }\n\n @Override\n public void render(MatrixStack stack, int mouseX, int mouseY, float partialTick)\n {\n super.render(stack, mouseX, mouseY, partialTick);\n\n if(!fallback && Hats.configClient.forceRenderToasts && minecraft.gameSettings.hideGUI)\n {\n minecraft.gameSettings.hideGUI = false;\n minecraft.getToastGui().func_238541_a_(new MatrixStack());\n minecraft.gameSettings.hideGUI = true;\n }\n }\n\n @Override\n public void tick()\n {\n super.tick();\n\n age++;\n\n if(age == Hats.configClient.guiAnimationTime + 21 && !Hats.configClient.shownTutorial && hatLauncher == null)\n {\n openWindowInCenter(new WindowConfirmation(this, renderMinecraftStyle() == 0 ? \"window.popup.title\" : \"\", I18n.format(\"hats.gui.tutorial.intro\"), w -> startTutorial(), w -> cancelTutorial()){\n @Override\n public void render(MatrixStack stack, int mouseX, int mouseY, float partialTick)\n {\n stack.push();\n stack.translate(0F, 0F, 375F); //silly ElementHatRender\n\n super.render(stack, mouseX, mouseY, partialTick);\n\n stack.pop();\n }\n }, 0.55D, 0.4D, true);\n }\n }\n\n @Override\n public void onClose()\n {\n super.onClose();\n\n if(Hats.eventHandlerClient.serverHasMod)\n {\n //Send to the server our customisations, and our new hat if we hit confirmed\n if(hatLauncher != null)\n {\n Hats.channel.sendToServer(new PacketHatLauncherCustomisation(HatHandler.getHatPart(hatLauncher)));\n\n }\n //Send the details of what we changed to the server. Server end only copies the customisation, not the count as well.\n //Don't send the new hat that we selected to the server if we're editing the item.\n Hats.channel.sendToServer(new PacketHatCustomisation(changedHats, true, hatLauncher == null ? HatHandler.getHatPart(hatEntity) : new HatsSavedData.HatPart()));\n\n //Update our inventory with what has been changed\n for(HatsSavedData.HatPart hatPart : Hats.eventHandlerClient.hatsInventory.hatParts)\n {\n for(int i = changedHats.size() - 1; i >= 0; i--)\n {\n HatsSavedData.HatPart changedHat = changedHats.get(i);\n if(hatPart.copyPersonalisation(changedHat))\n {\n changedHats.remove(i);\n }\n }\n }\n\n //If we somehow modified hats we don't own\n for(HatsSavedData.HatPart customisedHat : changedHats) //these are hats we don't own.\n {\n HatsSavedData.HatPart copy = customisedHat.createCopy();\n copy.setCountOfAllTo(0);\n Hats.eventHandlerClient.hatsInventory.hatParts.add(copy);\n }\n }\n\n changedHats.clear();\n }\n\n public void notifyChanged(@Nonnull HatsSavedData.HatPart part)\n {\n boolean found = false;\n for(int i = changedHats.size() - 1; i >= 0; i--)\n {\n if(changedHats.get(i).name.equals(part.name))\n {\n found = true;\n changedHats.remove(i);\n changedHats.add(i, part);\n break;\n }\n }\n\n if(!found)\n {\n changedHats.add(part);\n }\n }\n\n public void setNewHat(@Nullable HatsSavedData.HatPart newHat, boolean notify)\n {\n if(newHat == null)\n {\n if(hatLauncher != null)\n {\n HatHandler.setHatPart(hatLauncher, new HatsSavedData.HatPart());\n }\n else\n {\n HatHandler.assignSpecificHat(hatEntity, null); //remove the current hat\n }\n\n for(Element<?> element : windowHatsList.getCurrentView().list.elements)\n {\n if(element instanceof ElementHatRender)\n {\n ((ElementHatRender<?>)element).toggleState = false; //Deselect all the hat clicky thingimagigs\n }\n }\n }\n else\n {\n if(notify)\n {\n notifyChanged(newHat);\n }\n\n if(hatLauncher != null)\n {\n HatHandler.setHatPart(hatLauncher, newHat);\n }\n else\n {\n HatHandler.assignSpecificHat(hatEntity, newHat); //remove the current hat\n }\n }\n\n onNewHatSet(newHat);\n }\n\n public void popup(double widthRatio, double heightRatio, Consumer<Workspace> callback, String...text)\n {\n openWindowInCenter(new WindowPopup(this, renderMinecraftStyle() == 0 ? \"window.popup.title\" : \"\", callback, text) {\n @Override\n public void render(MatrixStack stack, int mouseX, int mouseY, float partialTick)\n {\n stack.push();\n stack.translate(0F, 0F, 375F); //silly ElementHatRender\n\n super.render(stack, mouseX, mouseY, partialTick);\n\n stack.pop();\n }\n }, widthRatio, heightRatio, true);\n }\n\n public void refreshHats()\n {\n onNewHatSet(hatLauncher != null ? HatHandler.getHatPart(hatLauncher) : HatHandler.getHatPart(hatEntity));\n\n windowHatsList.getCurrentView().updateSearch(windowHatsList.getCurrentView().textField.getText());\n\n resize(getMinecraft(), width, height);\n }\n\n public void startTutorial()\n {\n TutorialHandler.startTutorial(this);\n }\n\n public void cancelTutorial()\n {\n Element btn = windowSidebar.getCurrentView().getById(\"btnResourceManagement\");\n if(btn != null)\n {\n WindowTutorial dragTut = new WindowTutorial(this, WindowTutorial.Direction.RIGHT, btn.getLeft(), btn.getTop() + (btn.getHeight() / 2), (int)(this.windowHatsList.getLeft() * 0.8F), 150, w7 -> {\n finishTutorial();\n }, I18n.format(\"hats.gui.tutorial.skip\"));\n addWindowWithGreyout(dragTut);\n dragTut.init();\n }\n else\n {\n popup(0.6D, 0.4D, w1 -> finishTutorial(), I18n.format(\"hats.gui.tutorial.skip\"));\n }\n }\n\n public void finishTutorial()\n {\n Hats.configClient.shownTutorial = true;\n Hats.configClient.save();\n }\n}",
"public class ElementHatRender<T extends ElementHatRender> extends ElementClickable<T>\n{\n public static final String HAMBURGER = \"\\u2261\";//\"≡\";\n\n public HatsSavedData.HatPart hatOrigin;\n public HatsSavedData.HatPart hatLevel;\n public boolean toggleState;\n\n public boolean hasConflict;\n public boolean isViewAllHats;\n\n public ElementHatRender(@Nonnull Fragment parent, HatsSavedData.HatPart hatOrigin, HatsSavedData.HatPart hatLevel, Consumer<T> callback, boolean isViewAllHats)\n {\n super(parent, callback);\n this.hatOrigin = hatOrigin;\n this.hatLevel = hatLevel;\n this.isViewAllHats = isViewAllHats;\n\n if(((WorkspaceHats)parent.getWorkspace()).usePlayerInventory() && this.hatLevel.count <= 0 && !isViewAllHats)\n {\n this.disabled = true;\n }\n\n }\n\n public ElementHatRender(@Nonnull Fragment parent, HatsSavedData.HatPart hatOrigin, HatsSavedData.HatPart hatLevel, Consumer<T> callback)\n {\n this(parent, hatOrigin, hatLevel, callback, false);\n }\n\n public <T extends ElementHatRender<?>> T setToggled(boolean flag)\n {\n toggleState = flag;\n return (T)this;\n }\n\n @Override\n public boolean mouseReleased(double mouseX, double mouseY, int button) //we extended ElementRightClickable but we're not really much of that anymore\n {\n // boolean flag = super.mouseReleased(mouseX, mouseY, button); // unsets dragging;\n //copied out mouseReleased so we don't call ElementClickable's\n this.setDragging(false);\n boolean flag = getListener() != null && getListener().mouseReleased(mouseX, mouseY, button);\n\n parentFragment.setListener(null); //we're a one time click, stop focusing on us\n if(!(disabled || hasConflict) && isMouseOver(mouseX, mouseY))\n {\n if(button == 0 || button == 1)\n {\n trigger();\n if(button == 1 || isOverHamburger(mouseX, mouseY))\n {\n spawnOptionsButtons();\n }\n }\n }\n return flag;\n }\n\n public boolean isOverHamburger(double mouseX, double mouseY)\n {\n return isMouseBetween(mouseX, getLeft(), getLeft() + 3 + getFontRenderer().getStringWidth(HAMBURGER) + 2) && isMouseBetween(mouseY, getTop(), getTop() + getFontRenderer().FONT_HEIGHT + 2) && !(disabled || hasConflict);\n }\n\n public void spawnOptionsButtons()\n {\n if(Screen.hasControlDown() && this.hatLevel.hasUnlockedAccessory())\n {\n WindowHatOptions.ViewHatOptions.openPersonalizer((WorkspaceHats)getWorkspace(), this);\n }\n else if(Screen.hasShiftDown())\n {\n WindowHatOptions.ViewHatOptions.openColouriser((WorkspaceHats)getWorkspace(), this);\n }\n else\n {\n //Spawn the window and set focus to it.\n WindowHatOptions windowHatOptions = new WindowHatOptions((WorkspaceHats)getWorkspace(), this);\n windowHatOptions.setPosX(getLeft() - 21);\n windowHatOptions.setPosY(getTop());\n windowHatOptions.setWidth(21);\n windowHatOptions.setHeight(getHeight());\n if(windowHatOptions.getWorkspace().hasInit())\n {\n windowHatOptions.init();\n }\n windowHatOptions.getWorkspace().addWindow(windowHatOptions);\n windowHatOptions.getWorkspace().setListener(windowHatOptions);\n }\n }\n\n @Override\n public void onClickRelease()\n {\n if(!toggleState)\n {\n toggleState = true;\n }\n }\n\n @Override\n public void render(MatrixStack stack, int mouseX, int mouseY, float partialTick)\n {\n RenderSystem.enableAlphaTest();\n RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);\n\n super.render(stack, mouseX, mouseY, partialTick);\n if(renderMinecraftStyle() > 0)\n {\n renderMinecraftStyleButton(stack, getLeft(), getTop(), width, height, (disabled || hasConflict) || parentFragment.isDragging() && parentFragment.getListener() == this || toggleState ? ButtonState.CLICK : hover ? ButtonState.HOVER : ButtonState.IDLE, renderMinecraftStyle());\n }\n else\n {\n fill(stack, getTheme().elementButtonBorder, 0);\n int[] colour;\n if((disabled || hasConflict))\n {\n colour = getTheme().elementButtonBackgroundInactive;\n }\n else if(parentFragment.isDragging() && parentFragment.getListener() == this)\n {\n colour = getTheme().elementButtonClick;\n }\n else if(toggleState && hover)\n {\n colour = getTheme().elementButtonToggleHover;\n }\n else if(hover)\n {\n colour = getTheme().elementButtonBackgroundHover;\n }\n else if(toggleState)\n {\n colour = getTheme().elementButtonToggle;\n }\n else\n {\n colour = getTheme().elementButtonBackgroundInactive;\n }\n fill(stack, colour, 1);\n }\n\n int top = Math.max(getTop() + 1, parentFragment.getTop());\n int bottom = Math.min(getBottom() - 1, parentFragment.getBottom());\n\n HatsSavedData.HatPart partForRender = hatOrigin.createCopy().setNoNew().setNoFavourite().setModifier(hatLevel);\n\n if(bottom - top > 0)\n {\n int oriRenderCount = Hats.eventHandlerClient.renderCount;\n Hats.eventHandlerClient.renderCount = -1;\n\n RenderSystem.enableDepthTest();\n RenderSystem.depthMask(true);\n\n setScissor();\n\n RenderSystem.pushMatrix();\n RenderSystem.translatef(0F, 0F, 300F);\n\n LivingEntity livingEnt = ((WorkspaceHats)getWorkspace()).hatEntity;\n\n HatsSavedData.HatPart originalHat = HatHandler.getHatPart(livingEnt).createCopy();\n\n HatHandler.assignSpecificHat(livingEnt, partForRender);\n\n boolean isCrouching = false;\n ItemStack helm = livingEnt.getItemStackFromSlot(EquipmentSlotType.HEAD);\n ItemStack chest = livingEnt.getItemStackFromSlot(EquipmentSlotType.CHEST);\n if(Hats.configClient.invisibleEntityInHatSelector || ((WorkspaceHats)getWorkspace()).hatLauncher != null)\n {\n Hats.eventHandlerClient.forceRenderWhenInvisible = true;\n livingEnt.setInvisible(true);\n if(((WorkspaceHats)getWorkspace()).hatLauncher != null)\n {\n ((PlayerEntity)livingEnt).inventory.armorInventory.set(EquipmentSlotType.HEAD.getIndex(), ItemStack.EMPTY);\n ((PlayerEntity)livingEnt).inventory.armorInventory.set(EquipmentSlotType.CHEST.getIndex(), ItemStack.EMPTY);\n }\n if(livingEnt instanceof ClientPlayerEntity)\n {\n isCrouching = ((ClientPlayerEntity)livingEnt).isCrouching;\n ((ClientPlayerEntity)livingEnt).isCrouching = false;\n }\n }\n\n InventoryScreen.drawEntityOnScreen(getLeft() + (getWidth() / 2), (int)(getBottom() + livingEnt.getEyeHeight() * 32F), Math.max(50 - (int)(livingEnt.getWidth() * 10), 10), 20, -10, livingEnt);\n\n if(Hats.configClient.invisibleEntityInHatSelector || ((WorkspaceHats)getWorkspace()).hatLauncher != null)\n {\n Hats.eventHandlerClient.forceRenderWhenInvisible = false;\n livingEnt.setInvisible(false);\n if(((WorkspaceHats)getWorkspace()).hatLauncher != null)\n {\n ((PlayerEntity)livingEnt).inventory.armorInventory.set(EquipmentSlotType.HEAD.getIndex(), helm);\n ((PlayerEntity)livingEnt).inventory.armorInventory.set(EquipmentSlotType.CHEST.getIndex(), chest);\n }\n if(livingEnt instanceof ClientPlayerEntity)\n {\n ((ClientPlayerEntity)livingEnt).isCrouching = isCrouching;\n }\n }\n\n HatHandler.assignSpecificHat(livingEnt, originalHat);\n\n RenderSystem.popMatrix();\n\n resetScissorToParent();\n\n RenderSystem.depthMask(false);\n RenderSystem.disableDepthTest();\n\n Hats.eventHandlerClient.renderCount = oriRenderCount;\n }\n\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n\n if(hasConflict)\n {\n RenderHelper.drawColour(stack, 255, 0, 0, 30, getLeft() + 1, getTop() + 1, width - 2, height - 2, 0);\n }\n\n if(!isViewAllHats && ((WorkspaceHats)getWorkspace()).usePlayerInventory() && hatLevel.count <= 0 || isViewAllHats && hatLevel.count <= 0 && hatLevel.hsbiser[2] == 1F)\n {\n RenderHelper.drawColour(stack, 0, 0, 0, 120, getLeft() + 1, getTop() + 1, width - 2, height - 2, 0); //greyout\n }\n\n if(!Hats.configClient.disableHatNameRenderInHatSelector)\n {\n RenderHelper.drawColour(stack, 0, 0, 0, 150, getRight() - 10, getTop() + 1, 9, height - 2, 0);\n }\n\n HatInfo info = HatResourceHandler.getInfo(partForRender);\n String hatName = info != null ? info.getDisplayNameFor(hatLevel.name) : \"\";\n\n int topDist = height - 6;\n if(parentFragment instanceof ElementHatsScrollView && !isViewAllHats)\n {\n int renderIconX = getRight() - 9;\n if(partForRender.hasFavourite())\n {\n topDist = height - 14;\n\n if(!hatLevel.isFavourite)\n {\n RenderHelper.colour(0x00ffff);\n }\n RenderHelper.drawTexture(stack, WindowHatOptions.ViewHatOptions.TEX_FAVOURITE, renderIconX, getTop() + 2, 7, 7, 0);\n RenderHelper.colour(0xffffff); //reset the colour\n\n renderIconX -= 10;\n }\n if(partForRender.hasNew())\n {\n topDist = height - 14;\n\n stack.push();\n\n stack.translate(0F, 0F, 375F);\n\n getFontRenderer().drawString(stack, \"!\", renderIconX + 3, getTop() + 2, renderMinecraftStyle() > 0 ? 16777120 : Theme.getAsHex(getTheme().font));\n\n stack.pop();\n }\n }\n\n float scale = 0.5F;\n\n if(!Hats.configClient.disableHatNameRenderInHatSelector)\n {\n String s = reString(hatName, (int)((topDist) / scale));\n\n stack.push();\n stack.translate(getRight() - 5, getTop() + (height * scale), 0F);\n stack.rotate(Vector3f.ZP.rotationDegrees(-90F));\n stack.translate(-(height * scale) + 3, -(getFontRenderer().FONT_HEIGHT) * scale + 2, 375F);\n stack.scale(scale, scale, scale);\n\n //draw the text\n getFontRenderer().drawString(stack, s, 0, 0, renderMinecraftStyle() > 0 ? getMinecraftFontColour() : Theme.getAsHex(toggleState ? getTheme().font : getTheme().fontDim));\n\n stack.pop();\n }\n\n if(!isViewAllHats)\n {\n if(((WorkspaceHats)getWorkspace()).usePlayerInventory())\n {\n String s = \"x\" + WorkspaceHats.FORMATTER.format(hatLevel.count); // we count from the level\n\n stack.push();\n stack.translate(getLeft() + 3, getBottom() - (getFontRenderer().FONT_HEIGHT) * scale - 1, 375F);\n stack.scale(scale, scale, scale);\n\n //draw the text\n int clr = renderMinecraftStyle() > 0 ? getMinecraftFontColour() : Theme.getAsHex(toggleState ? getTheme().font : getTheme().fontDim);\n if(hatLevel.count <= 0)\n {\n clr = 0xaa0000;\n }\n getFontRenderer().drawString(stack, s, 0, 0, clr);\n\n stack.pop();\n }\n\n if(parentFragment instanceof ElementHatsScrollView && !(disabled || hasConflict))\n {\n if(hover) //only if we're hovering\n {\n stack.push();\n\n stack.translate(0F, 0F, 375F);\n\n boolean isHoveringHamburger = isOverHamburger(mouseX, mouseY);\n\n getFontRenderer().drawString(stack, HAMBURGER, getLeft() + 3, getTop() + 2, renderMinecraftStyle() > 0 ? isHoveringHamburger ? 16777120 : 14737632 : Theme.getAsHex(isHoveringHamburger ? getTheme().font : getTheme().fontDim));\n\n stack.pop();\n }\n else if(hatLevel.hasUnlockedAccessory())\n {\n stack.push();\n\n stack.translate(0F, 0F, 375F);\n\n getFontRenderer().drawString(stack, \"+\", getLeft() + 3, getTop() + 2, renderMinecraftStyle() > 0 ? 14737632 : Theme.getAsHex(getTheme().fontDim));\n\n stack.pop();\n }\n }\n }\n }\n\n @Nullable\n @Override\n public String tooltip(double mouseX, double mouseY)\n {\n HatsSavedData.HatPart partForRender = hatOrigin.createCopy().setNoNew().setNoFavourite().setModifier(hatLevel);\n HatInfo info = HatResourceHandler.getInfo(partForRender);\n if(info != null)\n {\n HatInfo accessoryInfo = info.getInfoFor(hatLevel.name);\n if(accessoryInfo != null)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(accessoryInfo.getDisplayName()).append(\"\\n\");\n if(!accessoryInfo.project.author.isEmpty())\n {\n sb.append(I18n.format(\"hats.gui.tooltip.author\", accessoryInfo.project.author)).append(\"\\n\");\n }\n sb.append(I18n.format(\"hats.gui.tooltip.rarity\", accessoryInfo.getRarity().getColour().toString() + accessoryInfo.getRarity().toString())).append(\"\\n\");\n if(hatLevel.count == 0 && hatLevel.hsbiser[2] == 1F)\n {\n sb.append(I18n.format(\"hats.gui.tooltip.notUnlocked\")).append(\"\\n\");\n }\n sb.append(\"\\n\");\n if(accessoryInfo.description != null)\n {\n sb.append(accessoryInfo.description).append(\"\\n\").append(\"\\n\");\n }\n if(Hats.eventHandlerClient.serverHasMod)\n {\n sb.append(I18n.format(\"hats.gui.tooltip.worth\", info.getWorthFor(accessoryInfo.name, 0)));\n }\n\n return sb.toString();\n }\n }\n\n return super.tooltip(mouseX, mouseY);\n }\n\n @Override\n public void setScissor()\n {\n if(parentFragment instanceof ElementHatsScrollView)\n {\n int top = Math.max(getTop() + 1, parentFragment.getTop());\n int bottom = Math.min(getBottom() - 1, parentFragment.getBottom());\n RenderHelper.startGlScissor(getLeft() + 1, top, width - 2, bottom - top);\n }\n else\n {\n RenderHelper.startGlScissor(getLeft() + 1, getTop() + 1, width - 2, height - 2);\n }\n }\n\n @Override\n public boolean requireScissor()\n {\n return true;\n }\n\n @Override\n public int getMinWidth()\n {\n return 50;\n }\n\n @Override\n public int getMinHeight()\n {\n return 70;\n }\n}",
"public class ElementHatsScrollView extends ElementFertile\n{\n public List<Element<?>> elements = new ArrayList<>();\n private @Nullable ElementScrollBar<?> scrollVert;\n\n public boolean hasInit;\n\n public ElementHatsScrollView(@Nonnull Fragment parent)\n {\n super(parent);\n }\n\n public <T extends ElementHatsScrollView> T setScrollVertical(ElementScrollBar<?> scroll)\n {\n scrollVert = scroll;\n scrollVert.setCallback((scr) -> alignItems());\n return (T)this;\n }\n\n public Element<?> addElement(Element<?> e)\n {\n elements.add(e);\n\n if(hasInit)\n {\n scrollToSelectedElement();\n alignItems();\n updateScrollBarSizes();\n }\n return e;\n }\n\n @Override\n public void init()\n {\n super.init();\n hasInit = true;\n scrollToSelectedElement();\n alignItems();\n updateScrollBarSizes();\n }\n\n @Override\n public void resize(Minecraft mc, int width, int height)\n {\n super.resize(mc, width, height);//code is here twice to fix resizing when init\n scrollToSelectedElement();\n alignItems();\n super.resize(mc, width, height);\n scrollToSelectedElement();\n alignItems();\n updateScrollBarSizes();\n }\n\n @Override\n public void render(MatrixStack stack, int mouseX, int mouseY, float partialTick)\n {\n if(renderMinecraftStyle() > 0)\n {\n bindTexture(resourceHorse());\n cropAndStitch(stack, getLeft() - 1, getTop() - 1, width + 2, height + 2, 2, 79, 17, 90, 54, 256, 256);\n }\n else\n {\n RenderHelper.drawColour(stack, getTheme().elementTreeBorder[0], getTheme().elementTreeBorder[1], getTheme().elementTreeBorder[2], 255, getLeft() - 1, getTop() - 1, width + 2, 1, 0); //top\n RenderHelper.drawColour(stack, getTheme().elementTreeBorder[0], getTheme().elementTreeBorder[1], getTheme().elementTreeBorder[2], 255, getLeft() - 1, getTop() - 1, 1, height + 2, 0); //left\n RenderHelper.drawColour(stack, getTheme().elementTreeBorder[0], getTheme().elementTreeBorder[1], getTheme().elementTreeBorder[2], 255, getLeft() - 1, getBottom(), width + 2, 1, 0); //bottom\n RenderHelper.drawColour(stack, getTheme().elementTreeBorder[0], getTheme().elementTreeBorder[1], getTheme().elementTreeBorder[2], 255, getRight(), getTop() - 1, 1, height + 2, 0); //right\n }\n\n setScissor();\n elements.forEach(item -> {\n if(item.getBottom() >= getTop() && item.getTop() < getBottom())\n {\n item.render(stack, mouseX, mouseY, partialTick);\n }\n });\n resetScissorToParent();\n }\n\n @Override\n public boolean mouseScrolled(double mouseX, double mouseY, double dist)\n {\n if(isMouseOver(mouseX, mouseY))\n {\n boolean defaultScroll = super.mouseScrolled(mouseX, mouseY, dist);\n if(defaultScroll)\n {\n return true;\n }\n else\n {\n if(scrollVert != null)\n {\n scrollVert.secondHandScroll((dist * 70 / getTotalItemHeight()) * 2D);\n return true;\n }\n }\n }\n return false;\n }\n\n public int getTotalItemHeight()\n {\n //calculate the total item width/height\n int padding = 3;\n int useableWidth = getWidth() - padding;\n int maxPerRow = (int)Math.floor(useableWidth / 50F); //this max hat renders we can have a row. 50 = min hat render width\n if(maxPerRow > elements.size())\n {\n maxPerRow = elements.size();\n }\n int rowCount = (int)Math.ceil(elements.size() / (float)maxPerRow);\n return (70 + padding) * rowCount + padding; //70 = min hat render height\n }\n\n public void scrollToSelectedElement()\n {\n if(scrollVert != null)\n {\n //MATCH getTotalItemHeight()\n int padding = 3;\n int useableWidth = getWidth() - padding;\n int maxPerRow = (int)Math.floor(useableWidth / 50F); //this max hat renders we can have a row. 50 = min hat render width\n if(maxPerRow > elements.size())\n {\n maxPerRow = elements.size();\n }\n int rowCount = (int)Math.ceil(elements.size() / (float)maxPerRow);\n int totalItemHeight = (70 + padding) * rowCount + padding; //70 = min hat render height\n\n for(int i = 0; i < elements.size(); i++)\n {\n ElementHatRender<?> hatRender = ((ElementHatRender<?>)elements.get(i));\n if(hatRender.toggleState)\n {\n int thisRow = (int)Math.floor(i / (float)maxPerRow);\n\n scrollVert.setScrollProg(((70 + padding) * thisRow) / (float)Math.max(0.1, totalItemHeight - height));\n break;\n }\n }\n }\n }\n\n public void alignItems()\n {\n //MATCH getTotalItemHeight()\n int padding = 3;\n int useableWidth = getWidth() - padding;\n int maxPerRow = (int)Math.floor(useableWidth / 50F); //this max hat renders we can have a row. 50 = min hat render width\n if(maxPerRow > elements.size())\n {\n maxPerRow = elements.size();\n }\n int rowCount = (int)Math.ceil(elements.size() / (float)maxPerRow);\n int totalItemHeight = (70 + padding) * rowCount + padding; //70 = min hat render height\n\n int offsetY = 0;\n if(scrollVert != null)\n {\n offsetY = (int)(Math.max(0, totalItemHeight - height) * scrollVert.scrollProg);\n }\n int offsetX = 0;\n\n int widthPerItem = (int)Math.floor(useableWidth / (float)maxPerRow) - padding;\n\n int currentWidth = 0; //we add some padding between elements\n int currentHeight = padding; //we add some padding between elements\n for(Element<?> item : elements)\n {\n currentWidth += padding;\n\n item.posX = currentWidth - offsetX;\n item.posY = currentHeight - offsetY;\n\n if(item.width != widthPerItem)\n {\n item.width = widthPerItem;\n }\n currentWidth += item.width;\n if(currentWidth + padding + widthPerItem > useableWidth) //time to reset\n {\n currentWidth = 0;\n currentHeight += padding;\n currentHeight += item.getHeight(); //should be 70\n }\n }\n }\n\n public void updateScrollBarSizes()\n {\n if(scrollVert != null)\n {\n scrollVert.setScrollBarSize(height / (float)getTotalItemHeight()); //if items height is higher than ours, scroll bar should appear\n }\n }\n\n @Override\n public List<? extends Element<?>> getEventListeners()\n {\n return elements;\n }\n\n @Override\n public boolean requireScissor()\n {\n return true;\n }\n\n @Override\n public boolean changeFocus(boolean direction) //we can't change focus on this\n {\n return false;\n }\n\n @Override\n public int getMinWidth()\n {\n return 58; // 50 + padding x2 + 1px border\n }\n\n @Override\n public int getMinHeight()\n {\n if(scrollVert != null)\n {\n return 14;\n }\n return super.getMinHeight();\n }\n\n @Override\n public int getBorderSize()\n {\n return 0;\n }\n}",
"@Mod(Hats.MOD_ID)\npublic class Hats\n{\n public static final String MOD_NAME = \"Hats\";\n public static final String MOD_ID = \"hats\";\n public static final String PROTOCOL = \"1\"; //Network protocol\n\n public static final Logger LOGGER = LogManager.getLogger();\n\n public static ConfigClient configClient;\n public static ConfigServer configServer;\n\n public static EventHandlerClient eventHandlerClient;\n public static EventHandlerServer eventHandlerServer;\n\n public static PacketChannel channel;\n\n private static ThreadReadHats threadReadHats;\n\n public Hats()\n {\n if(!HatResourceHandler.init())\n {\n LOGGER.fatal(\"Error initialising Resource Handler! Terminating init.\");\n return;\n }\n configServer = new ConfigServer().init();\n\n IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();\n\n EntityTypes.REGISTRY.register(bus);\n Items.REGISTRY.register(bus);\n Sounds.REGISTRY.register(bus);\n\n bus.addListener(this::onCommonSetup);\n bus.addListener(this::finishLoading);\n\n MinecraftForge.EVENT_BUS.register(eventHandlerServer = new EventHandlerServer());\n\n channel = new PacketChannel(new ResourceLocation(MOD_ID, \"channel\"), PROTOCOL, true, false,\n PacketPing.class,\n PacketRequestEntityHatDetails.class,\n PacketEntityHatDetails.class,\n PacketRequestHeadInfos.class,\n PacketHeadInfos.class,\n PacketNewHatPart.class,\n PacketUpdateHats.class,\n PacketHatCustomisation.class,\n PacketEntityHatEntityDetails.class,\n PacketRehatify.class,\n PacketHatLauncherCustomisation.class,\n PacketHatsList.class,\n PacketHatsListResponse.class,\n PacketHatFragment.class,\n PacketGiveHat.class\n );\n\n //Make sure the mod being absent on the other network side does not cause the client to display the server as incompatible\n ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.DISPLAYTEST, () -> Pair.of(() -> FMLNetworkConstants.IGNORESERVERONLY, (a, b) -> true));\n\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> {\n configClient = new ConfigClient().init();\n\n EntityDummy.init(bus); //we use this for the client-based entity for GUI rendering\n\n bus.addListener(this::onClientSetup);\n bus.addListener(this::enqueueIMC);\n bus.addListener(this::onModelBake);\n\n MinecraftForge.EVENT_BUS.register(eventHandlerClient = new EventHandlerClient());\n\n ItemEffectHandler.init();\n\n ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.CONFIGGUIFACTORY, () -> me.ichun.mods.ichunutil.client.core.EventHandlerClient::getConfigGui);\n });\n\n threadReadHats = new ThreadReadHats();\n threadReadHats.start();\n }\n\n private void onCommonSetup(FMLCommonSetupEvent event)\n {\n //We don't need a proper IStorage / factory: https://github.com/MinecraftForge/MinecraftForge/issues/7622\n CapabilityManager.INSTANCE.register(HatsSavedData.HatPart.class, new Capability.IStorage<HatsSavedData.HatPart>() {\n @Nullable\n @Override\n public INBT writeNBT(Capability<HatsSavedData.HatPart> capability, HatsSavedData.HatPart instance, Direction side)\n {\n return null;\n }\n\n @Override\n public void readNBT(Capability<HatsSavedData.HatPart> capability, HatsSavedData.HatPart instance, Direction side, INBT nbt)\n {\n\n }\n }, () -> null);\n\n Advancements.CriteriaTriggers.init();\n\n ArgumentTypes.register(\"hats:hat\", HatInfosArgument.class, new HatInfosArgument.Serializer());\n }\n\n @OnlyIn(Dist.CLIENT)\n private void onClientSetup(FMLClientSetupEvent event)\n {\n Hats.eventHandlerClient.keyBindHats = new KeyBind(new KeyBinding(\"hats.key.hatsMenu\", KeyConflictContext.IN_GAME, InputMappings.Type.KEYSYM.getOrMakeInput(GLFW.GLFW_KEY_H), \"key.categories.ui\"), keyBind -> eventHandlerClient.openHatsMenu(), null);\n\n RenderingRegistry.registerEntityRenderingHandler(EntityTypes.HAT.get(), new RenderHatEntity.RenderFactory());\n }\n\n @OnlyIn(Dist.CLIENT)\n private void enqueueIMC(final InterModEnqueueEvent event)\n {\n InterModComms.sendTo(\"tabula\", \"plugin\", HatsTabulaPlugin::new);\n }\n\n private void finishLoading(FMLLoadCompleteEvent event)\n {\n //Thanks ichttt\n if(threadReadHats.latch.getCount() > 0)\n {\n Hats.LOGGER.info(\"Waiting for file reader thread to finish\");\n try\n {\n threadReadHats.latch.await();\n }\n catch(InterruptedException e)\n {\n Hats.LOGGER.error(\"Got interrupted while waiting for FileReaderThread to finish\");\n e.printStackTrace();\n }\n }\n threadReadHats = null; //enjoy this thread, GC.\n\n\n HeadHandler.init(); //initialise our head trackers\n\n if(FMLEnvironment.dist.isClient())\n {\n eventHandlerClient.addLayers(); //Let's add the layers\n }\n }\n\n @OnlyIn(Dist.CLIENT)\n private void onModelBake(ModelBakeEvent event)\n {\n event.getModelRegistry().put(new ModelResourceLocation(\"hats:hat_launcher\", \"inventory\"), new ItemModelRenderer(ItemRenderHatLauncher.INSTANCE));\n }\n\n public static class EntityTypes\n {\n private static final DeferredRegister<EntityType<?>> REGISTRY = DeferredRegister.create(ForgeRegistries.ENTITIES, MOD_ID);\n\n public static final RegistryObject<EntityType<EntityHat>> HAT = REGISTRY.register(\"hat\", () -> EntityType.Builder.create(EntityHat::new, EntityClassification.MISC)\n .size(0.1F, 0.1F)\n .setTrackingRange(64)\n .setUpdateInterval(20)\n .setShouldReceiveVelocityUpdates(true)\n .build(\"an entity from \" + MOD_NAME + \". Ignore this.\")\n );\n }\n\n\n public static class Items\n {\n private static final DeferredRegister<Item> REGISTRY = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);\n\n public static final RegistryObject<ItemHatLauncher> HAT_LAUNCHER = REGISTRY.register(\"hat_launcher\", () -> new ItemHatLauncher(new Item.Properties().maxStackSize(1).group(ItemGroup.TOOLS)));\n }\n\n public static class Sounds\n {\n private static final DeferredRegister<SoundEvent> REGISTRY = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, MOD_ID); //.setRegistryName(new ResourceLocation(\"torched\", \"rpt\") ??\n\n public static final RegistryObject<SoundEvent> POOF = REGISTRY.register(\"poof\", () -> new SoundEvent(new ResourceLocation(\"hats\", \"poof\")));\n public static final RegistryObject<SoundEvent> TUBE = REGISTRY.register(\"tube\", () -> new SoundEvent(new ResourceLocation(\"hats\", \"tube\")));\n public static final RegistryObject<SoundEvent> BONK = REGISTRY.register(\"bonk\", () -> new SoundEvent(new ResourceLocation(\"hats\", \"bonk\")));\n }\n}",
"public class HatInfo\n implements Comparable<HatInfo>\n{\n public final @Nonnull String name;\n public final @Nonnull Project project;\n public final ArrayList<HatInfo> accessories = new ArrayList<>();\n public final ArrayList<String> hideParent = new ArrayList<>();\n public final ArrayList<Project.Part> allParts = new ArrayList<>();\n\n private EnumRarity rarity; //Config synching should set this for the client\n private int worth = -1;\n\n public String forcedPool;\n public int forcedWorth = -1;\n public EnumRarity forcedRarity;\n\n public UUID contributorUUID;\n\n public String description;\n\n public String accessoryFor;\n public ArrayList<String> accessoryLayer = new ArrayList<>();\n public String accessoryParent;\n\n @OnlyIn(Dist.CLIENT)\n public ModelHat model;\n\n public float[] colouriser = new float[] { 1F, 1F, 1F, 1F }; //hatpart is invert of this\n public float[] hsbiser = new float[] { 1F, 1F, 1F }; //hatpart is invert of this\n public boolean enchanted = false;\n\n @OnlyIn(Dist.CLIENT)\n public HashMap<String, NativeImageTexture> hsbToImage;\n\n public boolean hidden = false; //true to disable rendering\n\n public HatInfo(@Nonnull String name, @Nonnull Project project) //TODO head top/eye analyser for HeadInfo\n {\n this.name = name;\n this.project = project;\n this.project.name = name;\n this.allParts.addAll(this.project.getAllParts()); //yay optimising?\n\n if(FMLEnvironment.dist.isClient())\n {\n hsbToImage = new HashMap<>();\n }\n\n findMeta();\n }\n\n public String getDisplayName()\n {\n return (contributorUUID != null ? TextFormatting.AQUA : getRarity().getColour()).toString() + name;\n }\n\n public EnumRarity getRarity()\n {\n if(rarity == null)\n {\n if(forcedRarity != null)\n {\n rarity = forcedRarity;\n }\n else\n {\n HatHandler.RAND.setSeed(Math.abs((Hats.configServer.randSeed + getFullName()).hashCode()) * 154041013L); //Chat contributed random\n\n rarity = HatHandler.getRarityForChance(HatHandler.RAND.nextDouble());\n }\n }\n\n return rarity;\n }\n\n public void setRarity(EnumRarity rarity)\n {\n this.rarity = rarity;\n }\n\n public int getWorth()\n {\n if(worth < 0)\n {\n int value = Hats.configServer.tokensByRarity.get(getRarity());\n if(accessoryFor != null)\n {\n value = (int)Math.ceil(Hats.configServer.accessoryCostMultiplier * value);\n }\n worth = value;\n }\n return worth;\n }\n\n @OnlyIn(Dist.CLIENT)\n public ModelHat getModel()\n {\n if(model == null)\n {\n model = new ModelHat(this);\n }\n return model;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void destroy()\n {\n //Don't need to destroy the model\n project.destroy();\n\n for(NativeImageTexture value : hsbToImage.values())\n {\n Minecraft.getInstance().getTextureManager().deleteTexture(value.getResourceLocation());\n }\n hsbToImage.clear();\n\n for(HatInfo accessory : accessories)\n {\n accessory.destroy();\n }\n }\n\n @OnlyIn(Dist.CLIENT)\n public void render(MatrixStack stack, IRenderTypeBuffer bufferIn, int packedLightIn, int packedOverlayIn, boolean cull)\n {\n if(!hidden)\n {\n for(Project.Part part : allParts)\n {\n part.showModel = true;\n }\n\n for(HatInfo accessory : accessories)\n {\n if(!accessory.hidden && !accessory.hideParent.isEmpty())\n {\n for(String s : accessory.hideParent)\n {\n for(Project.Part part : allParts)\n {\n if(part.name.equals(s))\n {\n part.showModel = false;\n }\n }\n }\n }\n }\n\n ResourceLocation textureResourceLocation = getTextureResourceLocation();\n if(textureResourceLocation != null)\n {\n RenderType renderType = cull ? RenderType.getEntityTranslucentCull(textureResourceLocation) : RenderType.getEntityTranslucent(textureResourceLocation);\n getModel().render(stack, ItemRenderer.getEntityGlintVertexBuilder(bufferIn, renderType, false, enchanted), packedLightIn, packedOverlayIn, colouriser[0], colouriser[1], colouriser[2], colouriser[3]);\n }\n\n for(HatInfo accessory : accessories)\n {\n accessory.render(stack, bufferIn, packedLightIn, packedOverlayIn, cull);\n }\n }\n }\n\n @OnlyIn(Dist.CLIENT)\n public ResourceLocation getTextureResourceLocation()\n {\n byte[] textureBytes = project.getTextureBytes();\n\n if(textureBytes != null)\n {\n //Don't tell anyone how much memory I'm eating and I won't tell anyone I'm a bad boy\n String key = hsbiser[0] + \"H\" + hsbiser[1] + \"S\" + hsbiser[2] + \"B\";\n NativeImageTexture nit = hsbToImage.computeIfAbsent(key, k -> {\n\n try(NativeImage image = NativeImage.read(new ByteArrayInputStream(textureBytes)))\n {\n if(!(hsbiser[0] == 1F && hsbiser[1] == 1F && hsbiser[2] == 1F))\n {\n for(int x = 0; x < image.getWidth(); x++)\n {\n for(int y = 0; y < image.getHeight(); y++)\n {\n int clr = image.getPixelRGBA(x, y); //Actually ARGB\n if((clr >> 24 & 0xff) > 0) //not invisible\n {\n float[] hsb = Color.RGBtoHSB(clr >> 16 & 0xff, clr >> 8 & 0xff, clr & 0xff, null);\n hsb[0] += (1F - hsbiser[0]);\n for(int i = 1; i < hsbiser.length; i++)\n {\n hsb[i] *= hsbiser[i];\n }\n image.setPixelRGBA(x, y, ((clr >> 24 & 0xff) << 24) | (Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]) & 0xffffff));\n }\n }\n }\n }\n\n NativeImageTexture nativeImage = new NativeImageTexture(image);\n\n Minecraft.getInstance().getTextureManager().loadTexture(nativeImage.getResourceLocation(), nativeImage);\n\n return nativeImage;\n }\n catch(IOException e)\n {\n iChunUtil.LOGGER.error(\"Failed to read NativeImage for project: \" + name);\n e.printStackTrace();\n }\n return null;\n });\n return nit != null ? nit.getResourceLocation() : null;\n }\n return null;\n }\n\n private void findMeta()\n {\n for(String note : this.project.notes)\n {\n if(note.startsWith(\"hats-rarity:\"))\n {\n try\n {\n forcedRarity = EnumRarity.valueOf(note.substring(\"hats-rarity:\".length()).trim().toUpperCase(Locale.ROOT));\n }\n catch(IllegalArgumentException e)\n {\n Hats.LOGGER.error(\"Cannot find Hat Rarity of {}\", name);\n }\n }\n else if(note.startsWith(\"hats-pool:\"))\n {\n forcedPool = note.substring(\"hats-pool:\".length()).trim();\n }\n else if(note.startsWith(\"hats-worth:\"))\n {\n try\n {\n forcedWorth = Integer.parseInt(note.substring(\"hats-worth:\".length()).trim());\n }\n catch(NumberFormatException e)\n {\n Hats.LOGGER.error(\"Error parsing forced worth of hat: \\\"{}\\\" from project: {}\", note, this.project.saveFile);\n }\n }\n else if(note.startsWith(\"hats-contributor-uuid:\"))\n {\n contributorUUID = UUID.fromString(note.substring(\"hats-contributor-uuid:\".length()).trim());\n }\n else if(note.startsWith(\"hats-contributor-mini-me:\"))\n {\n if(contributorUUID == null) contributorUUID = EntityHelper.UUID_EXAMPLE;\n }\n else if(note.startsWith(\"hats-accessory:\"))\n {\n accessoryFor = note.substring(\"hats-accessory:\".length()).trim();\n }\n else if(note.startsWith(\"hats-accessory-layer:\"))\n {\n accessoryLayer.add(note.substring(\"hats-accessory-layer:\".length()).trim());\n }\n else if(note.startsWith(\"hats-accessory-parent:\"))\n {\n accessoryParent = note.substring(\"hats-accessory-parent:\".length()).trim();\n }\n else if(note.startsWith(\"hats-accessory-hide-parent-part:\"))\n {\n hideParent.add(note.substring(\"hats-accessory-hide-parent-part:\".length()).trim());\n }\n else if(note.startsWith(\"hats-description:\"))\n {\n description = note.substring(\"hats-description:\".length()).trim();\n }\n else if(note.startsWith(\"hat\"))\n {\n Hats.LOGGER.warn(\"We found a hats meta we don't understand: {} in Project: {}\", note, project.saveFile);\n }\n }\n }\n\n public void accessorise(ArrayList<HatInfo> newAccessories)\n {\n //take the accessories if the parent is null or is our name. The base calls this first, and will take all the null ones. We then pass on the list to the children to nab as they need.\n accessories.addAll(newAccessories.stream().filter(info -> info.accessoryParent == null || info.accessoryParent.equals(name)).collect(Collectors.toList()));\n newAccessories.removeAll(accessories);\n\n if(forcedWorth >= 0)\n {\n worth = forcedWorth;\n }\n\n for(HatInfo accessory : accessories)\n {\n accessory.accessorise(newAccessories);\n }\n }\n\n public String getDisplayNameFor(String accessoryName)\n {\n HatInfo info = getInfoFor(accessoryName);\n return info != null ? info.getDisplayName() : null;\n }\n\n public HatInfo getInfoFor(String accessoryName)\n {\n if(accessoryName.equals(name))\n {\n return this;\n }\n else\n {\n for(HatInfo accessory : accessories)\n {\n HatInfo s = accessory.getInfoFor(accessoryName);\n if(s != null)\n {\n return s;\n }\n }\n }\n return null;\n }\n\n public int getWorthFor(String accessoryName, int bonus)\n {\n if(accessoryName.equals(name))\n {\n return getWorth() + bonus;\n }\n else\n {\n for(HatInfo accessory : accessories)\n {\n int s = accessory.getWorthFor(accessoryName, getWorth() + bonus);\n if(s > 0)\n {\n return s;\n }\n }\n }\n return -1;\n }\n\n public HatsSavedData.HatPart getAsHatPart(int count)\n {\n HatsSavedData.HatPart part = new HatsSavedData.HatPart(name);\n part.isShowing = true;\n part.count = count;\n for(HatInfo accessory : accessories)\n {\n HatsSavedData.HatPart childPart = accessory.getAsHatPart(count);\n childPart.isShowing = false; //the function sets is as true\n part.hatParts.add(childPart);\n }\n return part;\n }\n\n public HatsSavedData.HatPart getFromList(ArrayList<String> names, int count)\n {\n HatsSavedData.HatPart hatPart = getAsHatPartShowingAll(count);\n hatPart.stripIfNameNotInList(names);\n return hatPart;\n }\n\n private HatsSavedData.HatPart getAsHatPartShowingAll(int count)\n {\n HatsSavedData.HatPart part = new HatsSavedData.HatPart(name);\n part.isShowing = true;\n part.count = count;\n for(HatInfo accessory : accessories)\n {\n HatsSavedData.HatPart childPart = accessory.getAsHatPartShowingAll(count);\n part.hatParts.add(childPart);\n }\n return part;\n }\n\n @Override\n public int compareTo(HatInfo o)\n {\n return name.compareTo(o.name);\n }\n\n public String getFullName()\n {\n StringBuilder sb = new StringBuilder();\n if(accessoryFor != null)\n {\n sb.append(accessoryFor);\n sb.append(\":\");\n }\n if(accessoryParent != null)\n {\n sb.append(accessoryParent);\n sb.append(\"|\");\n }\n sb.append(name);\n\n return sb.toString();\n }\n\n public void addFullNames(HashSet<String> names)\n {\n names.add(getFullName());\n\n for(HatInfo accessory : accessories)\n {\n accessory.addFullNames(names);\n }\n }\n\n public void addNameWithOrigin(ArrayList<String> names, String origin)\n {\n names.add(origin + \":\" + name);\n\n for(HatInfo accessory : accessories)\n {\n accessory.addNameWithOrigin(names, origin);\n }\n }\n\n public void assignAccessoriesToPart(HatsSavedData.HatPart hatPart, LivingEntity ent)\n {\n ArrayList<HatInfo> spawningAccessories = new ArrayList<>();\n HashMap<String, ArrayList<HatInfo>> conflicts = new HashMap<>();\n for(HatInfo accessory : accessories)\n {\n double accChance = Hats.configServer.rarityIndividual.get(accessory.getRarity().ordinal()); //calling getRarity sets the accessory's rarity.\n\n HatHandler.RAND.setSeed(Math.abs((Hats.configServer.randSeed + ent.getUniqueID() + accessory.getFullName()).hashCode()) * 53579997854L); //Chat contributed random\n HeadInfo<?> info = HeadHandler.getHelper(ent.getClass());\n if(info != null && info.isBoss)\n {\n accChance += Hats.configServer.bossRarityBonus;\n }\n\n if(HatHandler.RAND.nextDouble() < accChance) //spawn the accessory\n {\n spawningAccessories.add(accessory);\n if(!accessory.accessoryLayer.isEmpty()) //look for conflicts for accessories that already got to spawn\n {\n for(String layer : accessory.accessoryLayer)\n {\n conflicts.computeIfAbsent(layer, k -> new ArrayList<>()).add(accessory);\n }\n }\n }\n }\n\n //if there are no conflicts, remove\n conflicts.entrySet().removeIf(entry -> entry.getValue().size() <= 1);\n\n for(ArrayList<HatInfo> conflictAccessories : conflicts.values())\n {\n while(conflictAccessories.size() > 1)\n {\n HatInfo acc = conflictAccessories.get(ent.getRNG().nextInt(conflictAccessories.size()));// YOU LOST THE COIN TOSS\n spawningAccessories.remove(acc);\n conflictAccessories.remove(acc);\n }\n }\n\n for(HatInfo accessory : spawningAccessories)\n {\n HatsSavedData.HatPart accToSpawn = new HatsSavedData.HatPart(accessory.name);\n accToSpawn.isShowing = true;\n hatPart.hatParts.add(accToSpawn);\n\n accessory.assignAccessoriesToPart(accToSpawn, ent);\n }\n }\n\n @OnlyIn(Dist.CLIENT)\n public void assignAccessoriesToPartClient(HatsSavedData.HatPart hatPart, LivingEntity ent) //simplified version for clients on servers without Hats.\n {\n ArrayList<HatInfo> spawningAccessories = new ArrayList<>();\n HashMap<String, ArrayList<HatInfo>> conflicts = new HashMap<>();\n HatHandler.RAND.setSeed(Math.abs((Minecraft.getInstance().getSession().getUsername() + ent.getUniqueID()).hashCode()) * 53579997854L); //Chat contributed random\n for(HatInfo accessory : accessories)\n {\n if(HatHandler.RAND.nextBoolean()) //spawn the accessory\n {\n spawningAccessories.add(accessory);\n if(!accessory.accessoryLayer.isEmpty()) //look for conflicts for accessories that already got to spawn\n {\n for(String layer : accessory.accessoryLayer)\n {\n conflicts.computeIfAbsent(layer, k -> new ArrayList<>()).add(accessory);\n }\n }\n }\n }\n\n //if there are no conflicts, remove\n conflicts.entrySet().removeIf(entry -> entry.getValue().size() <= 1);\n\n for(ArrayList<HatInfo> conflictAccessories : conflicts.values())\n {\n while(conflictAccessories.size() > 1)\n {\n HatInfo acc = conflictAccessories.get(ent.getRNG().nextInt(conflictAccessories.size()));// YOU LOST THE COIN TOSS\n spawningAccessories.remove(acc);\n conflictAccessories.remove(acc);\n }\n }\n\n for(HatInfo accessory : spawningAccessories)\n {\n HatsSavedData.HatPart accToSpawn = new HatsSavedData.HatPart(accessory.name);\n accToSpawn.isShowing = true;\n hatPart.hatParts.add(accToSpawn);\n\n accessory.assignAccessoriesToPartClient(accToSpawn, ent);\n }\n }\n\n public void matchPart(HatsSavedData.HatPart part)\n {\n for(HatInfo accessory : accessories)\n {\n accessory.hidden = true;\n for(HatsSavedData.HatPart hatPart : part.hatParts)\n {\n if(hatPart.name.equals(accessory.name))\n {\n accessory.matchPart(hatPart);\n }\n }\n }\n\n hidden = part.count < 0 || !part.isShowing;\n for(int i = 0; i < part.colouriser.length; i++)\n {\n colouriser[i] = 1F - part.colouriser[i];\n }\n for(int i = 0; i < part.hsbiser.length; i++)\n {\n hsbiser[i] = 1F - part.hsbiser[i];\n }\n enchanted = part.enchanted;\n }\n\n public float[] getDimensions() //gets y min + y-max + width\n {\n if(hidden)\n {\n return new float[] { 0F, 0F, 0F, 0F, 0F, 0F };\n }\n\n float x1 = 10000;\n float x2 = -10000;\n float z1 = 10000;\n float z2 = -10000;\n\n float y1 = 10000;\n float y2 = -10000;\n\n\n for(Project.Part part : allParts)\n {\n for(Project.Part.Box box : part.boxes)\n {\n if(part.rotPX + box.posX < x1) //lowest point\n {\n x1 = part.rotPX + box.posX;\n }\n if(part.rotPX + box.posX + box.dimX > x2) //highest point\n {\n x2 = part.rotPX + box.posX + box.dimX;\n }\n if(part.rotPZ + box.posZ < z1) //lowest point\n {\n z1 = part.rotPZ + box.posZ;\n }\n if(part.rotPZ + box.posZ + box.dimZ > z2) //highest point\n {\n z2 = part.rotPZ + box.posZ + box.dimZ;\n }\n\n if(part.rotPY + box.posY < y1) //lowest point\n {\n y1 = part.rotPY + box.posY;\n }\n if(part.rotPY + box.posY + box.dimY > y2) //highest point\n {\n y2 = part.rotPY + box.posY + box.dimY;\n }\n }\n }\n\n float[] dims = new float[] { x1, x2, y1, y2, z1, z2 };\n\n for(HatInfo accessory : accessories)\n {\n float[] accDims = accessory.getDimensions();\n\n for(int i = 0; i < accDims.length; i++)\n {\n if(i % 2 == 0)\n {\n if(accDims[i] < dims[i])\n {\n dims[i] = accDims[i];\n }\n }\n else\n {\n if(accDims[i] > dims[i])\n {\n dims[i] = accDims[i];\n }\n }\n }\n }\n\n return dims;\n }\n}",
"public class HatResourceHandler\n{\n //Make it concurrent just in case we need to reload hats on client whilst integrated server is accessing?? Just in case\n public static final ConcurrentHashMap<String, HatInfo> HATS = new ConcurrentHashMap<>(); //Our reliance on Tabula is staggering.\n private static final ArrayList<HatInfo> HAT_ACCESSORIES = new ArrayList<>(); //Only used when loading all the hats.\n\n public static ArrayList<HatsSavedData.HatPart> HAT_PARTS = new ArrayList<>();\n\n private static Path hatsDir;\n private static boolean init;\n public static synchronized boolean init()\n {\n if(!init)\n {\n init = true;\n\n try\n {\n hatsDir = FMLPaths.MODSDIR.get().resolve(Hats.MOD_ID);\n if(!Files.exists(hatsDir)) Files.createDirectory(hatsDir);\n\n File extractedMarker = new File(hatsDir.toFile(), \"files.extracted\");\n if(!extractedMarker.exists()) //presume we haven't extracted anything yet\n {\n InputStream in = Hats.class.getResourceAsStream(\"/hats.zip\");\n if(in != null)\n {\n Hats.LOGGER.info(\"Extracted {} Hat files.\", IOUtil.extractFiles(hatsDir, in, true));\n }\n else\n {\n Hats.LOGGER.error(\"Error extracting hats.zip. InputStream was null.\");\n }\n\n FileUtils.writeStringToFile(extractedMarker, \"\", StandardCharsets.UTF_8);\n }\n }\n catch(IOException e)\n {\n Hats.LOGGER.fatal(\"Error initialising Hats resources!\");\n e.printStackTrace();\n return false;\n }\n }\n return init;\n }\n\n public static Path getHatsDir()\n {\n return hatsDir;\n }\n\n public static synchronized void loadAllHats()\n {\n HATS.clear();\n HAT_ACCESSORIES.clear();\n\n int count = 0;\n try\n {\n count += IOUtil.scourDirectoryForFiles(getHatsDir(), p -> p.getFileName().toString().endsWith(\".tbl\") && readHat(p.toFile())); //tabula format\n }\n catch(IOException e)\n {\n Hats.LOGGER.error(\"Error loading Hat files.\");\n e.printStackTrace();\n }\n\n int accessoryCount = HAT_ACCESSORIES.size();\n\n accessoriseHatInfos();\n\n int hatCount = HATS.size();\n\n HAT_PARTS = getAllHatsAsHatParts(1);\n\n Hats.LOGGER.info(\"Loaded {} files. {} hats, {} accessories.\", count, hatCount, accessoryCount);\n }\n\n public static synchronized boolean loadSingularHat(File file)\n {\n if(file.getName().endsWith(\".tbl\") && readHat(file))\n {\n accessoriseHatInfos();\n\n HAT_PARTS = getAllHatsAsHatParts(1);\n\n Hats.LOGGER.info(\"Loaded hat: {}\", file);\n\n return true;\n }\n return false;\n }\n\n public static boolean readHat(File file)\n {\n Project project = ImportList.createProjectFromFile(file);\n if(project == null)\n {\n Hats.LOGGER.warn(\"Error reading Tabula file: {}\", file);\n return false;\n }\n else\n {\n if(project.getTextureBytes() == null)\n {\n Hats.LOGGER.warn(\"Tabula file has no texture, rejecting: {}\", file);\n return false;\n }\n\n if(project.tampered)\n {\n Hats.LOGGER.warn(\"This hat file was tampered (which will be loaded anyway): {}\", file);\n }\n\n if(project.isOldTabula)\n {\n repairOldHat(file, project);\n Hats.LOGGER.warn(\"Loaded an old Tabula file. Updating to new Tabula & Hats format: {}\", file);\n }\n\n // if(file.getAbsolutePath().contains(\"mods\\\\hats\\\\_PORTALCRAFTER51\"))\n // {\n // project.author = \"Portalcrafter51\";\n // project.save(file);\n // Hats.LOGGER.info(\"Resaved: {}\", file);\n // }\n // if(file.getAbsolutePath().contains(\"mods\\\\hats\\\\_THEMUSHROOMCOW\"))\n // {\n // project.author = \"The_Mushroomcow\";\n // project.save(file);\n // Hats.LOGGER.info(\"Resaved: {}\", file);\n // }\n // if(file.getAbsolutePath().contains(\"mods\\\\hats\\\\_MRHAZARD\"))\n // {\n // project.author = \"Mr_Hazard\";\n // project.save(file);\n // Hats.LOGGER.info(\"Resaved: {}\", file);\n // }\n\n String hatName = file.getName().substring(0, file.getName().length() - 4);\n\n HatInfo hatInfo = createHatInfoFor(hatName, project);\n\n if(hatInfo.accessoryFor == null) //it is a base had\n {\n HATS.put(hatName, hatInfo);\n }\n else\n {\n HAT_ACCESSORIES.add(hatInfo);\n }\n\n return true;\n }\n }\n\n private static HatInfo createHatInfoFor(@Nonnull String name, @Nonnull Project project)\n {\n return new HatInfo(name, project);\n }\n\n public static void accessoriseHatInfos()\n {\n HashMap<String, ArrayList<HatInfo>> accessoriesByHat = new HashMap<>();\n for(HatInfo hatAccessory : HAT_ACCESSORIES)\n {\n accessoriesByHat.computeIfAbsent(hatAccessory.accessoryFor, k -> new ArrayList<>()).add(hatAccessory);\n }\n\n accessoriesByHat.forEach((hatName, hatInfos) -> {\n if(HATS.containsKey(hatName))\n {\n HATS.get(hatName).accessorise(hatInfos);\n\n if(!hatInfos.isEmpty())\n {\n for(HatInfo orphan : hatInfos)\n {\n Hats.LOGGER.warn(\"We couldn't find the hat parent for {}\", orphan.project.saveFile);\n }\n }\n }\n else\n {\n for(HatInfo orphan : hatInfos)\n {\n Hats.LOGGER.warn(\"We couldn't find the hat base for {}\", orphan.project.saveFile);\n }\n }\n });\n\n HAT_ACCESSORIES.clear(); //we don't need you anymore\n }\n\n public static HatInfo getInfo(HatsSavedData.HatPart part)\n {\n return HATS.get(part.name);\n }\n\n public static HatInfo getInfoAndSetToPart(HatsSavedData.HatPart part) //For rendering and hat entity calculation\n {\n HatInfo hatInfo = getInfo(part);\n if(hatInfo != null)\n {\n hatInfo.matchPart(part);\n return hatInfo;\n }\n return null;\n }\n\n public static ArrayList<HatsSavedData.HatPart> getAllHatsAsHatParts(int count)\n {\n ArrayList<HatsSavedData.HatPart> hatParts = new ArrayList<>();\n HATS.forEach((s, info) -> hatParts.add(info.getAsHatPart(count)));\n return hatParts;\n }\n\n public static void combineLists(ArrayList<HatsSavedData.HatPart> primary, ArrayList<HatsSavedData.HatPart> secondary)\n {\n for(HatsSavedData.HatPart invPart : secondary)\n {\n for(HatsSavedData.HatPart hatPart : primary)\n {\n if(hatPart.add(invPart))\n {\n break;\n }\n }\n }\n }\n\n public static HashSet<String> compileHatNames()\n {\n HashSet<String> names = new HashSet<>();\n HATS.forEach((s, info) -> info.addFullNames(names));\n return names;\n }\n\n public static HatInfo getInfoFromFullName(String name)\n {\n Splitter ON_COLON = Splitter.on(\":\").trimResults().omitEmptyStrings();\n Splitter ON_PIPE = Splitter.on(\"|\").trimResults().omitEmptyStrings();\n\n List<String> names = ON_COLON.splitToList(name);\n if(names.size() == 1) //is a base hat\n {\n return HATS.get(names.get(0));\n }\n else if(names.size() == 2)\n {\n HatInfo parentInfo = HATS.get(names.get(0));\n if(parentInfo != null)\n {\n List<String> accNames = ON_PIPE.splitToList(names.get(1));\n if(!accNames.isEmpty())\n {\n return parentInfo.getInfoFor(accNames.get(accNames.size() - 1));\n }\n }\n }\n return null;\n }\n\n private static void repairOldHat(File file, Project project)\n {\n project.name = file.getName().substring(0, file.getName().length() - 4);\n project.author = \"\";\n project.isOldTabula = false;\n project.isDirty = true;\n ArrayList<Project.Part> allParts = project.getAllParts();\n for(Project.Part part : allParts)\n {\n part.rotPY -= 16F; //we move the hat template up\n }\n project.save(file);\n }\n\n private static void parseMeta(File file, Project project)\n {\n boolean hasForcePool = false;\n boolean hasPool = false;\n for(int i = project.notes.size() - 1; i >= 0; i--)\n {\n String note = project.notes.get(i);\n if(note.startsWith(\"Hats:{\"))//we found the meta\n {\n project.notes.remove(i);\n try\n {\n JsonObject element = new JsonParser().parse(note.substring(5).trim()).getAsJsonObject();\n if(element.has(\"uuid\"))\n {\n project.notes.add(\"hats-contributor-uuid:\" + element.get(\"uuid\").getAsString());\n }\n if(element.has(\"isMiniMe\"))\n {\n project.notes.add(\"hats-contributor-mini-me:\" + element.get(\"isMiniMe\").getAsBoolean());\n }\n }\n catch(Throwable t)\n {\n t.printStackTrace();\n }\n }\n if(note.startsWith(\"hats-rarity\"))\n {\n hasForcePool = true;\n }\n if(note.startsWith(\"hats-pool\"))\n {\n hasPool = true;\n }\n }\n if(!hasForcePool)\n {\n project.notes.add(\"hats-rarity:legendary\");\n }\n if(!hasPool)\n {\n project.notes.add(\"hats-pool:contributors\");\n }\n project.save(file);\n }\n}",
"public class SortHandler\n{\n public static HashMap<String, Class<? extends HatSorter>> SORTERS = new HashMap<String, Class<? extends HatSorter>>() {{\n put(\"filterContributor\", FilterContributor.class);\n put(\"filterHas\", FilterHas.class);\n put(\"filterHasAccessories\", FilterHasAccessories.class);\n put(\"filterNotFavourite\", FilterNotFavourite.class);\n put(\"filterUndiscovered\", FilterUndiscovered.class);\n\n put(\"sorterAlphabetical\", SorterAlphabetical.class); //This is the only sorter that doesn't create a new category to sort.\n put(\"sorterCount\", SorterCount.class);\n put(\"sorterDiscovered\", SorterDiscovered.class);\n put(\"sorterFavourite\", SorterFavourite.class);\n put(\"sorterRarity\", SorterRarity.class);\n }};\n\n\n public static void sort(ArrayList<HatSorter> sorters, List<?> hats, boolean allowFilter)\n {\n for(HatSorter sorter : sorters)\n {\n if(!allowFilter && sorter.isFilter())\n {\n continue;\n }\n sorter.sortRecursive(hats);\n }\n\n ArrayList newHats = new ArrayList();\n digForHats(newHats, hats);\n\n hats.clear();\n hats.addAll(newHats);\n }\n\n private static void digForHats(ArrayList<HatsSavedData.HatPart> finalHatList, List<?> listOfHats)\n {\n for(Object listOfHat : listOfHats)\n {\n if(listOfHat instanceof List)\n {\n digForHats(finalHatList, (List<?>)listOfHat);\n }\n else if(listOfHat instanceof HatsSavedData.HatPart)\n {\n finalHatList.add((HatsSavedData.HatPart)listOfHat);\n }\n }\n }\n}",
"public class HatsSavedData extends WorldSavedData\n{\n public static final String ID = \"hats_save\";\n public HashMap<UUID, PlayerHatData> playerHats = new HashMap<>();\n\n public HatsSavedData()\n {\n super(ID);\n }\n\n @Override\n public void read(CompoundNBT tag)\n {\n playerHats.clear();\n\n int count = tag.getInt(\"count\");\n for(int i = 0; i < count; i++)\n {\n PlayerHatData playerData = new PlayerHatData();\n playerData.read(tag.getCompound(\"hats_\" + i));\n\n playerHats.put(playerData.owner, playerData);\n }\n }\n\n @Override\n public CompoundNBT write(CompoundNBT tag)\n {\n tag.putInt(\"count\", playerHats.size());\n\n int i = 0;\n for(Map.Entry<UUID, PlayerHatData> entry : playerHats.entrySet())\n {\n tag.put(\"hats_\" + i, entry.getValue().write(new CompoundNBT()));\n i++;\n }\n\n return tag;\n }\n\n public static class PlayerHatData\n {\n public UUID owner;\n public int tokenCount;\n public ArrayList<HatPart> hatParts = new ArrayList<>();\n\n public PlayerHatData(){}\n\n public PlayerHatData(UUID owner)\n {\n this.owner = owner;\n }\n\n public void read(CompoundNBT tag)\n {\n hatParts.clear();\n\n owner = tag.getUniqueId(\"owner\");\n\n tokenCount = tag.getInt(\"tokenCount\");\n\n int count = tag.getInt(\"partCount\");\n\n for(int i = 0; i < count; i++)\n {\n CompoundNBT hatTag = tag.getCompound(\"hat_\" + i);\n HatPart part = new HatPart();\n part.read(hatTag);\n\n if(!part.name.isEmpty())\n {\n hatParts.add(part);\n }\n }\n }\n\n public CompoundNBT write(CompoundNBT tag)\n {\n tag.putUniqueId(\"owner\", owner);\n\n tag.putInt(\"tokenCount\", tokenCount);\n\n tag.putInt(\"partCount\", hatParts.size());\n\n for(int i = 0; i < hatParts.size(); i++)\n {\n HatPart part = hatParts.get(i);\n\n tag.put(\"hat_\" + i, part.write(new CompoundNBT()));\n }\n\n return tag;\n }\n }\n\n public static class HatPart\n implements Comparable<HatPart>\n {\n @CapabilityInject(HatPart.class)\n public static Capability<HatPart> CAPABILITY_INSTANCE;\n public static final ResourceLocation CAPABILITY_IDENTIFIER = new ResourceLocation(\"hats\", \"capability_hat\");\n\n public String name = \"\";\n public int count = -1;\n public boolean isFavourite;\n public boolean isNew;\n public boolean isShowing;\n public float[] colouriser = new float[] { 0F, 0F, 0F, 0F }; //0 0 0 0 = no change to colours. goes up to 1 1 1 1 for black & invisible\n public float[] hsbiser = new float[] { 0F, 0F, 0F }; //0 0 0 = no change to colours. goes up to 1 1 1 HSB\n public boolean enchanted = false;\n public ArrayList<HatPart> hatParts = new ArrayList<>(); //yay infinite recursion\n\n public HatPart(){}\n\n public HatPart(String s)\n {\n name = s;\n count = 1;\n }\n\n public HatPart setNew()\n {\n isNew = true;\n return this;\n }\n\n public void copy(HatPart part)\n {\n name = part.name;\n count = part.count;\n isFavourite = part.isFavourite;\n isShowing = part.isShowing;\n isNew = part.isNew;\n colouriser = part.colouriser.clone();\n hsbiser = part.hsbiser.clone();\n enchanted = part.enchanted;\n\n hatParts.clear();\n for(HatPart hatPart : part.hatParts)\n {\n hatParts.add(hatPart.createCopy());\n }\n }\n\n public HatPart createCopy()\n {\n HatPart part = new HatPart();\n part.copy(this);\n return part;\n }\n\n public HatPart createRandom(Random random)\n {\n HatPart part = new HatPart();\n part.copy(this);\n\n part.randomize(random);\n\n return part;\n }\n\n public HatPart get(HatPart part)\n {\n if(part.name.equals(name))\n {\n return this;\n }\n\n for(HatPart hatPart : hatParts)\n {\n HatPart accPart = hatPart.get(part);\n if(accPart != null)\n {\n return accPart;\n }\n }\n\n return null;\n }\n\n public boolean remove(HatPart part)\n {\n if(hatParts.removeIf(hatPart -> part.name.equals(hatPart.name)))\n {\n return true;\n }\n else\n {\n for(HatPart hatPart : hatParts)\n {\n if(hatPart.remove(part))\n {\n return true;\n }\n }\n }\n return false;\n }\n\n public void randomize(Random random)\n {\n this.count = 1;\n this.isShowing = true;\n\n for(int i = hatParts.size() - 1; i >= 0; i--)\n {\n if(random.nextBoolean()) //you LOST the coin toss\n {\n hatParts.remove(i);\n }\n }\n\n for(HatPart hatPart : hatParts)\n {\n hatPart.randomize(random);\n }\n }\n\n public boolean isAHat()\n {\n return !name.isEmpty() && count >= 0;\n }\n\n public boolean hasNew()\n {\n boolean newStuff = isNew;\n if(!isNew)\n {\n for(HatPart hatPart : hatParts)\n {\n newStuff = newStuff | hatPart.hasNew();\n }\n }\n return newStuff;\n }\n\n public HatPart setNoNew()\n {\n isNew = false;\n for(HatPart hatPart : hatParts)\n {\n hatPart.setNoNew();\n }\n return this;\n }\n\n public boolean hasFavourite()\n {\n boolean hasFav = isFavourite;\n if(!isFavourite)\n {\n for(HatPart hatPart : hatParts)\n {\n hasFav = hasFav | hatPart.hasFavourite();\n }\n }\n return hasFav;\n }\n\n public HatPart setNoFavourite()\n {\n isFavourite = false;\n for(HatPart hatPart : hatParts)\n {\n hatPart.setNoFavourite();\n }\n return this;\n }\n\n public boolean add(HatPart part)\n {\n if(!name.isEmpty() && name.equals(part.name)) //we are the same my buddy, we are the same my friend.\n {\n count += part.count;\n\n if(count > 999999999)\n {\n count = 999999999; //blame jackylam5\n }\n else if(count < 0)\n {\n count = 0;\n }\n\n copyPersonalisation(part);\n\n ArrayList<HatPart> partParts = new ArrayList<>(part.hatParts);\n for(HatPart hatPart : hatParts) //look for matching accessories\n {\n for(int i = partParts.size() - 1; i >= 0; i--)\n {\n if(hatPart.add(partParts.get(i))) //if it matches\n {\n partParts.remove(i);\n break;\n }\n }\n }\n\n for(HatPart newPart : partParts)\n {\n if(newPart.count > 0)\n {\n newPart.setNew();\n }\n }\n\n hatParts.addAll(partParts); //add the accessories that don't match\n\n return true;\n }\n return false;\n }\n\n public boolean minusByOne(HatPart part)\n {\n if(!name.isEmpty() && name.equals(part.name)) //we are the same my buddy, we are the same my friend.\n {\n count -= 1;\n\n copyPersonalisation(part);\n\n ArrayList<HatPart> partParts = new ArrayList<>(part.hatParts);\n for(HatPart hatPart : hatParts) //look for matching accessories\n {\n for(int i = partParts.size() - 1; i >= 0; i--)\n {\n if(hatPart.minusByOne(partParts.get(i)) && hatPart.count <= 0) //if it matches\n {\n partParts.remove(i);\n break;\n }\n }\n }\n\n return true;\n }\n return false;\n }\n\n public boolean hasFullPart(HatPart part)\n {\n if(!name.isEmpty() && name.equals(part.name) && count >= part.count)\n {\n boolean flag = true;\n\n for(HatPart hatPart : part.hatParts)\n {\n boolean has = false;\n for(HatPart hatPart1 : hatParts)\n {\n if(hatPart1.hasFullPart(hatPart))\n {\n has = true;\n break;\n }\n }\n\n if(!has)\n {\n flag = false;\n break;\n }\n }\n\n return flag;\n }\n return false;\n }\n\n public boolean has(@Nonnull String partName) //this better already be lower case\n {\n if(name.toLowerCase(Locale.ROOT).contains(partName))\n {\n return true;\n }\n else\n {\n for(HatPart accessory : hatParts)\n {\n if(accessory.has(partName))\n {\n return true;\n }\n }\n }\n return false;\n }\n\n public void setCountOfAllTo(int count)\n {\n this.count = count;\n for(HatPart hatPart : hatParts)\n {\n hatPart.setCountOfAllTo(count);\n }\n }\n\n public void stripIfNameNotInList(ArrayList<String> names)\n {\n hatParts.removeIf(part -> !names.contains(part.name));\n for(HatPart hatPart : hatParts)\n {\n hatPart.stripIfNameNotInList(names);\n }\n }\n\n public boolean copyPersonalisation(HatPart part)\n {\n if(name.equals(part.name))\n {\n isFavourite = part.isFavourite;\n isNew = part.isNew;\n isShowing = part.isShowing;\n colouriser = part.colouriser.clone();\n hsbiser = part.hsbiser.clone();\n enchanted = part.enchanted;\n\n for(HatPart hatPart : hatParts)\n {\n for(HatPart hatPart1 : part.hatParts)\n {\n hatPart.copyPersonalisation(hatPart1);\n }\n }\n return true;\n }\n return false;\n }\n\n public void hideAll()\n {\n isShowing = false;\n for(HatPart hatPart : hatParts)\n {\n hatPart.hideAll();\n }\n }\n\n public int accessoriesUnlocked()\n {\n int count = 0;\n count += hatParts.size();\n for(HatPart hatPart : hatParts)\n {\n count += hatPart.accessoriesUnlocked();\n }\n return count;\n }\n\n public boolean hasUnlockedAccessory()\n {\n boolean flag = false;\n for(HatPart hatPart : hatParts)\n {\n if(!(hatPart.count == 0 && hatPart.hsbiser[2] == 1F) || hatPart.hasUnlockedAccessory())\n {\n flag = true;\n break;\n }\n }\n return flag;\n }\n\n public void eventDay(int age, float partialTick)\n {\n if(colouriser[0] == 0F && colouriser[1] == 0F && colouriser[2] == 0F)\n {\n HatHandler.RAND.setSeed(Math.abs(name.hashCode()));\n\n int ageR = 40 + HatHandler.RAND.nextInt(60);\n int ageG = 40 + HatHandler.RAND.nextInt(60);\n int ageB = 40 + HatHandler.RAND.nextInt(60);\n\n float offsetR = 180 * HatHandler.RAND.nextFloat();\n float offsetG = 180 * HatHandler.RAND.nextFloat();\n float offsetB = 180 * HatHandler.RAND.nextFloat();\n\n colouriser[0] = ((float)Math.sin(Math.toRadians(offsetR + ((age + partialTick) / (float)ageR) * 360F)) * 0.5F) + 0.5F;\n colouriser[1] = ((float)Math.sin(Math.toRadians(offsetG + ((age + partialTick) / (float)ageG) * 360F)) * 0.5F) + 0.5F;\n colouriser[2] = ((float)Math.sin(Math.toRadians(offsetB + ((age + partialTick) / (float)ageB) * 360F)) * 0.5F) + 0.5F;\n }\n\n for(HatPart hatPart : hatParts)\n {\n hatPart.eventDay(age, partialTick);\n }\n }\n\n public void read(CompoundNBT tag)\n {\n name = tag.getString(\"name\");\n count = tag.getInt(\"count\");\n isFavourite = tag.getBoolean(\"isFavourite\");\n\n isNew = tag.getBoolean(\"isNew\");\n\n isShowing = tag.getBoolean(\"isShowing\");\n\n colouriser = new float[] { tag.getFloat(\"clrR\"), tag.getFloat(\"clrG\"), tag.getFloat(\"clrB\"), tag.getFloat(\"clrA\") };\n hsbiser = new float[] { tag.getFloat(\"hsbH\"), tag.getFloat(\"hsbS\"), tag.getFloat(\"hsbB\") };\n enchanted = tag.getBoolean(\"enchanted\");\n\n int count = tag.getInt(\"partCount\");\n\n hatParts.clear();\n for(int i = 0; i < count; i++)\n {\n CompoundNBT partTag = tag.getCompound(\"part_\" + i);\n\n HatPart part = new HatPart();\n part.read(partTag);\n\n if(!part.name.isEmpty())\n {\n hatParts.add(part);\n }\n }\n }\n\n public CompoundNBT write(CompoundNBT tag)\n {\n tag.putString(\"name\", name);\n tag.putInt(\"count\", count);\n tag.putBoolean(\"isFavourite\", isFavourite);\n\n tag.putBoolean(\"isNew\", isNew);\n\n tag.putBoolean(\"isShowing\", isShowing);\n\n tag.putFloat(\"clrR\", colouriser[0]);\n tag.putFloat(\"clrG\", colouriser[1]);\n tag.putFloat(\"clrB\", colouriser[2]);\n tag.putFloat(\"clrA\", colouriser[3]);\n\n tag.putFloat(\"hsbH\", hsbiser[0]);\n tag.putFloat(\"hsbS\", hsbiser[1]);\n tag.putFloat(\"hsbB\", hsbiser[2]);\n\n tag.putBoolean(\"enchanted\", enchanted);\n\n tag.putInt(\"partCount\", hatParts.size());\n\n for(int i = 0; i < hatParts.size(); i++)\n {\n HatPart part = hatParts.get(i);\n\n tag.put(\"part_\" + i, part.write(new CompoundNBT()));\n }\n\n return tag;\n }\n\n @Override\n public int compareTo(HatPart o)\n {\n return name.compareTo(o.name);\n }\n\n public HatPart setModifier(HatPart modifier)\n {\n modify(modifier);\n return this;\n }\n\n public boolean modify(HatPart modifier) //returns true if this or any of it's children are the modifier\n {\n if(modifier == this)\n {\n return true;\n }\n\n if(name.equals(modifier.name))\n {\n copy(modifier);\n return true;\n }\n else\n {\n for(HatPart hatPart : hatParts)\n {\n if(hatPart.modify(modifier))\n {\n return true;\n }\n }\n }\n return false;\n }\n\n public void removeHiddenChildren()\n {\n hatParts.removeIf(part -> !part.isShowing);\n for(HatPart hatPart : hatParts)\n {\n hatPart.removeHiddenChildren();\n }\n }\n\n public void setBrightnessZero()\n {\n hsbiser[2] = 1F;\n\n for(HatPart hatPart : hatParts)\n {\n hatPart.setBrightnessZero();\n }\n }\n\n public static class CapProvider implements ICapabilitySerializable<CompoundNBT>\n {\n private final HatPart hatPart;\n private final LazyOptional<HatPart> optional;\n\n public CapProvider(HatPart hatPart)\n {\n this.hatPart = hatPart;\n this.optional = LazyOptional.of(() -> hatPart);\n }\n\n @Nonnull\n @Override\n public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side)\n {\n if(cap == CAPABILITY_INSTANCE)\n {\n return optional.cast();\n }\n return LazyOptional.empty();\n }\n\n @Override\n public CompoundNBT serializeNBT()\n {\n return hatPart.write(new CompoundNBT());\n }\n\n @Override\n public void deserializeNBT(CompoundNBT nbt)\n {\n hatPart.read(nbt);\n }\n }\n }\n}"
] | import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import me.ichun.mods.hats.client.gui.WorkspaceHats;
import me.ichun.mods.hats.client.gui.window.element.ElementHatRender;
import me.ichun.mods.hats.client.gui.window.element.ElementHatsScrollView;
import me.ichun.mods.hats.common.Hats;
import me.ichun.mods.hats.common.hats.HatInfo;
import me.ichun.mods.hats.common.hats.HatResourceHandler;
import me.ichun.mods.hats.common.hats.sort.SortHandler;
import me.ichun.mods.hats.common.world.HatsSavedData;
import me.ichun.mods.ichunutil.client.gui.bns.window.Window;
import me.ichun.mods.ichunutil.client.gui.bns.window.constraint.Constraint;
import me.ichun.mods.ichunutil.client.gui.bns.window.view.View;
import me.ichun.mods.ichunutil.client.gui.bns.window.view.element.*;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.math.MathHelper;
import javax.annotation.Nonnull;
import java.text.DecimalFormat;
import java.util.List;
import java.util.stream.Collectors; | package me.ichun.mods.hats.client.gui.window;
public class WindowAllHats extends Window<WorkspaceHats>
{
public int age;
public WindowAllHats(WorkspaceHats parent)
{
super(parent);
disableDockingEntirely();
disableDrag();
disableTitle();
setView(new ViewAllHats(this));
}
@Override
public void render(MatrixStack stack, int mouseX, int mouseY, float partialTick)
{ | if(age <= Hats.configClient.guiAnimationTime) | 3 |
ChillingVan/AndroidInstantVideo | app/src/main/java/com/chillingvan/instantvideo/sample/test/publisher/TestMp4MuxerActivity.java | [
"public class CameraPreviewTextureView extends GLMultiTexProducerView {\n\n private H264Encoder.OnDrawListener onDrawListener;\n private IAndroidCanvasHelper drawTextHelper = IAndroidCanvasHelper.Factory.createAndroidCanvasHelper(IAndroidCanvasHelper.MODE.MODE_ASYNC);\n private Paint textPaint;\n\n public CameraPreviewTextureView(Context context) {\n super(context);\n }\n\n public CameraPreviewTextureView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public CameraPreviewTextureView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n }\n\n @Override\n protected int getInitialTexCount() {\n return 2;\n }\n\n @Override\n public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {\n super.onSurfaceTextureAvailable(surface, width, height);\n if (mSharedEglContext == null) {\n setSharedEglContext(EglContextWrapper.EGL_NO_CONTEXT_WRAPPER);\n }\n }\n\n @Override\n public void onSurfaceChanged(int width, int height) {\n super.onSurfaceChanged(width, height);\n drawTextHelper.init(width, height);\n textPaint = new Paint();\n textPaint.setColor(Color.WHITE);\n textPaint.setTextSize(dp2px(15));\n }\n\n @Override\n protected void onGLDraw(ICanvasGL canvas, List<GLTexture> producedTextures, List<GLTexture> consumedTextures) {\n onDrawListener.onGLDraw(canvas, producedTextures, consumedTextures);\n drawTextHelper.draw(new IAndroidCanvasHelper.CanvasPainter() {\n @Override\n public void draw(Canvas androidCanvas) {\n androidCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);\n androidCanvas.drawText(\"白色, White\", 100, 100, textPaint);\n }\n });\n Bitmap outputBitmap = drawTextHelper.getOutputBitmap();\n canvas.invalidateTextureContent(outputBitmap);\n canvas.drawBitmap(outputBitmap, 0, 0);\n }\n\n private float dp2px(int dp) {\n return dp * getContext().getResources().getDisplayMetrics().density;\n }\n\n public void setOnDrawListener(H264Encoder.OnDrawListener l) {\n onDrawListener = l;\n }\n}",
"public class ScreenUtil {\n\n public static float dpToPx(Context context, float dp) {\n if (context == null) {\n return -1;\n }\n return dp * context.getResources().getDisplayMetrics().density;\n }\n}",
"public class InstantVideoCamera implements CameraInterface {\n\n private Camera camera;\n private boolean isOpened;\n private int currentCamera;\n private int previewWidth;\n private int previewHeight;\n\n @Override\n public void setPreview(SurfaceTexture surfaceTexture) {\n try {\n camera.setPreviewTexture(surfaceTexture);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public InstantVideoCamera(int currentCamera, int previewWidth, int previewHeight) {\n this.currentCamera = currentCamera;\n this.previewWidth = previewWidth;\n this.previewHeight = previewHeight;\n }\n\n @Override\n public void openCamera() {\n Camera.CameraInfo info = new Camera.CameraInfo();\n\n // Try to find a front-facing camera (e.g. for videoconferencing).\n int numCameras = Camera.getNumberOfCameras();\n for (int i = 0; i < numCameras; i++) {\n Camera.getCameraInfo(i, info);\n if (info.facing == currentCamera) {\n camera = Camera.open(i);\n break;\n }\n }\n if (camera == null) {\n camera = Camera.open();\n }\n\n Camera.Parameters parms = camera.getParameters();\n\n CameraUtils.choosePreviewSize(parms, previewWidth, previewHeight);\n isOpened = true;\n }\n\n @Override\n public void switchCamera() {\n switchCamera(previewWidth, previewHeight);\n }\n\n @Override\n public void switchCamera(int previewWidth, int previewHeight) {\n this.previewWidth = previewWidth;\n this.previewHeight = previewHeight;\n release();\n currentCamera = currentCamera == Camera.CameraInfo.CAMERA_FACING_BACK ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK;\n openCamera();\n }\n\n @Override\n public boolean isOpened() {\n return isOpened;\n }\n\n @Override\n public void startPreview() {\n camera.startPreview();\n }\n\n @Override\n public void stopPreview() {\n camera.stopPreview();\n }\n\n @Override\n public Camera getCamera() {\n return camera;\n }\n\n @Override\n public void release() {\n if (isOpened) {\n camera.stopPreview();\n camera.release();\n camera = null;\n isOpened = false;\n }\n }\n\n\n}",
"public class H264Encoder {\n\n private final Surface mInputSurface;\n private final MediaCodecInputStream mediaCodecInputStream;\n MediaCodec mEncoder;\n\n private static final String MIME_TYPE = \"video/avc\"; // H.264 Advanced Video Coding\n private static final int FRAME_RATE = 30; // 30fps\n private static final int IFRAME_INTERVAL = 5; // 5 seconds between I-frames\n protected final EncoderCanvas offScreenCanvas;\n private OnDrawListener onDrawListener;\n private boolean isStart;\n private int initialTextureCount = 1;\n\n\n public H264Encoder(StreamPublisher.StreamPublisherParam params) throws IOException {\n this(params, EglContextWrapper.EGL_NO_CONTEXT_WRAPPER);\n }\n\n\n /**\n *\n * @param eglCtx can be EGL10.EGL_NO_CONTEXT or outside context\n */\n public H264Encoder(final StreamPublisher.StreamPublisherParam params, final EglContextWrapper eglCtx) throws IOException {\n\n// MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, params.width, params.height);\n MediaFormat format = params.createVideoMediaFormat();\n\n\n // Set some properties. Failing to specify some of these can cause the MediaCodec\n // configure() call to throw an unhelpful exception.\n format.setInteger(MediaFormat.KEY_COLOR_FORMAT,\n MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);\n format.setInteger(MediaFormat.KEY_BIT_RATE, params.videoBitRate);\n format.setInteger(MediaFormat.KEY_FRAME_RATE, params.frameRate);\n format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, params.iframeInterval);\n mEncoder = MediaCodec.createEncoderByType(params.videoMIMEType);\n mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);\n mInputSurface = mEncoder.createInputSurface();\n mEncoder.start();\n mediaCodecInputStream = new MediaCodecInputStream(mEncoder, new MediaCodecInputStream.MediaFormatCallback() {\n @Override\n public void onChangeMediaFormat(MediaFormat mediaFormat) {\n params.setVideoOutputMediaFormat(mediaFormat);\n }\n });\n\n this.initialTextureCount = params.getInitialTextureCount();\n offScreenCanvas = new EncoderCanvas(params.width, params.height, eglCtx);\n }\n\n /**\n * If called, should be called before start() called.\n */\n public void addSharedTexture(GLTexture texture) {\n offScreenCanvas.addConsumeGLTexture(texture);\n }\n\n\n public Surface getInputSurface() {\n return mInputSurface;\n }\n\n public MediaCodecInputStream getMediaCodecInputStream() {\n return mediaCodecInputStream;\n }\n\n /**\n *\n * @param initialTextureCount Default is 1\n */\n public void setInitialTextureCount(int initialTextureCount) {\n if (initialTextureCount < 1) {\n throw new IllegalArgumentException(\"initialTextureCount must >= 1\");\n }\n this.initialTextureCount = initialTextureCount;\n }\n\n public void start() {\n offScreenCanvas.start();\n isStart = true;\n }\n\n public void close() {\n if (!isStart) return;\n\n Loggers.d(\"H264Encoder\", \"close\");\n offScreenCanvas.end();\n mediaCodecInputStream.close();\n synchronized (mEncoder) {\n mEncoder.stop();\n mEncoder.release();\n }\n isStart = false;\n }\n\n public boolean isStart() {\n return isStart;\n }\n\n public void requestRender() {\n offScreenCanvas.requestRender();\n }\n\n\n public void requestRenderAndWait() {\n offScreenCanvas.requestRenderAndWait();\n }\n\n public void setOnDrawListener(OnDrawListener l) {\n this.onDrawListener = l;\n }\n\n public interface OnDrawListener {\n /**\n * Called when a frame is ready to be drawn.\n * @param canvasGL The gl canvas\n * @param producedTextures The textures produced by internal. These can be used for camera or video decoder to render.\n * @param consumedTextures See {@link #addSharedTexture(GLTexture)}. The textures you set from outside. Then you can draw the textures render by other Views of OffscreenCanvas.\n */\n void onGLDraw(ICanvasGL canvasGL, List<GLTexture> producedTextures, List<GLTexture> consumedTextures);\n }\n\n private class EncoderCanvas extends MultiTexOffScreenCanvas {\n public EncoderCanvas(int width, int height, EglContextWrapper eglCtx) {\n super(width, height, eglCtx, H264Encoder.this.mInputSurface);\n }\n\n @Override\n protected void onGLDraw(ICanvasGL canvas, List<GLTexture> producedTextures, List<GLTexture> consumedTextures) {\n if (onDrawListener != null) {\n onDrawListener.onGLDraw(canvas, producedTextures, consumedTextures);\n }\n }\n\n @Override\n protected int getInitialTexCount() {\n return initialTextureCount;\n }\n }\n}",
"public class MP4Muxer extends BaseMuxer {\n private static final String TAG = \"MP4Muxer\";\n\n private MediaMuxer mMuxer;\n private Integer videoTrackIndex = null;\n private Integer audioTrackIndex = null;\n private int trackCnt = 0;\n private FrameSender frameSender;\n private StreamPublisher.StreamPublisherParam params;\n private boolean isStart;\n\n\n public MP4Muxer() {\n super();\n }\n\n @Override\n public int open(final StreamPublisher.StreamPublisherParam params) {\n isStart = false;\n trackCnt = 0;\n videoTrackIndex = null;\n audioTrackIndex = null;\n\n this.params = params;\n super.open(params);\n try {\n mMuxer = new MediaMuxer(params.outputFilePath,\n MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n frameSender = new FrameSender(new FrameSender.FrameSenderCallback(){\n\n @Override\n public void onStart() {\n isStart = true;\n mMuxer.start();\n }\n\n @Override\n public void onSendVideo(FramePool.Frame sendFrame) {\n if (isStart) {\n mMuxer.writeSampleData(videoTrackIndex, ByteBuffer.wrap(sendFrame.data), sendFrame.bufferInfo.getBufferInfo());\n }\n }\n\n @Override\n public void onSendAudio(FramePool.Frame sendFrame) {\n if (isStart) {\n mMuxer.writeSampleData(audioTrackIndex, ByteBuffer.wrap(sendFrame.data), sendFrame.bufferInfo.getBufferInfo());\n }\n }\n\n @Override\n public void close() {\n isStart = false;\n if (mMuxer != null) {\n mMuxer.stop();\n mMuxer.release();\n mMuxer = null;\n }\n }\n });\n\n\n\n return 1;\n }\n\n @Override\n public void writeVideo(byte[] buffer, int offset, int length, MediaCodec.BufferInfo bufferInfo) {\n super.writeVideo(buffer, offset, length, bufferInfo);\n\n addTrackAndReadyToStart(FramePool.Frame.TYPE_VIDEO);\n\n Loggers.d(TAG, \"writeVideo: \" + \" offset:\" + offset + \" length:\" + length);\n frameSender.sendAddFrameMessage(buffer, offset, length, new BufferInfoEx(bufferInfo, videoTimeIndexCounter.getTimeIndex()), FramePool.Frame.TYPE_VIDEO);\n }\n\n @Override\n public void writeAudio(byte[] buffer, int offset, int length, MediaCodec.BufferInfo bufferInfo) {\n super.writeAudio(buffer, offset, length, bufferInfo);\n addTrackAndReadyToStart(FramePool.Frame.TYPE_AUDIO);\n\n Loggers.d(TAG, \"writeAudio: \");\n frameSender.sendAddFrameMessage(buffer, offset, length, new BufferInfoEx(bufferInfo, audioTimeIndexCounter.getTimeIndex()), FramePool.Frame.TYPE_AUDIO);\n }\n\n private void addTrackAndReadyToStart(int type) {\n if (trackCnt == 2) {\n return;\n }\n\n if (videoTrackIndex == null && type == FramePool.Frame.TYPE_VIDEO) {\n MediaFormat videoOutputMediaFormat = params.getVideoOutputMediaFormat();\n videoOutputMediaFormat.getByteBuffer(\"csd-0\"); // SPS\n videoOutputMediaFormat.getByteBuffer(\"csd-1\"); // PPS\n videoTrackIndex = mMuxer.addTrack(videoOutputMediaFormat);\n trackCnt++;\n } else if (audioTrackIndex == null && type == FramePool.Frame.TYPE_AUDIO) {\n MediaFormat audioOutputMediaFormat = params.getAudioOutputMediaFormat();\n audioTrackIndex = mMuxer.addTrack(audioOutputMediaFormat);\n trackCnt++;\n }\n\n if (trackCnt == 2) {\n frameSender.sendStartMessage();\n }\n }\n\n @Override\n public int close() {\n if (frameSender != null) {\n frameSender.sendCloseMessage();\n }\n return 0;\n }\n}",
"public class CameraStreamPublisher {\n\n private StreamPublisher streamPublisher;\n private IMuxer muxer;\n private GLMultiTexProducerView cameraPreviewTextureView;\n private CameraInterface instantVideoCamera;\n private OnSurfacesCreatedListener onSurfacesCreatedListener;\n\n public CameraStreamPublisher(IMuxer muxer, GLMultiTexProducerView cameraPreviewTextureView, CameraInterface instantVideoCamera) {\n this.muxer = muxer;\n this.cameraPreviewTextureView = cameraPreviewTextureView;\n this.instantVideoCamera = instantVideoCamera;\n }\n\n private void initCameraTexture() {\n cameraPreviewTextureView.setOnCreateGLContextListener(new GLThread.OnCreateGLContextListener() {\n @Override\n public void onCreate(EglContextWrapper eglContext) {\n streamPublisher = new StreamPublisher(eglContext, muxer);\n }\n });\n cameraPreviewTextureView.setSurfaceTextureCreatedListener(new GLMultiTexProducerView.SurfaceTextureCreatedListener() {\n @Override\n public void onCreated(List<GLTexture> producedTextureList) {\n if (onSurfacesCreatedListener != null) {\n onSurfacesCreatedListener.onCreated(producedTextureList, streamPublisher);\n }\n GLTexture texture = producedTextureList.get(0);\n SurfaceTexture surfaceTexture = texture.getSurfaceTexture();\n streamPublisher.addSharedTexture(new GLTexture(texture.getRawTexture(), surfaceTexture));\n surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {\n @Override\n public void onFrameAvailable(SurfaceTexture surfaceTexture) {\n cameraPreviewTextureView.requestRenderAndWait();\n streamPublisher.drawAFrame();\n }\n });\n\n instantVideoCamera.setPreview(surfaceTexture);\n instantVideoCamera.startPreview();\n }\n });\n }\n\n public void prepareEncoder(StreamPublisher.StreamPublisherParam param, H264Encoder.OnDrawListener onDrawListener) {\n streamPublisher.prepareEncoder(param, onDrawListener);\n }\n\n public void resumeCamera() {\n if (instantVideoCamera.isOpened()) return;\n\n instantVideoCamera.openCamera();\n initCameraTexture();\n cameraPreviewTextureView.onResume();\n }\n\n public boolean isStart() {\n return streamPublisher != null && streamPublisher.isStart();\n }\n\n public void pauseCamera() {\n if (!instantVideoCamera.isOpened()) return;\n\n instantVideoCamera.release();\n cameraPreviewTextureView.onPause();\n }\n\n public void startPublish() throws IOException {\n streamPublisher.start();\n }\n\n\n public void closeAll() {\n streamPublisher.close();\n }\n\n public void setOnSurfacesCreatedListener(OnSurfacesCreatedListener onSurfacesCreatedListener) {\n this.onSurfacesCreatedListener = onSurfacesCreatedListener;\n }\n\n public interface OnSurfacesCreatedListener {\n void onCreated(List<GLTexture> producedTextureList, StreamPublisher streamPublisher);\n }\n}",
"public class StreamPublisher {\n\n public static final int MSG_OPEN = 1;\n public static final int MSG_WRITE_VIDEO = 2;\n private EglContextWrapper eglCtx;\n private IMuxer muxer;\n private AACEncoder aacEncoder;\n private H264Encoder h264Encoder;\n private boolean isStart;\n\n private HandlerThread writeVideoHandlerThread;\n\n private Handler writeVideoHandler;\n private StreamPublisherParam param;\n private List<GLTexture> sharedTextureList = new ArrayList<>();\n\n public StreamPublisher(EglContextWrapper eglCtx, IMuxer muxer) {\n this.eglCtx = eglCtx;\n this.muxer = muxer;\n }\n\n\n public void prepareEncoder(final StreamPublisherParam param, H264Encoder.OnDrawListener onDrawListener) {\n this.param = param;\n\n try {\n h264Encoder = new H264Encoder(param, eglCtx);\n for (GLTexture texture :sharedTextureList ) {\n h264Encoder.addSharedTexture(texture);\n }\n h264Encoder.setOnDrawListener(onDrawListener);\n aacEncoder = new AACEncoder(param);\n aacEncoder.setOnDataComingCallback(new AACEncoder.OnDataComingCallback() {\n private byte[] writeBuffer = new byte[param.audioBitRate / 8];\n\n @Override\n public void onComing() {\n MediaCodecInputStream mediaCodecInputStream = aacEncoder.getMediaCodecInputStream();\n MediaCodecInputStream.readAll(mediaCodecInputStream, writeBuffer, new MediaCodecInputStream.OnReadAllCallback() {\n @Override\n public void onReadOnce(byte[] buffer, int readSize, MediaCodec.BufferInfo bufferInfo) {\n if (readSize <= 0) {\n return;\n }\n muxer.writeAudio(buffer, 0, readSize, bufferInfo);\n }\n });\n }\n });\n\n } catch (IOException | IllegalStateException e) {\n e.printStackTrace();\n }\n\n writeVideoHandlerThread = new HandlerThread(\"WriteVideoHandlerThread\");\n writeVideoHandlerThread.start();\n writeVideoHandler = new Handler(writeVideoHandlerThread.getLooper()) {\n private byte[] writeBuffer = new byte[param.videoBitRate / 8 / 2];\n\n @Override\n public void handleMessage(Message msg) {\n super.handleMessage(msg);\n if (msg.what == MSG_WRITE_VIDEO) {\n MediaCodecInputStream mediaCodecInputStream = h264Encoder.getMediaCodecInputStream();\n MediaCodecInputStream.readAll(mediaCodecInputStream, writeBuffer, new MediaCodecInputStream.OnReadAllCallback() {\n @Override\n public void onReadOnce(byte[] buffer, int readSize, MediaCodec.BufferInfo bufferInfo) {\n if (readSize <= 0) {\n return;\n }\n Loggers.d(\"StreamPublisher\", String.format(\"onReadOnce: %d\", readSize));\n muxer.writeVideo(buffer, 0, readSize, bufferInfo);\n }\n });\n }\n }\n };\n }\n\n public void addSharedTexture(GLTexture outsideTexture) {\n sharedTextureList.add(outsideTexture);\n }\n\n\n public void start() throws IOException {\n if (!isStart) {\n if (muxer.open(param) <= 0) {\n Loggers.e(\"StreamPublisher\", \"muxer open fail\");\n throw new IOException(\"muxer open fail\");\n }\n h264Encoder.start();\n aacEncoder.start();\n isStart = true;\n }\n\n }\n\n public void close() {\n isStart = false;\n if (h264Encoder != null) {\n h264Encoder.close();\n }\n\n if (aacEncoder != null) {\n aacEncoder.close();\n }\n if (writeVideoHandlerThread != null) {\n writeVideoHandlerThread.quitSafely();\n }\n if (muxer != null) {\n muxer.close();\n }\n }\n\n public boolean isStart() {\n return isStart;\n }\n\n\n public boolean drawAFrame() {\n if (isStart) {\n h264Encoder.requestRender();\n writeVideoHandler.sendEmptyMessage(MSG_WRITE_VIDEO);\n return true;\n }\n return false;\n }\n\n public static class StreamPublisherParam {\n public int width = 640;\n public int height = 480;\n public int videoBitRate = 2949120;\n public int frameRate = 30;\n public int iframeInterval = 5;\n public int samplingRate = 44100;\n public int audioBitRate = 192000;\n public int audioSource;\n public int channelCfg = AudioFormat.CHANNEL_IN_STEREO;\n\n public String videoMIMEType = \"video/avc\";\n public String audioMIME = \"audio/mp4a-latm\";\n public int audioBufferSize;\n\n public String outputFilePath;\n public String outputUrl;\n private MediaFormat videoOutputMediaFormat;\n private MediaFormat audioOutputMediaFormat;\n\n private int initialTextureCount = 1;\n\n public StreamPublisherParam() {\n this(640, 480, 2949120, 30, 5, 44100, 192000, MediaRecorder.AudioSource.MIC, AudioFormat.CHANNEL_IN_STEREO);\n }\n\n private StreamPublisherParam(int width, int height, int videoBitRate, int frameRate,\n int iframeInterval, int samplingRate, int audioBitRate, int audioSource, int channelCfg) {\n this.width = width;\n this.height = height;\n this.videoBitRate = videoBitRate;\n this.frameRate = frameRate;\n this.iframeInterval = iframeInterval;\n this.samplingRate = samplingRate;\n this.audioBitRate = audioBitRate;\n this.audioBufferSize = AudioRecord.getMinBufferSize(samplingRate, channelCfg, AudioFormat.ENCODING_PCM_16BIT) * 2;\n this.audioSource = audioSource;\n this.channelCfg = channelCfg;\n }\n\n /**\n *\n * @param initialTextureCount Default is 1\n */\n public void setInitialTextureCount(int initialTextureCount) {\n if (initialTextureCount < 1) {\n throw new IllegalArgumentException(\"initialTextureCount must >= 1\");\n }\n this.initialTextureCount = initialTextureCount;\n }\n\n public int getInitialTextureCount() {\n return initialTextureCount;\n }\n\n public MediaFormat createVideoMediaFormat() {\n MediaFormat format = MediaFormat.createVideoFormat(videoMIMEType, width, height);\n\n // Set some properties. Failing to specify some of these can cause the MediaCodec\n // configure() call to throw an unhelpful exception.\n format.setInteger(MediaFormat.KEY_COLOR_FORMAT,\n MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);\n format.setInteger(MediaFormat.KEY_BIT_RATE, videoBitRate);\n format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);\n format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, iframeInterval);\n return format;\n }\n\n public MediaFormat createAudioMediaFormat() {\n MediaFormat format = MediaFormat.createAudioFormat(audioMIME, samplingRate, 2);\n format.setInteger(MediaFormat.KEY_BIT_RATE, audioBitRate);\n format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);\n format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, audioBufferSize);\n\n return format;\n }\n\n public void setVideoOutputMediaFormat(MediaFormat videoOutputMediaFormat) {\n this.videoOutputMediaFormat = videoOutputMediaFormat;\n }\n\n public void setAudioOutputMediaFormat(MediaFormat audioOutputMediaFormat) {\n this.audioOutputMediaFormat = audioOutputMediaFormat;\n }\n\n public MediaFormat getVideoOutputMediaFormat() {\n return videoOutputMediaFormat;\n }\n\n public MediaFormat getAudioOutputMediaFormat() {\n return audioOutputMediaFormat;\n }\n\n public static class Builder {\n private int width = 640;\n private int height = 480;\n private int videoBitRate = 2949120;\n private int frameRate = 30;\n private int iframeInterval = 5;\n private int samplingRate = 44100;\n private int audioBitRate = 192000;\n private int audioSource = MediaRecorder.AudioSource.MIC;\n private int channelCfg = AudioFormat.CHANNEL_IN_STEREO;\n\n public Builder setWidth(int width) {\n this.width = width;\n return this;\n }\n\n public Builder setHeight(int height) {\n this.height = height;\n return this;\n }\n\n public Builder setVideoBitRate(int videoBitRate) {\n this.videoBitRate = videoBitRate;\n return this;\n }\n\n public Builder setFrameRate(int frameRate) {\n this.frameRate = frameRate;\n return this;\n }\n\n public Builder setIframeInterval(int iframeInterval) {\n this.iframeInterval = iframeInterval;\n return this;\n }\n\n public Builder setSamplingRate(int samplingRate) {\n this.samplingRate = samplingRate;\n return this;\n }\n\n public Builder setAudioBitRate(int audioBitRate) {\n this.audioBitRate = audioBitRate;\n return this;\n }\n\n public Builder setAudioSource(int audioSource) {\n this.audioSource = audioSource;\n return this;\n }\n\n public Builder setChannelCfg(int channelCfg) {\n this.channelCfg = channelCfg;\n return this;\n }\n\n public StreamPublisherParam createStreamPublisherParam() {\n return new StreamPublisherParam(width, height, videoBitRate, frameRate, iframeInterval, samplingRate, audioBitRate, audioSource, channelCfg);\n }\n }\n }\n\n}"
] | import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.chillingvan.canvasgl.ICanvasGL;
import com.chillingvan.canvasgl.androidCanvas.IAndroidCanvasHelper;
import com.chillingvan.canvasgl.glcanvas.BasicTexture;
import com.chillingvan.canvasgl.glcanvas.RawTexture;
import com.chillingvan.canvasgl.glview.texture.GLTexture;
import com.chillingvan.canvasgl.textureFilter.BasicTextureFilter;
import com.chillingvan.canvasgl.textureFilter.HueFilter;
import com.chillingvan.canvasgl.textureFilter.TextureFilter;
import com.chillingvan.canvasgl.util.Loggers;
import com.chillingvan.instantvideo.sample.R;
import com.chillingvan.instantvideo.sample.test.camera.CameraPreviewTextureView;
import com.chillingvan.instantvideo.sample.util.ScreenUtil;
import com.chillingvan.lib.camera.InstantVideoCamera;
import com.chillingvan.lib.encoder.video.H264Encoder;
import com.chillingvan.lib.muxer.MP4Muxer;
import com.chillingvan.lib.publisher.CameraStreamPublisher;
import com.chillingvan.lib.publisher.StreamPublisher;
import java.io.IOException;
import java.util.List; | /*
*
* *
* * * Copyright (C) 2017 ChillingVan
* * *
* * * 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.chillingvan.instantvideo.sample.test.publisher;
/**
* This sample shows how to record a mp4 file. It cannot pause but only can restart. If you want to pause when recording, you need to generate a new file and merge old files and new file.
*/
public class TestMp4MuxerActivity extends AppCompatActivity {
private CameraStreamPublisher streamPublisher;
private CameraPreviewTextureView cameraPreviewTextureView;
private InstantVideoCamera instantVideoCamera;
private Handler handler;
private HandlerThread handlerThread;
private TextView outDirTxt;
private String outputDir;
private MediaPlayerHelper mediaPlayer = new MediaPlayerHelper();
private Surface mediaSurface;
private IAndroidCanvasHelper drawTextHelper = IAndroidCanvasHelper.Factory.createAndroidCanvasHelper(IAndroidCanvasHelper.MODE.MODE_ASYNC);
private Paint textPaint;
private Button startButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initTextPaint();
outputDir = getExternalFilesDir(null) + "/test_mp4_encode.mp4";
setContentView(R.layout.activity_test_mp4_muxer);
cameraPreviewTextureView = findViewById(R.id.camera_produce_view);
cameraPreviewTextureView.setOnDrawListener(new H264Encoder.OnDrawListener() {
@Override
public void onGLDraw(ICanvasGL canvasGL, List<GLTexture> producedTextures, List<GLTexture> consumedTextures) {
GLTexture texture = producedTextures.get(0);
GLTexture mediaTexture = producedTextures.get(1);
drawVideoFrame(canvasGL, texture.getSurfaceTexture(), texture.getRawTexture(), mediaTexture);
}
});
outDirTxt = (TextView) findViewById(R.id.output_dir_txt);
outDirTxt.setText(outputDir);
startButton = findViewById(R.id.test_camera_button);
instantVideoCamera = new InstantVideoCamera(Camera.CameraInfo.CAMERA_FACING_FRONT, 640, 480);
// instantVideoCamera = new InstantVideoCamera(Camera.CameraInfo.CAMERA_FACING_FRONT, 1280, 720);
handlerThread = new HandlerThread("StreamPublisherOpen");
handlerThread.start();
handler = new Handler(handlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
playMedia();
// StreamPublisher.StreamPublisherParam streamPublisherParam = new StreamPublisher.StreamPublisherParam();
// StreamPublisher.StreamPublisherParam streamPublisherParam = new StreamPublisher.StreamPublisherParam(1080, 640, 9500 * 1000, 30, 1, 44100, 19200);
StreamPublisher.StreamPublisherParam.Builder builder = new StreamPublisher.StreamPublisherParam.Builder();
StreamPublisher.StreamPublisherParam streamPublisherParam = builder
.setWidth(1080)
.setHeight(750)
.setVideoBitRate(1500 * 1000)
.setFrameRate(30)
.setIframeInterval(1)
.setSamplingRate(44100)
.setAudioBitRate(19200)
.setAudioSource(MediaRecorder.AudioSource.MIC)
.createStreamPublisherParam();
streamPublisherParam.outputFilePath = outputDir;
streamPublisherParam.setInitialTextureCount(2);
streamPublisher.prepareEncoder(streamPublisherParam, new H264Encoder.OnDrawListener() {
@Override
public void onGLDraw(ICanvasGL canvasGL, List<GLTexture> producedTextures, List<GLTexture> consumedTextures) {
GLTexture texture = consumedTextures.get(1);
GLTexture mediaTexture = consumedTextures.get(0);
drawVideoFrame(canvasGL, texture.getSurfaceTexture(), texture.getRawTexture(), mediaTexture);
Loggers.i("DEBUG", "gl draw");
}
});
try {
streamPublisher.startPublish();
} catch (IOException e) {
e.printStackTrace();
((TextView)findViewById(R.id.test_camera_button)).setText("START");
}
}
};
streamPublisher = new CameraStreamPublisher(new MP4Muxer(), cameraPreviewTextureView, instantVideoCamera);
streamPublisher.setOnSurfacesCreatedListener(new CameraStreamPublisher.OnSurfacesCreatedListener() {
@Override
public void onCreated(List<GLTexture> producedTextureList, StreamPublisher streamPublisher) {
GLTexture texture = producedTextureList.get(1);
GLTexture mediaTexture = producedTextureList.get(1);
streamPublisher.addSharedTexture(new GLTexture(mediaTexture.getRawTexture(), mediaTexture.getSurfaceTexture()));
mediaSurface = new Surface(texture.getSurfaceTexture());
}
});
}
private void initTextPaint() {
textPaint = new Paint();
textPaint.setColor(Color.WHITE); | textPaint.setTextSize(ScreenUtil.dpToPx(getApplicationContext(), 15)); | 1 |
Chat-Wane/LSEQ | src/main/java/alma/fr/modules/GreedRandDoubleModule.java | [
"public class BaseDouble implements IBase {\n\n\tprivate final Integer baseBase;\n\n\t@Inject\n\tpublic BaseDouble(@Basebase Integer baseBase) {\n\t\tthis.baseBase = baseBase;\n\t}\n\n\tpublic Integer getBitBase(Integer depth) {\n\t\treturn baseBase + depth - 1;\n\t}\n\n\tpublic Integer getSumBit(Integer depth) {\n\t\tint n = getBitBase(depth);\n\t\tint m = baseBase - 1;\n\t\treturn (n * (n + 1)) / 2 - (m * (m + 1) / 2);\n\t}\n\n\tpublic Integer getBaseBase() {\n\t\treturn baseBase;\n\t}\n\n\tpublic BigInteger sub(BigInteger r, BigInteger value) {\n\t\treturn r.subtract(value);\n\t}\n\n\tpublic BigInteger add(BigInteger r, BigInteger value) {\n\t\treturn r.add(value);\n\t}\n\n\tpublic BigInteger interval(BigInteger p, BigInteger q, Integer index) {\n\t\tint prevBitLength = p.bitLength() - 1;\n\t\tint nextBitLength = q.bitLength() - 1;\n\n\t\tint bitBaseSum = getSumBit(index);\n\t\tBigInteger result = BigInteger.ZERO;\n\n\t\t// #1 truncate or add\n\t\t// #1a: on previous digit\n\t\tBigInteger prev;\n\t\tif (prevBitLength < bitBaseSum) { // Add 0 and +1 to result\n\t\t\tprev = p.shiftLeft(bitBaseSum - prevBitLength);\n\t\t\t//result = BigInteger.ONE;\n\t\t} else {\n\t\t\tprev = p.shiftRight(prevBitLength - bitBaseSum);\n\t\t}\n\n\t\t// #1b: on next digit\n\t\tBigInteger next;\n\t\tif (nextBitLength < bitBaseSum) { // Add 1 and +1 to result\n\t\t\tnext = q.shiftLeft(bitBaseSum - nextBitLength);\n\t\t\t//next = next.add(BigInteger.valueOf(2)\n\t\t\t//\t\t.pow(bitBaseSum - nextBitLength).subtract(BigInteger.ONE));\n\t\t\t//result = result.add(BigInteger.ONE);\n\t\t} else {\n\t\t\tnext = q.shiftRight(nextBitLength - bitBaseSum);\n\t\t}\n\n\t\tresult = result.add(next.subtract(prev).subtract(BigInteger.ONE));\n\n\t\treturn result;\n\t}\n}",
"public interface IBase {\n\n\t/**\n\t * Return the number of bit to a depth\n\t * \n\t * @param depth\n\t * @return bit number\n\t */\n\tpublic Integer getSumBit(Integer depth);\n\n\t/**\n\t * The number of bit used at a given depth\n\t * \n\t * @param depth\n\t * @return bit number\n\t */\n\tInteger getBitBase(Integer depth);\n\n\t/**\n\t * the number of bit at depth 1\n\t * \n\t * @return bit number\n\t */\n\tInteger getBaseBase();\n\n\t/**\n\t * Substract value to r\n\t * \n\t * @param r\n\t * @param value\n\t * @return r-value\n\t */\n\tBigInteger sub(BigInteger r, BigInteger value);\n\n\t/**\n\t * Add value to r\n\t * \n\t * @param r\n\t * @param value\n\t * @return r+value\n\t */\n\tBigInteger add(BigInteger r, BigInteger value);\n\n\t/**\n\t * Process the interval (i.e. number of id possible) between p and q, p <_id\n\t * q.\n\t * \n\t * @param p\n\t * previous digit\n\t * @param q\n\t * next digit\n\t * @param index\n\t * depth of processing\n\t * @return the interval at given depth\n\t */\n\tBigInteger interval(BigInteger p, BigInteger q, Integer index);\n\n}",
"public class BeginningBoundaryIdProvider implements IIdProviderStrategy {\n\n\tprivate Random rand = new Random();\n\n\t@Inject\n\tprivate IBase base;\n\n\t@Inject\n\tprivate IBoundary boundary;\n\n\t@Inject\n\tpublic BeginningBoundaryIdProvider(IBase base, IBoundary boundary) {\n\t\tthis.base = base;\n\t\tthis.boundary = boundary;\n\t}\n\n\tpublic Iterator<Positions> generateIdentifiers(Positions p, Positions q,\n\t\t\tInteger N, Replica rep, BigInteger interval, int index) {\n\t\tArrayList<Positions> positions = new ArrayList<Positions>();\n\n\t\t// #0 process the interval for random\n\t\tBigInteger step = interval.divide(BigInteger.valueOf(N));\n\t\tstep = (step.min(boundary.getBoundary(index))).max(BigInteger\n\t\t\t\t.valueOf(1));\n\n\t\t// #1 Truncate tail or add bits\n\t\tint prevBitCount = p.getD().bitLength() - 1;\n\t\tint diffBitCount = prevBitCount - base.getSumBit(index);\n\n\t\tBigInteger r = p.getD().shiftRight(diffBitCount);\n\n\t\t// #2 create position by adding a random value; N times\n\t\tfor (int j = 0; j < N; ++j) {\n\t\t\tBigInteger randomInt;\n\n\t\t\t// Random\n\t\t\tif (!(step.compareTo(BigInteger.valueOf(1)) == 1)) { // step <= 1\n\t\t\t\trandomInt = BigInteger.valueOf(1);\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\trandomInt = new BigInteger(step.subtract(\n\t\t\t\t\t\t\tBigInteger.valueOf(1)).bitLength(), rand);\n\t\t\t\t} while (randomInt.compareTo(step.subtract(BigInteger\n\t\t\t\t\t\t.valueOf(1))) >= 0);\n\t\t\t\trandomInt = randomInt.add(BigInteger.valueOf(1));\n\t\t\t}\n\t\t\t// // Construct\n\t\t\tBigInteger newR = base.add(r, randomInt);\n\t\t\trep.setClock(rep.getClock() + 1);\n\t\t\tPositions tempPositions = new Positions(newR,\n\t\t\t\t\tbase.getSumBit(index), rep);\n\t\t\tpositions.add(tempPositions);\n\t\t\tr = base.add(r, step);\n\t\t}\n\n\t\treturn positions.iterator();\n\t}\n\n}",
"public class EndingBoundaryIdProvider implements IIdProviderStrategy {\n\n\tprivate Random rand = new Random();\n\n\t@Inject\n\tprivate IBase base;\n\n\t@Inject\n\tprivate IBoundary boundary;\n\n\t@Inject\n\tpublic EndingBoundaryIdProvider(IBase base, IBoundary boundary) {\n\t\tthis.base = base;\n\t\tthis.boundary = boundary;\n\t}\n\n\tpublic Iterator<Positions> generateIdentifiers(Positions p, Positions q,\n\t\t\tInteger N, Replica rep, BigInteger interval, int index) {\n\t\tArrayList<Positions> positions = new ArrayList<Positions>();\n\n\t\t// #0 process the interval for random\n\t\tBigInteger step = interval.divide(BigInteger.valueOf(N));\n\n\t\tstep = (step.min(boundary.getBoundary(index))).max(BigInteger\n\t\t\t\t.valueOf(1));\n\n\t\t// #1 Truncate tail or add bits\n\t\tint nextBitCount = q.getD().bitLength() - 1;\n\t\tint diffBitCount = nextBitCount - base.getSumBit(index);\n\n\t\tBigInteger r = q.getD().shiftRight(diffBitCount);\n\n\t\t// #2 create position by adding a random value; N times\n\t\tfor (int j = 0; j < N; ++j) {\n\t\t\tBigInteger randomInt;\n\n\t\t\t// Random\n\t\t\tif (!(step.compareTo(BigInteger.valueOf(1)) == 1)) { // step <= 1\n\t\t\t\trandomInt = BigInteger.valueOf(1);\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\trandomInt = new BigInteger(step.subtract(\n\t\t\t\t\t\t\tBigInteger.valueOf(1)).bitLength(), rand);\n\t\t\t\t} while (randomInt.compareTo(step.subtract(BigInteger\n\t\t\t\t\t\t.valueOf(1))) >= 0);\n\t\t\t\trandomInt = randomInt.add(BigInteger.valueOf(1));\n\t\t\t}\n\t\t\t// // Construct\n\t\t\tBigInteger newR = base.sub(r, randomInt);\n\t\t\trep.setClock(rep.getClock() + 1);\n\t\t\tPositions tempPositions = new Positions(newR,\n\t\t\t\t\tbase.getSumBit(index), rep);\n\t\t\tpositions.add(tempPositions);\n\t\t\tr = base.sub(r, step);\n\t\t}\n\n\t\tCollections.reverse(positions);\n\t\treturn positions.iterator();\n\t}\n\n}",
"public interface IIdProviderStrategy {\n\n\t/**\n\t * Generate N identifier between p & q\n\t * \n\t * @param p\n\t * previous identifier\n\t * @param q\n\t * next identifier\n\t * @param N\n\t * number of line inserted\n\t * @param rep\n\t * replica informations to store\n\t * @return list of unique identifiers which can be used in logoot\n\t */\n\tpublic Iterator<Positions> generateIdentifiers(Positions p, Positions q,\n\t\t\tInteger N, Replica rep, BigInteger interval, int index);\n}",
"public class ConstantBoundary implements IBoundary {\n\n\tprivate BigInteger value;\n\n\t@Inject\n\tpublic ConstantBoundary(@BoundaryValue BigInteger value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic BigInteger getBoundary(Integer depth) {\n\t\treturn value;\n\t}\n\n}",
"public interface IBoundary {\n\n\t/**\n\t * Return the boundary value at the specified depth. \n\t * @param depth\n\t * @return\n\t */\n\tBigInteger getBoundary(Integer depth);\n\t\n\t\n}",
"public interface IStrategyChoice {\n\n\t/**\n\t * Function which will defer the creation of identifiers to a bunch of\n\t * IdProviders\n\t * \n\t * @param p\n\t * previous identifier\n\t * @param q\n\t * next identifier\n\t * @param N\n\t * number of line inserted\n\t * @param rep\n\t * replica informations to store\n\t * @return list of unique identifiers which can be used in logoot\n\t */\n\tpublic Iterator<Positions> generateIdentifiers(Positions p,\n\t\t\tPositions q, Integer N, Replica rep);\n\n\t/**\n\t * Add data to the strategy choice\n\t * \n\t * @param p\n\t * previous Id\n\t * @param id\n\t * inserted\n\t * @param q\n\t * next Id\n\t */\n\tpublic void add(Positions p, Positions id, Positions q);\n\n\t\n\tpublic void del(Positions id);\n\t\n\tpublic void incDate();\n\t\n\tpublic HashMap<Positions, FakeListNode> getSpectrum();\n}",
"public class RandomStrategyChoice implements IStrategyChoice {\n\tprivate HashMap<Positions, FakeListNode> spectrum = new HashMap<Positions, FakeListNode>();\n\n\tprivate Integer date = 0;\n\n\tBitSet strategies;\n\n\tstatic final Random r = new Random();\n\n\t@Inject\n\tIBase base;\n\n\tprivate IIdProviderStrategy strategy1;\n\tprivate IIdProviderStrategy strategy2;\n\n\t@Inject\n\tpublic RandomStrategyChoice(IBase base,\n\t\t\t@Strat1 IIdProviderStrategy strategy1,\n\t\t\t@Strat2 IIdProviderStrategy strategy2) {\n\t\tthis.base = base;\n\t\tthis.strategy1 = strategy1;\n\t\tthis.strategy2 = strategy2;\n\t\tstrategies = new BitSet(0);\n\t}\n\n\t/** add the new id in the structure **/\n\tpublic void add(Positions prev, Positions id, Positions next) {\n\n\t\tif (!spectrum.containsKey(prev)) {\n\t\t\tFakeListNode prevfln = new FakeListNode(null, date, id);\n\t\t\tspectrum.put(prev, prevfln);\n\t\t} else {\n\t\t\tspectrum.get(prev).setNext(id);\n\t\t}\n\n\t\tif (!spectrum.containsKey(next)) {\n\t\t\tFakeListNode nextfln = new FakeListNode(id, date, null);\n\t\t\tspectrum.put(next, nextfln);\n\t\t} else {\n\t\t\tspectrum.get(next).setPrev(id);\n\t\t}\n\n\t\tFakeListNode fln = new FakeListNode(prev, date, next);\n\n\t\tspectrum.put(id, fln);\n\t}\n\n\tpublic void del(Positions id) {\n\t\tFakeListNode fln = spectrum.get(id);\n\t\tif (fln.getPrev() != null) {\n\t\t\tspectrum.get(fln.getPrev()).setNext(fln.getNext());\n\n\t\t}\n\t\tif (fln.getNext() != null) {\n\t\t\tspectrum.get(fln.getNext()).setPrev(fln.getPrev());\n\t\t}\n\t\tspectrum.remove(id);\n\t}\n\n\tpublic Iterator<Positions> generateIdentifiers(Positions p, Positions q,\n\t\t\tInteger N, Replica rep) {\n\n\t\t// #1 count interval between p and q, until itz enough\n\t\tBigInteger interval = BigInteger.ZERO;\n\t\tint index = 0;\n\t\twhile (BigInteger.valueOf(N).compareTo(interval) > 0) {\n\t\t\t// #1 a: obtain index value\n\t\t\t++index;\n\t\t\t// #1 b: obtain interval value\n\t\t\tinterval = base.interval(p.getD(), q.getD(), index);\n\t\t}\n\n\t\t// #2 if not already setted value in strategies\n\t\t// random a full 64 bits of strategies, bitsize.size limitation\n\t\tif (index >= strategies.size()) {\n\t\t\tint sizeBefore = strategies.size();\n\t\t\tstrategies.set(strategies.size());\n\t\t\tfor (int j = sizeBefore; j < strategies.size(); ++j) {\n\t\t\t\tif (r.nextBoolean()) {\n\t\t\t\t\tstrategies.set(j);\n\t\t\t\t} else {\n\t\t\t\t\tstrategies.clear(j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// #3 chose the strategy\n\t\tif (strategies.get(index)) {\n\t\t\treturn strategy1.generateIdentifiers(p, q, N, rep, interval, index);\n\t\t} else {\n\t\t\treturn strategy2.generateIdentifiers(p, q, N, rep, interval, index);\n\t\t}\n\t}\n\n\tpublic void incDate() {\n\t\t++date;\n\t}\n\n\tpublic HashMap<Positions, FakeListNode> getSpectrum() {\n\t\treturn spectrum;\n\t}\n\n}"
] | import java.math.BigInteger;
import alma.fr.basecomponents.BaseDouble;
import alma.fr.basecomponents.Basebase;
import alma.fr.basecomponents.IBase;
import alma.fr.strategiescomponents.BeginningBoundaryIdProvider;
import alma.fr.strategiescomponents.EndingBoundaryIdProvider;
import alma.fr.strategiescomponents.IIdProviderStrategy;
import alma.fr.strategiescomponents.boundary.BoundaryValue;
import alma.fr.strategiescomponents.boundary.ConstantBoundary;
import alma.fr.strategiescomponents.boundary.IBoundary;
import alma.fr.strategychoicecomponents.IStrategyChoice;
import alma.fr.strategychoicecomponents.RandomStrategyChoice;
import alma.fr.strategychoicecomponents.Strat1;
import alma.fr.strategychoicecomponents.Strat2;
import com.google.inject.Binder;
import com.google.inject.Module; | package alma.fr.modules;
/**
* Constant boundary but greed and double base
*/
public class GreedRandDoubleModule implements Module {
public void configure(Binder binder) {
Integer baseBase = new Integer(5);
BigInteger boundary = new BigInteger("10");
/* BASE */
binder.bind(Integer.class).annotatedWith(Basebase.class).toInstance(
baseBase); | binder.bind(IBase.class).to(BaseDouble.class); | 0 |
fvalente/LogDruid | src/logdruid/ui/table/StatRecordingEditorTable.java | [
"public class Repository {\n\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tprivate ArrayList<Recording> recordings;\n\tprivate ArrayList<Source> sources;\n\tprivate String baseSourcePath;\n\tprivate ArrayList<DateFormat> dates;\n\tprivate boolean recursiveMode;\n\tprivate boolean onlyMatches;\n\tprivate boolean stats; // unused\n\tprivate boolean timings; // unused\n\tprivate HashMap<String, String> preferences;\n\n\tpublic Repository() {\n\t\tpreferences = new HashMap<String, String>();\n\t\tpreferences.put(\"timings\", \"false\");\n\t\tpreferences.put(\"stats\", \"true\");\n\t\tpreferences.put(\"chartSize\", \"350\");\n\t\tpreferences.put(\"ThreadPool_Group\", \"4\");\n\t\tpreferences.put(\"ThreadPool_File\", \"8\");\n\t\tpreferences.put(\"editorCommand\", \"gvim -R +$line $file\");\n\t\tpreferences.put(\"gatherstats\", \"true\");\n\t\tpreferences.put(\"gatherevents\", \"true\");\n\t\tpreferences.put(\"gatherreports\", \"true\");\n\t\trecordings = new ArrayList<Recording>();\n\t\tdates = new ArrayList<DateFormat>();\n\t\tsources = new ArrayList<Source>();\n\t\trecursiveMode = false;\n\t\t// logger.info(\"repository ArrayList initialized\");\n\t}\n\n\tpublic boolean isRecursiveMode() {\n\t\treturn recursiveMode;\n\t}\n\n\tpublic void setPreference(String key, String value) {\n\t\tpreferences.put(key, value);\n\t}\n\n\tpublic String getPreference(String key) {\n\t\treturn getPreferences().get(key);\n\t}\n\n\tpublic void setRecursiveMode(boolean recursiveMode) {\n\t\t// logger.info(\"recursive mode is :\"+recursiveMode);\n\t\tthis.recursiveMode = recursiveMode;\n\t}\n\n\tpublic ArrayList<Source> getSources() {\n\t\treturn sources;\n\t}\n\n\tpublic Source getSource(String name) {\n\t\tIterator sourceIterator = sources.iterator();\n\t\tint cnt = 0;\n\t\twhile (sourceIterator.hasNext()) {\n\t\t\tSource src = (Source) sourceIterator.next();\n\t\t\tif (src.getSourceName() == name) {\n\t\t\t\treturn src;\n\t\t\t}\n\t\t}\n\t\treturn (Source) null;\n\t}\n\n\tpublic void setSources(ArrayList<Source> sources) {\n\t\tthis.sources = sources;\n\t}\n\n\tpublic void addSource(Source s) {\n\t\tif (sources == null) {\n\t\t\tsources = new ArrayList<Source>();\n\t\t}\n\t\tsources.add(s);\n\t}\n\n\tpublic void deleteSource(int id) {\n\t\tsources.remove(id);\n\t}\n\n\tpublic Source getSource(int id) {\n\t\treturn sources.get(id);\n\t}\n\n\tpublic void updateSource(int id, String txtName, String txtRegularExp, Boolean active) {\n\t\tsources.get(id).setSourceName(txtName);\n\t\tsources.get(id).setSourcePattern(txtRegularExp);\n\t\tsources.get(id).setActive(active);\n\t}\n\n\tpublic ArrayList<Recording> getRecordings() {\n\t\t// logger.info(xstream.toXML(recordings));\n\t\treturn recordings;\n\t}\n\n\tpublic ArrayList<Recording> getRecordings(Class _class, boolean onlyActive) {\n\n\t\tArrayList<Recording> statRecordingArrayList = new ArrayList<Recording>();\n\t\tIterator recordingIterator = recordings.iterator();\n\t\tint cnt = 0;\n\t\twhile (recordingIterator.hasNext()) {\n\t\t\tRecording r = (Recording) recordingIterator.next();\n\t\t\tif (r.getClass().equals(_class)) { \n\t\t\t\tif (onlyActive){\n\t\t\t\t\tif (r.getIsActive())\n\t\t\t\t\tstatRecordingArrayList.add(r);\t\n\t\t\t\t} else {\n\t\t\t\tstatRecordingArrayList.add(r);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn (ArrayList<Recording>) statRecordingArrayList;\n\t}\n\n\n\tpublic ArrayList getReportRecordings(MineResultSet mineResultSet1, boolean b) {\n\t\tArrayList<Recording> temp = new ArrayList<Recording>();\n\t\tArrayList<Recording> returned= new ArrayList<Recording>();\t\t\n\t\tIterator<Map<Recording, Map<List<Object>, Long>>> it1 = mineResultSet1.getOccurenceReport().values().iterator();\n\t\twhile (it1.hasNext()){\n\t\t\tIterator test = (Iterator) it1.next().keySet().iterator();\n\t\t\twhile (test.hasNext())\n\t\t\t{\n\t\t\ttemp.add((Recording) test.next());\n\t\t\t}\n\t\t}\n\t\t\n\t\tIterator<Map<Recording, Map<List<Object>, Double>>> it2 =mineResultSet1.getSumReport().values().iterator();\n\t\twhile (it2.hasNext()){\n\t\t\tIterator test = (Iterator) it2.next().keySet().iterator();\n\t\t\twhile (test.hasNext())\n\t\t\t{\n\t\t\ttemp.add((Recording) test.next());\n\t\t\t}\n\t\t}\n\t\t\n\t\tIterator<Map<Recording, SortedMap<Double, List<Object>>>> it3 =mineResultSet1.getTop100Report().values().iterator();\n\t\twhile (it3.hasNext()){\n\t\t\tIterator test = (Iterator) it3.next().keySet().iterator();\n\t\t\twhile (test.hasNext())\n\t\t\t{\n\t\t\ttemp.add((Recording) test.next());\n\t\t\t}\n\t\t}\n\t\t\n\t\tArrayList<Recording> aL = getRecordings(ReportRecording.class, b);\n\t\tIterator ite = aL.iterator();\n\t\twhile (ite.hasNext()){\n\t\t\tRecording rec= (Recording) ite.next();\n\t\t\tif (temp.contains(rec))\t{\n\t\t\treturned.add(rec);\t\n\t\t\t}\n\t\t}\n\t\treturn returned;\n\t}\n\t\n\t\n\tpublic Recording getRecording(Class _class, int id, boolean onlyActive) {\n\t\treturn getRecordings(_class,onlyActive).get(id);\n\t}\n\n\tpublic HashMap<String, String> getPreferences() {\n\t\tif (preferences == null) {\n\t\t\tpreferences = new HashMap<String, String>();\n\t\t\tlogger.info(\"new preferences\");\n\t\t}\n\t\tif (!preferences.containsKey(\"timings\")) {\n\t\t\tpreferences.put(\"timings\", \"false\");\n\t\t}\n\n\t\tif (!preferences.containsKey(\"stats\")) {\n\t\t\tlogger.info(\"stats set to true\");\n\t\t\tpreferences.put(\"stats\", \"true\");\n\t\t}\n\n\t\tif (!preferences.containsKey(\"chartSize\")) {\n\t\t\tpreferences.put(\"chartSize\", \"350\");\n\t\t}\n\n\t\tif (!preferences.containsKey(\"ThreadPool_Group\")) {\n\t\t\tpreferences.put(\"ThreadPool_Group\", \"4\");\n\t\t}\n\t\tif (!preferences.containsKey(\"ThreadPool_File\")) {\n\t\t\tpreferences.put(\"ThreadPool_File\", \"8\");\n\t\t}\n\t\tif (!preferences.containsKey(\"editorCommand\")) {\n\t\t\tpreferences.put(\"editorCommand\", \"gvim -R +$line $file\");\n\t\t}\n\t\t\n\t\treturn preferences;\n\t}\n\n\tpublic void addRecording(Recording r) {\n\t\trecordings.add(r);\n\t\t// logger.info(xstream.toXML(recordings));<\n\t}\n\n\tpublic int getRecordingCount() {\n\t\treturn recordings.size();\n\t}\n\n\tpublic void deleteRecording(int id) {\n\t\trecordings.remove(id);\n\t\tArrayList<Source> sources= this.getSources();\n\t\tIterator<Source> ite=sources.iterator();\n\t\twhile (ite.hasNext()){\n\t\t\tSource src=(Source) ite.next();\n\t\t\tsrc.removeActiveRecording(recordings.get(id));\n\t\t}\n\t}\n\n\tpublic Recording getRecording(int id) {\n\t\treturn recordings.get(id);\n\t}\n\n\tpublic Recording getRecording(String _id) {\n\t\tIterator recordingIterator = recordings.iterator();\n\t\tRecording recReturn = null; \n\t\tint cnt = 0;\n\t\twhile (recordingIterator.hasNext()) {\n\t\t\tRecording r = (Recording) recordingIterator.next();\n\t\t\tif (r.getId() == _id) {\n\t\t\t\trecReturn = r;\n\t\t\t}\n\t\t}\n\t\treturn recReturn;\n\t}\n\n\tpublic void duplicateRecording(int id) {\n\t\tRecording newRecording = recordings.get(id).duplicate();\n\t\tthis.addRecording(newRecording);\n\t\tArrayList<Source> sources= this.getSources();\n\t\tIterator<Source> ite=sources.iterator();\n\t\tif (!MetadataRecording.class.isInstance(recordings.get(id))){\n\t\twhile (ite.hasNext()){\n\t\t\tSource src=(Source) ite.next();\n\t\t\tif (src.isActiveRecordingOnSource(recordings.get(id))){\n\t\t\t\tsrc.toggleActiveRecording(newRecording);\n\t\t\t}\n\t\t}}\n\t}\n\n\tpublic void update(Repository repo) {\n\t\trecordings = repo.getRecordings();\n\t}\n\n\tpublic void save(File file) {\n\n\t\tFileOutputStream fos = null;\n\t\ttry {\n\t\t\tString xml = new XStream(new StaxDriver()).toXML(recordings);\n\t\t\tfos = new FileOutputStream(file);\n\t\t\t// fos.write(\"<?xml version=\\\"1.0\\\"?>\".getBytes(\"UTF-8\"));\n\t\t\tbyte[] bytes = xml.getBytes(\"UTF-8\");\n\t\t\tfos.write(bytes);\n\n\t\t} catch (Exception e) {\n\t\t\tSystem.err.println(\"Error in XML Write: \" + e.getMessage());\n\t\t} finally {\n\t\t\tif (fos != null) {\n\t\t\t\ttry {\n\t\t\t\t\tfos.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void open(File file) {\n\t\t// XStream xstream = new XStream(new StaxDriver());\n\t\tFileOutputStream fos = null;\n\t\ttry {\n\t\t\trecordings = (ArrayList<Recording>) new XStream(new StaxDriver()).fromXML(file);\n\t\t\t/*\n\t\t\t * fos = new FileOutputStream(file);\n\t\t\t * \n\t\t\t * byte[] bytes = xml.getBytes(\"UTF-8\"); fos.write(bytes);\n\t\t\t */\n\t\t\tlogger.info(new XStream(new StaxDriver()).toXML(recordings));\n\t\t} catch (Exception e) {\n\t\t\tSystem.err.println(\"Error in XML Write: \" + e.getMessage());\n\t\t} finally {\n\t\t\tif (fos != null) {\n\t\t\t\ttry {\n\t\t\t\t\tfos.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setRecordings(ArrayList recordings) {\n\t\tthis.recordings = recordings;\n\t}\n\n\tpublic void save() {\n\n\t}\n\n\tpublic String getBaseSourcePath() {\n\t\treturn baseSourcePath;\n\t}\n\n\tpublic void setBaseSourcePath(String baseSourcePath) {\n\t\tthis.baseSourcePath = baseSourcePath;\n\t}\n\n\tpublic ArrayList<DateFormat> getDates() {\n\t\treturn dates;\n\t}\n\n\tpublic void setDates(ArrayList<DateFormat> hm) {\n\t\tdates = hm;\n\t}\n\n\tpublic void addDateFormat(DateFormat df) {\n\t\tif (dates == null) {\n\t\t\tdates = new ArrayList<DateFormat>();\n\t\t}\n\t\tdates.add(df);\n\t\t// logger.info(xstream.toXML(recordings));\n\t}\n\n\tpublic void deleteDateFormat(int id) {\n\t\tdates.remove(id);\n\t}\n\n\tpublic DateFormat getDateFormat(int id) {\n\t\treturn dates.get(id);\n\t}\n\n\tpublic DateFormat getDateFormat(String id) {\n\t\tIterator dateFormatIterator = dates.iterator();\n\t\tint cnt = 0;\n\t\twhile (dateFormatIterator.hasNext()) {\n\t\t\tDateFormat df = (DateFormat) dateFormatIterator.next();\n\t\t\tif (df.getId() == id) {\n\t\t\t\treturn df;\n\t\t\t}\n\t\t}\n\t\treturn (DateFormat) null;\n\t}\n\n\tpublic void setOnlyMatches(boolean selected) {\n\t\tonlyMatches = selected;\n\n\t}\n\n\tpublic boolean isOnlyMatches() {\n\t\treturn onlyMatches;\n\t}\n\n\tpublic boolean isStats() {\n\t\treturn Boolean.parseBoolean(getPreference(\"stats\"));\n\t}\n\n\tpublic void setStats(boolean stats) {\n\t\tsetPreference(\"stats\", Boolean.toString(stats));\n\t}\n\n\tpublic boolean isTimings() {\n\t\treturn Boolean.parseBoolean(getPreference(\"timings\"));\n\t}\n\n\tpublic void setTimings(boolean timings) {\n\t\tsetPreference(\"timings\", Boolean.toString(timings));\n\t}\n\n}",
"public class EventRecording extends Recording {\n\tprivate static Logger logger = Logger.getLogger(EventRecording.class.getName());\n\tprivate String dateFormat;\n\n\tpublic EventRecording(String _name, String _regexp, String _exampleLine, String _dateFormat, Boolean _isActive, Boolean _useSourceDateFormat, boolean _caseSensitive, ArrayList<RecordingItem> _recordingItem) {\n\t\tsetName(_name);\n\t\tsetRegexp(_regexp);\n\t\tsetExampleLine(_exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetUseSourceDateFormat(_useSourceDateFormat);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tsuper.id = generate();\n\t\tlogger.info(\"New EventRecording name: \" + _name + \", regexp: \" + _regexp + \", id: \" + super.id);\n\t\tif (recordingItem != null)\n\t\t\tlogger.info(\"New EventRecording with recordingItem ArrayList: \" + recordingItem.toString());\n\t}\n\n\tpublic String getType() {\n\t\treturn \"Event\";\n\t}\n\n\tpublic String getDateFormat() {\n\t\treturn dateFormat;\n\t}\n\n\tpublic void setDateFormat(String dateFormat) {\n\t\tthis.dateFormat = dateFormat;\n\t}\n\n\tpublic void setRecordingItem(ArrayList<RecordingItem> recordingItem) {\n\t\tthis.recordingItem = recordingItem;\n\t}\n\n\tpublic void update(String txtName, String txtRegularExp, String exampleLine, String _dateFormat, Boolean _isActive, Boolean _useSourceDateFormat, Boolean _caseSensitive, ArrayList<RecordingItem> _recordingItem) {\n\t\tsetName(txtName);\n\t\tsetRegexp(txtRegularExp);\n\t\tsetExampleLine(exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tsetUseSourceDateFormat(_useSourceDateFormat);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tlogger.debug(\"RIArrayLit size: \"+ recordingItem.size());\n\t\tif (this.id == null) {\n\t\t\tsuper.id = generate();\n\t\t}\n\t}\n\n\tpublic Recording duplicate() {\n\n\t\tArrayList<RecordingItem> _recordingItem = null;\n\t\t// might need put back .toString() to those?? *** TBR\n\t\tString _name = getName().toString();\n\t\tString _regexp = getRegexp().toString();\n\t\tString _exampleLine = getExampleLine().toString();\n\t\tString _dateFormat = dateFormat.toString();\n\n\t\tBoolean _isActive = getIsActive().booleanValue();\n\t\tBoolean _caseSensitive = isCaseSensitive();\n\t\tBoolean _useSourceDateFormat=getUseSourceDateFormat();\n\t\tif (recordingItem != null) {\n\t\t\t_recordingItem = (ArrayList<RecordingItem>) recordingItem.clone();\n\t\t}\n\t\tEventRecording eR=new EventRecording(_name, _regexp, _exampleLine, _dateFormat, _isActive, _useSourceDateFormat, _caseSensitive, _recordingItem);\n\t\teR.setDateFormatID(this.getDateFormatID());\n\t\treturn eR;\n\t}\n}",
"public class MetadataRecording extends Recording {\n\tprivate static Logger logger = Logger.getLogger(MetadataRecording.class.getName());\n\tprivate ArrayList recordingItem;\n\tprivate String dateFormat;\n\n\tpublic String getType() {\n\t\treturn \"File Grouping\";\n\t}\n\n\tpublic MetadataRecording(String _name, String _regexp, String _exampleLine, String _dateFormat, Boolean _isActive, Boolean _caseSensitive, ArrayList _recordingItem) {\n\t\tsetName(_name);\n\t\tsetRegexp(_regexp);\n\t\tsetExampleLine(_exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tsuper.id = generate();\n\t\tlogger.info(\"New MetadataRecording name: \" + _name + \", regexp: \" + _regexp + \", id: \" + super.id);\n\t\tif (recordingItem != null)\n\t\t\tlogger.info(\"New MetadataRecording with recordingItem ArrayList: \" + recordingItem.toString());\n\t}\n\n\tpublic String getDateFormat() {\n\t\treturn dateFormat;\n\t}\n\n\tpublic void setDelimitator(String delimitator) {\n\t//\tthis.dateFormat = dateFormat;\n\t}\n\n\tpublic ArrayList getRecordingItem() {\n\t\t// logger.info(\"***********\"+recordingItem.toString()+recordingItem.size());\n\t\t// Thread.currentThread().dumpStack();\n\t\treturn (ArrayList) recordingItem;\n\t}\n\n\tpublic void setRecordingItem(ArrayList recordingItem) {\n\t\tthis.recordingItem = recordingItem;\n\t}\n\n\tpublic void update(String txtName, String txtRegularExp, String exampleLine, String _dateFormat, Boolean _isActive, Boolean _caseSensitive, ArrayList _recordingItem) {\n\t\tsetName(txtName);\n\t\tsetRegexp(txtRegularExp);\n\t\tsetExampleLine(exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t}\n\n\tpublic Recording duplicate() {\n\n\t\tArrayList _recordingItem = null;\n\t\t// might need put back .toString() to those?? *** TBR\n\t\tString _name = getName().toString();\n\t\tString _regexp = getRegexp().toString();\n\t\tString _exampleLine = getExampleLine().toString();\n\t\tString _dateFormat = getDateFormat().toString();\n\n\t\tBoolean _isActive = getIsActive().booleanValue();\n\t\tBoolean _caseSensitive = isCaseSensitive();\n\t\tif (getRecordingItem() != null) {\n\t\t\t_recordingItem = (ArrayList) getRecordingItem().clone();\n\t\t}\n\t\t\n\t\tMetadataRecording eR=new MetadataRecording(_name, _regexp, _exampleLine, _dateFormat, _isActive, _caseSensitive, _recordingItem);\n\t\teR.setDateFormatID(this.getDateFormatID());\n\t\treturn eR;\n\t\t\n\t}\n\n}",
"public abstract class Recording {\n\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tprivate String name;\n\tprivate String regexp;\n\tprotected ArrayList recordingItem;\n\tprivate String FastDateFormat;\n\tprivate String exampleLine;\n\tprivate Boolean isActive;\n\tprotected String id;\n\tprivate Boolean caseSensitive;\n\tprivate Boolean useSourceDateFormat;\n\tprivate String dateFormatID;\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String generate() {\n\t\tString generatedUniqueId = UUID.randomUUID().toString();\n\t\tlogger.info(\"unique ID: \" + generatedUniqueId);\n\t\treturn generatedUniqueId;\n\t}\n\n\tpublic ArrayList getRecordingItem() {\n\t\t// logger.info(\"***********\"+recordingItem.toString()+recordingItem.size());\n\t\t// Thread.currentThread().dumpStack();\n\t\treturn recordingItem;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getRegexp() {\n\t\treturn regexp;\n\t}\n\n\tpublic void setRegexp(String regexp) {\n\t\tthis.regexp = regexp;\n\t}\n\n\tpublic String getExampleLine() {\n\t\treturn exampleLine;\n\t}\n\n\tpublic void setExampleLine(String exampleLine) {\n\t\tthis.exampleLine = exampleLine;\n\t}\n\n\tpublic abstract String getType();\n\n\tpublic Boolean getIsActive() {\n\t\treturn isActive;\n\t}\n\n\tpublic boolean isCaseSensitive() {\n\t\tif (caseSensitive!=null){\n\t\t\treturn caseSensitive;\n\t\t}else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic void setCaseSensitive(boolean caseSensitive) {\n\t\tthis.caseSensitive = caseSensitive;\n\t}\n\n\tpublic void setIsActive(Boolean isActive) {\n\t\tthis.isActive = isActive;\n\t}\n\n\tabstract public Recording duplicate();\n\n\tpublic String getDateFormatID() {\n\t\treturn dateFormatID;\n\t}\n\n\tpublic void setDateFormatID(String dateFormatID) {\n\t\tthis.dateFormatID = dateFormatID;\n\t}\n\n\tpublic Boolean getUseSourceDateFormat() {\n\t\tif (useSourceDateFormat==null){\n\t\t\treturn false;\n\t\t} else{\n\t\treturn useSourceDateFormat;}\n\t}\n\n\tpublic void setUseSourceDateFormat(Boolean useSourceDateFormat) {\n\t\tthis.useSourceDateFormat = useSourceDateFormat;\n\t}\n\n}",
"public class RecordingItem {\n\tprivate String processingType;\n\tprotected String name;\n\tprotected String before;\n\tprotected String after;\n\tprotected String type;\n\tprotected String inside;\n\tprotected String value;\n\tprotected boolean selected;\n\tprotected boolean show;\n\n\tpublic String getBefore() {\n\t\treturn before;\n\t}\n\n\tpublic void setBefore(String before) {\n\t\tthis.before = before;\n\t}\n\n\tpublic String getAfter() {\n\t\treturn after;\n\t}\n\n\tpublic void setAfter(String after) {\n\t\tthis.after = after;\n\t}\n\n\tpublic String getProcessingType() {\n\t\treturn processingType;\n\t}\n\n\tpublic void setProcessingType(String processingType) {\n\t\tthis.processingType = processingType;\n\t}\n\n\tpublic RecordingItem(String name, String before, String type, String processingType, String insideRegex, String after, Boolean isSelected, Boolean show, String value) {\n\t\tthis.name = name;\n\t\tthis.before = before;\n\t\tthis.after = after;\n\t\tthis.value = value;\n\t\tthis.type = type;\n\t\tthis.selected = isSelected;\n\t\tthis.processingType = processingType;\n\t\tthis.inside=insideRegex;\n\t\tthis.show=show;\n\t\t// super(name, before, type, after, isSelected, value);\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\tpublic RecordingItem(String name, String before, String type, String insideRegex, String after, Boolean isSelected, Boolean show, String value) {\n\t\tthis.name = name;\n\t\tthis.before = before;\n\t\tthis.after = after;\n\t\tthis.value = value;\n\t\tthis.type = type;\n\t\tthis.selected = isSelected;\n\t\tthis.inside=insideRegex;\n\t\tthis.show=show;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(String type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\tpublic void setValue(String value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic boolean isSelected() {\n\t\treturn selected;\n\t}\n\n\tpublic void setSelected(boolean selected) {\n\t\tthis.selected = selected;\n\t}\n\n\tpublic boolean isShow() {\n\t\treturn show;\n\t}\n\n\tpublic void setShow(boolean show) {\n\t\tthis.show = show;\n\t}\n\n\tpublic String getInside() {\n\t\treturn inside;\n\t}\n\n\tpublic void setInside(String _inside) {\n\t\tthis.inside = _inside;\n\t}\n\t\n\t\n\n}",
"public class StatRecording extends Recording {\n\tprivate static Logger logger = Logger.getLogger(StatRecording.class.getName());\n//\tprivate ArrayList recordingItem;\n\tprivate String dateFormat;\n\n\tpublic String getType() {\n\t\treturn \"Stat\";\n\t}\n\n\tpublic StatRecording(String _name, String _regexp, String _exampleLine, String _dateFormat, Boolean _isActive, Boolean _useSourceDateFormat, Boolean _caseSensitive, ArrayList _recordingItem) {\n\t\tsetName(_name);\n\t\tsetRegexp(_regexp);\n\t\tsetExampleLine(_exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetUseSourceDateFormat(_useSourceDateFormat);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tsuper.id = generate();\n\t\t// logger.info(\"New EventRecording name: \"+_name + \", regexp: \"+ _regexp\n\t\t// + \", id: \"+ super.id +recordingItem.toString());\n\t}\n\n\tpublic String getDateFormat() {\n\t\treturn dateFormat;\n\t}\n\n\tpublic void setDelimitator(String delimitator) {\n\t//\tthis.dateFormat = dateFormat;\n\t}\n\n\tpublic ArrayList getRecordingItem() {\n\t\t// logger.info(\"***********\"+recordingItem.toString()+recordingItem.size());\n\t\t// Thread.currentThread().dumpStack();\n\t\treturn recordingItem;\n\t}\n\n\tpublic void setRecordingItem(ArrayList recordingItem) {\n\t\tthis.recordingItem = recordingItem;\n\t}\n\n\tpublic void update(String txtName, String txtRegularExp, String exampleLine, String _dateFormat, Boolean _isActive, Boolean _useSourceDateFormat, Boolean _caseSensitive, ArrayList _recordingItem) {\n\t\tsetName(txtName);\n\t\tsetRegexp(txtRegularExp);\n\t\tsetExampleLine(exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tsetUseSourceDateFormat(_useSourceDateFormat);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tif (this.id == null) {\n\t\t\tsuper.id = generate();\n\t\t}\n\t}\n\n\tpublic Recording duplicate() {\n\n\t\tArrayList _recordingItem = null;\n\t\t// might need put back .toString() to those?? *** TBR\n\t\tString _name = getName().toString();\n\t\tString _regexp = getRegexp().toString();\n\t\tString _exampleLine = getExampleLine().toString();\n\t\tString _dateFormat = dateFormat.toString();\n\n\t\tBoolean _isActive = getIsActive().booleanValue();\n\t\tBoolean _caseSensitive = isCaseSensitive();\n\t\tBoolean _useSourceDateFormat=getUseSourceDateFormat();\n\t\tif (recordingItem != null) {\n\t\t\t_recordingItem = (ArrayList) recordingItem.clone();\n\t\t}\n\t\tStatRecording eR=new StatRecording(_name, _regexp, _exampleLine, _dateFormat, _isActive,_useSourceDateFormat, _caseSensitive, _recordingItem);\n\t\teR.setDateFormatID(this.getDateFormatID());\n\t\treturn eR;\n\t\t\n\t}\n}",
"public class NoProcessingRegexTableRenderer extends DefaultTableCellRenderer {\n\tprivate static Logger logger = Logger.getLogger(NoProcessingRegexTableRenderer.class.getName());\n\t @Override\n\t public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n\t Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\t\n\t \n\t //inside type\n\t Object type = table.getValueAt(row, 2);\n\t Object regex = table.getValueAt(row, 3);\n\t \n\t if (column==1 || column==4){\n \t\t Color clr = new Color(233, 255, 229);\n \t\t component.setBackground(clr);\n\t }\n\t \n\t if (type != null && column==3) {\n\t \tif(((String)type).equals(\"manual\")){\n\t \t \t//logger.info(((String)type));\n\t \t\t Color clr = new Color(233, 255, 229);\n\t \t\t component.setBackground(clr);\n\t \t}else {\n\t \t\t Color clr = new Color(255, 229, 229);\n\t\t \t\t component.setBackground(clr);\n\t \t}\n\t }\n\t return component;\n\t }\n}",
"public class DataMiner {\n\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tstatic List<File> listOfFiles = null;\n\tprivate static ExecutorService ThreadPool_FileWorkers = null;\n\tprivate static ExecutorService ThreadPool_GroupWorkers = null;\n\tstatic long estimatedTime = 0;\n\tstatic long startTime = 0;\n\tstatic final Map<Source, Map<Recording, Map<List<Object>, Long>>> occurenceReport = new ConcurrentHashMap<Source, Map<Recording, Map<List<Object>, Long>>>();\n\tstatic final Map<Source, Map<Recording, Map<List<Object>, Double>>> sumReport = new ConcurrentHashMap<Source, Map<Recording, Map<List<Object>, Double>>>();\n\tstatic final Map<Source, Map<Recording, SortedMap<Double,List<Object>>>> top100Report = new ConcurrentHashMap<Source, Map<Recording, SortedMap<Double,List<Object>>>>();;\n\t\n\tpublic static MineResultSet gatherMsineResultSet(ChartData cd, final Repository repo, final MainFrame mainFrame) {\n\t\tString test = Preferences.getPreference(\"ThreadPool_Group\");\n\t\tint ini = Integer.parseInt(test);\n\t\tlogger.info(\"gatherMineResultSet parallelism: \" + ini);\n\t\tThreadPool_GroupWorkers = Executors.newFixedThreadPool(ini);\n\t//\tChartData cd = new ChartData();\n\t\tCollection<Callable<MineResult>> tasks = new ArrayList<Callable<MineResult>>();\n\t\tMineResultSet mineResultSet = new MineResultSet();\n\t\toccurenceReport.clear();\n\t\tsumReport.clear();\n\t\ttop100Report.clear();\n\t\t// tOP100Report = new ConcurrentHashMap<Recording,Map<String, Long>>();\n\n\t\tstartTime = System.currentTimeMillis();\n\t/*\ttry {\n\t\t\tcd = gatherSourceData(repo);\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}*/\n\t\t\n\t\t// if (logger.isEnabledFor(Level.INFO))\n\t\t// logger.info(\"ArrayList sourceFileGroup\" + sourceFileGroup);\n\t\tIterator<Source> sourceIterator2 = repo.getSources().iterator();\n\t\tint progressCount = 0;\n\t\twhile (sourceIterator2.hasNext()) {\n\t\t\tfinal Source source = sourceIterator2.next();\n\t\t\t// sourceFiles contains all the matched files for a given source\n\t\t\tif (source.getActive() && source.getActiveMetadata()!=null) {\n\t\t\t\tIterator<Entry<String, ArrayList<FileRecord>>> it = cd.getGroupFilesMap(source).entrySet().iterator();\n\t\t\t\twhile (it.hasNext()) {\n\t\t\t\t\tfinal Map.Entry<String, ArrayList<FileRecord>> pairs = it.next();\n\t\t\t\t\tprogressCount = progressCount + pairs.getValue().size();\n\t\t\t\t\tlogger.debug(\"Source:\" + source.getSourceName() + \", group: \" + pairs.getKey() + \" = \" + pairs.getValue().toString());\n\t\t\t\t\ttasks.add(new Callable<MineResult>() {\n\t\t\t\t\t\tpublic MineResult call() throws Exception {\n\t\t\t\t\t\t\treturn DataMiner.mine(pairs.getKey(), pairs.getValue(), repo, source, Preferences.isStats(),\n\t\t\t\t\t\t\t\t\tPreferences.isTimings(), Preferences.isMatches(), mainFrame);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t});\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmainFrame.setMaxProgress(progressCount);\n\t\t// logger.info(\"progressCount \"+ progressCount);\n\t\t/*\n\t\t * invokeAll blocks until all service requests complete, or a max of\n\t\t * 1000 seconds.\n\t\t */\n\t\tList<Future<MineResult>> results = null;\n\t\ttry {\n\t\t\tresults = ThreadPool_GroupWorkers.invokeAll(tasks, 100000, TimeUnit.SECONDS);\n\t\t} catch (InterruptedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tfor (Future<MineResult> f : results) {\n\t\t\tMineResult mineRes = null;\n\t\t\ttry {\n\t\t\t\t// if (mineRes!=null)\n\t\t\t\tmineRes = f.get();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tif (mineRes != null) {\n\t\t\t\tmineResultSet.updateStartDate(mineRes.getStartDate());\n\t\t\t\tmineResultSet.updateEndDate(mineRes.getEndDate());\n\t\t\t\tif (!mineResultSet.mineResults.keySet().contains(mineRes.getSource())) {\n\t\t\t\t\tmineResultSet.mineResults.put(mineRes.getSource(), new HashMap<String, MineResult>());\n\t\t\t\t}\n\t\t\t\tmineResultSet.mineResults.get(mineRes.getSource()).put(mineRes.getSource().getSourceName() + mineRes.getGroup(), mineRes);\n\t\t\t}\n\t\t}\n\t\testimatedTime = System.currentTimeMillis() - startTime;\n\t\tlogger.info(\"gathering time: \" + estimatedTime);\n\t\t/*\n\t\t * Iterator oRIte= occurenceReport.keySet().iterator(); while\n\t\t * (oRIte.hasNext()) { String occString=(String) oRIte.next();\n\t\t * logger.info(\"nb: \"+ occurenceReport.get(occString)+\" string: \"\n\t\t * +occString); }\n\t\t */\n\t\tmineResultSet.setOccurenceReport(occurenceReport);\n\t\tmineResultSet.setTop100Report(top100Report);\n\t\tmineResultSet.setSumReport(sumReport);\t\n\n\t\treturn mineResultSet;\n\n\t}\n\t\n\t// handle gathering for ArrayList of file for one source-group\n\tpublic static MineResult mine(String group, ArrayList<FileRecord> arrayList, final Repository repo, final Source source, final boolean stats, final boolean timings,\n\t\t\tfinal boolean matches, final MainFrame mainFrame) {\n\t\tlogger.debug(\"call to mine for source \" + source.getSourceName() + \" on group \" + group);\n\t\tThreadPool_FileWorkers = Executors.newFixedThreadPool(Integer.parseInt(Preferences.getPreference(\"ThreadPool_File\")));\n\t\tDate startDate = null;\n\t\tDate endDate = null;\n\t\t// Map<String, ExtendedTimeSeries> statMap = HashObjObjMaps<String,\n\t\t// ExtendedTimeSeries>();\n\t\tMap<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>();\n\t\tMap<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>();\n\t\tMap<String, long[]> timingStatsMap = new HashMap<String, long[]>();\n\t\tMap<String, Map<Date, FileLine>> fileLine = new HashMap<String, Map<Date, FileLine>>();\n\t\tCollection<Callable<FileMineResult>> tasks = new ArrayList<Callable<FileMineResult>>();\n\t\t\n\t\tfinal Map<Recording, String> recMatch1 = getAllRegexSingleMap(repo, source); \n\n\t\tArrayList<Object> mapArrayList;\n\t\tmapArrayList = new ArrayList<>();\n\t\tif (logger.isEnabledFor(Level.INFO))\n\t\t\tlogger.info(\"mine called on \" + source.getSourceName());\n\t\tIterator<FileRecord> fileArrayListIterator = arrayList.iterator();\n\t\twhile (fileArrayListIterator.hasNext()) {\n\t\t\tfinal FileRecord fileRec = fileArrayListIterator.next();\n\t\t\ttasks.add(new Callable<FileMineResult>() {\n\t\t\t\tpublic FileMineResult call() throws Exception {\n\t\t\t\t\tlogger.debug(\"file mine on \" + fileRec);\n\t\t\t\t\treturn fileMine(fileRec, recMatch1, repo, source, stats, timings, matches, mainFrame);\n\t\t\t\t}\n\n\t\t\t});\n\n\t\t}\n\t\tList<Future<FileMineResult>> results = null;\n\t\ttry {\n\t\t\tresults = ThreadPool_FileWorkers.invokeAll(tasks, 100000, TimeUnit.SECONDS);\n\t\t} catch (InterruptedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tfor (Future<FileMineResult> f : results) {\n\t\t\tFileMineResult fileMineRes = null;\n\t\t\ttry {\n\t\t\t\tif (f != null) {\n\t\t\t\t\tfileMineRes = f.get();\n\t\t\t\t}\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (NullPointerException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t// e.printStackTrace();\n\t\t\t}\n\t\t\tif (fileMineRes != null) {\n\t\t\t\tmapArrayList.add(fileMineRes);\n\t\t\t}\n\n\t\t}\n\t\tArrayList<Object[]> fileDates = new ArrayList<Object[]>();\n\t\tIterator<Object> mapArrayListIterator = mapArrayList.iterator();\n\t\twhile (mapArrayListIterator.hasNext()) {\n\t\t\tFileMineResult fMR = (FileMineResult) mapArrayListIterator.next();\n\n\t\t\tif (startDate == null) {\n\t\t\t\tstartDate = fMR.getStartDate();\n\t\t\t}\n\t\t\tif (endDate == null) {\n\t\t\t\tendDate = fMR.getEndDate();\n\t\t\t}\n\t\t\tif (fMR.getEndDate() != null && fMR.getStartDate() != null) {\n\t\t\t\tif (fMR.getEndDate().after(endDate)) {\n\t\t\t\t\tendDate = fMR.getEndDate();\n\t\t\t\t} else if (fMR.getStartDate().before(startDate)) {\n\t\t\t\t\tstartDate = fMR.getStartDate();\n\t\t\t\t}\n\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\tlogger.debug(\"1: \" + fMR.getStartDate() + \"2: \" + fMR.getEndDate() + \"3: \" + fMR.getFile());\n\t\t\t\t}\n\t\t\t\tfileDates.add(new Object[] { fMR.getStartDate(), fMR.getEndDate(), fMR.getFile() });\n\t\t\t}\n\n\t\t\tMap<String, ExtendedTimeSeries> tempStatMap = fMR.statGroupTimeSeries;\n\t\t\ttempStatMap.entrySet();\n\t\t\tIterator it = tempStatMap.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMap.Entry<String, ExtendedTimeSeries> pairs = (Map.Entry<String, ExtendedTimeSeries>) it.next();\n\t\t\t\tif (!statMap.containsKey(pairs.getKey())) {\n\t\t\t\t\tstatMap.put(pairs.getKey(), pairs.getValue());\n\t\t\t\t} else {\n\t\t\t\t\tExtendedTimeSeries ts = statMap.get(pairs.getKey());\n\t\t\t\t\tif (stats) {\n\t\t\t\t\t\tint[] array = { pairs.getValue().getStat()[0] + ts.getStat()[0], pairs.getValue().getStat()[1] + ts.getStat()[1] };\n\t\t\t\t\t\tts.setStat(array);\n\t\t\t\t\t}\n\t\t\t\t\tts.getTimeSeries().addAndOrUpdate(pairs.getValue().getTimeSeries());\n\t\t\t\t\tstatMap.put(pairs.getKey(), ts);\n\t\t\t\t\t// logger.info(pairs.getKey());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMap tempEventMap = fMR.eventGroupTimeSeries;\n\t\t\ttempEventMap.entrySet();\n\t\t\tit = tempEventMap.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMap.Entry<String, ExtendedTimeSeries> pairs = (Map.Entry<String, ExtendedTimeSeries>) it.next();\n\t\t\t\tif (!eventMap.containsKey(pairs.getKey())) {\n\t\t\t\t\teventMap.put(pairs.getKey(), pairs.getValue());\n\t\t\t\t} else {\n\t\t\t\t\tExtendedTimeSeries ts = eventMap.get(pairs.getKey());\n\t\t\t\t\tif (stats) {\n\t\t\t\t\t\tint[] array = { pairs.getValue().getStat()[0] + ts.getStat()[0], pairs.getValue().getStat()[1] + ts.getStat()[1] };\n\t\t\t\t\t\tts.setStat(array);\n\t\t\t\t\t}\n\t\t\t\t\tts.getTimeSeries().addAndOrUpdate(pairs.getValue().getTimeSeries());\n\t\t\t\t\teventMap.put(pairs.getKey(), ts);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tit = fMR.matchingStats.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMap.Entry<String, long[]> pairs = (Map.Entry<String, long[]>) it.next();\n\t\t\t\tif (!timingStatsMap.containsKey(pairs.getKey())) {\n\t\t\t\t\ttimingStatsMap.put(pairs.getKey(), pairs.getValue());\n\t\t\t\t} else {\n\t\t\t\t\tlong[] array = timingStatsMap.get(pairs.getKey());\n\t\t\t\t\t// 0-> sum of time for success matching of given\n\t\t\t\t\t// recording ; 1-> sum of time for failed\n\t\t\t\t\t// matching ; 2-> count of match attempts,\n\t\t\t\t\t// 3->count of success attempts\n\t\t\t\t\tlong[] array2 = { pairs.getValue()[0] + array[0], pairs.getValue()[1] + array[1], pairs.getValue()[2] + array[2],\n\t\t\t\t\t\t\tpairs.getValue()[3] + array[3] };\n\t\t\t\t\ttimingStatsMap.put(pairs.getKey(), array2);\n\t\t\t\t}\n\t\t\t}\n\t\t\tit = fMR.fileLineDateMap.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMap.Entry<String, Map<Date, FileLine>> pairs = (Map.Entry<String, Map<Date, FileLine>>) it.next();\n\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\tlogger.debug(\"Entry<String,Map<Date, FileLine>> : \" + pairs);\n\t\t\t\t}\n\t\t\t\tif (!fileLine.containsKey(pairs.getKey())) {\n\t\t\t\t\tfileLine.put(pairs.getKey(), pairs.getValue());\n\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\tlogger.debug(\"groupFileLineMap.put \" + pairs.getKey() + \" -> \" + pairs.getValue());\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tMap<Date, FileLine> ts = fileLine.get(pairs.getKey());\n\t\t\t\t\tMap<Date, FileLine> newDateFileLineEntries = pairs.getValue();\n\t\t\t\t\tIterator it2 = newDateFileLineEntries.entrySet().iterator();\n\t\t\t\t\twhile (it2.hasNext()) {\n\t\t\t\t\t\tMap.Entry<Date, FileLine> pairs2 = (Map.Entry<Date, FileLine>) it2.next();\n\t\t\t\t\t\tfileLine.get(pairs.getKey()).put(pairs2.getKey(), pairs2.getValue());\n\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\tlogger.debug(\"groupFileLineMap.put \" + pairs2.getKey() + \" -> \" + pairs2.getValue().getFileId() + \":\" + pairs2.getValue().getLineNumber());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// logger.info(\"cont2: \"+groupFileLineMap.get(pairs.getKey()));\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tFileMineResultSet fMRS = new FileMineResultSet(fileDates, statMap, eventMap, timingStatsMap, fileLine, startDate, endDate);\n\t\treturn new MineResult(group, fMRS, arrayList, repo, source);\n\t}\n\n\tpublic static String readFileLine(Source src, FileLine fileLine, ChartData cd) {\n\t\tFileReader flstr = null;\n\t\tString line = \"\";\n\t\tFileRecord fileRecord = cd.sourceFileArrayListMap.get(src).get(fileLine.getFileId());\n\t\ttry {\n\t\t\tflstr = new FileReader(fileRecord.getCompletePath());\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tBufferedReader r = new BufferedReader(flstr);\n\t\tfor (int i = 0; i < fileLine.getLineNumber(); i++) {\n\t\t\ttry {\n\t\t\t\tline = r.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn line;\n\n\t}\n\n\t// handle gathering for a single file\n\tpublic static FileMineResult fileMine(FileRecord fileRecord, Map<Recording, String> recMatch1, Repository repo, Source source, boolean stats, boolean timings, boolean matches,\n\t\t\tfinal MainFrame mainFrame) {\n\t\tExtendedTimeSeries ts = null;\n\t\tPatternCache patternCache = new PatternCache();\n\t\tClassCache classCache = new ClassCache();\n\t\tDate startDate = null;\n\t\tDate endDate = null;\n\t\tDecimalFormat decimalFormat = new DecimalFormat(\"#.#\", new DecimalFormatSymbols(Locale.US));\n\t\tjava.text.DateFormat fastDateFormat = null;\n\t\tFileReader flstr = null;\n\t\tBufferedReader buf1st;\n\t\tMatcher matcher;\n\t\tMatcher matcher2;\n\t\tFixedMillisecond fMS = null;\n\t\tDateFormat df = null;\n\t\tint statHit = 0;\n\t\tint statMatch = 0;\n\t\tint eventHit = 0;\n\t\tint eventMatch = 0;\n\t\tlong[] arrayBefore;\n\t\tlong match0 = 0;\n\t\tlong match1 = 0;\n\t\tlong timing0 = 0;\n\t\tlong timing1 = 0;\n\t\tMap<Recording, String> recMatch = new HashMap<Recording, String>(recMatch1);\n\t\tMap<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>();\n\t\tMap<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>();\n\t\tMap<String, Map<Date, FileLine>> RIFileLineDateMap = new HashMap<String, Map<Date, FileLine>>();\n\t\tMap<String, long[]> matchTimings = new HashMap<String, long[]>();\n\t\tboolean gatherStats = Preferences.getBooleanPreference(\"gatherstats\");\n\t\tboolean gatherReports = Preferences.getBooleanPreference(\"gatherreports\");\n\t\tboolean gatherEvents = Preferences.getBooleanPreference(\"gatherevents\");\n\t\tlong recordingMatchStart = 0;\n\t\tlong recordingMatchEnd = 0;\n\t\ttry {\n\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\tlogger.debug(\"++file: \" + repo.getBaseSourcePath() + \" + \" + (String) fileRecord.getCompletePath().toString());\n\t\t\t}\n\t\t\tflstr = new FileReader(fileRecord.getCompletePath());\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\n\t\tif (!occurenceReport.containsKey(source)) {\n\t\t\toccurenceReport.put(source, new ConcurrentHashMap<Recording, Map<List<Object>, Long>>());\n\t\t}\n\t\tif (!top100Report.containsKey(source)) {\n\t\t\ttop100Report.put(source, new ConcurrentHashMap<Recording, SortedMap<Double,List<Object>>>());\n\t\t}\n\t\t\n\t\tif (!sumReport.containsKey(source)) {\n\t\t\tsumReport.put(source, new ConcurrentHashMap<Recording, Map<List<Object>, Double>>());\n\t\t}\n\t\t\n\t\tbuf1st = new BufferedReader(flstr);\n\t\tString line;\n\t\ttry {\n\t\t\t//recMatch = getRegexp(repo, source);\n\t\t\tint lineCount = 1;\n\t\t\twhile ((line = buf1st.readLine()) != null) {\n\t\t\t\t// check against one Recording pattern at a tim\n\t\t\t\t// if (logger.isDebugEnabled()) {\n\t\t\t\t// logger.debug(\"line \" + line);\n\t\t\t\t// }\n\t\t\t\tIterator<Entry<Recording, String>> recMatchIte = recMatch.entrySet().iterator();\n\t\t\t\twhile (recMatchIte.hasNext()) {\n\t\t\t\t\tif (timings) {\n\t\t\t\t\t\trecordingMatchStart = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t}\n\t\t\t\t\tEntry<Recording, String> me = recMatchIte.next();\n\t\t\t\t\tRecording rec = (Recording) me.getKey();\n\t\t\t\t\tmatcher = patternCache.getMatcher((String) (rec.getRegexp()),rec.isCaseSensitive(),line);\n\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\tBoolean isStatRecording = classCache.getClass(rec).equals(StatRecording.class);\n\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\tif (isStatRecording) {\n\t\t\t\t\t\t\t\tstatMatch++;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\teventMatch++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// logger.info(\"1**** matched: \" + line);\n\t\t\t\t\t\tArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();\n\t\t\t\t\t\tmatcher2 = patternCache.getMatcher((String) me.getValue(),rec.isCaseSensitive(),line);\n\t\t\t\t\t\tif (matcher2.find()) {\n\t\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\t\tif (isStatRecording) {\n\t\t\t\t\t\t\t\t\tstatHit++;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\teventHit++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!classCache.getClass(rec).equals(ReportRecording.class)) {\n\t\t\t\t\t\t\t\tint count = 1;\n\t\t\t\t\t\t\t\tDate date1 = null;\n\t\t\t\t\t\t\t\t// handling capture for each recording item\n\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t// logger.info(\"3A**** \" +\n\t\t\t\t\t\t\t\t\t// recItem2.getType());\n\t\t\t\t\t\t\t\t\tif (recItem2.getType().equals(\"date\")) {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tdf = repo.getDateFormat(rec.getDateFormatID());\n\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"4**** rec name\" + rec.getName() + \" df: \" + df.getId());\n\t\t\t\t\t\t\t\t\t\t\tfastDateFormat =ThreadLocalDateFormatMap.getInstance().createSimpleDateFormat(df.getDateFormat());\n\t\t\t\t\t\t\t\t\t\t//\tfastDateFormat = FastDateFormat.getInstance(df.getDateFormat());\n\t\t\t\t\t\t\t\t\t\t\tdate1 = fastDateFormat.parse(matcher2.group(count));\n\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"4b**** \" + df.getDateFormat() + \" date: \" + date1.toString());\n\t\t\t\t\t\t\t\t\t\t\t// logger.info(\"4**** \" +\n\t\t\t\t\t\t\t\t\t\t\t// date1.toString());\n\t\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch\n\t\t\t\t\t\t\t\t\t\t\t// block\n\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else if (date1 != null) {\n\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"FileRecord: \" + fileRecord.getFile().getName() + \", Source: \" + source.getSourceName() + \", \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ recItem2.getName() + \", \" + fileRecord.getFile().getName() + \", \" + lineCount);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t// recording line of match in file\n\t\t\t\t\t\t\t\t\t\t\t// in map RIFileLineDateMap - note\n\t\t\t\t\t\t\t\t\t\t\t// the FileLine object use an int to\n\t\t\t\t\t\t\t\t\t\t\t// identify the files to save memory\n\t\t\t\t\t\t\t\t\t\t\tMap<Date, FileLine> dateFileLineMap = null;\n\t\t\t\t\t\t\t\t\t\t\t//change this to recItem2 to differentiate recording items with same name ?? TBD\n\t\t\t\t\t\t\t\t\t\t\t//if (RIFileLineDateMap.containsKey(recItem2.getName())) {\n\t\t\t\t\t\t\t\t\t\t\t\tdateFileLineMap = RIFileLineDateMap.get(recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\tif (dateFileLineMap==null){\n\t\t\t\t\t\t\t\t\t\t\t\t\tdateFileLineMap = new HashMap<Date, FileLine>();\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tdateFileLineMap.put(date1, new FileLine(fileRecord.getId(), lineCount));\n\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(fileRecord.getFile().getName() + \" dateFileLineMap put: \" + date1 + \"groupFileLineMap: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ new FileLine(fileRecord.getId(), lineCount));\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(fileRecord.getFile().getName() + \" FileRecord: \" + fileRecord.getFile().getName()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ \", RIFileLineDateMap.put: \" + recItem2.getName() + \", line: \" + lineCount\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ \" RIFileLineDateMap size: \" + RIFileLineDateMap.size() + \" dateFileLineMap size: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ dateFileLineMap.size());\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tRIFileLineDateMap.put(recItem2.getName(), dateFileLineMap);\n\n\t\t\t\t\t\t\t\t\t\t\tif (startDate == null) {\n\t\t\t\t\t\t\t\t\t\t\t\tstartDate = date1;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (endDate == null) {\n\t\t\t\t\t\t\t\t\t\t\t\tendDate = date1;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (date1.after(startDate)) {\n\t\t\t\t\t\t\t\t\t\t\t\tendDate = date1;\n\t\t\t\t\t\t\t\t\t\t\t} else if (date1.before(startDate)) {\n\t\t\t\t\t\t\t\t\t\t\t\tstartDate = date1;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif (isStatRecording && (gatherStats)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tts = statMap.get(recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\t if (ts==null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tts = new ExtendedTimeSeries(recItem2, FixedMillisecond.class);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"5**** Adding record to Map: \" + recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tfMS = new FixedMillisecond(date1);\n\t\t\t\t\t\t\t\t\t\t\t\tif (matcher2.group(count) == null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(\"null in match on \" + recItem2.getName() + \" at \" + fileRecord.getFile().getName()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ \" line cnt:\" + lineCount);\n\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(\"line : \" + line);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tif (recItem2.getType().equals(\"long\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS, Long.valueOf((String) matcher2.group(count)))));\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(new TimeSeriesDataItem(fMS, Double.parseDouble(String.valueOf(decimalFormat\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.parse((String) matcher2.group(count).replace(',', '.')))))));\n\t\t\t\t\t\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tint[] array = ts.getStat();\n\t\t\t\t\t\t\t\t\t\t\t\t\tarray[1] = array[1] + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\tarray[0] = array[0] + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\tts.setStat(array);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"stats \" + array[0] + \" \" + array[1]);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tstatMap.put(recItem2.getName(), ts);\n\t\t\t\t\t\t\t\t\t\t\t\t// performance: add the\n\t\t\t\t\t\t\t\t\t\t\t\t// TmeSeriesDataItem to the\n\t\t\t\t\t\t\t\t\t\t\t\t// TimeSeries instead of\n\t\t\t\t\t\t\t\t\t\t\t\t// updating\n\t\t\t\t\t\t\t\t\t\t\t\t// the TimeSeries in the Map\n\n\t\t\t\t\t\t\t\t\t\t\t} else if (classCache.getClass(rec).equals(EventRecording.class) && (gatherEvents )) {\n\t\t\t\t\t\t\t\t\t\t\t\tts = eventMap.get(recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\tif (ts==null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tts = new ExtendedTimeSeries(recItem2, FixedMillisecond.class);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"5**** Adding record to Map: \" + recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t//\t\tSimpleTimePeriod stp = new SimpleTimePeriod(date1,DateUtils.addMilliseconds(date1,1));\n\t\t\t\t\t\t\t\t\t\t\t\tfMS = new FixedMillisecond(date1);\n\n\t\t\t\t\t\t\t\t\t\t\t\tif (((RecordingItem) recItem2).getProcessingType().equals(\"occurrences\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tTimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (t != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS, (double)t.getValue()+1))); // +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// (double)t.getValue()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// need some way to show\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// several occurrences\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().add((new TimeSeriesDataItem(fMS, 1)));\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t} else if (((RecordingItem) recItem2).getProcessingType().equals(\"duration\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(new TimeSeriesDataItem(fMS, Double.parseDouble(String.valueOf(decimalFormat.parse(matcher2\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.group(count)))))));\n\t\t\t\t\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Auto-generated\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// catch block\n\t\t\t\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t// ts.addOrUpdate((new\n\t\t\t\t\t\t\t\t\t\t\t\t// TimeSeriesDataItem(fMS,\n\t\t\t\t\t\t\t\t\t\t\t\t// 100)));\n\t\t\t\t\t\t\t\t\t\t\t} else if (((RecordingItem) recItem2).getProcessingType().equals(\"sum\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tTimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (t != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!recItem2.getType().equals(\"date\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(new TimeSeriesDataItem(fMS,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDouble.parseDouble(String.valueOf(decimalFormat.parse(matcher2.group(count)))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ ts.getTimeSeries().getDataItem(fMS).getValue()))));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(ts.getTimeSeries().getDataItem(fMS).getValue());\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Auto-generated\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// catch block\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// to improve - should use the right type here\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().add(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(new TimeSeriesDataItem(fMS, Double.parseDouble(String.valueOf(decimalFormat.parse(matcher2\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.group(count)))))));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Auto-generated\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// catch block\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t} else if (((RecordingItem) recItem2).getProcessingType().equals(\"capture\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t\t\t\t\t// logger.debug(recItem2.getName()\n\t\t\t\t\t\t\t\t\t\t\t\t// +\n\t\t\t\t\t\t\t\t\t\t\t\t// \" \" +\n\t\t\t\t\t\t\t\t\t\t\t\t// Double.parseDouble((matcher2.group(count))));\n\t\t\t\t\t\t\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tint[] array = ts.getStat();\n\t\t\t\t\t\t\t\t\t\t\t\t\tarray[1] = array[1] + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\tarray[0] = array[0] + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\tts.setStat(array);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"stats \" + array[0] + \" \" + array[1]);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\teventMap.put(recItem2.getName(), ts);\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} // rec.getClass().equals(ReportRecording.class)\n\n\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t// logger.info(\"event statistics: \"+eventMatch\n\t\t\t\t\t\t\t\t\t// +\n\t\t\t\t\t\t\t\t\t// \" and \" +eventHit +\n\t\t\t\t\t\t\t\t\t// \" ; stat statistics: \"+statMatch +\n\t\t\t\t\t\t\t\t\t// \" and \"\n\t\t\t\t\t\t\t\t\t// +statHit);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else { if (gatherReports){\n\t\t\t\t\t\t\t\tint count = 0;\n\t\t\t\t\t\t\t\tif (((ReportRecording) rec).getSubType().equals(\"histogram\") && rec.getIsActive()) {\n\t\t\t\t\t\t\t\t\tList<Object> temp = new ArrayList<Object>();\n\t\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\ttemp.add(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tMap<List<Object>,Long> occMap = occurenceReport.get(source).get(rec);\n\t\t\t\t\t\t\t\t\tif (occMap==null) {\n\t\t\t\t\t\t\t\t\t\toccurenceReport.get(source).put(rec, new ConcurrentHashMap<List<Object>, Long>());\n\t\t\t\t\t\t\t\t\t\toccMap = occurenceReport.get(source).get(rec);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tsynchronized (occMap) {\n\t\t\t\t\t\t\t\t\tObject occ = occMap.get(temp);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif (occ==null) {\n\t\t\t\t\t\t\t\t\t\toccMap.put(temp, (long) 1);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toccMap.put(temp, (long) occ + 1);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (((ReportRecording) rec).getSubType().equals(\"top100\") && rec.getIsActive()) {\n\t\t\t\t\t\t\t\t\tdouble itemIndex = 0;\n\n\t\t\t\t\t\t\t\t\tSortedMap<Double,List<Object>> t100 = top100Report.get(source).get(rec);\n\t\t\t\t\t\t\t\t\tif (t100==null) {\n\t\t\t\t\t\t\t\t\t\ttop100Report.get(source).put(rec, Collections.synchronizedSortedMap(new TreeMap<Double,List<Object>>()));\n\t\t\t\t\t\t\t\t\t\tt100 = top100Report.get(source).get(rec);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\titemIndex = (double)Double.valueOf(matcher2.group(((ReportRecording) rec).getTop100RecordID()+1));\n\t\t\t\t\t\t\t\t\t} catch (NullPointerException npe){\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t//nothing\n\t\t\t\t\t\t\t\t\t}\t\t\n\t\t\t\t\t\t\t\t\tcatch (NumberFormatException nfe){\n\t\t\t\t\t\t\t\t\t\t//nothing\n\t\t\t\t\t\t\t\t\t\tlogger.info(matcher2.group(0));\n\t\t\t\t\t\t\t\t\t\tlogger.info(matcher2.group(((ReportRecording) rec).getTop100RecordID()+1));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tsynchronized (t100) {\n\t\t\t\t\t\t\t\t\tif (t100.size()<100){\t\t\t\n\t\t\t\t\t\t\t\t\t\tList<Object> temp = new ArrayList<Object>();\n\t\t\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (recItem2.getProcessingType().equals(\"top100\")){\n\t\t\t\t\t\t\t\t\t\t\t\titemIndex=(double)Double.valueOf(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\ttemp.add(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\t\t\tt100.put(itemIndex, temp);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if (t100.size()==100){\n\t\t\t\t\t\t\t\t\t\t\tif (itemIndex>t100.firstKey()){\n\t\t\t\t\t\t\t\t\t\t\t\tList<Object> temp = new ArrayList<Object>();\n\t\t\t\t\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (recItem2.getProcessingType().equals(\"top100\")){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\titemIndex=(double)Double.valueOf(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttemp.add(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tt100.remove(t100.firstKey());\n\t\t\t\t\t\t\t\t\t\t\t\tt100.put(itemIndex, temp);\t\n\t\t\t\t\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\telse if (((ReportRecording) rec).getSubType().equals(\"sum\") && rec.getIsActive()) {\n\t\t\t\t\t\t\t\t\tdouble itemIndex = 0;\n\t\t\t\t\t\t\t\t\tList<Object> temp = new ArrayList<Object>();\n\t\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\tif (recItem2.getProcessingType().equals(\"sum\")){\n\t\t\t\t\t\t\t\t\t\t\titemIndex=(double)Double.valueOf(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\ttemp.add(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tMap<List<Object>,Double> sumMap = sumReport.get(source).get(rec);\n\t\t\t\t\t\t\t\t\tif (sumMap==null) {\n\t\t\t\t\t\t\t\t\t\tsumReport.get(source).put(rec, new ConcurrentHashMap<List<Object>, Double>());\n\t\t\t\t\t\t\t\t\t\tsumMap = sumReport.get(source).get(rec);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tsynchronized (sumMap) {\n\t\t\t\t\t\t\t\t\tObject sum = sumMap.get(temp);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif (sum==null) {\n\t\t\t\t\t\t\t\t\t\tsumMap.put(temp, (double)itemIndex);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tsumMap.put(temp, (double) sum + itemIndex);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (timings || matches) {\n\t\t\t\t\t\t\t\tarrayBefore = matchTimings.get(rec.getName());\n\t\t\t\t\t\t\t\tif (arrayBefore!=null) {\n\t\t\t\t\t\t\t\t// logger.info(file.getName() + \" contains \" +\n\t\t\t\t\t\t\t\t// arrayBefore);\n\t\t\t\t\t\t\t\t// 0-> sum of time for success matching of given\n\t\t\t\t\t\t\t\t// recording ; 1-> sum of time for failed\n\t\t\t\t\t\t\t\t// matching ; 2-> count of match attempts,\n\t\t\t\t\t\t\t\t// 3->count of success attempts\n\t\t\t\t\t\t\t\tif (timings) {\n\t\t\t\t\t\t\t\t\trecordingMatchEnd = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t\t\t\t\ttiming0 = arrayBefore[0] + recordingMatchEnd - recordingMatchStart;\n\t\t\t\t\t\t\t\t\ttiming1 = arrayBefore[1];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (matches) {\n\t\t\t\t\t\t\t\t\tmatch0 = arrayBefore[2] + 1;\n\t\t\t\t\t\t\t\t\tmatch1 = arrayBefore[3] + 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlong[] array = { timing0, timing1, match0, match1 };\n\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (timings) {\n\t\t\t\t\t\t\t\t\trecordingMatchEnd = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t\t\t\t\tlong[] array = { recordingMatchEnd - recordingMatchStart, 0, 1, 1 };\n\t\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\t\t\tlong[] array = { 0, 0, 1, 1 };\n\t\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (timings || matches) {\n\t\t\t\t\t\t\t\tarrayBefore = matchTimings.get(rec.getName());\n\t\t\t\t\t\t\t\tif (arrayBefore!=null) {\n\t\t\t\t\t\t\t\t// logger.info(file.getName() + \" contains \" +\n\t\t\t\t\t\t\t\t// arrayBefore);\n\t\t\t\t\t\t\t\t// 0-> sum of time for success matching of given\n\t\t\t\t\t\t\t\t// recording ; 1-> sum of time for failed\n\t\t\t\t\t\t\t\t// matching ; 2-> count of match attempts,\n\t\t\t\t\t\t\t\t// 3->count of success attempts\n\t\t\t\t\t\t\t\tif (timings) {\n\t\t\t\t\t\t\t\t\trecordingMatchEnd = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t\t\t\t\ttiming0 = arrayBefore[0];\n\t\t\t\t\t\t\t\t\ttiming1 = arrayBefore[1] + recordingMatchEnd - recordingMatchStart;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (matches) {\n\t\t\t\t\t\t\t\t\tmatch0 = arrayBefore[2] + 1;\n\t\t\t\t\t\t\t\t\tmatch1 = arrayBefore[3];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlong[] array = { timing0, timing1, match0, match1 };\n\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (timings) {\n\t\t\t\t\t\t\t\t\trecordingMatchEnd = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t\t\t\t\tlong[] array = { 0, recordingMatchEnd - recordingMatchStart, 1, 0 };\n\t\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\t\t\tlong[] array = { 0, 0, 1, 0 };\n\t\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlineCount++;\n\n\t\t\t\t// timing\n\t\t\t}\n\t\t} catch (NumberFormatException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tbuf1st.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\tmainFrame.progress();\n\t\treturn new FileMineResult(fileRecord, statMap, eventMap, matchTimings, RIFileLineDateMap, startDate, endDate);\n\t}\n\n\t/*\n\t * public Map<String,ArrayList> getSourceFileGroup(ArrayList<String>\n\t * sourceFiles,Source src) { String patternString = \"\";\n\t * Map<String,ArrayList> Map=new\n\t * Map<String,ArrayList>(); while (it.hasNext()){ it.next(); }}\n\t * \n\t * returns Map with group id in key and a ArrayList of matching files in\n\t * value.\n\t * \n\t * @param repo\n\t */\n\tpublic static Map<String, ArrayList<FileRecord>> getSourceFileGroup(Map<Integer, FileRecord> sourceFiles, Source src, Repository repo, boolean order) {\n\t\tPatternCache patternCache = new PatternCache();\n\t\tString patternString = \"\";\n\t\tMap<String, ArrayList<FileRecord>> sourceFileGroup = new HashMap<String, ArrayList<FileRecord>>();\n\t\tArrayList<FileRecord> groupedFiles = new ArrayList<FileRecord>();\n\t\tMatcher matcher = null;\n\t\tRecording rec = src.getActiveMetadata();\n\t\tif (src!=null && rec!=null){\n\t\t\t\t\tArrayList<RecordingItem> rIV = ((MetadataRecording) rec).getRecordingItem();\n\t\t\t\t\tIterator<RecordingItem> itV = rIV.iterator();\n\t\t\t\t\tint nbRec = 0;\n\t\t\t\t\twhile (itV.hasNext()) {\n\t\t\t\t\t\tRecordingItem rI = itV.next();\n\t\t\t\t\t\tString type = rI.getType();\n\t\t\t\t\t\tif (type == \"date\") {\n\t\t\t\t\t\t\tpatternString += rI.getBefore() + \"(\" + repo.getDateFormat(rec.getDateFormatID()) + \")\" + rI.getAfter();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpatternString += rI.getBefore() + \"(\" + DataMiner.getTypeString(type) + \")\" + rI.getAfter();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// logger.info(\"patternString: \" + patternString\n\t\t\t\t\t\t// + \" getType: \" +\n\t\t\t\t\t\t// DataMiner.getTypeString(rI.getType()));\n\t\t\t\t\t\tnbRec++;\n\t\t\t\t\t}\n\t\t\t\t\tIterator<FileRecord> sourceFileIterator = sourceFiles.values().iterator();\n\t\t\t\t\tString key = \"\";\n\t\t\t\t\t// tempV = new ArrayList<String>();\n\t\t\t\t\twhile (sourceFileIterator.hasNext()) {\n\t\t\t\t\t\tgroupedFiles.clear();\n\t\t\t\t\t\tFileRecord fileName = sourceFileIterator.next();\n\t\t\t\t\t\t// logger.info(\"file: \"+fileName);\n\t\t\t\t\t\ttry {\n\n\t\t\t\t\t\t\tif (logger.isTraceEnabled()){\n\t\t\t\t\t\t\t\tlogger.trace(\"patternString: \" + patternString);\n\t\t\t\t\t\t\t\tlogger.trace(\"filename: \" + fileName);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmatcher = patternCache.getMatcher(patternString + \".*\",rec.isCaseSensitive(),\n\t\t\t\t\t\t\t\t\tnew File(repo.getBaseSourcePath()).toURI().relativize(new File(fileName.getFile().getCanonicalPath()).toURI()).getPath());\n\t\t\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\tlogger.trace(\"found filename \" + fileName + \" with group\");\n\n\t\t\t\t\t\t\t\tkey = \"\";\n\t\t\t\t\t\t\t\tint i = 0;\n\t\t\t\t\t\t\t\tfor (i = 0; i < matcher.groupCount(); i++) {\n\t\t\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\t\t\tlogger.trace(\"group matched : \" + matcher.group(i));\n\t\t\t\t\t\t\t\t\t\tkey += matcher.group(i + 1) + \" \";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\tlogger.trace(\"i : \" + i + \" nbRec: \" + nbRec);\n\t\t\t\t\t\t\t\tif (i == nbRec) {\n\t\t\t\t\t\t\t\t\tif (!sourceFileGroup.containsKey(key)) {\n\t\t\t\t\t\t\t\t\t\tArrayList<FileRecord> v = new ArrayList<FileRecord>();\n\t\t\t\t\t\t\t\t\t\tv.add(fileName);\n\t\t\t\t\t\t\t\t\t\tsourceFileGroup.put(key, v);\n\t\t\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\t\t\tlogger.trace(\" to key: \" + key + \" added : \" + fileName);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tsourceFileGroup.get(key).add(fileName);\n\t\t\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\t\t\tlogger.trace(\" to key: \" + key + \" added : \" + fileName);\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t * if (tempV != null) { sourceFileGroup.put(key,\n\t\t\t\t\t\t\t\t * tempV); logger.info(\"Added file \" + fileName\n\t\t\t\t\t\t\t\t * + \" to group \" + key.toString());\n\t\t\t\t\t\t\t\t * logger.info(\"files \" + tempV);\n\t\t\t\t\t\t\t\t * \n\t\t\t\t\t\t\t\t * }\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} catch (Exception e1) {\n\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t\t// System.exit(1);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// logger.info(\"found group \" + key + \"with \" +\n\t\t\t\t\t\t// groupedFiles.size() + \" files in source \" +\n\t\t\t\t\t\t// src.getSourceName());\n\t\t\t\t\t\t\n\t\t\t\t\t\t//option for ordering files by date of lines - useless at this point\n\t\t\t\t\t\tif (order)\n\t\t\t\t\t\t\t{sourceFileGroup.put(key,Tools.orderFiles(sourceFileGroup.get(key),src));\n\t\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\t\tsourceFileGroup.put(key,sourceFileGroup.get(key));\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\treturn sourceFileGroup;\n\t\t}\nelse {return null;}\n\t}\n\t\n\tprivate static Map<Class,Map<Recording, String>> getAllRegexp(Repository repo, Source source) {\n\t\tMap<Class,Map<Recording, String>> recMatch = new HashMap<Class,Map<Recording, String>>();\n\t\trecMatch.put(StatRecording.class,getRegexp(repo,source,StatRecording.class));\n\t\trecMatch.put(EventRecording.class,getRegexp(repo,source,StatRecording.class));\n\t\trecMatch.put(ReportRecording.class,getRegexp(repo,source,StatRecording.class));\n\t\treturn recMatch;\n\t}\n\n\tpublic static Map<Recording, String> getAllRegexSingleMap(Repository repo, Source source) {\n\t\tlong startTime = System.currentTimeMillis();\n\t\tMap<Recording, String> recMatch = new HashMap<Recording, String>();\n\t\tif (Preferences.getBooleanPreference(\"gatherstats\")){\n\t\t\tMap<Recording, String> g1= getRegexp(repo,source,StatRecording.class);\n\t\t\tif (g1!=null){\n\t\t\trecMatch.putAll(g1);\n\t\t\t}\n\t\t}\n\t\tif (Preferences.getBooleanPreference(\"gatherevents\")){\n\t\t\tMap<Recording, String> g2= getRegexp(repo,source,EventRecording.class);\n\t\t\tif (g2!=null){\n\t\t\t\trecMatch.putAll(g2);\t\n\t\t\t}\n\t\t}\n\t\tif (Preferences.getBooleanPreference(\"gatherreports\")){\n\t\t\tMap<Recording, String> g3= getRegexp(repo,source,ReportRecording.class);\n\t\t\tif (g3!=null){\n\t\t\trecMatch.putAll(g3);\n\t\t\t}\n\t\t}\n\t\testimatedTime = System.currentTimeMillis() - startTime;\n\t\tlogger.debug(\"getAllRegexSingleMap time: \" + estimatedTime);\n\t\treturn recMatch;\n\t}\n\t\n\t\n\tprivate static Map<Recording, String> getRegexp(Repository repo, Source source, Class recordingClass) {\n\t\tMap<Recording, String> recMatch = new HashMap<Recording, String>();\n\t\tMap<Recording, Boolean> activeRecordingOnSourceCache = new HashMap<Recording, Boolean>();\n\t\tArrayList<Recording> recordings;\n\t\tStringBuffer sb = new StringBuffer(200);\n\t\trecordings = repo.getRecordings(recordingClass,true);\n\t\tIterator<Recording> recordingIterator = recordings.iterator();\n\t\tboolean forceSourceDateFormat = Preferences.getBooleanPreference(\"ForceSourceDateFormat\");\n\t\t\n\t\twhile (recordingIterator.hasNext()) {\n\t\t\tRecording rec = recordingIterator.next();\n\t\t\tif (!activeRecordingOnSourceCache.containsKey(rec)) {\n\t\t\t\tactiveRecordingOnSourceCache.put(rec, source.isActiveRecordingOnSource(rec));\n\t\t\t}\n\t\t\tif (activeRecordingOnSourceCache.get(rec)) {\n\t\t\t\tif (rec.getIsActive() == true) {\n\t\t\t\t\tArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();\n\t\t\t\t\tIterator<RecordingItem> recItemIte = recordingItem.iterator();\n\t\t\t\t\tif (logger.isTraceEnabled()) {\n\t\t\t\t\t\tlogger.trace(\"Record: \" + rec.getName());\n\t\t\t\t\t}\n\t\t\t\t\tsb.setLength(0);\n\t\t\t\t\t// processing each line of the table\n\t\t\t\t\twhile (recItemIte.hasNext()) {\n\t\t\t\t\t\tRecordingItem recItem = recItemIte.next();\n\t\t\t\t\t\tString stBefore = (String) recItem.getBefore();\n\t\t\t\t\t\tString stType = (String) recItem.getType();\n\t\t\t\t\t\tString stAfter = (String) recItem.getAfter();\n\t\t\t\t\t\tString stInside = recItem.getInside();\n\t\t\t\t\t\tsb.append(stBefore);\n\t\t\t\t\t\tsb.append(\"(\");\n\t\t\t\t\t\tif (forceSourceDateFormat){\n\t\t\t\t\t\t\tsb.append(getMainRegex(stType,stInside,source.getDateFormat()));\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tsb.append(getMainRegex(stType,stInside,repo.getDateFormat(rec.getDateFormatID())));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsb.append(\")\");\n\t\t\t\t\t\tsb.append(stAfter);\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\trecMatch.put(rec, sb.toString());\n\t\t\t\t\tif (logger.isTraceEnabled()) {\n\t\t\t\t\t\tlogger.trace(\"regexp: \" +rec.getRegexp());\n\t\t\t\t\t\tlogger.trace(\"Pattern: \" + sb.toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn recMatch;\n\t}\n\n\tpublic static String getMainRegex(String stType, String stInside, DateFormat dateFormat) {\n\t\tif (stType.equals(\"date\")) {\n\t\treturn dateFormat.getPattern();\n\t\t} else{\n\t\t\tif (!stType.equals(\"manual\")){\n\t\t\t\treturn (getTypeString(stType));\n\t\t\t} else {\n\t\t\t\treturn (stInside);\n\t\t\t}}\n\t}\n\n\t// public static get\n\tpublic static String getTypeString(String type) {\n\t\tString typeString = \"\";\n\t\tswitch (type) {\n\t\tcase \"integer\":\n\t\t\ttypeString = \"\\\\d+\";\n\t\t\tbreak;\n\t\tcase \"percent\":\n\t\t\ttypeString = \"\\\\d+\";\n\t\t\tbreak;\n\t\tcase \"word\":\n\t\t\ttypeString = \"\\\\w+\";\n\t\t\tbreak;\n\t\tcase \"stringminimum\":\n\t\t\ttypeString = \".*?\";\n\t\t\tbreak;\n\t\tcase \"string\":\n\t\t\ttypeString = \".*\";\n\t\t\tbreak;\n\t\tcase \"double\":\n\t\t\ttypeString = \"[-+]?[0-9]*.?[0-9]+(?:[eE][-+]?[0-9]+)?\";\n\t\t\tbreak;\n\t\tcase \"long\": // keeping for compatibility with older templates\n\t\t\ttypeString = \"\\\\d+\";\n\t\t\tbreak;\n\t\t/*\n\t\t * case \"date\": typeString = repo.getDateFormat(rec.getDateFormatID());\n\t\t * break;\n\t\t */\n\t\tdefault:\n\t\t\ttypeString = \".*\";\n\t\t\tbreak;\n\t\t}\n\t\treturn typeString;\n\t}\n\t\n\tpublic static ChartData gatherSourceData(final Repository repo, boolean order) {\n\n\t\tPatternCache patternCache = new PatternCache();\n\t\tChartData cd = new ChartData();\n\t\tList<File> listOfFiles = null;\n\t\tlogger.debug(\"Base file path: \" + repo.getBaseSourcePath());\n\t\tif (repo.getBaseSourcePath() == null)\n\t\t\treturn null;\n\t\tFile folder = new File(repo.getBaseSourcePath());\n\t\ttry {\n\t\t\tif (repo.isRecursiveMode()) {\n\t\t\t\tlistOfFiles = FileListing.getFileListing(folder);\n\t\t\t} else {\n\t\t\t\tlistOfFiles = Arrays.asList(folder.listFiles());\n\n\t\t\t}\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tif (listOfFiles != null)\n\t\t\tlogger.debug(\"number of files: \" + listOfFiles.size());\n\t\tcd.sourceArrayList = repo.getSources();\n\t\tIterator<Source> sourceIterator = cd.sourceArrayList.iterator();\n\n\t\twhile (sourceIterator.hasNext()) {\n\t\t\tfinal Source source = sourceIterator.next();\n\t\t\tcd.selectedSourceFiles = new HashMap<Integer, FileRecord>();\n\t\t\t// sourceFiles contains all the matched files for a given source\n\t\t\tif (source.getActive()) {\n\t\t\t\tfor (int i = 0; i < listOfFiles.size(); i++) {\n\t\t\t\t\tif (listOfFiles.get(i).isFile()) {\n\t\t\t\t\t\tString s1 = source.getSourcePattern();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tMatcher matcher = patternCache.getMatcher(s1,true,\n\t\t\t\t\t\t\t\t\tnew File(repo.getBaseSourcePath()).toURI().relativize(new File(listOfFiles.get(i).getCanonicalPath()).toURI()).getPath());\n\n\t\t\t\t\t\t\tif (logger.isTraceEnabled()) {\n\t\t\t\t\t\t\t\tlogger.trace(i\n\t\t\t\t\t\t\t\t\t\t+ \" matching file: \"\n\t\t\t\t\t\t\t\t\t\t+ new File(repo.getBaseSourcePath()).toURI().relativize(new File(listOfFiles.get(i).getCanonicalPath()).toURI())\n\t\t\t\t\t\t\t\t\t\t\t\t.getPath() + \" with pattern: \" + s1);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (matcher.find()) {\n\n\t\t\t\t\t\t\t\tFileRecord tempFileRecord = new FileRecord(i, new File(listOfFiles.get(i).getCanonicalPath()));\n\t\t\t\t\t\t\t\tcd.selectedSourceFiles.put(i, tempFileRecord);\n\t\t\t\t\t\t\t\tif (logger.isTraceEnabled()) {\n\n\t\t\t\t\t\t\t\t\tlogger.trace(\"Source: \" + source.getSourceName() + \" file: \" + listOfFiles.get(i).getCanonicalPath());\n\t\t\t\t\t\t\t\t\tlogger.trace(\" Graphpanel file: \"\n\t\t\t\t\t\t\t\t\t\t\t+ new File(repo.getBaseSourcePath()).toURI().relativize(new File(listOfFiles.get(i).getCanonicalPath()).toURI())\n\t\t\t\t\t\t\t\t\t\t\t\t\t.getPath());\n\t\t\t\t\t\t\t\t\tlogger.trace(tempFileRecord.getCompletePath());\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (logger.isEnabledFor(Level.DEBUG))\n\t\t\t\t\tlogger.debug(\"matched file: \" + cd.selectedSourceFiles.size() + \" to source \" + source.getSourceName());\n\t\t\t}\n\t\t\tcd.sourceFileArrayListMap.put(source, cd.selectedSourceFiles);\n\t\t}\n\t\tMap<String, ArrayList<FileRecord>> sourceFileGroup = null;\n\t\tIterator<Entry<Source, Map<Integer, FileRecord>>> ite = cd.sourceFileArrayListMap.entrySet().iterator();\n\t\twhile (ite.hasNext()) {\n\t\t\tfinal Map.Entry sourcePairs = ite.next();\n\t\t\tfinal Source src = (Source) sourcePairs.getKey();\n\t\t\tMap<Integer, FileRecord> sourceFiles = (Map<Integer, FileRecord>) sourcePairs.getValue();\n\t\t\tsourceFileGroup = getSourceFileGroup(sourceFiles, src, repo,order);\n\t\t\tif (sourceFileGroup!=null && sourceFileGroup.keySet().size()>0)\n\t\t\t\tlogger.info(\"matched groups: \" + (sourceFileGroup!=null? sourceFileGroup.keySet().size():\"\") + \" for source \" + src.getSourceName());\n\t\t//\tlogger.debug(sourceFileGroup.toString());\n\t\t\tcd.setGroupFilesArrayListMap(src, sourceFileGroup);\n\t\t}\n\t\treturn cd;\n\t}\n\n\tpublic static void populateRecordingSamples(Repository repo) {\n\t\tPatternCache patternCache = new PatternCache();\n\t\tFileReader flstr = null;\n\t\tBufferedReader buf1st;\n\t\tMap<Recording, String> recMatch = new HashMap<Recording, String>();\n\t\tMatcher matcher;\n\t\tMatcher matcher2;\n\t\tif (repo.getBaseSourcePath() == null)\n\t\t\treturn;\n\t\tFile folder = new File(repo.getBaseSourcePath());\n\t\ttry {\n\t\t\tif (repo.isRecursiveMode()) {\n\t\t\t\tlistOfFiles = FileListing.getFileListing(folder);\n\t\t\t} else {\n\t\t\t\tlistOfFiles = Arrays.asList(folder.listFiles());\n\t\t\t}\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t}\n\t\tif (repo != null && repo.getBaseSourcePath() != null) {\n\t\t\tChartData cd = DataMiner.gatherSourceData(repo,false);\n\t\t\tArrayList sources = repo.getSources();\n\t\t\tIterator sourceArrayListIte = sources.iterator();\n\t\t\twhile (sourceArrayListIte.hasNext()) {\n\n\t\t\t\t// Map<Recording, String> regMap=getRegexp(repo, src);\n\t\t\t\tcd.sourceArrayList = repo.getSources();\n\t\t\t\tIterator<Source> sourceIterator = cd.sourceArrayList.iterator();\n\n\t\t\t\tSource src = (Source) sourceArrayListIte.next();\n\t\t\t\tMap<String, ArrayList<FileRecord>> hm = cd.getGroupFilesMap(src);\n\t\t\t\tlogger.info(\"population\");\n\t\t\t\tif (hm != null && hm.entrySet() != null) {\n\t\t\t\t\tIterator it = hm.entrySet().iterator();\n\t\t\t\t\twhile (it.hasNext()) {\n\t\t\t\t\t\tfinal Map.Entry pairs = (Map.Entry) it.next();\n\t\t\t\t\t\tlogger.info(\"populating: \" + pairs.getKey());\n\t\t\t\t\t\tArrayList<FileRecord> grouFile = (ArrayList<FileRecord>) pairs.getValue();\n\t\t\t\t\t\t// return DataMiner.mine((String) pairs.getKey(),\n\t\t\t\t\t\t// (ArrayList<String>) pairs.getValue(), repo, source,\n\t\t\t\t\t\t// repo.isStats(), repo.isTimings());\n\t\t\t\t\t\tIterator<FileRecord> fileArrayListIterator = grouFile.iterator();\n\t\t\t\t\t\twhile (fileArrayListIterator.hasNext()) {\n\t\t\t\t\t\t\tfinal FileRecord fileName = fileArrayListIterator.next();\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tflstr = new FileReader(new File(fileName.getCompletePath()));\n\t\t\t\t\t\t\t} catch (FileNotFoundException e1) {\n\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbuf1st = new BufferedReader(flstr);\n\t\t\t\t\t\t\tString line;\n\t\t\t\t\t\t\tlogger.info(\"matched file:\" + fileName);\n\t\t\t\t\t\t\trecMatch = getAllRegexSingleMap(repo, src);\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\twhile ((line = buf1st.readLine()) != null) {\n\t\t\t\t\t\t\t\t\t// check against one Recording pattern at a\n\t\t\t\t\t\t\t\t\t// tim\n\t\t\t\t\t\t\t\t\t// if (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\t\t// logger.debug(\"line \" + line);\n\t\t\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\t\t\tIterator recMatchIte = recMatch.entrySet().iterator();\n\t\t\t\t\t\t\t\t\twhile (recMatchIte.hasNext()) {\n\t\t\t\t\t\t\t\t\t\tMap.Entry me = (Map.Entry) recMatchIte.next();\n\t\t\t\t\t\t\t\t\t\tRecording rec = (Recording) me.getKey();\n\t\t\t\t\t\t\t\t\t\tmatcher = patternCache.getMatcher((String) (rec.getRegexp()), rec.isCaseSensitive(),line);\n\t\t\t\t\t\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\t\t\t\t\t\t// logger.info(\"1**** matched: \" +\n\t\t\t\t\t\t\t\t\t\t\t// line);\n\t\t\t\t\t\t\t\t\t\t\tArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();\n\t\t\t\t\t\t\t\t\t\t\tint cnt = 0;\n\t\t\t\t\t\t\t\t\t\t\tmatcher2 = patternCache.getMatcher((String) me.getValue(), rec.isCaseSensitive(),line);\n\t\t\t\t\t\t\t\t\t\t\tif (matcher2.find()) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tDataVault.addMatchedLines(rec, line);\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tDataVault.addUnmatchedLines(rec, line);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n/*\tpublic static ArrayList<Map> exportData(Repository repo) {\n\t\tgatherMineResultSet(null,repo, null);\n\t\treturn null;\n\n\t}*/\n\t/*\n\t * public static ArrayList<Map> exportData(Repository repo) { PatternCache\n\t * patternCache = new PatternCache(); Matcher matcher = null; ArrayList<Map>\n\t * expVec = new ArrayList<Map>(); File folder = new\n\t * File(repo.getBaseSourcePath()); try { if (repo.isRecursiveMode()) {\n\t * listOfFiles = FileListing.getFileListing(folder); } else { listOfFiles =\n\t * Arrays.asList(folder.listFiles());\n\t * \n\t * } } catch (FileNotFoundException e) { // TODO Auto-generated catch block\n\t * e.printStackTrace(); } if (logger.isEnabledFor(Level.INFO))\n\t * logger.info(\"number of files: \" + listOfFiles.size()); // int[][]\n\t * fileListMatches = new int[listOfFiles.size()][3];\n\t * \n\t * Iterator sourceIterator = repo.getSources().iterator();\n\t * \n\t * while (sourceIterator.hasNext()) { Source r = (Source)\n\t * sourceIterator.next(); ArrayList<String> sourceFiles = new\n\t * ArrayList<String>(); // sourceFiles contains all the matched files for a\n\t * given source\n\t * \n\t * if (r.getActive()) {\n\t * \n\t * for (int i = 0; i < listOfFiles.size(); i++) { if\n\t * (listOfFiles.get(i).isFile()) { // logger.info(\"File \" + //\n\t * listOfFiles.get(i).getName()); String s1 = r.getSourcePattern(); matcher\n\t * = patternCache.getPattern(s1).matcher(listOfFiles.get(i).getName()); if\n\t * (matcher.find()) { try { sourceFiles.add(new\n\t * File(repo.getBaseSourcePath()).toURI().relativize(new\n\t * File(listOfFiles.get(i).getCanonicalPath()).toURI()) .getPath());\n\t * \n\t * //\n\t * logger.info(\" Graphpanel file1: \"+listOfFiles.get(i).getCanonicalPath());\n\t * // logger.info(\" Graphpanel file: \"+new //\n\t * File(repo.getBaseSourcePath()).toURI() // .relativize(new //\n\t * File(listOfFiles.get(i).getCanonicalPath()).toURI()).getPath()); } catch\n\t * (IOException e) { // TODO Auto-generated catch block e.printStackTrace();\n\t * } // sourceFiles.add(listOfFiles.get(i).getAbsolutePath() // +\n\t * listOfFiles.get(i).getName()); } } } logger.info(\"matched file: \" +\n\t * sourceFiles.size() + \" to source group \" + r.getSourceName()); }\n\t * Map<String, ArrayList<String>> sourceFileGroup =\n\t * getSourceFileGroup(sourceFiles, r, repo); expVec.add(sourceFileGroup);\n\t * logger.info(\"matched groups: \" + sourceFileGroup.keySet().size() +\n\t * \" for source \" + r.getSourceName()); Iterator it =\n\t * sourceFileGroup.entrySet().iterator(); while (it.hasNext()) { Map.Entry\n\t * pairs = (Map.Entry) it.next(); logger.info(pairs.getKey().toString() +\n\t * \" = \" + pairs.getValue()); // it.remove(); // avoids a\n\t * ConcurrentModificationException\n\t * \n\t * FileMineResultSet fMR = fastMine((ArrayList<String>) pairs.getValue(),\n\t * repo, r, false, false);\n\t * \n\t * expVec.add(fMR.eventGroupTimeSeries);\n\t * expVec.add(fMR.statGroupTimeSeries); } } return expVec; }\n\t */\n}",
"public class PatternCache {\n//\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tprivate Map<String, Pattern> pattern = new HashMap<String, Pattern>();\n\tprivate Map<String, Matcher> matcher = new HashMap<String, Matcher>();\n\n\tpublic Pattern getPattern(String regexp, boolean caseSensitive) {\n\t\tPattern temp = pattern.get(regexp+Boolean.toString(caseSensitive));\n\t\tif (temp!=null){\n\t\t\treturn temp;\n\t\t} else{\n\t\t\tif (caseSensitive){\n\t\t\t\tpattern.put(regexp+caseSensitive, Pattern.compile(regexp));\n\t\t\t}else{\n\t\t\t\tpattern.put(regexp+caseSensitive, Pattern.compile(regexp, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));\n\t\t\t}\t\t\t\n\t\t}\n\t\treturn pattern.get(regexp+caseSensitive);\n\t}\n\t\n\tpublic Matcher getMatcher(String regexp, boolean caseSensitive,String str) {\n\t\tMatcher tempMatcher=matcher.get(regexp+caseSensitive);\n\t\tif (tempMatcher!=null){\n\t\t\treturn tempMatcher.reset(str);\n\t\t} else{\n\t\t\tif (caseSensitive){\n\t\t\t\tmatcher.put(regexp+caseSensitive, getPattern(regexp,caseSensitive).matcher(str));\n\t\t\t}else{\n\t\t\t\tmatcher.put(regexp+caseSensitive, getPattern(regexp,caseSensitive).matcher(str));\t\n\t\t\t}\n\t\t}\n\t\treturn matcher.get(regexp+caseSensitive);\n\t}\n\t\n\tpublic Matcher getNewMatcher(String regexp, boolean caseSensitive,String str) {\n\t\treturn getPattern(regexp,caseSensitive).matcher(str);\n\t}\n\t\n}"
] | import javax.swing.JPanel;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import org.apache.log4j.Logger;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.text.ParseException;
import org.apache.commons.lang3.time.FastDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import logdruid.data.Repository;
import logdruid.data.record.EventRecording;
import logdruid.data.record.MetadataRecording;
import logdruid.data.record.Recording;
import logdruid.data.record.RecordingItem;
import logdruid.data.record.StatRecording;
import logdruid.ui.NoProcessingRegexTableRenderer;
import logdruid.util.DataMiner;
import logdruid.util.PatternCache; | /*******************************************************************************
* LogDruid : Generate charts and reports using data gathered in log files
* Copyright (C) 2016 Frederic Valente ([email protected])
*
* 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 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 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/.
*******************************************************************************/
package logdruid.ui.table;
public class StatRecordingEditorTable extends JPanel {
private static Logger logger = Logger.getLogger(DataMiner.class.getName());
private boolean DEBUG = false;
static Matcher m;
static ArrayList records = null;
private MyTableModel model;
private String[] header = { "Name", "Before", "Inside type", "Inside regex", "After", "Active", "Show", "Value" };
private ArrayList<Object[]> data = new ArrayList<Object[]>();
JTable table = null;
private String theLine = "";
private JTextPane examplePane; | private Repository rep = null; | 0 |
jurihock/voicesmith | tests/src/de/jurihock/voicesmith/services/AudioServiceTestBase.java | [
"public class AudioDeviceManager\n{\n private final Context context;\n\n public AudioDeviceManager(Context context)\n {\n this.context = context;\n }\n\n public AudioDevice getInputDevice(HeadsetMode mode) throws IOException\n {\n // TEST: Read input signal from file instead of mic device\n // return new FileInDevice(context, \"voicesmith_input.raw\");\n\n return new PcmInDevice(context, mode);\n }\n\n public AudioDevice getOutputDevice(HeadsetMode mode) throws IOException\n {\n // TEST: Write output signal to file instead of output jack\n // (also enable WRITE_EXTERNAL_STORAGE permission in the manifest file)\n // return new FileOutDevice(context, \"voicesmith_output.raw\");\n\n return new PcmOutDevice(context, mode);\n }\n}",
"public class HeadsetManager\n{\n\tprivate static final int\t\tWIRED_HEADSET_SOURCE\t\t\t= AudioManager.STREAM_MUSIC;\n\tprivate static final int\t\tBLUETOOTH_HEADSET_SOURCE\t\t= 6;\n\t// Undocumented \"6\" instead of STREAM_VOICE_CALL:\n\t// http://stackoverflow.com/questions/4472613/android-bluetooth-earpiece-volume\n\n\t// Another undocumented Bluetooth constants:\n\t// http://www.netmite.com/android/mydroid/2.0/frameworks/base/core/java/android/bluetooth/BluetoothHeadset.java\n\tprivate static final String\t\tACTION_BLUETOOTH_STATE_CHANGED\t= \"android.bluetooth.headset.action.STATE_CHANGED\";\n\tprivate static final String\t\tBLUETOOTH_STATE\t\t\t\t\t= \"android.bluetooth.headset.extra.STATE\";\n\tprivate static final int\t\tBLUETOOTH_STATE_ERROR\t\t\t= -1;\n\tprivate static final int\t\tBLUETOOTH_STATE_DISCONNECTED\t= 0;\n\tprivate static final int\t\tBLUETOOTH_STATE_CONNECTING\t\t= 1;\n\tprivate static final int\t\tBLUETOOTH_STATE_CONNECTED\t\t= 2;\n\n\tprivate final Context\t\t\tcontext;\n\tprivate final AudioManager audioManager;\n\n\tprivate HeadsetManagerListener\tlistener\t\t\t\t\t\t= null;\n\tprivate BroadcastReceiver\t\theadsetDetector\t\t\t\t\t= null;\n\n\tpublic HeadsetManager(Context context)\n\t{\n\t\tthis.context = context;\n\n\t\taudioManager = (AudioManager)\n\t\t\tcontext.getSystemService(Context.AUDIO_SERVICE);\n\t}\n\n\tpublic void setListener(HeadsetManagerListener listener)\n\t{\n\t\tthis.listener = listener;\n\t}\n\n\tpublic void restoreVolumeLevel(HeadsetMode headsetMode)\n\t{\n\t\tint source;\n\n\t\tswitch (headsetMode)\n\t\t{\n case WIRED_HEADPHONES:\n\t\tcase WIRED_HEADSET:\n\t\t\tsource = WIRED_HEADSET_SOURCE;\n\t\t\tbreak;\n\t\tcase BLUETOOTH_HEADSET:\n\t\t\tsource = BLUETOOTH_HEADSET_SOURCE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tnew Utils(context).log(new IOException(\"Unknown HeadsetMode!\"));\n\t\t\tsource = WIRED_HEADSET_SOURCE;\n\t\t}\n\n try\n {\n // VOL = VOL% * (MAX / 100)\n double volumeLevel = audioManager\n .getStreamMaxVolume(source) / 100D;\n volumeLevel *= new Preferences(context).getVolumeLevel(headsetMode);\n\n audioManager.setStreamVolume(\n source,\n (int) Math.round(volumeLevel),\n // Display the volume dialog\n // AudioManager.FLAG_SHOW_UI);\n // Display nothing\n AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);\n }\n catch (Exception exception)\n {\n new Utils(context).log(\"Cannot set audio stream volume!\");\n new Utils(context).log(exception);\n }\n\t}\n\n\tpublic boolean isWiredHeadsetOn()\n\t{\n\t\treturn audioManager.isWiredHeadsetOn();\n\t}\n\n\tpublic boolean isBluetoothHeadsetOn()\n\t{\n\t\tboolean isHeadsetConnected = false;\n\n\t\ttry\n\t\t{\n\t\t\tBluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();\n\t\t\tif (adapter != null && adapter.isEnabled())\n\t\t\t{\n\t\t\t\tSet<BluetoothDevice> devices = adapter.getBondedDevices();\n\n\t\t\t\tisHeadsetConnected = devices != null\n\t\t\t\t\t&& devices.size() > 0;\n\n\t\t\t\t// TODO: Check device classes, what sort of devices it is\n\t\t\t}\n\t\t}\n\t\tcatch (Exception exception)\n\t\t{\n\t\t\tnew Utils(context).log(exception);\n\t\t}\n\n\t\treturn isHeadsetConnected\n\t\t\t&& audioManager.isBluetoothScoAvailableOffCall();\n\t}\n\n\tpublic boolean isBluetoothScoOn()\n\t{\n\t\treturn audioManager.isBluetoothScoOn();\n\t}\n\n\tpublic void setBluetoothScoOn(boolean on)\n\t{\n\t\tif (audioManager.isBluetoothScoOn() == on) return;\n\n\t\tif (on)\n\t\t{\n\t\t\tnew Utils(context).log(\"Starting Bluetooth SCO.\");\n\t\t\taudioManager.startBluetoothSco();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnew Utils(context).log(\"Stopping Bluetooth SCO.\");\n\t\t\taudioManager.stopBluetoothSco();\n\t\t}\n\t}\n\n\t/**\n\t * Waits until Bluetooth SCO becomes available.\n\t **/\n\tpublic boolean waitForBluetoothSco()\n\t{\n\t\tfinal long timeout = 1000 * 3;\n\t\tfinal long idlePeriod = 50;\n\n\t\tfinal long start = SystemClock.elapsedRealtime();\n\t\tlong end = start;\n\n\t\twhile (!audioManager.isBluetoothScoOn())\n\t\t{\n\t\t\tend = SystemClock.elapsedRealtime();\n\n\t\t\tif (end - start > timeout)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tThread.sleep(idlePeriod);\n\t\t\t}\n\t\t\tcatch (InterruptedException exception)\n\t\t\t{\n\t\t\t}\n\t\t}\n\n\t\tnew Utils(context).log(\n\t\t\t\"Waited %s ms for Bluetooth SCO.\",\n\t\t\tend - start);\n\n\t\treturn true;\n\t}\n\n\tpublic void registerHeadsetDetector()\n\t{\n\t\tif (headsetDetector == null)\n\t\t{\n\t\t\theadsetDetector = new BroadcastReceiver()\n\t\t\t{\n\t\t\t\t@Override\n\t\t\t\tpublic void onReceive(Context context, Intent intent)\n\t\t\t\t{\n\t\t\t\t\t// WIRED HEADSET BROADCAST\n\n\t\t\t\t\tboolean isWiredHeadsetBroadcast = intent.getAction()\n\t\t\t\t\t\t.equals(Intent.ACTION_HEADSET_PLUG);\n\n\t\t\t\t\tif (isWiredHeadsetBroadcast)\n\t\t\t\t\t{\n\t\t\t\t\t\tboolean isWiredHeadsetPlugged =\n\t\t\t\t\t\t\tintent.getIntExtra(\"state\", 0) == 1;\n\n\t\t\t\t\t\tif (isWiredHeadsetPlugged)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnew Utils(context).log(\n\t\t\t\t\t\t\t\t\"Wired headset plugged.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnew Utils(context).log(\n\t\t\t\t\t\t\t\t\"Wired headset unplugged.\");\n\n\t\t\t\t\t\t\tif (listener != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tlistener.onWiredHeadsetOff();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// TODO: Maybe handle the microphone indicator too\n\t\t\t\t\t}\n\n\t\t\t\t\t// BLUETOOTH HEADSET BROADCAST\n\n\t\t\t\t\tboolean isBluetoothHeadsetBroadcast = intent.getAction()\n\t\t\t\t\t\t.equals(ACTION_BLUETOOTH_STATE_CHANGED);\n\n\t\t\t\t\tif (isBluetoothHeadsetBroadcast)\n\t\t\t\t\t{\n\t\t\t\t\t\tint bluetoothHeadsetState = intent.getIntExtra(\n\t\t\t\t\t\t\tBLUETOOTH_STATE,\n\t\t\t\t\t\t\tBLUETOOTH_STATE_ERROR);\n\n\t\t\t\t\t\tswitch (bluetoothHeadsetState)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase BLUETOOTH_STATE_CONNECTING:\n\t\t\t\t\t\tcase BLUETOOTH_STATE_CONNECTED:\n\t\t\t\t\t\t\tnew Utils(context).log(\n\t\t\t\t\t\t\t\t\"Bluetooth headset connecting or connected.\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase BLUETOOTH_STATE_DISCONNECTED:\n\t\t\t\t\t\tcase BLUETOOTH_STATE_ERROR:\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tnew Utils(context).log(\n\t\t\t\t\t\t\t\t\"Bluetooth headset disconnected or error.\");\n\t\t\t\t\t\t\tif (listener != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tlistener.onBluetoothHeadsetOff();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// BLUETOOTH SCO BROADCAST (Build.VERSION.SDK_INT < 14)\n\n /*\n\t\t\t\t\tboolean isBluetoothScoBroadcast = intent.getAction()\n\t\t\t\t\t\t.equals(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);\n\n\t\t\t\t\tif (isBluetoothScoBroadcast)\n\t\t\t\t\t{\n\t\t\t\t\t\tint bluetoothScoState = intent.getIntExtra(\n\t\t\t\t\t\t\tAudioManager.EXTRA_SCO_AUDIO_STATE,\n\t\t\t\t\t\t\tAudioManager.SCO_AUDIO_STATE_ERROR);\n\n\t\t\t\t\t\tswitch (bluetoothScoState)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase AudioManager.SCO_AUDIO_STATE_CONNECTED:\n\t\t\t\t\t\t\tnew Utils(context).log(\n\t\t\t\t\t\t\t\t\"Bluetooth SCO connected.\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase AudioManager.SCO_AUDIO_STATE_DISCONNECTED:\n\t\t\t\t\t\tcase AudioManager.SCO_AUDIO_STATE_ERROR:\n\t\t\t\t\t\t\tnew Utils(context).log(\n\t\t\t\t\t\t\t\t\"Bluetooth SCO disconnected or error.\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t*/\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tIntentFilter filter = new IntentFilter();\n\t\t\t{\n\t\t\t\tfilter.addAction(Intent.ACTION_HEADSET_PLUG);\n\t\t\t\tfilter.addAction(ACTION_BLUETOOTH_STATE_CHANGED);\n\n // Build.VERSION.SDK_INT < 14\n\t\t\t\t// filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);\n\t\t\t}\n\n\t\t\tcontext.registerReceiver(headsetDetector, filter);\n\t\t}\n\t}\n\n\tpublic void unregisterHeadsetDetector()\n\t{\n\t\tif (headsetDetector != null)\n\t\t{\n\t\t\tcontext.unregisterReceiver(headsetDetector);\n\t\t\theadsetDetector = null;\n\t\t}\n\t}\n}",
"public enum HeadsetMode\n{\n WIRED_HEADPHONES,\n\tWIRED_HEADSET,\n\tBLUETOOTH_HEADSET\n}",
"public abstract class AudioDevice implements Disposable\n{\n\tprotected final Context\tcontext;\n\n\tpublic Context getContext()\n\t{\n\t\treturn context;\n\t}\n\n\tprivate int\tsampleRate;\n\n\tpublic int getSampleRate()\n\t{\n\t\treturn sampleRate;\n\t}\n\t\n\tprotected void setSampleRate(int sampleRate)\n\t{\n\t\tthis.sampleRate = sampleRate;\n\t}\n\t\n\tpublic AudioDevice(Context context)\n\t{\n\t\tthis(context, new Preferences(context).getSampleRate());\n\t}\n\n\tpublic AudioDevice(Context context, int\tsampleRate)\n\t{\n\t\tthis.context = context;\n\t\tthis.sampleRate = sampleRate;\n\t\tnew Utils(context).log(\"Current sample rate is %s Hz.\", sampleRate);\n\t}\n\n\tpublic int read(short[] buffer, int offset, int count)\n\t{\n\t\treturn -1;\n\t}\n\n\tpublic final boolean read(short[] buffer)\n\t{\n if (buffer == null) return false;\n if (buffer.length == 0) return false;\n\n\t\tint count = 0;\n\n\t\tdo\n\t\t{\n int result = read(buffer, count, buffer.length - count);\n if (result < 0) return false; // error on reading data\n\t\t\tcount += result;\n\t\t}\n\t\twhile (count < buffer.length);\n\n\t\treturn true;\n\t}\n\n\tpublic int write(short[] buffer, int offset, int count)\n\t{\n\t\treturn -1;\n\t}\n\n\tpublic final boolean write(short[] buffer)\n\t{\n if (buffer == null) return false;\n if (buffer.length == 0) return false;\n\n\t\tint count = 0;\n\n\t\tdo\n\t\t{\n int result = write(buffer, count, buffer.length - count);\n if (result < 0) return false; // error on writing data\n count += result;\n\t\t}\n\t\twhile (count < buffer.length);\n\n return true;\n\t}\n\n\tpublic void flush()\n\t{\n\t}\n\n\tpublic void start()\n\t{\n\t}\n\n\tpublic void stop()\n\t{\n\t}\n\n\tpublic void dispose()\n\t{\n\t}\n}",
"public final class DummyInDevice extends AudioDevice\n{\n public DummyInDevice(Context context)\n {\n super(context);\n }\n\n @Override\n public int read(short[] buffer, int offset, int count)\n {\n // TODO: Simulate AD conversion timeout\n\n for (int i = offset; i < count; i++)\n {\n buffer[i] = 0;\n }\n\n return count;\n }\n}",
"public final class DummyOutDevice extends AudioDevice\n{\n public DummyOutDevice(Context context)\n {\n super(context);\n }\n\n @Override\n public int write(short[] buffer, int offset, int count)\n {\n // TODO: Simulate DA conversion timeout\n\n return count;\n }\n}"
] | import java.io.IOException;
import static org.mockito.Mockito.*;
import android.content.Intent;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.SmallTest;
import de.jurihock.voicesmith.audio.AudioDeviceManager;
import de.jurihock.voicesmith.audio.HeadsetManager;
import de.jurihock.voicesmith.audio.HeadsetMode;
import de.jurihock.voicesmith.io.AudioDevice;
import de.jurihock.voicesmith.io.dummy.DummyInDevice;
import de.jurihock.voicesmith.io.dummy.DummyOutDevice;
import org.mockito.Mock; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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 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 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/>.
*/
package de.jurihock.voicesmith.services;
public abstract class AudioServiceTestBase<T extends AudioService> extends MockableServiceTestCase<T> implements ServiceListener
{
private ServiceFailureReason serviceFailureReason;
@Mock
private HeadsetManager headsetManagerMock;
@Mock
private AudioDeviceManager deviceManagerMock;
public AudioServiceTestBase(Class<T> serviceClass)
{
super(serviceClass);
}
private static void sleep(double seconds)
{
try
{
long millis = (long)(seconds * 1000D);
Thread.sleep(millis);
}
catch (InterruptedException exception)
{
return;
}
}
@Override
public void onServiceFailed(ServiceFailureReason reason)
{
serviceFailureReason = reason;
}
@Override
protected void setUp() throws Exception
{
super.setUp();
serviceFailureReason = null;
}
@Override
protected void startService()
{
super.startService();
getService().setListener(this);
}
@Override
protected void initMocks()
{
super.initMocks();
doNothing().when(headsetManagerMock).restoreVolumeLevel(any(HeadsetMode.class));
doNothing().when(headsetManagerMock).setBluetoothScoOn(any(boolean.class));
doNothing().when(headsetManagerMock).registerHeadsetDetector();
doNothing().when(headsetManagerMock).unregisterHeadsetDetector();
try
{ | AudioDevice dummyInDevice = new DummyInDevice(getContext()); | 3 |
ev3dev-lang-java/ev3dev-lang-java | src/main/java/ev3dev/utils/io/NativeTTY.java | [
"public static final int KDGKBMODE = 0x4B44; /* gets current keyboard mode */",
"public static final int KDSETMODE = 0x4B3A; /* set text/graphics mode */",
"public static final int KDSKBMODE = 0x4B45; /* sets current keyboard mode */",
"public static final int VT_GETMODE = 0x5601; /* get mode of active vt */",
"public static final int VT_GETSTATE = 0x5603; /* get global vt state info */",
"public static final int VT_RELDISP = 0x5605; /* release display */",
"public static final int VT_SETMODE = 0x5602; /* set mode of active vt */"
] | import com.sun.jna.LastErrorException;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.ptr.IntByReference;
import lombok.NonNull;
import java.util.Arrays;
import java.util.List;
import static ev3dev.utils.io.NativeConstants.KDGKBMODE;
import static ev3dev.utils.io.NativeConstants.KDSETMODE;
import static ev3dev.utils.io.NativeConstants.KDSKBMODE;
import static ev3dev.utils.io.NativeConstants.VT_GETMODE;
import static ev3dev.utils.io.NativeConstants.VT_GETSTATE;
import static ev3dev.utils.io.NativeConstants.VT_RELDISP;
import static ev3dev.utils.io.NativeConstants.VT_SETMODE; | package ev3dev.utils.io;
/**
* Wrapper for basic actions on Linux VT/TTY
*
* @author Jakub Vaněk
* @since 2.4.7
*/
public class NativeTTY extends NativeDevice {
/**
* Initialize new TTY.
*
* @param dname Path to TTY device.
* @throws LastErrorException when the operation fails.
*/
public NativeTTY(@NonNull String dname) throws LastErrorException {
super(dname, NativeConstants.O_RDWR);
}
/**
* Initialize new TTY.
*
* @param dname Path to TTY device.
* @param flags Opening mode, e.g. read, write or both.
* @throws LastErrorException when the operation fails.
*/
public NativeTTY(@NonNull String dname, int flags) throws LastErrorException {
super(dname, flags);
}
/**
* Initialize new TTY.
*
* @param dname Path to TTY device.
* @param libc standard C library interface to be used.
* @throws LastErrorException when the operation fails.
*/
public NativeTTY(@NonNull String dname, @NonNull ILibc libc) throws LastErrorException {
super(dname, NativeConstants.O_RDWR, libc);
}
/**
* Initialize new TTY.
*
* @param dname Path to TTY device.
* @param flags Opening mode, e.g. read, write or both.
* @param libc standard C library interface to be used.
* @throws LastErrorException when the operation fails.
*/
public NativeTTY(@NonNull String dname, int flags, @NonNull ILibc libc) throws LastErrorException {
super(dname, flags, libc);
}
/**
* Get current TTY mode. TTY mode is mostly about VT switching.
*
* @return TTY mode.
* @throws LastErrorException when the operation fails.
*/
public vt_mode getVTmode() throws LastErrorException {
vt_mode mode = new vt_mode();
super.ioctl(VT_GETMODE, mode.getPointer());
mode.read();
return mode;
}
/**
* Set current TTY mode. TTY mode is mostly about VT switching.
*
* @param mode TTY mode.
* @throws LastErrorException when the operation fails.
*/
public void setVTmode(@NonNull vt_mode mode) throws LastErrorException {
mode.write();
super.ioctl(VT_SETMODE, mode.getPointer());
}
/**
* Get current TTY state.
*
* @return TTY state.
* @throws LastErrorException when the operation fails.
*/
public vt_stat getVTstate() throws LastErrorException {
vt_stat stat = new vt_stat();
super.ioctl(VT_GETSTATE, stat.getPointer());
stat.read();
return stat;
}
/**
* Get current keyboard mode.
*
* @return Keyboard mode (raw, transformed or off) - K_* constants.
* @throws LastErrorException when the operation fails.
*/
public int getKeyboardMode() throws LastErrorException {
IntByReference kbd = new IntByReference(0);
super.ioctl(KDGKBMODE, kbd);
return kbd.getValue();
}
/**
* Set keyboard mode.
*
* @param mode Keyboard mode (raw, transformed or off) - K_* constants.
* @throws LastErrorException when the operation fails.
*/
public void setKeyboardMode(int mode) throws LastErrorException { | super.ioctl(KDSKBMODE, mode); | 2 |
izumin5210/Sunazuri | app/src/main/java/info/izumin/android/sunazuri/infrastructure/InfrastructureComponent.java | [
"public interface OauthRepository {\n Single<AuthorizedUser> getToken(String code);\n}",
"public interface TeamsRepository {\n Single<List<Team>> get(AuthorizedUser user);\n}",
"public interface UsersRepository {\n Observable<AuthorizedUser> getCurrentUser();\n Single<List<AuthorizedUser>> getAuthorizedUsers();\n Observable<LoginInfo> getLoginInfo();\n}",
"@Module\npublic class ApiModule {\n public static final String TAG = ApiModule.class.getSimpleName();\n\n private final String apiEndpoint;\n private final OauthParams oauthParams;\n private final List<String> responseEnvelopKeys;\n\n public ApiModule(String apiEndpoint, OauthParams oauthParams, List<String> responseEnvelopKeys) {\n this.apiEndpoint = apiEndpoint;\n this.oauthParams = oauthParams;\n this.responseEnvelopKeys = responseEnvelopKeys;\n }\n\n @Provides\n @Singleton\n EnvelopeTypeAdapterFactory envelopeTypeAdapterFactory() {\n return new EnvelopeTypeAdapterFactory(responseEnvelopKeys);\n }\n\n @Provides\n @Singleton\n Gson gson(EnvelopeTypeAdapterFactory envelopeTypeAdapterFactory) {\n return new GsonBuilder()\n .registerTypeAdapterFactory(StaticGsonTypeAdapterFactory.newInstance())\n .registerTypeAdapterFactory(envelopeTypeAdapterFactory)\n .create();\n }\n\n @Provides\n @Singleton\n Retrofit retrofit(OkHttpClient client, Gson gson) {\n return new Retrofit.Builder()\n .client(client)\n .baseUrl(apiEndpoint)\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .addConverterFactory(GsonConverterFactory.create(gson))\n .build();\n }\n\n @Provides\n @Singleton\n OauthApi oauthApi(Retrofit retrofit) {\n return retrofit.create(OauthApi.class);\n }\n\n @Provides\n @Singleton\n TeamsApi teamsApi(Retrofit retrofit) {\n return retrofit.create(TeamsApi.class);\n }\n\n @Provides\n @Singleton\n UsersApi usersApi(Retrofit retrofit) {\n return retrofit.create(UsersApi.class);\n }\n\n @Provides\n @Singleton\n OauthParams oauthParams() {\n return oauthParams;\n }\n}",
"@Module\npublic class CacheModule {\n public static final String TAG = CacheModule.class.getSimpleName();\n\n @Provides\n @Singleton\n LoginCache loginCache(LoginCacheImpl cache) {\n return cache;\n }\n}",
"public class OauthParams {\n public static final String TAG = OauthParams.class.getSimpleName();\n\n public final String endpoint;\n public final String clientId;\n public final String clientSecret;\n public final String redirectUri;\n public final String scope;\n public final String responseType;\n public final String authorizePath;\n public final String grantType;\n\n public OauthParams(String endpoint, String clientId, String clientSecret, String redirectUri, String scope, String responseType, String authorizePath, String grantType) {\n this.endpoint = endpoint;\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n this.redirectUri = redirectUri;\n this.scope = scope;\n this.responseType = responseType;\n this.authorizePath = authorizePath;\n this.grantType = grantType;\n }\n\n public String getAuthorizeUri() {\n return endpoint + authorizePath\n + \"?client_id=\" + clientId\n + \"&redirect_uri=\" + redirectUri\n + \"&scope=\" + scope\n + \"&response_type=\" + responseType;\n }\n}",
"@Module(\n includes = {\n OauthRepositoryModule.class,\n TeamsRepositoryModule.class\n }\n)\npublic class RepositoryModule {\n public static final String TAG = RepositoryModule.class.getSimpleName();\n\n @Provides\n @Singleton\n UsersRepository usersRepository(UsersRepositoryImpl repo) {\n return repo;\n }\n}"
] | import dagger.Component;
import info.izumin.android.sunazuri.domain.repository.OauthRepository;
import info.izumin.android.sunazuri.domain.repository.TeamsRepository;
import info.izumin.android.sunazuri.domain.repository.UsersRepository;
import info.izumin.android.sunazuri.infrastructure.api.ApiModule;
import info.izumin.android.sunazuri.infrastructure.cache.CacheModule;
import info.izumin.android.sunazuri.infrastructure.entity.OauthParams;
import info.izumin.android.sunazuri.infrastructure.repository.RepositoryModule;
import okhttp3.OkHttpClient;
import javax.inject.Singleton; | package info.izumin.android.sunazuri.infrastructure;
/**
* Created by izumin on 5/13/2016 AD.
*/
@Singleton
@Component(
modules = {
InfrastructureModule.class,
RepositoryModule.class,
HttpClientModule.class,
ApiModule.class,
CacheModule.class
}
)
public interface InfrastructureComponent {
TeamsRepository teamsRepository(); | OauthRepository oauthRepository(); | 0 |
maoruibin/AppPlus | app/src/main/java/com/gudong/appkit/receiver/BootReceiver.java | [
"public class App extends Application {\n private static final String DB_NAME = \"appplus.db\";\n public static LiteOrm sDb;\n public static Context sContext;\n @Override\n public void onCreate() {\n super.onCreate();\n sDb = LiteOrm.newSingleInstance(this, DB_NAME);\n sContext = this;\n Once.initialise(this);\n Logger.init(\"AppPlusLog\").setLogLevel(BuildConfig.IS_DEBUG?LogLevel.FULL:LogLevel.NONE);\n sDb.setDebugged(BuildConfig.IS_DEBUG);\n }\n}",
"@Table(\"app_entity\") public class AppEntity implements Parcelable{\n public static final String COLUMN_FAVORITE = \"favorite\";\n public static final String COLUMN_PACKAGE_NAME = \"packageName\";\n public static final String COLUMN_LAST_MODIFY_TIME = \"lastModifyTime\";\n public static final String COLUMN_TOTAL_SPACE = \"totalSpace\";\n @PrimaryKey(AssignType.AUTO_INCREMENT)\n @Column(\"_id\") protected long id;\n\n @Column(\"appName\") private String appName=\"\";\n @Column(COLUMN_PACKAGE_NAME) private String packageName=\"\";\n @Column(\"versionName\") private String versionName=\"\";\n @Column(\"versionCode\") private int versionCode=0;\n @Column(\"appIconData\") private byte[] appIconData=null;\n @Column(\"srcPath\") private String srcPath;\n @Column(\"uid\") private int uid;\n\n //add in 2016.6.21\n @Default(\"false\")\n @Column(COLUMN_FAVORITE) private boolean isFavorite;\n //add in 2016.8.1\n @Column(COLUMN_LAST_MODIFY_TIME) private long lastModifyTime;\n @Column(COLUMN_TOTAL_SPACE) private long totalSpace;\n\n private int status;\n\n public AppEntity() {\n }\n\n public AppEntity(String packageName) {\n this.packageName = packageName;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getAppName() {\n return appName;\n }\n\n public void setAppName(String appName) {\n this.appName = appName;\n }\n\n public String getPackageName() {\n return packageName;\n }\n\n public void setPackageName(String packageName) {\n this.packageName = packageName;\n }\n\n public String getVersionName() {\n return versionName;\n }\n\n public void setVersionName(String versionName) {\n this.versionName = versionName;\n }\n\n public int getVersionCode() {\n return versionCode;\n }\n\n public void setVersionCode(int versionCode) {\n this.versionCode = versionCode;\n }\n\n public String getSrcPath() {\n return srcPath;\n }\n\n public void setSrcPath(String srcPath) {\n this.srcPath = srcPath;\n }\n\n public byte[] getAppIconData() {\n return appIconData;\n }\n\n public void setAppIconData(byte[] appIconData) {\n this.appIconData = appIconData;\n }\n\n public int getUid() {\n return uid;\n }\n\n public void setUid(int uid) {\n this.uid = uid;\n }\n\n public int getStatus() {\n return status;\n }\n\n public void setStatus(int status) {\n this.status = status;\n }\n\n public boolean isFavorite() {\n return isFavorite;\n }\n\n public void setFavorite(boolean favorite) {\n isFavorite = favorite;\n }\n\n public long getLastModifyTime() {\n return lastModifyTime;\n }\n\n public void setLastModifyTime(long lastModifyTime) {\n this.lastModifyTime = lastModifyTime;\n }\n\n public long getTotalSpace() {\n return totalSpace;\n }\n\n public void setTotalSpace(long totalSpace) {\n this.totalSpace = totalSpace;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n AppEntity entity = (AppEntity) o;\n\n if (versionCode != entity.versionCode) return false;\n if (appName != null ? !appName.equals(entity.appName) : entity.appName != null)\n return false;\n if (packageName != null ? !packageName.equals(entity.packageName) : entity.packageName != null)\n return false;\n if (versionName != null ? !versionName.equals(entity.versionName) : entity.versionName != null)\n return false;\n if (appIconData != null ? !(appIconData.length == entity.appIconData.length) : entity.appIconData != null)\n return false;\n return srcPath != null ? srcPath.equals(entity.srcPath) : entity.srcPath == null;\n\n }\n\n @Override\n public int hashCode() {\n return packageName != null ? packageName.hashCode() : 0;\n }\n\n\n\n @Override\n public String toString() {\n return \"AppEntity{\" +\n \"appIconData size =\" + appIconData.length +\n \", id=\" + id +\n \", appName='\" + appName + '\\'' +\n \", packageName='\" + packageName + '\\'' +\n \", versionName='\" + versionName + '\\'' +\n \", versionCode=\" + versionCode +\n \", srcPath='\" + srcPath + '\\'' +\n \", uid=\" + uid +\n '}';\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeLong(this.id);\n dest.writeString(this.appName);\n dest.writeString(this.packageName);\n dest.writeString(this.versionName);\n dest.writeInt(this.versionCode);\n dest.writeByteArray(this.appIconData);\n dest.writeString(this.srcPath);\n dest.writeInt(this.uid);\n dest.writeByte(this.isFavorite ? (byte) 1 : (byte) 0);\n dest.writeLong(this.lastModifyTime);\n dest.writeLong(this.totalSpace);\n dest.writeInt(this.status);\n }\n\n protected AppEntity(Parcel in) {\n this.id = in.readLong();\n this.appName = in.readString();\n this.packageName = in.readString();\n this.versionName = in.readString();\n this.versionCode = in.readInt();\n this.appIconData = in.createByteArray();\n this.srcPath = in.readString();\n this.uid = in.readInt();\n this.isFavorite = in.readByte() != 0;\n this.lastModifyTime = in.readLong();\n this.totalSpace = in.readLong();\n this.status = in.readInt();\n }\n\n public static final Creator<AppEntity> CREATOR = new Creator<AppEntity>() {\n @Override\n public AppEntity createFromParcel(Parcel source) {\n return new AppEntity(source);\n }\n\n @Override\n public AppEntity[] newArray(int size) {\n return new AppEntity[size];\n }\n };\n}",
"public class AppInfoEngine {\n private Context mContext;\n private PackageManager mPackageManager;\n\n private static class SingletonHolder{\n private static final AppInfoEngine INSTANCE = new AppInfoEngine(App.sContext);\n }\n\n public static AppInfoEngine getInstance(){\n return SingletonHolder.INSTANCE;\n }\n\n private AppInfoEngine(Context context) {\n this.mContext = context;\n mPackageManager = mContext.getApplicationContext().getPackageManager();\n }\n\n /**\n * get all app info list which is installed by user\n * @return all installed app info list\n */\n public Observable<List<AppEntity>> getInstalledAppList() {\n return RxUtil.makeObservable(new Callable<List<AppEntity>>() {\n @Override\n public List<AppEntity> call() throws Exception {\n List<AppEntity> list = new ArrayList<>();\n List<PackageInfo>packageInfos = mPackageManager.getInstalledPackages(PackageManager.GET_META_DATA);\n for (PackageInfo info:packageInfos){\n if(!isUserApp(info))continue;\n AppEntity entity = warpAppEntity(info);\n if (entity == null)continue;;\n list.add(entity);\n }\n return list;\n }\n });\n }\n\n /**\n * get installed AppEntity by packageName\n * @param packageName Application's package name\n * @return installed app if not found package name will return null\n */\n public AppEntity getAppByPackageName(String packageName){\n List<PackageInfo>packageInfos = mPackageManager.getInstalledPackages(PackageManager.GET_META_DATA);\n for (PackageInfo packageInfo : packageInfos) {\n if(!isUserApp(packageInfo))continue;\n if(packageName.equals(packageInfo.packageName)){\n return warpAppEntity(packageInfo);\n }\n }\n return null;\n }\n\n /**\n * get recent running app list\n * @return recent running app list\n */\n @Deprecated\n public List<AppEntity> getRecentAppList() {\n List<AppEntity> list = new ArrayList<>();\n ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);\n List<ActivityManager.RecentTaskInfo> recentTasks = mActivityManager.getRecentTasks(10, 0);\n for (ActivityManager.RecentTaskInfo taskInfo : recentTasks) {\n Intent intent = taskInfo.baseIntent;\n ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);\n if (resolveInfo == null)continue;\n String packageName = resolveInfo.activityInfo.packageName;\n if (isSystemApp(packageName)) continue;\n if (isShowSelf(packageName)) continue;\n AppEntity appEntity = DataHelper.getAppByPackageName(packageName);\n if (appEntity == null)continue;\n list.add (appEntity);\n }\n return list;\n }\n\n /**\n * check running list should show AppPlus or not\n * @param packagename\n * @return true if show else false\n */\n private boolean isShowSelf(String packagename){\n return !Utils.isShowSelf() && packagename.equals(mContext.getPackageName());\n }\n\n /**\n * check package is system app or not\n * @param packageName\n * @return if package is system app return true else return false\n */\n private boolean isSystemApp(String packageName){\n try {\n PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);\n ApplicationInfo applicationInfo = packageInfo.applicationInfo;\n if(applicationInfo == null)return false;\n return ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n boolean isUserApp(PackageInfo packageInfo) {\n if(packageInfo == null)return false;\n int mask = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;\n return (packageInfo.applicationInfo.flags & mask) == 0;\n }\n\n private boolean isSelf(String packageName) {\n return packageName.equals(mContext.getPackageName());\n }\n\n //////////////////////// Android L ///////////////////////////////////\n @Deprecated\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n public List<UsageStats> getUsageStatsList(){\n UsageStatsManager usm = getUsageStatsManager();\n Calendar calendar = Calendar.getInstance();\n long endTime = calendar.getTimeInMillis();\n calendar.add(Calendar.MONTH, -1);\n long startTime = calendar.getTimeInMillis();\n List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);\n return usageStatsList;\n }\n\n @Deprecated\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n public List<AppEntity> getRecentAppInfo(){\n List<UsageStats> usageStatsList = getUsageStatsList();\n List<AppEntity> list = new ArrayList<>();\n for (UsageStats u : usageStatsList){\n String packageName = u.getPackageName();\n ApplicationInfo applicationInfo = getAppInfo(packageName);\n //system app will not appear recent list\n //if(isSystemApp(packageName))continue;\n if (isShowSelf(packageName)) continue;\n AppEntity entity = DataHelper.getAppByPackageName(packageName);\n if (entity == null)continue;\n list.add (entity);\n }\n return list;\n }\n\n @SuppressWarnings(\"ResourceType\")\n @Deprecated\n private UsageStatsManager getUsageStatsManager(){\n UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(\"usagestats\");\n return usm;\n }\n\n /**\n * make PackageInfo warp to AppEntity\n * @param packageInfo PackageInfo\n * @return AppEntity\n */\n private AppEntity warpAppEntity(PackageInfo packageInfo){\n if (packageInfo == null)return null;\n AppEntity entity = new AppEntity();\n entity.setAppName(mPackageManager.getApplicationLabel(packageInfo.applicationInfo).toString());\n entity.setPackageName(packageInfo.packageName);\n Bitmap iconBitmap = drawableToBitmap(mPackageManager.getApplicationIcon(packageInfo.applicationInfo));\n entity.setAppIconData(formatBitmapToBytes(iconBitmap));\n entity.setSrcPath(packageInfo.applicationInfo.sourceDir);\n entity.setVersionName(packageInfo.versionName);\n entity.setVersionCode(packageInfo.versionCode);\n entity.setUid(packageInfo.applicationInfo.uid);\n return entity;\n }\n\n //根据包名获取对应的ApplicationInfo 信息\n private ApplicationInfo getAppInfo(String packageName){\n ApplicationInfo appInfo = null;\n try {\n appInfo = mPackageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n return appInfo;\n }\n\n /**\n * 将Drawable转化为Bitmap\n * @param drawable\n * @return\n */\n private static Bitmap drawableToBitmap (Drawable drawable) {\n Bitmap bitmap = null;\n\n if (drawable instanceof BitmapDrawable) {\n BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;\n if(bitmapDrawable.getBitmap() != null) {\n return bitmapDrawable.getBitmap();\n }\n }\n\n if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {\n bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel\n } else {\n bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);\n }\n\n Canvas canvas = new Canvas(bitmap);\n drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n drawable.draw(canvas);\n return bitmap;\n }\n\n public List<AppEntity> getRecentAppListV1() {\n List<AppEntity> list = new ArrayList<>();\n ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);\n List<ActivityManager.RecentTaskInfo> recentTasks = mActivityManager.getRecentTasks(10, 0);\n for (ActivityManager.RecentTaskInfo taskInfo : recentTasks) {\n Intent intent = taskInfo.baseIntent;\n ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);\n if (resolveInfo == null)continue;\n\n if (isSystemApp(resolveInfo.resolvePackageName)) continue;\n\n ActivityInfo activityInfo = resolveInfo.activityInfo;\n if(activityInfo==null)continue;\n\n if (isShowSelf(activityInfo.packageName)) continue;\n AppEntity entity = new AppEntity();\n Bitmap bitmap = drawableToBitmap(resolveInfo.loadIcon(mPackageManager));\n entity.setAppIconData(formatBitmapToBytes(bitmap));\n entity.setAppName(resolveInfo.loadLabel(mPackageManager).toString());\n entity.setPackageName(activityInfo.packageName);\n ApplicationInfo applicationInfo = activityInfo.applicationInfo;\n if (applicationInfo == null)continue;\n\n if(applicationInfo.publicSourceDir!= null){\n entity.setSrcPath(applicationInfo.publicSourceDir);\n }\n list.add(entity);\n }\n return list;\n }\n\n private byte[] formatBitmapToBytes(Bitmap bitmap){\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n bitmap.compress(Bitmap.CompressFormat.PNG,100,bos);\n try {\n bos.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return bos.toByteArray();\n }\n\n public void getRunningProcesses(){\n List<AndroidProcess>list = new ArrayList<>();\n File[]files = new File(\"/proc\").listFiles();\n for (File file:files){\n if(file.isDirectory()){\n int pid;\n try{\n pid = Integer.parseInt(file.getName());\n AndroidProcess process = new AndroidProcess(pid);\n Logger.i(\"pid is \"+file.getName() +\" name is \"+process.name);\n list.add(process);\n }catch (NumberFormatException e){\n continue;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n}",
"public class DataHelper {\n\n public static AppEntity checkAndSetAppEntityStatus(final AppEntity installedEntity){\n final AppEntity localResult = getAppByPackageName(installedEntity.getPackageName());\n //this app is a new app,now it not exist in my local db\n if(localResult ==null){\n installedEntity.setStatus(AppStatus.CREATE.ordinal());\n // the installed app info is change,so the\n } else if(!installedEntity.equals(localResult)){\n installedEntity.setStatus(AppStatus.CHANGE.ordinal());\n }else{\n installedEntity.setStatus(AppStatus.NORMAL.ordinal());\n }\n return installedEntity;\n }\n\n /**\n * query App info by local db\n * @param packageName Application's package name\n * @return return AppEntity if this package name is not exist db will return null\n */\n public static AppEntity getAppByPackageName(String packageName){\n if(TextUtils.isEmpty(packageName))return null;\n QueryBuilder queryBuilder = new QueryBuilder(AppEntity.class);\n queryBuilder = queryBuilder.whereEquals(\"packageName \", packageName);\n List<AppEntity>result = App.sDb.query(queryBuilder);\n try {\n return result.get(0);\n }catch (IndexOutOfBoundsException e){\n return null;\n }\n }\n\n public static Observable<List<AppEntity>>getAllEntityByDbAsyn(){\n return RxUtil.makeObservable(new Callable<List<AppEntity>>() {\n @Override\n public List<AppEntity> call() throws Exception {\n List<AppEntity> list = App.sDb.query(AppEntity.class);\n for (int i = 0; i < list.size(); i++) {\n Logger.i(\"\"+list.get(i).getAppName()+\" is favorite \"+list.get(i).isFavorite());\n }\n return list;\n }\n });\n }\n\n public static Observable<List<AppEntity>>getFavoriteEntityByDbAsyn(){\n return RxUtil.makeObservable(new Callable<List<AppEntity>>() {\n @Override\n public List<AppEntity> call() throws Exception {\n return App.sDb.query(new QueryBuilder<AppEntity>(AppEntity.class)\n .whereEquals(AppEntity.COLUMN_FAVORITE, true));\n }\n });\n }\n\n public static AppEntity getEntityByPackageName(String packageName){\n List<AppEntity>list = App.sDb.query(\n new QueryBuilder<AppEntity>(AppEntity.class)\n .whereEquals(AppEntity.COLUMN_PACKAGE_NAME, packageName).limit(0,1));\n if(list.isEmpty()){\n return null;\n }\n return list.get(0);\n }\n\n /**\n * get AppEntity for Application of AppPlus\n * @return AppEntity\n */\n public static AppEntity getAppPlusEntity(){\n return getAppByPackageName(App.sContext.getPackageName());\n }\n\n /**\n * get the running app list info\n * @param ctx\n * @return\n */\n public static Observable<List<AppEntity>> getRunningAppEntity(final Context ctx) {\n return RxUtil.makeObservable(new Callable<List<AppEntity>>() {\n @Override\n public List<AppEntity> call() throws Exception {\n List<ActivityManager.RunningAppProcessInfo> runningList = ProcessManager.getRunningAppProcessInfo(ctx);\n Logger.i(\"=====\",\"runing size is \"+runningList.size());\n List<AppEntity> list = new ArrayList<>();\n for (ActivityManager.RunningAppProcessInfo processInfo : runningList) {\n String packageName = processInfo.processName;\n if (isNotShowSelf(ctx, packageName)) continue;\n AppEntity entity = DataHelper.getAppByPackageName(packageName);\n if (entity == null) continue;\n list.add(entity);\n }\n return list;\n }\n });\n }\n\n @TargetApi(24)\n public static Observable<List<AppEntity>>getAppList(final Context ctx){\n return RxUtil.makeObservable(new Callable<List<AppEntity>>() {\n @Override\n public List<AppEntity> call() throws Exception {\n List<UsageStats> listStats = UStats.getUsageStatsList(ctx);\n List<AppEntity> list = new ArrayList<>();\n for (UsageStats stats:listStats) {\n stats.getPackageName();\n String packageName = stats.getPackageName();\n if(packageName.contains(\"android\") || packageName.contains(\"google\")){\n continue;\n }\n if (isNotShowSelf(ctx, packageName)) continue;\n AppEntity entity = DataHelper.getAppByPackageName(packageName);\n if (entity == null) continue;\n list.add(entity);\n }\n return list;\n }\n });\n }\n\n public static Observable<List<AppEntity>>getExportedAppEntity(){\n return RxUtil.makeObservable(new Callable<List<AppEntity>>() {\n @Override\n public List<AppEntity> call() throws Exception {\n File parent = FileUtil.createDir(FileUtil.getSDPath(),FileUtil.KEY_EXPORT_DIR);\n File[]exportArray = parent.listFiles();\n List<AppEntity>exportList = new ArrayList<>();\n AppEntity entity = null;\n for(File file : exportArray){\n ApkParser parser = ApkParser.create(file);\n ApkMeta meta = parser.getApkMeta();\n entity = new AppEntity();\n entity.setAppName(meta.label);\n entity.setAppIconData(parser.getIconFile().data);\n entity.setVersionName(meta.versionName);\n entity.setSrcPath(file.getAbsolutePath());\n entity.setLastModifyTime(file.lastModified());\n entity.setTotalSpace(file.length());\n exportList.add(entity);\n }\n return exportList;\n }\n });\n }\n\n\n /**\n * check running list should show AppPlus or not\n * @param packagename\n * @return true if show else false\n */\n private static boolean isNotShowSelf(Context ctx, String packagename) {\n return !Utils.isShowSelf() && packagename.equals(ctx.getPackageName());\n }\n}",
"public enum EEvent {\n /**\n * in setting activity,when user clicked Show AppPlus setting item,this Event will be trigger\n */\n RECENT_LIST_IS_SHOW_SELF_CHANGE,\n /**\n * in setting activity,when user clicked Brief mode setting item,this Event will be trigger\n */\n LIST_ITEM_BRIEF_MODE_CHANGE,\n /**\n * uninstall a application from system,the app list need update data right now\n */\n UNINSTALL_APPLICATION_FROM_SYSTEM,\n /**\n * install a new application from system,the all app list need update date right now\n */\n INSTALL_APPLICATION_FROM_SYSTEM,\n /**\n * when enter SplashActivity app will load installed app and store list to local db\n * when load finish, need notify all installed list reload data,otherwise the list will empty\n */\n PREPARE_FOR_ALL_INSTALLED_APP_FINISH,\n /**\n * delete exported file successfully\n */\n DELETE_SINGLE_EXPORT_FILE_FAIL,\n /**\n * delete exported file fail\n */\n DELETE_SINGLE_EXPORT_FILE_SUC,\n\n UPDATE_ENTITY_FAVORITE_STATUS,\n\n /**\n * OPEN export dir\n */\n OPEN_EXPORT_DIR;\n}",
"public class RxBus<T, R> {\n private final Subject<T,R> rxBus;\n\n private RxBus(){\n rxBus = new SerializedSubject(PublishSubject.<T>create());\n }\n\n private static class SingletonHolder{\n private static RxBus instance = new RxBus();\n }\n\n public static RxBus getInstance(){\n return SingletonHolder.instance;\n }\n\n public void send(T msg){\n rxBus.onNext(msg);\n }\n\n public Observable<R> toObservable(){\n return rxBus.asObservable().onBackpressureBuffer();\n }\n\n /**\n * check the observers has subscribe or not DeadEvent https://github.com/square/otto/blob/master/otto/src/main/java/com/squareup/otto/DeadEvent.java\n *\n * @return\n */\n public boolean hasObservers() {\n return rxBus.hasObservers();\n }\n}",
"public class RxEvent {\n private EEvent mType;\n private Bundle mData;\n\n public RxEvent() {\n }\n\n public RxEvent(EEvent type) {\n mType = type;\n }\n\n public RxEvent(EEvent type,Bundle data) {\n mData = data;\n mType = type;\n }\n\n public static RxEvent get(EEvent mType){\n return new RxEvent(mType);\n }\n\n public Bundle getData() {\n return mData;\n }\n\n public void setData(Bundle data) {\n mData = data;\n }\n\n public EEvent getType() {\n return mType;\n }\n\n public void setType(EEvent type) {\n mType = type;\n }\n}",
"public class Logger {\n private static Setting setting;\n public static Setting init(String tag){\n if (tag == null) {\n throw new NullPointerException(\"tag may not be null\");\n }\n if (tag.trim().length() == 0) {\n throw new IllegalStateException(\"tag may not be empty\");\n }\n setting = Setting.getInstance();\n setting.setTag(tag);\n return setting;\n }\n\n\n public static void i(String message){\n log(Log.INFO, setting.getDefTag(), message);\n }\n\n public static void e(String message){\n log(Log.ERROR, setting.getDefTag(), message);\n }\n\n public static void i(String tag,String message){\n log(Log.INFO,tag, message);\n }\n\n public static void e(String tag,String message){\n log(Log.ERROR,tag, message);\n }\n\n public static void d(String tag,String message){\n log(Log.DEBUG,tag, message);\n }\n\n public static void w(String tag,String message){\n log(Log.WARN,tag, message);\n }\n\n private static synchronized void log(int logType, String tag,String msg) {\n if(setting == null){\n throw new NullPointerException(\"before use Logger ,please init Logger in Application and set param\");\n }\n if (setting.getLevel() == LogLevel.NONE) {\n return;\n }\n String finalTag = formatTag(tag);\n switch (logType){\n case Log.INFO:\n Log.i(finalTag,msg);\n break;\n case Log.ERROR:\n Log.e(finalTag,msg);\n break;\n case Log.WARN:\n Log.w(finalTag,msg);\n break;\n case Log.DEBUG:\n Log.d(finalTag,msg);\n break;\n }\n }\n private static String formatTag(String tag) {\n if (!TextUtils.isEmpty(tag) && !TextUtils.equals(setting.getDefTag(), tag)) {\n return setting.getTag() + \"-\" + tag;\n }\n return setting.getTag();\n }\n}"
] | import com.gudong.appkit.dao.AppInfoEngine;
import com.gudong.appkit.dao.DataHelper;
import com.gudong.appkit.event.EEvent;
import com.gudong.appkit.event.RxBus;
import com.gudong.appkit.event.RxEvent;
import com.gudong.appkit.utils.logger.Logger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import com.gudong.appkit.App;
import com.gudong.appkit.dao.AppEntity; | /*
* Copyright (c) 2015 GuDong
*
* 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 com.gudong.appkit.receiver;
/**
* Created by GuDong on 12/7/15 22:49.
* Contact with [email protected].
*/
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String packageName = intent.getDataString();
if(TextUtils.isEmpty(packageName))return;
if(packageName.contains("package:")){
packageName = packageName.replace("package:","");
}
// receive uninstall action , now we need remove uninstalled app from list
if(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){
// AppEntity uninstalledApp = new AppEntity(packageName); | AppEntity uninstalledApp = DataHelper.getAppByPackageName(packageName); | 3 |
paulirotta/cascade | cascade/src/main/java/com/reactivecascade/util/NetUtil.java | [
"@NotCallOrigin\npublic class RunnableAltFuture<IN, OUT> extends AbstractAltFuture<IN, OUT> implements IRunnableAltFuture<IN, OUT> {\n private final IActionR<OUT> mAction;\n\n /**\n * Create a {@link java.lang.Runnable} which will be executed one time on the\n * {@link com.reactivecascade.i.IThreadType} implementation to perform an {@link IBaseAction}\n *\n * @param threadType the thread pool to run this command on\n * @param action a function that receives one input and no return from\n */\n @SuppressWarnings(\"unchecked\")\n public RunnableAltFuture(@NonNull IThreadType threadType,\n @NonNull IAction<? extends IN> action) {\n super(threadType);\n\n this.mAction = () -> {\n IAltFuture<?, ? extends IN> previousAltFuture = getUpchain();\n OUT out;\n\n if (previousAltFuture == null) {\n out = (OUT) COMPLETE;\n } else {\n AssertUtil.assertTrue(\"The previous RunnableAltFuture to Iaction is not finished\", previousAltFuture.isDone());\n out = (OUT) previousAltFuture.get();\n }\n action.call();\n return out; // T and A are the same when there is no return type from the mOnFireAction\n };\n }\n\n /**\n * Constructor\n *\n * @param threadType the thread pool to run this command on\n * @param action a function that receives one input and no return from\n */\n @SuppressWarnings(\"unchecked\")\n public RunnableAltFuture(@NonNull IThreadType threadType,\n @NonNull IActionOne<IN> action) {\n super(threadType);\n\n this.mAction = () -> {\n IAltFuture<?, ? extends IN> paf = getUpchain();\n\n AssertUtil.assertNotNull(paf);\n AssertUtil.assertTrue(\"The previous RunnableAltFuture in the chain is not finished\", paf.isDone());\n final IN in = paf.get();\n action.call(in);\n\n return (OUT) in; // T and A are the same when there is no return type from the mOnFireAction\n };\n }\n\n /**\n * Create a {@link java.lang.Runnable} which will be executed one time on the\n * {@link com.reactivecascade.i.IThreadType} implementation to perform an {@link IBaseAction}\n *\n * @param threadType the thread pool to run this command on\n * @param mAction a function that does not vary with the input from\n */\n public RunnableAltFuture(@NonNull IThreadType threadType,\n @NonNull IActionR<OUT> mAction) {\n super(threadType);\n\n this.mAction = mAction;\n }\n\n /**\n * Create a {@link java.lang.Runnable} which will be executed one time on the\n * {@link com.reactivecascade.i.IThreadType} implementation to perform an {@link IBaseAction}\n *\n * @param threadType the thread pool to run this command on\n * @param mAction a mapping function\n */\n public RunnableAltFuture(@NonNull IThreadType threadType,\n @NonNull IActionOneR<IN, OUT> mAction) {\n super(threadType);\n\n this.mAction = () -> {\n IAltFuture<?, ? extends IN> previousAltFuture = getUpchain();\n\n AssertUtil.assertNotNull(previousAltFuture);\n AssertUtil.assertTrue(\"The previous RunnableAltFuture in the chain is not finished:\" + getOrigin(), previousAltFuture.isDone());\n\n return mAction.call(previousAltFuture.get());\n };\n }\n\n// @CallSuper\n// @CallOrigin\n// @Override // IAltFuture\n// public boolean cancel(@NonNull final String reason) {\n// assertNotDone();\n// final Object state = stateAR.get();\n//\n// if (state instanceof AltFutureStateCancelled) {\n// RCLog.d(this, mOrigin, \"Ignoring cancel (reason=\" + reason + \") since already in StateError\\nstate=\" + state);\n// } else {\n// if (stateAR.compareAndSet(state, new AltFutureStateCancelled(reason))) {\n// RCLog.d(this, mOrigin, \"Cancelled, reason=\" + reason);\n// return true;\n// } else {\n// RCLog.d(this, mOrigin, \"Ignoring cancel (reason=\" + reason + \") due to a concurrent state change during cancellation\\nstate=\" + state);\n// }\n// }\n// return false;\n// }\n\n /**\n * The {@link java.util.concurrent.ExecutorService} of this <code>RunnableAltFuture</code>s {@link com.reactivecascade.i.IThreadType}\n * will call this for you. You will {@link #fork()} when all prerequisite tasks have completed\n * to <code>{@link #isDone()} == true</code> state. If this <code>RunnableAltFuture</code> is part of an asynchronous functional\n * chain, subscribe it will be forked for you when the prerequisites have finished.\n * <p>\n * This is called for you from the {@link IThreadType}'s {@link java.util.concurrent.ExecutorService}\n */\n @Override\n @NotCallOrigin\n public final void run() {\n boolean stateChanged = false;\n\n try {\n if (isCancelled()) {\n RCLog.d(this, \"RunnableAltFuture was cancelled before execution. state=\" + stateAR.get());\n throw new CancellationException(\"Cancelled before execution started: \" + stateAR.get().toString());\n }\n final OUT out = mAction.call();\n\n if (!(stateAR.compareAndSet(VALUE_NOT_AVAILABLE, out) || stateAR.compareAndSet(FORKED, out))) {\n RCLog.d(this, \"RunnableAltFuture was cancelled() or otherwise changed during execution. Returned from of function is ignored, but any direct side-effects not cooperatively stopped or rolled back in mOnError()/onCatch() are still in effect. state=\" + stateAR.get());\n throw new CancellationException(stateAR.get().toString());\n }\n stateChanged = true;\n } catch (CancellationException e) {\n stateChanged = cancel(\"RunnableAltFuture threw a CancellationException (accepted behavior, will not fail fast): \" + e);\n stateChanged = true;\n } catch (InterruptedException e) {\n stateChanged = cancel(\"RunnableAltFuture was interrupted (may be normal but NOT RECOMMENDED as behaviour is non-deterministic, but app will not fail fast): \" + e);\n } catch (Exception e) {\n AltFutureStateError stateError = new AltFutureStateError(\"RunnableAltFuture run problem\", e);\n\n if (!(stateAR.compareAndSet(VALUE_NOT_AVAILABLE, stateError) && !(stateAR.compareAndSet(FORKED, stateError)))) {\n RCLog.i(this, \"RunnableAltFuture had a problem, but can not transition to stateError as the state has already changed. This is either a logic error or a possible but rare legitimate cancel() race condition: \" + e);\n stateChanged = true;\n }\n } finally {\n if (stateChanged) {\n if (!isDone()) {\n RCLog.e(this, \"Not done\");\n }\n try {\n doThen();\n } catch (Exception e) {\n RCLog.e(this, \"RunnableAltFuture.run() state=\" + stateAR.get() + \"\\nProblem in resulting .doThen()\", e);\n }\n\n try {\n clearPreviousAltFuture(); // Allow garbage collect of past values as the chain burns\n } catch (Exception e) {\n RCLog.e(this, \"RunnableAltFuture.run() state=\\\" + stateAR.get() + \\\"\\nCan not clearPreviousAltFuture()\", e);\n }\n }\n }\n }\n\n /**\n * Called from {@link AbstractAltFuture#fork()} if preconditions for forking are met.\n * <p>\n * Non-atomic check-do race conditions must still guard from this point on against concurrent fork()\n */\n @CallSuper\n @NotCallOrigin\n protected void doFork() {\n this.threadType.fork(this);\n }\n}",
"@NotCallOrigin\npublic class SettableAltFuture<T> extends AbstractAltFuture<T, T> implements ISettableAltFuture<T> {\n /**\n * Create, from is not yet determined\n *\n * @param threadType on which downchain actions continue\n */\n public SettableAltFuture(@NonNull IThreadType threadType) {\n super(threadType);\n }\n\n /**\n * Create, immutable from is set and will immediately fork() downchain actions\n *\n * @param threadType on which downchain actions continue\n * @param value\n */\n public SettableAltFuture(@NonNull IThreadType threadType,\n @NonNull T value) {\n this(threadType);\n set(value);\n }\n\n @Override // ISettable\n public void set(@NonNull T value) {\n if (stateAR.compareAndSet(VALUE_NOT_AVAILABLE, value) || stateAR.compareAndSet(FORKED, value)) {\n // Previous state was FORKED, so set completes the mOnFireAction and continues the chain\n RCLog.v(this, \"SettableAltFuture set, from= \" + value);\n doFork();\n clearPreviousAltFuture();\n return;\n }\n\n // Already set, cancelled or error state\n RCLog.throwIllegalArgumentException(this, \"Attempted to set \" + this + \" to from=\" + value + \", but the from can only be set once and was already set to from=\" + get());\n }\n\n protected void doFork() {\n // This is not an IRunnableAltFuture, so nothing to fork() or run(). But RunnableAltFuture overrides this and does more\n }\n}",
"public interface IAltFuture<IN, OUT> extends ICancellable, ISafeGettable<OUT>, IAsyncOrigin {\n /**\n * A method which returns a new (unforked) <code>IAltFuture</code> should follow the naming conventiond <code>..Async</code>\n * and be annotated <code>@CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)</code> to {@link CheckResult} that\n * it is either stored or manually {@link #fork()}ed.\n * <p>\n * TODO This annotation is not ideal for disambiguating all cases, look at creating a new one\n */\n String CHECK_RESULT_SUGGESTION = \"IAltFuture#fork()\";\n\n /**\n * Find which thread pool and related support functions are used\n *\n * @return thread group\n */\n @NonNull\n IThreadType getThreadType();\n\n /**\n * Find if the final, immutable state has been entered either with a successful result or an error\n * code\n *\n * @return <code>true</code> once final state has been determined\n */\n boolean isDone();\n\n /**\n * Find if this object has already been submitted to an executor. Execution may finish at any time,\n * or already have finished if this is true.\n *\n * @return <code>true</code> once queued for execution\n */\n boolean isForked();\n\n /**\n * Place this {@link IAltFuture} in the ready-to-run-without-blocking\n * queue of its {@link com.reactivecascade.i.IThreadType}. If there is a {@link #getUpchain()}\n * subscribe that will be forked instead until finding one where {@link #isDone()} is false.\n *\n * @return <code>this</code>, which is usually the <code>IAltFuture</code> which was actually forked.\n * The fork may be indirect and only after other items complete because there is a search upchain\n * (which may be a different branch spliced into the current chain) to find the first unforked from.\n */\n @NonNull\n IAltFuture<IN, OUT> fork();\n\n /**\n * Find the previous step in the chain.\n * <p>\n * Once {@link #isDone()}, this may return <code>null</code> even if there was a previous alt future\n * at one point. This is done to allow a chain to reduce peak load and increase memory throughput\n * by freeing memory of previous steps as it goes.\n *\n * @return the previous {@link IAltFuture} in the chain, or <code>null</code> if this is currently\n * the head of the chain\n */\n @Nullable\n IAltFuture<?, ? extends IN> getUpchain();\n\n /**\n * This is done for you when you add functions to a chain. You do not need to call it yourself.\n * <p>\n * The implementation may call this multiple times to support merging chains. This happens most\n * often when a method returns the tail of a section of chain. The returned from in this case is\n * a new chain link stopping the merged chain section which might start burning before the merger\n * is created to not burn past the merger point until the primary chain reaches that point also.\n *\n * @param altFuture the previous alt future in the chain to which this is attached\n */\n void setUpchain(@NonNull IAltFuture<?, ? extends IN> altFuture);\n\n /**\n * Notification from an up-chain {@link IAltFuture} that the stream is broken\n * and will not complete normally. This RunnableAltFuture will be set to an error state.\n * <p>\n * If an mOnError or catch method has been defined, it will be\n * notified of the original cause of the failure. If the RunnableAltFuture's mOnError method consumes the error\n * (returns <code>true</code>), subscribe anything else down-chain methods will be notified with\n * {@link #onCancelled(StateCancelled)} instead.\n *\n * @param stateError the state indicating the reason and origin of the exception\n * @throws Exception if there is a problem performing synchronous downchain notifications\n */\n void onError(@NonNull StateError stateError) throws Exception;\n\n /**\n * Notification indicates an up-chain {@link IAltFuture} has been cancelled.\n * This RunnableAltFuture will be set to a cancelled state and not be given a chance to complete normally.\n * All down-chain AltFutures will similarly be notified that they were cancelled.\n *\n * @param stateCancelled the state indicating the reason and origin of cancellation\n * @throws Exception if there is a problem performing synchronous downchain notifications\n */\n void onCancelled(@NonNull StateCancelled stateCancelled) throws Exception;\n\n /**\n * Switch following (downchain) actions to run on the specified {@link IThreadType}\n *\n * @param theadType the thread execution group to change to for the next chain operation\n * @return the previous chain link alt future from continuing the chain on the new {@link IThreadType}\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n IAltFuture<?, OUT> on(@NonNull IThreadType theadType);\n\n /**\n * Execute the mOnFireAction after this <code>RunnableAltFuture</code> finishes.\n *\n * @param action function to be performed, often a lambda statement\n * @return an alt future representing the eventual output value of the action\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n IAltFuture<OUT, OUT> then(@NonNull IAction<OUT> action);\n\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n @SuppressWarnings(\"unchecked\")\n ISettableAltFuture<OUT> then(@NonNull IAction<? extends OUT>... actions);\n\n /**\n * Execute the action after this <code>RunnableAltFuture</code> finishes.\n *\n * @param action function to be performed, often a lambda statement\n * @return an alt future representing the eventual output value of the action\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n IAltFuture<OUT, OUT> then(@NonNull IActionOne<OUT> action);\n\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n @SuppressWarnings(\"unchecked\")\n ISettableAltFuture<OUT> then(@NonNull IActionOne<OUT>... actions);\n\n /**\n * Execute the mOnFireAction after this <code>RunnableAltFuture</code> finishes.\n *\n * @param action function to be performed, often a lambda statement\n * @return an alt future representing the eventual output value of the action\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <DOWNCHAIN_OUT> IAltFuture<OUT, DOWNCHAIN_OUT> then(@NonNull IActionR<DOWNCHAIN_OUT> action);\n\n /**\n * Start an action wrapped as an alt futre after this alt future completes. This next alt future\n * may be on a different {@link IThreadType} thread pool.\n * <p>\n * Multiple altFutures may be chained after the current alt future. They will be fork()ed in the\n * orderin which they were attached. Depending on their thread type, the resulting execution may\n * be concurrent or serial.\n *\n * @param altFuture the next action in the chain\n * @param <DOWNCHAIN_OUT> the type that the OUT value will be mapped to. This may not be a mapping alt future, in which case the type DOWNCHAIN_OUT = OUT and the value is also identical\n * @return altFuture\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <DOWNCHAIN_OUT> IAltFuture<OUT, DOWNCHAIN_OUT> then(@NonNull IAltFuture<OUT, DOWNCHAIN_OUT> altFuture);\n\n /**\n * Execute the mOnFireAction after this <code>RunnableAltFuture</code> finishes.\n *\n * @param action function to be performed, often a lambda statement\n * @param <DOWNCHAIN_OUT> the type that the OUT value will be mapped to\n * @return an alt future value representing the eventual output from the mapping function\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <DOWNCHAIN_OUT> IAltFuture<OUT, DOWNCHAIN_OUT> map(@NonNull IActionOneR<OUT, DOWNCHAIN_OUT> action);\n\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n @SuppressWarnings(\"unchecked\")\n <DOWNCHAIN_OUT> IAltFuture<OUT, DOWNCHAIN_OUT>[] map(@NonNull IActionOneR<OUT, DOWNCHAIN_OUT>... actions);\n\n /**\n * Pause execution of this chain for a fixed time interval. Other chains will be able to execute\n * in the meanwhile- no threads are blocked.\n * <p>\n * Note that the chain realizes immediately in the event of {@link #cancel(String)} or a runtime error\n *\n * @param sleepTime to pause the chain, in timeUnit values\n * @param timeUnit to pause\n * @return the input value from upchain\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n ISettableAltFuture<OUT> sleep(long sleepTime,\n @NonNull TimeUnit timeUnit);\n\n /**\n * Continue to next step(s) in the chain only after the {@link IAltFuture} being waited for is complete. The from\n * is not propaged in the chain, but if there is an error that will be adopted into this chain.\n *\n * @param altFuture to pause this chain until it <code>{@link #isDone()}</code>\n * @return the upchain value of this chain, execution held until the other alt future completes\n */\n// @NonNull\n// @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n// ISettableAltFuture<OUT> await(@NonNull IAltFuture<?, ?> altFuture);\n\n /**\n * Continue chain execution once all upchain futures realize and have completed their side effects.\n * <p>\n * The await operation will be cancelled or exception state and trigger {@link #onError(IActionOne)}\n * if <em>any</em> of the joined operations have a problem running to completion.\n *\n * @param altFutures to pause this chain until they are done (<code>{@link #isDone()}</code>)\n * @return the upchain value of this chain, execution held until other alt futures complete\n */\n @NonNull\n @SuppressWarnings(\"unchecked\")\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n ISettableAltFuture<OUT> await(@NonNull IAltFuture<?, ?>... altFutures);\n\n /**\n * Pass through to the next function only if element meet a logic test, otherwise {@link #cancel(String)}\n *\n * @param action function to be performed, often a lambda statement\n * @return the input value, now guaranteed to meet the logic test\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n IAltFuture<IN, IN> filter(@NonNull IActionOneR<IN, Boolean> action);\n\n /**\n * Set the reactiveTarget (one time only) when this is asserted\n *\n * @param reactiveTarget\n * @return <code>this</code>\n */\n @NonNull\n IAltFuture<OUT, OUT> set(@NonNull IReactiveTarget<OUT> reactiveTarget);\n\n /**\n * Add an action which will be performed if this AltFuture or any AltFuture up-chain either has\n * a runtime error or is {@link #cancel(String)}ed.\n * <p>\n * This is typically a user notification or cleanup such as removing an ongoing process indicator (spinner).\n *\n * @param action function to be performed, often a lambda statement\n * @return <code>this</code>\n */\n @NonNull\n ISettableAltFuture<OUT> onError(@NonNull IActionOne<Exception> action);\n\n /**\n * Add an action which will be performed if this AltFuture or any AltFuture up-chain either has\n * a runtime error or is {@link #cancel(String)}ed.\n * <p>\n * This is typically used for cleanup such as changing the screen to notify the user or remove\n * an ongoing process indicator (spinner).\n *\n * @param action function to be performed, often a lambda statement\n * @return <code>this</code>\n */\n @NonNull\n ISettableAltFuture<OUT> onCancelled(@NonNull IActionOne<String> action);\n}",
"public interface IGettable<T> {\n /**\n * A null object indicating that the <code>IGettable</code> is not able to meaningfully provide its state\n * as a string at this time. For example, the from may not yet be determined.\n * <p>\n * This will appear as \"VALUE_NOT_AVAILABLE\" in debugging outputs\n */\n IGettable<?> VALUE_NOT_AVAILABLE = (IGettable<?>) new IGettable<Object>() {\n @NonNull\n @Override // IGettable\n public Object get() {\n throw new IllegalStateException(\"Can not get() from IGettable.VALUE_NOT_AVALIABLE. Perhaps you want ISafaGettable.safeGet() instead? You could also safely check the value before getting since you can not return to this state. Another choice is to examine the logic flow and sequence for initializing this variable.\");\n }\n\n @NonNull\n @Override // IGettable\n public String toString() {\n return \"VALUE_NOT_AVAILABLE\";\n }\n };\n\n /**\n * Get the current from of a variable or the next from in a list.\n *\n * @return the current from, or the next from in the series\n * @throws IllegalStateException if the current from is not available. See also {@link ISafeGettable#safeGet()}\n */\n @NonNull\n T get();\n\n /**\n * Must be the {@link Object#toString()} of the from returned by {@link #get()}\n *\n * @return string representation of the current from, or {@link #VALUE_NOT_AVAILABLE}\n */\n @NonNull\n String toString();\n}",
"public interface IThreadType extends INamed {\n /**\n * Determine if this asynchronous implementation guarantees in-order execution such that one\n * mOnFireAction completes before the next begins.\n *\n * @return <code>true</code> if the exector associated with this thread type is single threaded or\n * otherwise guarantees that the previous item in the queue has completed execution before the next\n * item begins.\n */\n boolean isInOrderExecutor();\n\n /**\n * Run this mOnFireAction after all previously submitted actions (FIFO).\n *\n * @param action the work to be performed\n * @param <IN> the type of input argument expected by the action\n */\n @NotCallOrigin\n <IN> void execute(@NonNull IAction<IN> action);\n\n /**\n * Execute a runnable. Generally this is an action that has already been error-catch wrapped using for example\n * {@link #wrapActionWithErrorProtection(IAction)}\n *\n * @param runnable\n */\n @NotCallOrigin\n void run(@NonNull Runnable runnable);\n\n /**\n * Run this mOnFireAction after all previously submitted actions (FIFO).\n *\n * @param action the work to be performed\n * @param onErrorAction work to be performed if the action throws a {@link Throwable}\n * @param <OUT> the type of input argument expected by the action\n */\n @NotCallOrigin\n <OUT> void run(@NonNull IAction<OUT> action,\n @NonNull IActionOne<Exception> onErrorAction);\n\n /**\n * If this ThreadType permits out-of-order execution, run this mOnFireAction before any previously\n * submitted tasks. This is a LIFO mOnFireAction. Think of it as a \"high priority\" or \"depth first\" solution\n * to complete a sequence of actions already started before opening a new sequence of actions.\n * <p>\n * If this ThreadType does not permit out-of-order execution, this will become a {@link #execute(IAction)}\n * FIFO mOnFireAction.\n *\n * @param <OUT> the type of input argument expected by the action\n * @param action the work to be performed\n */\n @NotCallOrigin\n <OUT> void runNext(@NonNull IAction<OUT> action);\n\n /**\n * Like {@link #run(Runnable)} but the task is queued LIFO as the first item of the\n * {@link java.util.Deque} if this executor supports out of order execution.\n * <p>\n * Generally out of order execution is supported on multi-thread pools such as\n * {@link com.reactivecascade.Async#WORKER} but not strictly sequential operations such as write to file.\n * <p>\n * This is called for you when it is time to add the {@link RunnableAltFuture} to the\n * {@link java.util.concurrent.ExecutorService}. If the <code>RunnableAltFuture</code> is not the head\n * of the queue split the underlying <code>ExecutorService</code> uses a {@link java.util.concurrent.BlockingDeque}\n * to allow out-of-order execution, subscribe the <code>RunnableAltFuture</code> will be added so as to be the next\n * item to run. In an execution resource constrained situation this is \"depth-first\" behaviour\n * decreases execution latency for a complete chain once the head of the chain has started.\n * It also will generally decrease peak memory load split increase memory throughput versus a simpler \"bredth-first\"\n * approach which keeps intermediate chain states around for a longer time. Some\n * {@link com.reactivecascade.i.IThreadType} implementations disallow this optimization\n * due to algorithmic requirements such as in-order execution to maintain side effect integrity.\n * They do this by setting <code>inOrderExecution</code> to <code>true</code> or executing from\n * a {@link java.util.concurrent.BlockingQueue}, not a {@link java.util.concurrent.BlockingDeque}\n * <p>\n * Overriding alternative implementations may safely choose to call synchronously or with\n * additional run restrictions\n * <p>\n * Concurrent algorithms may support last-to-first execution order to speed execution of chains\n * once they have started execution, but users and developers are\n * confused if \"I asked for that before this, but this usually happens first (always if a single threaded ThreadType)\".\n *\n * @param runnable\n */\n @NotCallOrigin\n void runNext(@NonNull Runnable runnable);\n\n /**\n * The same as {@link #runNext(IAction)}, however it is only moved if it is already in the\n * queue. If it is not found in the queue, it will not be added.\n * <p>\n * This is part of singleton executor pattern where an action that can be queued multiple\n * times should be executing or queued only once at any given time.\n *\n * @param runnable the work to be performed\n * @return <code>true</code> if found in the queue and moved\n */\n boolean moveToHeadOfQueue(@NonNull Runnable runnable);\n\n /**\n * Run this mOnFireAction after all previously submitted actions (FIFO).\n *\n * @param action the work to be performed\n * @param onErrorAction work to be performed if the action throws a {@link Throwable}\n * @param <OUT> the type of input argument expected by the action\n */\n <OUT> void runNext(@NonNull IAction<OUT> action,\n @NonNull IActionOne<Exception> onErrorAction);\n\n /**\n * Convert this action into a runnable which will catch and handle\n *\n * @param action the work to be performed\n * @param <IN> the type of input argument expected by the action\n * @return a Runnable which invokes the action\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <IN> Runnable wrapActionWithErrorProtection(@NonNull IAction<IN> action);\n\n /**\n * Convert this action into a runnable\n *\n * @param action the work to be performed\n * @param onErrorAction\n * @param <IN> the type of input argument expected by the action\n * @return\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <IN> Runnable wrapActionWithErrorProtection(@NonNull IAction<IN> action,\n @NonNull IActionOne<Exception> onErrorAction);\n\n /**\n * Complete the action asynchronously.\n * <p>\n * No input values are fed in from the chain.\n *\n * @param action the work to be performed\n * @param <IN> the type of input argument expected by the action\n * @return a chainable handle to track completion of this unit of work\n */\n @NonNull\n <IN> IAltFuture<IN, IN> then(@NonNull IAction<IN> action);\n\n /**\n * Complete the action asynchronously.\n * <p>\n * One input from is fed in from the chain and thus determined at execution time.\n *\n * @param action the work to be performed\n * @param <IN> the type of input argument expected by the action\n * @return\n */\n @NonNull\n <IN> IAltFuture<IN, IN> then(@NonNull IActionOne<IN> action);\n\n /**\n * Complete several actions asynchronously.\n * <p>\n * No input values are fed in from the chain, they may\n * be fetched directly at execution time.\n *\n * @param actions a comma-seperated list of work items to be performed\n * @param <IN> the type of input argument expected by the action\n * @return a list of chainable handles to track completion of each unit of work\n */\n @SuppressWarnings(\"unchecked\")\n @NonNull\n <IN> List<IAltFuture<IN, IN>> then(@NonNull IAction<IN>... actions);\n\n /**\n * Set the chain from to a from which can be determined at the time the chain is built.\n * This is most suitable for starting a chain. It is also useful to continue other actions after\n * some initial mOnFireAction or actions complete, but those use values that for example you may set\n * by using closure values at chain construction time.\n *\n * @param value the pre-determined from to be injected into the chain at this point\n * @param <OUT> the type of input argument expected by the action\n * @return a chainable handle to track completion of this unit of work\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <OUT> ISettableAltFuture<OUT> from(@NonNull OUT value);\n\n /**\n * Set the chain to start with a value which will be set in the future.\n * <p>\n * To start execution of the chain, set(OUT) the value of the returned IAltFuture\n *\n * @param <OUT> the type of input argument expected by the action\n * @return a chainable handle to track completion of this unit of work\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <OUT> ISettableAltFuture<OUT> from();\n\n /**\n * Complete the mOnFireAction asynchronously\n *\n * @param action the work to be performed\n * @param <IN> the type of input argument expected by the action\n * @param <OUT> the type of output returned by the action\n * @return a chainable handle to track completion of this unit of work\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <IN, OUT> IAltFuture<IN, OUT> then(@NonNull IActionR<OUT> action);\n\n /**\n * Perform several actions which need no input from (except perhaps values from closure escape),\n * each of which returns a from of the same type, and return those results in a list.\n *\n * @param actions a comma-seperated list of work items to be performed\n * @param <IN> the type of input argument expected by the action\n * @param <OUT> the type of output returned by the action\n * @return a list of chainable handles to track completion of each unit of work\n */\n @SuppressWarnings(\"unchecked\")\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <IN, OUT> List<IAltFuture<IN, OUT>> then(@NonNull IActionR<OUT>... actions);\n\n /**\n * Transform input A to output T, possibly with other input which may be fetched directly in the function.\n *\n * @param action the work to be performed\n * @param <IN> the type of input argument expected by the action\n * @param <OUT> the type of output returned by the action\n * @return a chainable handle to track completion of this unit of work\n */\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <IN, OUT> IAltFuture<IN, OUT> map(@NonNull IActionOneR<IN, OUT> action);\n\n /**\n * Transform input A to output T using each of the several actions provided and return\n * the result as a list of the transformed values.\n *\n * @param actions a comma-seperated list of work items to be performed\n * @param <IN> the type of input argument expected by the action\n * @param <OUT> the type of output returned by the action\n * @return a list of chainable handles to track completion of each unit of work\n */\n @SuppressWarnings(\"unchecked\")\n @NonNull\n @CheckResult(suggest = IAltFuture.CHECK_RESULT_SUGGESTION)\n <IN, OUT> List<IAltFuture<IN, OUT>> map(@NonNull IActionOneR<IN, OUT>... actions);\n\n /**\n * Place this the {@link IRunnableAltFuture} implementation such as the default {@link RunnableAltFuture}\n * in to an execution queue associated with this {@link IThreadType}.\n * <p>\n * You generally do not call this directly, but rather call {@link IAltFuture#fork()} so that it\n * can check and adjust state and call this on its specified <code>IThreadType</code>for you.\n *\n * @param runnableAltFuture the holder for an evaluate-once-a-discard function which is ready to be queued because it can now be evaluated in a non-blocking manner\n * @param <IN> the type of input argument expected by the action\n * @param <OUT> the type of output returned by the action\n */\n <IN, OUT> void fork(@NonNull IRunnableAltFuture<IN, OUT> runnableAltFuture);\n\n /**\n * Wait for all pending actions to complete. This is used in cases where your application or\n * service chooses to itself. In such cases you can wait an arbitrary amount of time for the\n * orderly completion of any pending tasks split run some mOnFireAction once this finishes.\n * <p>\n * Under normal circumstances, you do call this. Most Android application let the Android lifecycle end tasks\n * as they will. Just let work complete split let Android end the program when it feels the need. This\n * is the safest design Android offers since there are no guarantees your application will change\n * Android run states with graceful notification. Design for split battle harden your code\n * against sudden shutdowns instead of expecting this method to be called.\n * <p>\n * This method returns immediately split does not wait. It will start to shut down the executor\n * threads. No more asynchronous tasks may be sent to the executor after this point.\n * <p>\n * Use the returned Future to know when current tasks complete.\n * <p>\n * After shutdown starts, new WORKER operations (operations queued to a WORKER) will throw a runtime Exception.\n * <p>\n * Note that you must kill the Program or Service using ALog after shutdown. It can not be restarted even if for example\n * a new Activity is created later without first reacting a new Program.\n *\n * @param timeoutMillis length of time to wait for shutdown to complete normally before forcing completion\n * @param afterShutdownAction start on a dedicated thread after successful shutdown. The returned\n * {@link java.util.concurrent.Future} will complete only after this operation completes\n * split <code>afterShutdownAction</code> will not be called\n * @param <IN> the type of input argument expected by the action\n * @return a Future that will return true if the shutdown completes within the specified time, otherwise shutdown continues\n */\n @NonNull\n <IN> Future<Boolean> shutdown(long timeoutMillis,\n @Nullable final IAction<IN> afterShutdownAction);\n\n /**\n * @return <code>true</code> if thread executor is shutdown\n */\n boolean isShutdown();\n\n /**\n * Halt execution of all functional and reactive subscriptions in this threadType.\n *\n * @param reason An explanation to track to the source for debugging the clear cause for cancelling all active chain elements\n * and unbinding all reactive chain elements which have not otherwise expired.\n * @param actionOnDedicatedThreadAfterAlreadyStartedTasksComplete optional callback once current tasks completely finished\n * @param actionOnDedicatedThreadIfTimeout optional what to do if an already started task blocks for too long\n * @param timeoutMillis length of time to wait for shutdown to complete normally before forcing completion\n * @param <IN> the type of input argument expected by the action\n * @return a list of work which failed to complete before shutdown\n */\n @NonNull\n <IN> List<Runnable> shutdownNow(@NonNull String reason,\n @Nullable IAction<IN> actionOnDedicatedThreadAfterAlreadyStartedTasksComplete,\n @Nullable IAction<IN> actionOnDedicatedThreadIfTimeout,\n long timeoutMillis);\n}",
"public static final IThreadType NET_READ = (ASYNC_BUILDER == null) ? null : ASYNC_BUILDER.getNetReadThreadType();",
"public static final IThreadType NET_WRITE = (ASYNC_BUILDER == null) ? null : ASYNC_BUILDER.getNetWriteThreadType();"
] | import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.support.annotation.WorkerThread;
import android.telephony.TelephonyManager;
import com.reactivecascade.functional.RunnableAltFuture;
import com.reactivecascade.functional.SettableAltFuture;
import com.reactivecascade.i.IAltFuture;
import com.reactivecascade.i.IGettable;
import com.reactivecascade.i.IThreadType;
import java.io.IOException;
import java.util.Collection;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.framed.Header;
import static android.telephony.TelephonyManager.NETWORK_TYPE_1xRTT;
import static android.telephony.TelephonyManager.NETWORK_TYPE_CDMA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EDGE;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EHRPD;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_0;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_A;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_B;
import static android.telephony.TelephonyManager.NETWORK_TYPE_GPRS;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSDPA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSPA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSPAP;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSUPA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_IDEN;
import static android.telephony.TelephonyManager.NETWORK_TYPE_LTE;
import static android.telephony.TelephonyManager.NETWORK_TYPE_UMTS;
import static android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN;
import static com.reactivecascade.Async.NET_READ;
import static com.reactivecascade.Async.NET_WRITE; | /*
This file is part of Reactive Cascade which is released under The MIT License.
See license.md , https://github.com/futurice/cascade and http://reactivecascade.com for details.
This is open source for the common good. Please contribute improvements by pull request or contact [email protected]
*/
package com.reactivecascade.util;
/**
* OkHttp convenience wrapper methods
*/
public final class NetUtil extends Origin {
public enum NetType {NET_2G, NET_2_5G, NET_3G, NET_3_5G, NET_4G, NET_5G}
private static final int MAX_NUMBER_OF_WIFI_NET_CONNECTIONS = 6;
private static final int MAX_NUMBER_OF_3G_NET_CONNECTIONS = 4;
private static final int MAX_NUMBER_OF_2G_NET_CONNECTIONS = 2;
@NonNull
private final OkHttpClient mOkHttpClient;
@NonNull
private final TelephonyManager mTelephonyManager;
@NonNull
private final WifiManager mWifiManager;
@NonNull
private final IThreadType mNetReadThreadType;
@NonNull
private final IThreadType mNetWriteThreadType;
@RequiresPermission(allOf = {
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_WIFI_STATE})
public NetUtil(@NonNull final Context context) { | this(context, NET_READ, NET_WRITE); | 5 |
Biacode/presentations | tdd/service/src/test/java/com/barcamp/tdd/service/user/impl/UserServiceImplTest.java | [
"@Entity\n@Table(name = \"USER\")\npublic class User implements Serializable {\n private static final long serialVersionUID = 415031695037724472L;\n\n //region Properties\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n\n @Column(name = \"email\")\n private String email;\n\n @Column(name = \"password\")\n private String password;\n //endregion\n\n //region Constructors\n public User() {\n }\n\n public User(final String email, final String password) {\n this.email = email;\n this.password = password;\n }\n\n public User(final Long id, final String email, final String password) {\n this.id = id;\n this.email = email;\n this.password = password;\n }\n //endregion\n\n //region Equals, HashCode and ToString\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof User)) {\n return false;\n }\n final User user = (User) o;\n return new EqualsBuilder()\n .append(id, user.id)\n .append(email, user.email)\n .append(password, user.password)\n .isEquals();\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder()\n .append(id)\n .append(email)\n .append(password)\n .toHashCode();\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this)\n .append(\"id\", id)\n .append(\"email\", email)\n .append(\"password\", password)\n .toString();\n }\n //endregion\n\n //region Properties getters and setters\n public Long getId() {\n return id;\n }\n\n public void setId(final Long id) {\n this.id = id;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(final String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(final String password) {\n this.password = password;\n }\n //endregion\n}",
"@Repository\npublic interface UserRepository extends JpaRepository<User, Long> {\n User findByEmail(final String email);\n}",
"public interface UserService {\n User create(final UserCreationDto dto);\n\n User getById(final Long id);\n}",
"public class UserCreationDto implements Serializable {\n private static final long serialVersionUID = -3795826265205920863L;\n\n //region Properties\n private String email;\n\n private String password;\n //endregion\n\n //region Constructors\n public UserCreationDto() {\n }\n\n public UserCreationDto(final String email, final String password) {\n this.email = email;\n this.password = password;\n }\n //endregion\n\n //region Equals, HashCode and ToString\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof UserCreationDto)) {\n return false;\n }\n final UserCreationDto that = (UserCreationDto) o;\n return new EqualsBuilder()\n .append(email, that.email)\n .append(password, that.password)\n .isEquals();\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder()\n .append(email)\n .append(password)\n .toHashCode();\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this)\n .append(\"email\", email)\n .append(\"password\", password)\n .toString();\n }\n //endregion\n\n //region Properties getters and setters\n public String getEmail() {\n return email;\n }\n\n public void setEmail(final String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(final String password) {\n this.password = password;\n }\n //endregion\n}",
"public class UserAlreadyExistsForEmailException extends RuntimeException {\n private static final long serialVersionUID = -1885175502484780110L;\n\n //region Properties\n private final String email;\n //endregion\n\n //region Constructors\n public UserAlreadyExistsForEmailException(final String message, final String email) {\n super(message);\n this.email = email;\n }\n //endregion\n\n //region Properties getters and setters\n public String getEmail() {\n return email;\n }\n //endregion\n}",
"public class UserNotFoundForIdException extends RuntimeException {\n private static final long serialVersionUID = -7980996165478861321L;\n\n //region Properties\n private final Long id;\n //endregion\n\n //region Constructors\n public UserNotFoundForIdException(final String message, final Long id) {\n super(message);\n this.id = id;\n }\n //endregion\n\n //region Properties getters and setters\n public Long getId() {\n return id;\n }\n //endregion\n}",
"@RunWith(EasyMockRunner.class)\n@Ignore\npublic abstract class AbstractServiceImplTest extends EasyMockSupport {\n\n //region Dependencies\n private final ServiceImplTestHelper serviceImplTestHelper;\n //endregion\n\n //region Constructors\n public AbstractServiceImplTest() {\n serviceImplTestHelper = new ServiceImplTestHelper();\n }\n //endregion\n\n //region Public methods\n public ServiceImplTestHelper getServiceImplTestHelper() {\n return serviceImplTestHelper;\n }\n //endregion\n\n}"
] | import com.barcamp.tdd.domain.user.User;
import com.barcamp.tdd.repository.user.UserRepository;
import com.barcamp.tdd.service.user.UserService;
import com.barcamp.tdd.service.user.dto.UserCreationDto;
import com.barcamp.tdd.service.user.exception.UserAlreadyExistsForEmailException;
import com.barcamp.tdd.service.user.exception.UserNotFoundForIdException;
import com.barcamp.tdd.test.AbstractServiceImplTest;
import org.apache.commons.lang3.SerializationUtils;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Test;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*; | package com.barcamp.tdd.service.user.impl;
/**
* Author: Arthur Asatryan
* Company: SFL LLC
* Date: 6/18/16
* Time: 11:26 PM
*/
public class UserServiceImplTest extends AbstractServiceImplTest {
//region Test subject and mocks
@TestSubject
private UserService userService = new UserServiceImpl();
@Mock
private UserRepository userRepository;
//endregion
//region Constructors
public UserServiceImplTest() {
}
//endregion
//region Test methods
//region initial
@Test
public void testHaveUserService() {
resetAll();
// test data
// expectations
replayAll();
// run test scenario
assertNotNull(userService);
verifyAll();
}
@Test
public void testHaveUserRepository() {
resetAll();
// test data
// expectations
replayAll();
// run test scenario
assertNotNull(userRepository);
verifyAll();
}
//endregion
//region create
@Test
public void testCreateWithInvalidArguments() {
resetAll();
// test data
final UserCreationDto validDto = getServiceImplTestHelper().buildUserCreationDto();
UserCreationDto invalidDto;
// expectations
replayAll();
// run test scenario
// the dto should not be null
invalidDto = null;
try {
userService.create(invalidDto);
fail("exception should be thrown");
} catch (final IllegalArgumentException ignore) {
// expected
}
// the email should not be null
invalidDto = SerializationUtils.clone(validDto);
invalidDto.setEmail(null);
try {
userService.create(invalidDto);
fail("exception should be thrown");
} catch (final IllegalArgumentException ignore) {
// expected
}
// the password should not be null
invalidDto = SerializationUtils.clone(validDto);
invalidDto.setPassword(null);
try {
userService.create(invalidDto);
fail("exception should be thrown");
} catch (final IllegalArgumentException ignore) {
// expected
}
verifyAll();
}
@Test
public void testCreateWhenUserAlreadyExists() {
resetAll();
// test data
final UserCreationDto dto = getServiceImplTestHelper().buildUserCreationDto();
final User user = getServiceImplTestHelper().buildUser();
// expectations
expect(userRepository.findByEmail(dto.getEmail())).andReturn(user);
replayAll();
// run test scenario
try {
userService.create(dto);
fail("exception should be thrown");
} catch (final UserAlreadyExistsForEmailException ex) {
// expected
assertNotNull(ex);
assertEquals(dto.getEmail(), ex.getEmail());
}
verifyAll();
}
@Test
public void testCreate() {
resetAll();
// test data
final UserCreationDto dto = getServiceImplTestHelper().buildUserCreationDto();
// expectations
expect(userRepository.findByEmail(dto.getEmail())).andReturn(null);
expect(userRepository.save(isA(User.class))).andAnswer(() -> (User) getCurrentArguments()[0]);
replayAll();
// run test scenario
final User result = userService.create(dto);
getServiceImplTestHelper().assertPersistentUserAndCreationDto(dto, result);
verifyAll();
}
//endregion
//region getById
@Test
public void testGetByIdWithInvalidArguments() {
resetAll();
// test data
// expectations
replayAll();
// run test scenario
try {
userService.getById(null);
fail("exception should be thrown");
} catch (final IllegalArgumentException ignore) {
// expected
}
verifyAll();
}
@Test
public void testGetByIdWhenUserNotFound() {
resetAll();
// test data
final Long id = 7L;
// expectations
expect(userRepository.findOne(id)).andReturn(null);
replayAll();
// run test scenario
try {
userService.getById(id);
fail("exception should be thrown"); | } catch (final UserNotFoundForIdException ex) { | 5 |
datanerds-io/avropatch | src/test/java/io/datanerds/avropatch/serialization/ConcurrencyTest.java | [
"@ThreadSafe\npublic class Patch<T> {\n\n @AvroSchema(DefaultSchema.HEADERS)\n private final Map<String, Object> headers;\n @AvroSchema(DefaultSchema.VALUE)\n private final T resource;\n @AvroSchema(DefaultSchema.TIMESTAMP)\n private final Date timestamp;\n private final List<Operation> operations;\n\n @SuppressWarnings(\"unused\") // no-arg constructor needed by Avro\n private Patch() {\n this(null, null, null, null);\n }\n\n private Patch(T resource, List<Operation> operations, Map<String, ? super Object> headers, Date timestamp) {\n this.resource = resource;\n this.operations = operations;\n this.headers = headers;\n this.timestamp = timestamp;\n }\n\n /**\n * Minimalistic factory method setting the timestamp to {@code new Date()} and initializing the operation list and\n * headers map with {@link Collections#emptyList()} / {@link Collections#emptyMap()}.\n * @param resource resource identifier\n * @param <T> type of the resource identifier\n * @return new instance of a {@link Patch}\n */\n public static <T> Patch<T> from(T resource) {\n Objects.requireNonNull(resource);\n return new Patch<>(resource, Collections.emptyList(), Collections.emptyMap(), new Date());\n }\n\n /**\n * This factory method sets the timestamp to {@code new Date()} and initializes the headers map with\n * {@link Collections#emptyMap()}.\n * @param resource resource identifier\n * @param operations sequence of operations to apply to a object identifiable by {@code resource}\n * @param <T> type of the resource identifier\n * @return new instance of a {@link Patch}\n */\n public static <T> Patch<T> from(T resource, List<Operation> operations) {\n Objects.requireNonNull(resource);\n return new Patch<>(resource, unmodifiableNullableList(operations), Collections.emptyMap(), new Date());\n }\n\n /**\n * This factory method sets the timestamp to {@code new Date()} and initializes the operation list with\n * {@link Collections#emptyList()}.\n * @param resource resource identifier\n * @param headers arbitrary header information\n * @param <T> type of the resource identifier\n * @return new instance of a {@link Patch}\n */\n public static <T> Patch<T> from(T resource, Map<String, Object> headers) {\n Objects.requireNonNull(resource);\n return new Patch<>(resource, Collections.emptyList(), unmodifiableNullableMap(headers), new Date());\n }\n\n /**\n * This factory method sets the timestamp to {@code new Date()}.\n * @param resource resource identifier\n * @param operations sequence of operations to apply to a object identifiable by {@code resource}\n * @param headers arbitrary header information\n * @param <T> type of the resource identifier\n * @return new instance of a {@link Patch}\n */\n public static <T> Patch<T> from(T resource, List<Operation> operations, Map<String, Object> headers) {\n Objects.requireNonNull(resource);\n return new Patch<>(resource, unmodifiableNullableList(operations), unmodifiableNullableMap(headers), new Date());\n }\n\n /**\n *\n * @param resource resource identifier\n * @param operations sequence of operations to apply to a object identifiable by {@code resource}\n * @param headers arbitrary header information\n * @param timestamp timestamp\n * @param <T> type of the resource identifier\n * @return new instance of a {@link Patch}\n */\n public static <T> Patch<T> from(T resource, List<Operation> operations, Map<String, Object> headers, Date timestamp) {\n Objects.requireNonNull(resource);\n Objects.requireNonNull(timestamp);\n return new Patch<>(resource, unmodifiableNullableList(operations), unmodifiableNullableMap(headers), timestamp);\n }\n\n private static Map<String, Object> unmodifiableNullableMap(Map<String, Object> map) {\n return Collections.unmodifiableMap(new HashMap<>(Optional.ofNullable(map).orElse(Collections.emptyMap())));\n }\n\n private static List<Operation> unmodifiableNullableList(List<Operation> operations) {\n return Collections.unmodifiableList(\n new ArrayList<>(Optional.ofNullable(operations).orElse(Collections.emptyList())));\n }\n\n public Operation getOperation(int index) {\n return operations.get(index);\n }\n\n public int size() {\n return operations.size();\n }\n\n public Stream<Operation> stream() {\n return operations.stream();\n }\n\n public boolean isEmpty() {\n return operations.isEmpty();\n }\n\n public Map<String, Object> getHeaders() {\n return headers;\n }\n\n /**\n * Convenient method to retrieve and cast a specific header value.\n * @param name name of the header\n * @param <V> expected value type for given header\n * @return header value if exists, {@code null} otherwise\n * @throws ClassCastException if given header is not of type {@link T}\n */\n @SuppressWarnings(\"unchecked\")\n public <V> V getHeader(String name) {\n return (V) headers.get(name);\n }\n\n public boolean hasHeader(String name) {\n return headers.containsKey(name);\n }\n\n public T getResource() {\n return resource;\n }\n\n public Date getTimestamp() {\n return timestamp;\n }\n\n @Override\n @Generated(\"IntelliJ IDEA\")\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Patch<T> patch = (Patch<T>) o;\n return Objects.equals(headers, patch.headers) &&\n Objects.equals(resource, patch.resource) &&\n Objects.equals(timestamp, patch.timestamp) &&\n Objects.equals(operations, patch.operations);\n }\n\n @Override\n @Generated(\"IntelliJ IDEA\")\n public int hashCode() {\n return Objects.hash(headers, resource, timestamp, operations);\n }\n}",
"@Union({Add.class, Copy.class, Move.class, Remove.class, Replace.class, Test.class})\npublic interface Operation {\n}",
"public enum OperationGenerator {\n\n ADD(() -> new Add<>(generatePath(), generateValue())),\n COPY(() -> new Copy(generatePath(), generatePath())),\n MOVE(() -> new Move(generatePath(), generatePath())),\n REMOVE(() -> new Remove(generatePath())),\n REPLACE(() -> new Replace<>(generatePath(), generateValue())),\n TEST(() -> new io.datanerds.avropatch.operation.Test<>(generatePath(), generateValue()));\n\n private static final Random random = new Random();\n private static final int MAX_LIST_SIZE = 50;\n private final Supplier<Operation> operationSupplier;\n\n OperationGenerator(Supplier<Operation> operationSupplier) {\n this.operationSupplier = operationSupplier;\n }\n\n public static Operation randomOperation() {\n return values()[random.nextInt(values().length)].getOperation();\n }\n\n public static List<Operation> createSomeOperations(Function<Object, Operation> operationFunction) {\n List<Operation> operations = new ArrayList<>();\n operations.add(createOperation(operationFunction, \"hello world\"));\n operations.add(createOperation(operationFunction, 42));\n operations.add(createOperation(operationFunction, 42L));\n operations.add(createOperation(operationFunction, 123.456d));\n operations.add(createOperation(operationFunction, 123.456f));\n operations.add(createOperation(operationFunction, new BigInteger(\"8364789684563949576378945698056348956\")));\n operations.add(createOperation(operationFunction, new BigDecimal(\"956740578902345.56734895627895\")));\n operations.add(createOperation(operationFunction, UUID.randomUUID()));\n operations.add(createOperation(operationFunction, new Date()));\n\n return operations;\n }\n\n public static <T> Add<T> add(T value) {\n return new Add<>(Path.of(\"hello\", \"world\"), value);\n }\n\n public static <T> Replace<T> replace(T value) {\n return new Replace<>(Path.of(\"hello\", \"world\"), value);\n }\n\n public static <T> io.datanerds.avropatch.operation.Test<T> test(T value) {\n return new io.datanerds.avropatch.operation.Test<>(Path.of(\"hello\", \"world\"), value);\n }\n\n private static <T> Operation createOperation(Function<T, Operation> operationFunction, T value) {\n return operationFunction.apply(value);\n }\n\n private static Object generateValue() { return ValueType.generateObject(); }\n\n private static Path generatePath() {\n return Path.of(\"hello\", \"world\");\n }\n\n private Operation getOperation() {\n return operationSupplier.get();\n }\n\n enum ValueType {\n BOOLEAN(random::nextBoolean),\n DOUBLE(random::nextDouble),\n FLOAT(random::nextFloat),\n INTEGER(random::nextInt),\n LONG(random::nextLong),\n NULL(() -> null),\n STRING(ValueType::randomString),\n BIG_INTEGER(() -> new BigInteger(random.nextInt(256), random)),\n BIG_DECIMAL(ValueType::randomBigDecimal),\n UUID(java.util.UUID::randomUUID),\n DATE(() -> new Date(random.nextLong())),\n BIMMEL(ValueType::randomBimmel);\n\n private final Supplier<Object> valueSupplier;\n\n ValueType(Supplier<Object> valueSupplier) {\n this.valueSupplier = valueSupplier;\n }\n\n public static Object generateObject() {\n if (random.nextBoolean()) {\n return generateList(randomValueType());\n }\n return randomValueType().generate();\n }\n\n private Object generate() {\n return valueSupplier.get();\n }\n\n private static ValueType randomValueType() {\n return values()[random.nextInt(ValueType.values().length)];\n }\n\n private static List<?> generateList(ValueType type) {\n return IntStream\n .range(0, MAX_LIST_SIZE)\n .mapToObj(i -> type.generate())\n .collect(Collectors.toList());\n }\n\n private static String randomString() {\n return java.util.UUID.randomUUID().toString();\n }\n\n private static BigDecimal randomBigDecimal() {\n BigInteger unscaledValue = new BigInteger(random.nextInt(256), random);\n int numberOfDigits = getDigitCount(unscaledValue);\n int scale = random.nextInt(numberOfDigits + 1);\n return new BigDecimal(unscaledValue, scale);\n }\n\n private static int getDigitCount(BigInteger number) {\n double factor = Math.log(2) / Math.log(10);\n int digitCount = (int) (factor * number.bitLength() + 1);\n if (BigInteger.TEN.pow(digitCount - 1).compareTo(number) > 0) {\n return digitCount - 1;\n }\n return digitCount;\n }\n\n private static Bimmel randomBimmel() {\n return new Bimmel(\n (String) STRING.generate(),\n (int) INTEGER.generate(),\n (java.util.UUID) UUID.generate(),\n new Bimmel.Bommel(randomString()));\n }\n }\n}",
"public class Bimmel {\n\n public final String name;\n public final int number;\n public final UUID id;\n public final Bommel bommel;\n\n @SuppressWarnings(\"unused\") // no-arg constructor for Avro\n private Bimmel() {\n this(null, -42, null, null);\n }\n\n public Bimmel(String name, int number, UUID id, Bommel bommel) {\n this.name = name;\n this.number = number;\n this.id = id;\n this.bommel = bommel;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Bimmel bimmel = (Bimmel) o;\n return number == bimmel.number &&\n Objects.equals(name, bimmel.name) &&\n Objects.equals(id, bimmel.id) &&\n Objects.equals(bommel, bimmel.bommel);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, number, id, bommel);\n }\n\n public static class Bommel {\n public final String name;\n\n @SuppressWarnings(\"unused\")\n private Bommel() {\n this(null);\n }\n\n public Bommel(String name) {\n this.name = name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Bommel bommel = (Bommel) o;\n return Objects.equals(name, bommel.name);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name);\n }\n }\n}",
"public static ValueSchemaBuilder<Schema> arrayBuilder() {\n return ValueSchemaBuilder.arrayBuilder();\n}",
"public static ValueSchemaBuilder<PatchMapper> builder() {\n return new ValueSchemaBuilder<>(schema -> new PatchMapper(Types.Patch.create(schema)));\n}"
] | import com.google.common.collect.ImmutableList;
import io.datanerds.avropatch.Patch;
import io.datanerds.avropatch.operation.Operation;
import io.datanerds.avropatch.operation.OperationGenerator;
import io.datanerds.avropatch.value.Bimmel;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
import static io.datanerds.avropatch.serialization.PatchMapper.arrayBuilder;
import static io.datanerds.avropatch.serialization.PatchMapper.builder;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat; | package io.datanerds.avropatch.serialization;
public class ConcurrencyTest {
private static Logger logger = LoggerFactory.getLogger(ConcurrencyTest.class);
private static final int NUMBER_OF_THREADS = 200;
private static final int NUMBER_OF_PATCHES = 100;
private static final int MAX_PATCH_SIZE = 50; | private static final List<Patch> PATCHES = Collections.unmodifiableList(generateData()); | 0 |
sfPlayer1/Matcher | src/matcher/type/ClassEnvironment.java | [
"public enum NameType {\n\tPLAIN(true, false, false, 0),\n\tMAPPED(false, true, false, 0),\n\tAUX(false, false, false, 1),\n\tAUX2(false, false, false, 2),\n\n\tMAPPED_PLAIN(true, true, false, 0),\n\tMAPPED_AUX_PLAIN(true, true, false, 1),\n\tMAPPED_AUX2_PLAIN(true, true, false, 2),\n\tMAPPED_TMP_PLAIN(true, true, true, 0),\n\tMAPPED_LOCTMP_PLAIN(true, true, false, 0),\n\n\tUID_PLAIN(true, false, false, 0),\n\tTMP_PLAIN(true, false, true, 0),\n\tLOCTMP_PLAIN(true, false, false, 0),\n\tAUX_PLAIN(true, false, false, 1),\n\tAUX2_PLAIN(true, false, false, 2);\n\n\tNameType(boolean plain, boolean mapped, boolean tmp, int aux) {\n\t\tthis.plain = plain;\n\t\tthis.mapped = mapped;\n\t\tthis.tmp = tmp;\n\t\tthis.aux = aux;\n\t}\n\n\tpublic NameType withPlain(boolean value) {\n\t\tif (plain == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn VALUES[AUX_PLAIN.ordinal() + aux - 1];\n\t\t} else if (this == MAPPED_PLAIN) {\n\t\t\treturn MAPPED;\n\t\t} else if (aux > 0 && !mapped && !tmp) {\n\t\t\treturn VALUES[AUX.ordinal() + aux - 1];\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\t}\n\n\tpublic NameType withMapped(boolean value) {\n\t\tif (mapped == value) return this;\n\n\t\tif (value) {\n\t\t\tif (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];\n\t\t\tif (tmp) return MAPPED_TMP_PLAIN;\n\t\t\tif (plain) return MAPPED_PLAIN;\n\n\t\t\treturn MAPPED;\n\t\t} else {\n\t\t\tif (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];\n\t\t\tif (tmp) return TMP_PLAIN;\n\t\t\tif (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\tpublic NameType withAux(int index, boolean value) {\n\t\tif ((aux - 1 == index) == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];\n\t\t\tif (plain) return VALUES[AUX_PLAIN.ordinal() + index];\n\n\t\t\treturn VALUES[AUX.ordinal() + index];\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\tpublic NameType withTmp(boolean value) {\n\t\tif (tmp == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_TMP_PLAIN;\n\n\t\t\treturn TMP_PLAIN;\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\t// transform between tmp <-> loctmp\n\tpublic NameType withUnmatchedTmp(boolean value) {\n\t\tboolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;\n\n\t\tif (value == locTmp || !tmp && !locTmp) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_LOCTMP_PLAIN;\n\n\t\t\treturn LOCTMP_PLAIN;\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_TMP_PLAIN;\n\n\t\t\treturn TMP_PLAIN;\n\t\t}\n\t}\n\n\tpublic boolean isAux() {\n\t\treturn aux > 0;\n\t}\n\n\tpublic int getAuxIndex() {\n\t\tif (aux == 0) throw new NoSuchElementException();\n\n\t\treturn aux - 1;\n\t}\n\n\tpublic static NameType getAux(int index) {\n\t\tObjects.checkIndex(index, AUX_COUNT);\n\n\t\treturn VALUES[NameType.AUX.ordinal() + index];\n\t}\n\n\tpublic static final int AUX_COUNT = 2;\n\n\tprivate static final NameType[] VALUES = values();\n\n\tpublic final boolean plain;\n\tpublic final boolean mapped;\n\tpublic final boolean tmp;\n\tprivate final int aux;\n}",
"public class Util {\n\tpublic static <T> Set<T> newIdentityHashSet() {\n\t\treturn Collections.newSetFromMap(new IdentityHashMap<>());//new IdentityHashSet<>();\n\t}\n\n\tpublic static <T> Set<T> newIdentityHashSet(Collection<? extends T> c) {\n\t\tSet<T> ret = Collections.newSetFromMap(new IdentityHashMap<>(c.size()));\n\t\tret.addAll(c);\n\n\t\treturn ret;//new IdentityHashSet<>(c);\n\t}\n\n\tpublic static <T> Set<T> copySet(Set<T> set) {\n\t\tif (set instanceof HashSet) {\n\t\t\treturn new HashSet<>(set);\n\t\t} else {\n\t\t\treturn newIdentityHashSet(set);\n\t\t}\n\t}\n\n\tpublic static FileSystem iterateJar(Path archive, boolean autoClose, Consumer<Path> handler) {\n\t\tboolean existing = false;\n\t\tFileSystem fs = null;\n\n\t\ttry {\n\t\t\tURI uri = new URI(\"jar:\"+archive.toUri().toString());\n\n\t\t\tsynchronized (Util.class) {\n\t\t\t\ttry {\n\t\t\t\t\tfs = FileSystems.getFileSystem(uri);\n\t\t\t\t\texisting = true;\n\t\t\t\t\tautoClose = false;\n\t\t\t\t} catch (FileSystemNotFoundException e) {\n\t\t\t\t\tfs = FileSystems.newFileSystem(uri, Collections.emptyMap());\n\t\t\t\t\texisting = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tFiles.walkFileTree(fs.getPath(\"/\"), new SimpleFileVisitor<Path>() {\n\t\t\t\t@Override\n\t\t\t\tpublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n\t\t\t\t\tif (file.toString().endsWith(\".class\")) {\n\t\t\t\t\t\thandler.accept(file);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn FileVisitResult.CONTINUE;\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\tcloseSilently(fs);\n\t\t\tthrow new UncheckedIOException(e);\n\t\t} catch (URISyntaxException e) {\n\t\t\tcloseSilently(fs);\n\t\t\tthrow new RuntimeException(e);\n\t\t} catch (Throwable t) {\n\t\t\tcloseSilently(fs);\n\t\t\tthrow t;\n\t\t}\n\n\t\tif (autoClose) closeSilently(fs);\n\n\t\treturn autoClose || existing ? null : fs;\n\t}\n\n\tpublic static boolean clearDir(Path path, Predicate<Path> disallowed) throws IOException {\n\t\ttry (Stream<Path> stream = Files.walk(path, FileVisitOption.FOLLOW_LINKS)) {\n\t\t\tif (stream.anyMatch(disallowed)) return false;\n\t\t}\n\n\t\tAtomicBoolean ret = new AtomicBoolean(true);\n\n\t\tFiles.walkFileTree(path, new SimpleFileVisitor<Path>() {\n\t\t\t@Override\n\t\t\tpublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n\t\t\t\tif (disallowed.test(file)) {\n\t\t\t\t\tret.set(false);\n\n\t\t\t\t\treturn FileVisitResult.TERMINATE;\n\t\t\t\t} else {\n\t\t\t\t\tFiles.delete(file);\n\n\t\t\t\t\treturn FileVisitResult.CONTINUE;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n\t\t\t\tif (exc != null) throw exc;\n\t\t\t\tif (!dir.equals(path)) Files.delete(dir);\n\n\t\t\t\treturn FileVisitResult.CONTINUE;\n\t\t\t}\n\t\t});\n\n\t\treturn ret.get();\n\t}\n\n\tpublic static void closeSilently(Closeable c) {\n\t\tif (c == null) return;\n\n\t\ttry {\n\t\t\tc.close();\n\t\t} catch (IOException e) { }\n\t}\n\n\tpublic static boolean isCallToInterface(MethodInsnNode insn) {\n\t\tassert insn.itf || insn.getOpcode() != Opcodes.INVOKEINTERFACE;\n\n\t\treturn insn.itf;\n\t\t/*return insn.getOpcode() == Opcodes.INVOKEINTERFACE\n\t\t\t\t|| (insn.getOpcode() == Opcodes.INVOKESPECIAL || insn.getOpcode() == Opcodes.INVOKESTATIC) && insn.itf;*/\n\t}\n\n\tpublic static boolean isCallToInterface(Handle handle) {\n\t\tassert handle.isInterface() || handle.getTag() != Opcodes.H_INVOKEINTERFACE;\n\n\t\treturn handle.isInterface();\n\n\t\t/*return handle.getTag() == Opcodes.H_INVOKEINTERFACE\n\t\t\t\t|| (handle.getTag() == Opcodes.H_INVOKESPECIAL || handle.getTag() == Opcodes.H_NEWINVOKESPECIAL || handle.getTag() == Opcodes.H_INVOKESTATIC) && handle.isInterface();*/\n\t}\n\n\tpublic static String formatAccessFlags(int access, AFElementType type) {\n\t\tint assoc = type.assoc;\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tfor (int i = 0; i < accessFlags.length; i++) {\n\t\t\tif ((accessAssoc[i] & assoc) == 0) continue;\n\t\t\tif ((access & accessFlags[i]) == 0) continue;\n\n\t\t\tif (sb.length() != 0) sb.append(' ');\n\t\t\tsb.append(accessNames[i]);\n\n\t\t\taccess &= ~accessFlags[i];\n\t\t}\n\n\t\tif (access != 0) {\n\t\t\tif (sb.length() != 0) sb.append(' ');\n\t\t\tsb.append(\"0x\");\n\t\t\tsb.append(Integer.toHexString(access));\n\t\t}\n\n\t\treturn sb.toString();\n\t}\n\n\tpublic enum AFElementType {\n\t\tClass(1), Method(2), Field(4), Parameter(8), InnerClass(16);\n\n\t\tAFElementType(int assoc) {\n\t\t\tthis.assoc = assoc;\n\t\t}\n\n\t\tfinal int assoc;\n\t}\n\n\tprivate static final int[] accessFlags = new int[] { Opcodes.ACC_PUBLIC, Opcodes.ACC_PRIVATE, Opcodes.ACC_PROTECTED, Opcodes.ACC_STATIC,\n\t\t\tOpcodes.ACC_FINAL, Opcodes.ACC_SUPER, Opcodes.ACC_SYNCHRONIZED, Opcodes.ACC_VOLATILE, Opcodes.ACC_BRIDGE, Opcodes.ACC_VARARGS,\n\t\t\tOpcodes.ACC_TRANSIENT, Opcodes.ACC_NATIVE, Opcodes.ACC_INTERFACE, Opcodes.ACC_ABSTRACT, Opcodes.ACC_STRICT, Opcodes.ACC_SYNTHETIC,\n\t\t\tOpcodes.ACC_ANNOTATION, Opcodes.ACC_ENUM, Opcodes.ACC_MANDATED };\n\tprivate static final String[] accessNames = new String[] { \"public\", \"private\", \"protected\", \"static\",\n\t\t\t\"final\", \"super\", \"synchronized\", \"volatile\", \"bridge\", \"varargs\",\n\t\t\t\"transient\", \"native\", \"interface\", \"abstract\", \"strict\", \"synthetic\",\n\t\t\t\"annotation\", \"enum\", \"mandated\" };\n\tprivate static final byte[] accessAssoc = new byte[] { 7, 7, 7, 6,\n\t\t\t15, 1, 2, 4, 2, 2,\n\t\t\t4, 2, 1, 3, 2, 15,\n\t\t\t1, 21, 8 };\n\n\tpublic static Handle getTargetHandle(Handle bsm, Object[] bsmArgs) {\n\t\tif (isJavaLambdaMetafactory(bsm)) {\n\t\t\treturn (Handle) bsmArgs[1];\n\t\t} else if (isIrrelevantBsm(bsm)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tSystem.out.printf(\"unknown invokedynamic bsm: %s/%s%s (tag=%d iif=%b)%n\", bsm.getOwner(), bsm.getName(), bsm.getDesc(), bsm.getTag(), bsm.isInterface());\n\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static boolean isJavaLambdaMetafactory(Handle bsm) {\n\t\treturn bsm.getTag() == Opcodes.H_INVOKESTATIC\n\t\t\t\t&& bsm.getOwner().equals(\"java/lang/invoke/LambdaMetafactory\")\n\t\t\t\t&& (bsm.getName().equals(\"metafactory\")\n\t\t\t\t\t\t&& bsm.getDesc().equals(\"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;\")\n\t\t\t\t\t\t|| bsm.getName().equals(\"altMetafactory\")\n\t\t\t\t\t\t&& bsm.getDesc().equals(\"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;\"))\n\t\t\t\t&& !bsm.isInterface();\n\t}\n\n\tpublic static boolean isIrrelevantBsm(Handle bsm) {\n\t\treturn bsm.getOwner().equals(\"java/lang/invoke/StringConcatFactory\")\n\t\t\t\t|| bsm.getOwner().equals(\"java/lang/runtime/ObjectMethods\");\n\t}\n\n\tpublic static boolean isValidJavaIdentifier(String s) {\n\t\tif (s.isEmpty()) return false;\n\n\t\tint cp = s.codePointAt(0);\n\t\tif (!Character.isJavaIdentifierStart(cp)) return false;\n\n\t\tfor (int i = Character.charCount(cp), max = s.length(); i < max; i += Character.charCount(cp)) {\n\t\t\tcp = s.codePointAt(i);\n\t\t\tif (!Character.isJavaIdentifierPart(cp)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic static int compareNatural(String a, String b) {\n\t\tfinal int lenA = a.length();\n\t\tfinal int lenB = b.length();\n\t\tint posA = 0;\n\t\tint lastSize = 0;\n\n\t\tfor (int max = Math.min(lenA, lenB); posA < max; ) {\n\t\t\tint cA = Character.codePointAt(a, posA);\n\t\t\tint cB = Character.codePointAt(b, posA);\n\n\t\t\tif (cA != cB) break;\n\n\t\t\tlastSize = Character.charCount(cA);\n\t\t\tposA += lastSize;\n\t\t}\n\n\t\tif (posA == lenA && lenA == lenB) return 0;\n\n\t\tint posB = posA = posA - lastSize;\n\t\tint endA = -1;\n\t\tint endB = -1;\n\n\t\tfor (;;) {\n\t\t\tint startA = posA;\n\t\t\tboolean isNumA = false;\n\n\t\t\twhile (posA < lenA) {\n\t\t\t\tint c = Character.codePointAt(a, posA);\n\n\t\t\t\tif ((c >= '0' && c <= '9') != isNumA) {\n\t\t\t\t\tif (posA == startA) {\n\t\t\t\t\t\tisNumA = !isNumA; // isNum had the wrong initial value\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (endA < posA) {\n\t\t\t\t\t\t\tendA = posA;\n\n\t\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\t\tendA += Character.charCount(c);\n\t\t\t\t\t\t\t} while (endA < lenA && (c = Character.codePointAt(a, endA)) != '.' && c != '/');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (c == '.' || c == '/') {\n\t\t\t\t\tendA = posA; // unconditionally mark end to handle 0-length segments (those won't be re-visited)\n\t\t\t\t\tif (posA == startA) posA++; // consume only if first to avoid polluting comparisons within segments, otherwise trigger revisit\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (c == '$') {\n\t\t\t\t\tif (posA == startA) posA++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tposA += Character.charCount(c);\n\t\t\t}\n\n\t\t\tint startB = posB;\n\t\t\tboolean isNumB = false;\n\n\t\t\twhile (posB < lenB) {\n\t\t\t\tint c = Character.codePointAt(b, posB);\n\n\t\t\t\tif ((c >= '0' && c <= '9') != isNumB) {\n\t\t\t\t\tif (posB == startB) {\n\t\t\t\t\t\tisNumB = !isNumB;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (endB < posB) {\n\t\t\t\t\t\t\tendB = posB;\n\n\t\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\t\tendB += Character.charCount(c);\n\t\t\t\t\t\t\t} while (endB < lenB && (c = Character.codePointAt(b, endB)) != '.' && c != '/');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (c == '.' || c == '/') {\n\t\t\t\t\tendB = posB;\n\t\t\t\t\tif (posB == startB) posB++;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (c == '$') {\n\t\t\t\t\tif (posB == startB) posB++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tposB += Character.charCount(c);\n\t\t\t}\n\n\t\t\tboolean hasEndA = endA >= startA && endA < lenA; // segment separator exists after current region\n\t\t\tboolean hasEndB = endB >= startB && endB < lenB;\n\n\t\t\tif (hasEndA != hasEndB) {\n\t\t\t\treturn hasEndA ? 1 : -1;\n\t\t\t}\n\n\t\t\tif (isNumA && isNumB) {\n\t\t\t\tint segLenA = posA - startA;\n\t\t\t\tint segLenB = posB - startB;\n\n\t\t\t\tif (segLenA != segLenB) {\n\t\t\t\t\treturn segLenA < segLenB ? -1 : 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile (startA < posA) {\n\t\t\t\tif (startB == posB) return 1;\n\n\t\t\t\tint cA = Character.codePointAt(a, startA);\n\t\t\t\tint cB = Character.codePointAt(b, startB);\n\n\t\t\t\tif (cA != cB) {\n\t\t\t\t\treturn cA < cB ? -1 : 1;\n\t\t\t\t}\n\n\t\t\t\tstartA += Character.charCount(cA);\n\t\t\t\tstartB += Character.charCount(cB);\n\t\t\t}\n\n\t\t\tif (startB != posB) return -1;\n\t\t}\n\t}\n\n\tpublic static final Object asmNodeSync = new Object();\n}",
"public class ClassifierUtil {\n\tpublic static boolean checkPotentialEquality(ClassInstance a, ClassInstance b) {\n\t\tif (a == b) return true;\n\t\tif (a.getMatch() != null) return a.getMatch() == b;\n\t\tif (b.getMatch() != null) return b.getMatch() == a;\n\t\tif (!a.isMatchable() || !b.isMatchable()) return false;\n\t\tif (a.isArray() != b.isArray()) return false;\n\t\tif (a.isArray() && !checkPotentialEquality(a.getElementClass(), b.getElementClass())) return false;\n\t\tif (!checkNameObfMatch(a, b)) return false;\n\n\t\treturn true;\n\t}\n\n\tprivate static boolean checkNameObfMatch(Matchable<?> a, Matchable<?> b) {\n\t\tboolean nameObfA = a.isNameObfuscated();\n\t\tboolean nameObfB = b.isNameObfuscated();\n\n\t\tif (nameObfA && nameObfB) { // both obf\n\t\t\treturn true;\n\t\t} else if (nameObfA != nameObfB) { // one obf\n\t\t\treturn !a.getEnv().getGlobal().assumeBothOrNoneObfuscated;\n\t\t} else { // neither obf\n\t\t\treturn a.getName().equals(b.getName());\n\t\t}\n\t}\n\n\tpublic static boolean checkPotentialEquality(MethodInstance a, MethodInstance b) {\n\t\tif (a == b) return true;\n\t\tif (a.getMatch() != null) return a.getMatch() == b;\n\t\tif (b.getMatch() != null) return b.getMatch() == a;\n\t\tif (!a.isMatchable() || !b.isMatchable()) return false;\n\t\tif (!checkPotentialEquality(a.getCls(), b.getCls())) return false;\n\t\tif (!checkNameObfMatch(a, b)) return false;\n\t\tif ((a.getId().startsWith(\"<\") || b.getId().startsWith(\"<\")) && !a.getName().equals(b.getName())) return false; // require <clinit> and <init> to match\n\n\t\tMethodInstance hierarchyMatch = a.getHierarchyMatch();\n\t\tif (hierarchyMatch != null && !hierarchyMatch.getAllHierarchyMembers().contains(b)) return false;\n\n\t\tif (a.getType() == MethodType.LAMBDA_IMPL && b.getType() == MethodType.LAMBDA_IMPL) { // require same \"outer method\" for lambdas\n\t\t\tboolean found = false;\n\n\t\t\tmaLoop: for (MethodInstance ma : a.getRefsIn()) {\n\t\t\t\tfor (MethodInstance mb : b.getRefsIn()) {\n\t\t\t\t\tif (checkPotentialEquality(ma, mb)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak maLoop;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!found) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic static boolean checkPotentialEquality(FieldInstance a, FieldInstance b) {\n\t\tif (a == b) return true;\n\t\tif (a.getMatch() != null) return a.getMatch() == b;\n\t\tif (b.getMatch() != null) return b.getMatch() == a;\n\t\tif (!a.isMatchable() || !b.isMatchable()) return false;\n\t\tif (!checkPotentialEquality(a.getCls(), b.getCls())) return false;\n\t\tif (!checkNameObfMatch(a, b)) return false;\n\n\t\treturn true;\n\t}\n\n\tpublic static boolean checkPotentialEquality(MethodVarInstance a, MethodVarInstance b) {\n\t\tif (a == b) return true;\n\t\tif (a.getMatch() != null) return a.getMatch() == b;\n\t\tif (b.getMatch() != null) return b.getMatch() == a;\n\t\tif (!a.isMatchable() || !b.isMatchable()) return false;\n\t\tif (a.isArg() != b.isArg()) return false;\n\t\tif (!checkPotentialEquality(a.getMethod(), b.getMethod())) return false;\n\t\tif (!checkNameObfMatch(a, b)) return false;\n\n\t\treturn true;\n\t}\n\n\tpublic static boolean checkPotentialEqualityNullable(ClassInstance a, ClassInstance b) {\n\t\tif (a == null && b == null) return true;\n\t\tif (a == null || b == null) return false;\n\n\t\treturn checkPotentialEquality(a, b);\n\t}\n\n\tpublic static boolean checkPotentialEqualityNullable(MethodInstance a, MethodInstance b) {\n\t\tif (a == null && b == null) return true;\n\t\tif (a == null || b == null) return false;\n\n\t\treturn checkPotentialEquality(a, b);\n\t}\n\n\tpublic static boolean checkPotentialEqualityNullable(FieldInstance a, FieldInstance b) {\n\t\tif (a == null && b == null) return true;\n\t\tif (a == null || b == null) return false;\n\n\t\treturn checkPotentialEquality(a, b);\n\t}\n\n\tpublic static boolean checkPotentialEqualityNullable(MethodVarInstance a, MethodVarInstance b) {\n\t\tif (a == null && b == null) return true;\n\t\tif (a == null || b == null) return false;\n\n\t\treturn checkPotentialEquality(a, b);\n\t}\n\n\tpublic static double compareCounts(int countA, int countB) {\n\t\tint delta = Math.abs(countA - countB);\n\t\tif (delta == 0) return 1;\n\n\t\treturn 1 - (double) delta / Math.max(countA, countB);\n\t}\n\n\tpublic static <T> double compareSets(Set<T> setA, Set<T> setB, boolean readOnly) {\n\t\tif (readOnly) setB = Util.copySet(setB);\n\n\t\tint oldSize = setB.size();\n\t\tsetB.removeAll(setA);\n\n\t\tint matched = oldSize - setB.size();\n\t\tint total = setA.size() - matched + oldSize;\n\n\t\treturn total == 0 ? 1 : (double) matched / total;\n\t}\n\n\tpublic static double compareClassSets(Set<ClassInstance> setA, Set<ClassInstance> setB, boolean readOnly) {\n\t\treturn compareIdentitySets(setA, setB, readOnly, ClassifierUtil::checkPotentialEquality);\n\t}\n\n\tpublic static double compareMethodSets(Set<MethodInstance> setA, Set<MethodInstance> setB, boolean readOnly) {\n\t\treturn compareIdentitySets(setA, setB, readOnly, ClassifierUtil::checkPotentialEquality);\n\t}\n\n\tpublic static double compareFieldSets(Set<FieldInstance> setA, Set<FieldInstance> setB, boolean readOnly) {\n\t\treturn compareIdentitySets(setA, setB, readOnly, ClassifierUtil::checkPotentialEquality);\n\t}\n\n\tprivate static <T extends Matchable<T>> double compareIdentitySets(Set<T> setA, Set<T> setB, boolean readOnly, BiPredicate<T, T> comparator) {\n\t\tif (setA.isEmpty() || setB.isEmpty()) {\n\t\t\treturn setA.isEmpty() && setB.isEmpty() ? 1 : 0;\n\t\t}\n\n\t\tif (readOnly) {\n\t\t\tsetA = Util.newIdentityHashSet(setA);\n\t\t\tsetB = Util.newIdentityHashSet(setB);\n\t\t}\n\n\t\tfinal int total = setA.size() + setB.size();\n\t\tfinal boolean assumeBothOrNoneObfuscated = setA.iterator().next().getEnv().getGlobal().assumeBothOrNoneObfuscated;\n\t\tint unmatched = 0;\n\n\t\t// precise matches, nameObfuscated a\n\t\tfor (Iterator<T> it = setA.iterator(); it.hasNext(); ) {\n\t\t\tT a = it.next();\n\n\t\t\tif (setB.remove(a)) {\n\t\t\t\tit.remove();\n\t\t\t} else if (a.getMatch() != null) {\n\t\t\t\tif (!setB.remove(a.getMatch())) {\n\t\t\t\t\tunmatched++;\n\t\t\t\t}\n\n\t\t\t\tit.remove();\n\t\t\t} else if (assumeBothOrNoneObfuscated && !a.isNameObfuscated()) {\n\t\t\t\tunmatched++;\n\t\t\t\tit.remove();\n\t\t\t}\n\t\t}\n\n\t\t// nameObfuscated b\n\t\tif (assumeBothOrNoneObfuscated) {\n\t\t\tfor (Iterator<T> it = setB.iterator(); it.hasNext(); ) {\n\t\t\t\tT b = it.next();\n\n\t\t\t\tif (!b.isNameObfuscated()) {\n\t\t\t\t\tunmatched++;\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (Iterator<T> it = setA.iterator(); it.hasNext(); ) {\n\t\t\tT a = it.next();\n\n\t\t\tassert a.getMatch() == null && (!assumeBothOrNoneObfuscated || a.isNameObfuscated());\n\t\t\tboolean found = false;\n\n\t\t\tfor (T b : setB) {\n\t\t\t\tif (comparator.test(a, b)) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!found) {\n\t\t\t\tunmatched++;\n\t\t\t\tit.remove();\n\t\t\t}\n\t\t}\n\n\t\tfor (T b : setB) {\n\t\t\tboolean found = false;\n\n\t\t\tfor (T a : setA) {\n\t\t\t\tif (comparator.test(a, b)) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!found) {\n\t\t\t\tunmatched++;\n\t\t\t}\n\t\t}\n\n\t\tassert unmatched <= total;\n\n\t\treturn (double) (total - unmatched) / total;\n\t}\n\n\tpublic static double compareClassLists(List<ClassInstance> listA, List<ClassInstance> listB) {\n\t\treturn compareLists(listA, listB, List::get, List::size, (a, b) -> ClassifierUtil.checkPotentialEquality(a, b) ? COMPARED_SIMILAR : COMPARED_DISTINCT);\n\t}\n\n\tpublic static double compareInsns(MethodInstance a, MethodInstance b) {\n\t\tif (a.getAsmNode() == null || b.getAsmNode() == null) return 1;\n\n\t\tInsnList ilA = a.getAsmNode().instructions;\n\t\tInsnList ilB = b.getAsmNode().instructions;\n\n\t\treturn compareLists(ilA, ilB, InsnList::get, InsnList::size, (inA, inB) -> compareInsns(inA, inB, ilA, ilB, (list, item) -> list.indexOf(item), a, b, a.getEnv().getGlobal()));\n\t}\n\n\tpublic static double compareInsns(List<AbstractInsnNode> listA, List<AbstractInsnNode> listB, ClassEnvironment env) {\n\t\treturn compareLists(listA, listB, List::get, List::size, (inA, inB) -> compareInsns(inA, inB, listA, listB, (list, item) -> list.indexOf(item), null, null, env));\n\t}\n\n\tprivate static <T> int compareInsns(AbstractInsnNode insnA, AbstractInsnNode insnB, T listA, T listB, ToIntBiFunction<T, AbstractInsnNode> posProvider,\n\t\t\tMethodInstance mthA, MethodInstance mthB, ClassEnvironment env) {\n\t\tif (insnA.getOpcode() != insnB.getOpcode()) return COMPARED_DISTINCT;\n\n\t\tswitch (insnA.getType()) {\n\t\tcase AbstractInsnNode.INT_INSN: {\n\t\t\tIntInsnNode a = (IntInsnNode) insnA;\n\t\t\tIntInsnNode b = (IntInsnNode) insnB;\n\n\t\t\treturn a.operand == b.operand ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.VAR_INSN: {\n\t\t\tVarInsnNode a = (VarInsnNode) insnA;\n\t\t\tVarInsnNode b = (VarInsnNode) insnB;\n\n\t\t\tif (mthA != null && mthB != null) {\n\t\t\t\tMethodVarInstance varA = mthA.getArgOrVar(a.var, posProvider.applyAsInt(listA, insnA));\n\t\t\t\tMethodVarInstance varB = mthB.getArgOrVar(b.var, posProvider.applyAsInt(listB, insnB));\n\n\t\t\t\tif (varA != null && varB != null) {\n\t\t\t\t\tif (!checkPotentialEquality(varA, varB)) {\n\t\t\t\t\t\treturn COMPARED_DISTINCT;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn checkPotentialEquality(varA.getType(), varB.getType()) ? COMPARED_SIMILAR : COMPARED_POSSIBLE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.TYPE_INSN: {\n\t\t\tTypeInsnNode a = (TypeInsnNode) insnA;\n\t\t\tTypeInsnNode b = (TypeInsnNode) insnB;\n\t\t\tClassInstance clsA = env.getClsByNameA(a.desc);\n\t\t\tClassInstance clsB = env.getClsByNameB(b.desc);\n\n\t\t\treturn checkPotentialEqualityNullable(clsA, clsB) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.FIELD_INSN: {\n\t\t\tFieldInsnNode a = (FieldInsnNode) insnA;\n\t\t\tFieldInsnNode b = (FieldInsnNode) insnB;\n\t\t\tClassInstance clsA = env.getClsByNameA(a.owner);\n\t\t\tClassInstance clsB = env.getClsByNameB(b.owner);\n\n\t\t\tif (clsA == null && clsB == null) return COMPARED_SIMILAR;\n\t\t\tif (clsA == null || clsB == null) return COMPARED_DISTINCT;\n\n\t\t\tFieldInstance fieldA = clsA.resolveField(a.name, a.desc);\n\t\t\tFieldInstance fieldB = clsB.resolveField(b.name, b.desc);\n\n\t\t\treturn checkPotentialEqualityNullable(fieldA, fieldB) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.METHOD_INSN: {\n\t\t\tMethodInsnNode a = (MethodInsnNode) insnA;\n\t\t\tMethodInsnNode b = (MethodInsnNode) insnB;\n\n\t\t\treturn compareMethods(a.owner, a.name, a.desc, Util.isCallToInterface(a),\n\t\t\t\t\tb.owner, b.name, b.desc, Util.isCallToInterface(b),\n\t\t\t\t\tenv) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.INVOKE_DYNAMIC_INSN: {\n\t\t\tInvokeDynamicInsnNode a = (InvokeDynamicInsnNode) insnA;\n\t\t\tInvokeDynamicInsnNode b = (InvokeDynamicInsnNode) insnB;\n\n\t\t\tif (!a.bsm.equals(b.bsm)) return COMPARED_DISTINCT;\n\n\t\t\tif (Util.isJavaLambdaMetafactory(a.bsm)) {\n\t\t\t\tHandle implA = (Handle) a.bsmArgs[1];\n\t\t\t\tHandle implB = (Handle) b.bsmArgs[1];\n\n\t\t\t\tif (implA.getTag() != implB.getTag()) return COMPARED_DISTINCT;\n\n\t\t\t\tswitch (implA.getTag()) {\n\t\t\t\tcase Opcodes.H_INVOKEVIRTUAL:\n\t\t\t\tcase Opcodes.H_INVOKESTATIC:\n\t\t\t\tcase Opcodes.H_INVOKESPECIAL:\n\t\t\t\tcase Opcodes.H_NEWINVOKESPECIAL:\n\t\t\t\tcase Opcodes.H_INVOKEINTERFACE:\n\t\t\t\t\treturn compareMethods(implA.getOwner(), implA.getName(), implA.getDesc(), Util.isCallToInterface(implA),\n\t\t\t\t\t\t\timplB.getOwner(), implB.getName(), implB.getDesc(), Util.isCallToInterface(implB),\n\t\t\t\t\t\t\tenv) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t\t\tdefault:\n\t\t\t\t\tSystem.out.println(\"unexpected impl tag: \"+implA.getTag());\n\t\t\t\t}\n\t\t\t} else if (!Util.isIrrelevantBsm(a.bsm)) {\n\t\t\t\tSystem.out.printf(\"unknown invokedynamic bsm: %s/%s%s (tag=%d iif=%b)%n\", a.bsm.getOwner(), a.bsm.getName(), a.bsm.getDesc(), a.bsm.getTag(), a.bsm.isInterface());\n\t\t\t}\n\n\t\t\t// TODO: implement\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.JUMP_INSN: {\n\t\t\tJumpInsnNode a = (JumpInsnNode) insnA;\n\t\t\tJumpInsnNode b = (JumpInsnNode) insnB;\n\n\t\t\t// check if the 2 jumps have the same direction\n\t\t\tint dirA = Integer.signum(posProvider.applyAsInt(listA, a.label) - posProvider.applyAsInt(listA, a));\n\t\t\tint dirB = Integer.signum(posProvider.applyAsInt(listB, b.label) - posProvider.applyAsInt(listB, b));\n\n\t\t\treturn dirA == dirB ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.LABEL: {\n\t\t\t// TODO: implement\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.LDC_INSN: {\n\t\t\tLdcInsnNode a = (LdcInsnNode) insnA;\n\t\t\tLdcInsnNode b = (LdcInsnNode) insnB;\n\t\t\tClass<?> typeClsA = a.cst.getClass();\n\n\t\t\tif (typeClsA != b.cst.getClass()) return COMPARED_DISTINCT;\n\n\t\t\tif (typeClsA == Type.class) {\n\t\t\t\tType typeA = (Type) a.cst;\n\t\t\t\tType typeB = (Type) b.cst;\n\n\t\t\t\tif (typeA.getSort() != typeB.getSort()) return COMPARED_DISTINCT;\n\n\t\t\t\tswitch (typeA.getSort()) {\n\t\t\t\tcase Type.ARRAY:\n\t\t\t\tcase Type.OBJECT:\n\t\t\t\t\treturn checkPotentialEqualityNullable(env.getClsByIdA(typeA.getDescriptor()), env.getClsByIdB(typeB.getDescriptor())) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t\t\tcase Type.METHOD:\n\t\t\t\t\t// TODO: implement\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn a.cst.equals(b.cst) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.IINC_INSN: {\n\t\t\tIincInsnNode a = (IincInsnNode) insnA;\n\t\t\tIincInsnNode b = (IincInsnNode) insnB;\n\n\t\t\tif (a.incr != b.incr) return COMPARED_DISTINCT;\n\n\t\t\tif (mthA != null && mthB != null) {\n\t\t\t\tMethodVarInstance varA = mthA.getArgOrVar(a.var, posProvider.applyAsInt(listA, insnA));\n\t\t\t\tMethodVarInstance varB = mthB.getArgOrVar(b.var, posProvider.applyAsInt(listB, insnB));\n\n\t\t\t\tif (varA != null && varB != null) {\n\t\t\t\t\treturn checkPotentialEquality(varA, varB) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.TABLESWITCH_INSN: {\n\t\t\tTableSwitchInsnNode a = (TableSwitchInsnNode) insnA;\n\t\t\tTableSwitchInsnNode b = (TableSwitchInsnNode) insnB;\n\n\t\t\treturn a.min == b.min && a.max == b.max ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.LOOKUPSWITCH_INSN: {\n\t\t\tLookupSwitchInsnNode a = (LookupSwitchInsnNode) insnA;\n\t\t\tLookupSwitchInsnNode b = (LookupSwitchInsnNode) insnB;\n\n\t\t\treturn a.keys.equals(b.keys) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.MULTIANEWARRAY_INSN: {\n\t\t\tMultiANewArrayInsnNode a = (MultiANewArrayInsnNode) insnA;\n\t\t\tMultiANewArrayInsnNode b = (MultiANewArrayInsnNode) insnB;\n\n\t\t\tif (a.dims != b.dims) return COMPARED_DISTINCT;\n\n\t\t\tClassInstance clsA = env.getClsByNameA(a.desc);\n\t\t\tClassInstance clsB = env.getClsByNameB(b.desc);\n\n\t\t\treturn checkPotentialEqualityNullable(clsA, clsB) ? COMPARED_SIMILAR : COMPARED_DISTINCT;\n\t\t}\n\t\tcase AbstractInsnNode.FRAME: {\n\t\t\t// TODO: implement\n\t\t\tbreak;\n\t\t}\n\t\tcase AbstractInsnNode.LINE: {\n\t\t\t// TODO: implement\n\t\t\tbreak;\n\t\t}\n\t\t}\n\n\t\treturn COMPARED_SIMILAR;\n\t}\n\n\tprivate static boolean compareMethods(String ownerA, String nameA, String descA, boolean toIfA, String ownerB, String nameB, String descB, boolean toIfB, ClassEnvironment env) {\n\t\tClassInstance clsA = env.getClsByNameA(ownerA);\n\t\tClassInstance clsB = env.getClsByNameB(ownerB);\n\n\t\tif (clsA == null && clsB == null) return true;\n\t\tif (clsA == null || clsB == null) return false;\n\n\t\treturn compareMethods(clsA, nameA, descA, toIfA, clsB, nameB, descB, toIfB);\n\t}\n\n\tprivate static boolean compareMethods(ClassInstance ownerA, String nameA, String descA, boolean toIfA, ClassInstance ownerB, String nameB, String descB, boolean toIfB) {\n\t\tMethodInstance methodA = ownerA.resolveMethod(nameA, descA, toIfA);\n\t\tMethodInstance methodB = ownerB.resolveMethod(nameB, descB, toIfB);\n\n\t\tif (methodA == null && methodB == null) return true;\n\t\tif (methodA == null || methodB == null) return false;\n\n\t\treturn checkPotentialEquality(methodA, methodB);\n\t}\n\n\tprivate static <T, U> double compareLists(T listA, T listB, ListElementRetriever<T, U> elementRetriever, ListSizeRetriever<T> sizeRetriever, ElementComparator<U> elementComparator) {\n\t\tfinal int sizeA = sizeRetriever.apply(listA);\n\t\tfinal int sizeB = sizeRetriever.apply(listB);\n\n\t\tif (sizeA == 0 && sizeB == 0) return 1;\n\t\tif (sizeA == 0 || sizeB == 0) return 0;\n\n\t\tif (sizeA == sizeB) {\n\t\t\tboolean match = true;\n\n\t\t\tfor (int i = 0; i < sizeA; i++) {\n\t\t\t\tif (elementComparator.compare(elementRetriever.apply(listA, i), elementRetriever.apply(listB, i)) != COMPARED_SIMILAR) {\n\t\t\t\t\tmatch = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (match) return 1;\n\t\t}\n\n\t\t// levenshtein distance as per wp (https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows)\n\t\tint[] v0 = new int[sizeB + 1];\n\t\tint[] v1 = new int[sizeB + 1];\n\n\t\tfor (int i = 1; i < v0.length; i++) {\n\t\t\tv0[i] = i * COMPARED_DISTINCT;\n\t\t}\n\n\t\tfor (int i = 0; i < sizeA; i++) {\n\t\t\tv1[0] = (i + 1) * COMPARED_DISTINCT;\n\n\t\t\tfor (int j = 0; j < sizeB; j++) {\n\t\t\t\tint cost = elementComparator.compare(elementRetriever.apply(listA, i), elementRetriever.apply(listB, j));\n\t\t\t\tv1[j + 1] = Math.min(Math.min(v1[j] + COMPARED_DISTINCT, v0[j + 1] + COMPARED_DISTINCT), v0[j] + cost);\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < v0.length; j++) {\n\t\t\t\tv0[j] = v1[j];\n\t\t\t}\n\t\t}\n\n\t\tint distance = v1[sizeB];\n\t\tint upperBound = Math.max(sizeA, sizeB) * COMPARED_DISTINCT;\n\t\tassert distance >= 0 && distance <= upperBound;\n\n\t\treturn 1 - (double) distance / upperBound;\n\t}\n\n\tpublic static int[] mapInsns(MethodInstance a, MethodInstance b) {\n\t\tif (a.getAsmNode() == null || b.getAsmNode() == null) return null;\n\n\t\tInsnList ilA = a.getAsmNode().instructions;\n\t\tInsnList ilB = b.getAsmNode().instructions;\n\n\t\tif (ilA.size() * ilB.size() < 1000) {\n\t\t\treturn mapInsns(ilA, ilB, a, b, a.getEnv().getGlobal());\n\t\t} else {\n\t\t\treturn a.getEnv().getGlobal().getCache().compute(ilMapCacheToken, a, b, (mA, mB) -> mapInsns(mA.getAsmNode().instructions, mB.getAsmNode().instructions, mA, mB, mA.getEnv().getGlobal()));\n\t\t}\n\t}\n\n\tpublic static int[] mapInsns(InsnList listA, InsnList listB, MethodInstance mthA, MethodInstance mthB, ClassEnvironment env) {\n\t\treturn mapLists(listA, listB, InsnList::get, InsnList::size, (inA, inB) -> compareInsns(inA, inB, listA, listB, (list, item) -> list.indexOf(item), mthA, mthB, env));\n\t}\n\n\tprivate static <T, U> int[] mapLists(T listA, T listB, ListElementRetriever<T, U> elementRetriever, ListSizeRetriever<T> sizeRetriever, ElementComparator<U> elementComparator) {\n\t\tfinal int sizeA = sizeRetriever.apply(listA);\n\t\tfinal int sizeB = sizeRetriever.apply(listB);\n\n\t\tif (sizeA == 0 && sizeB == 0) return new int[0];\n\n\t\tfinal int[] ret = new int[sizeA];\n\n\t\tif (sizeA == 0 || sizeB == 0) {\n\t\t\tArrays.fill(ret, -1);\n\n\t\t\treturn ret;\n\t\t}\n\n\t\tif (sizeA == sizeB) {\n\t\t\tboolean match = true;\n\n\t\t\tfor (int i = 0; i < sizeA; i++) {\n\t\t\t\tif (elementComparator.compare(elementRetriever.apply(listA, i), elementRetriever.apply(listB, i)) != COMPARED_SIMILAR) {\n\t\t\t\t\tmatch = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (match) {\n\t\t\t\tfor (int i = 0; i < ret.length; i++) {\n\t\t\t\t\tret[i] = i;\n\t\t\t\t}\n\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\t// levenshtein distance as per wp (https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows)\n\t\tint size = sizeA + 1;\n\t\tint[] v = new int[size * (sizeB + 1)];\n\n\t\tfor (int i = 1; i <= sizeA; i++) {\n\t\t\tv[i + 0] = i * COMPARED_DISTINCT;\n\t\t}\n\n\t\tfor (int j = 1; j <= sizeB; j++) {\n\t\t\tv[0 + j * size] = j * COMPARED_DISTINCT;\n\t\t}\n\n\t\tfor (int j = 1; j <= sizeB; j++) {\n\t\t\tfor (int i = 1; i <= sizeA; i++) {\n\t\t\t\tint cost = elementComparator.compare(elementRetriever.apply(listA, i - 1), elementRetriever.apply(listB, j - 1));\n\n\t\t\t\tv[i + j * size] = Math.min(Math.min(v[i - 1 + j * size] + COMPARED_DISTINCT,\n\t\t\t\t\t\tv[i + (j - 1) * size] + COMPARED_DISTINCT),\n\t\t\t\t\t\tv[i - 1 + (j - 1) * size] + cost);\n\t\t\t}\n\t\t}\n\n\t\t/*for (int j = 0; j <= sizeB; j++) {\n\t\t\tfor (int i = 0; i <= sizeA; i++) {\n\t\t\t\tSystem.out.printf(\"%2d \", v[i + j * size]);\n\t\t\t}\n\n\t\t\tSystem.out.println();\n\t\t}*/\n\n\t\tint i = sizeA;\n\t\tint j = sizeB;\n\t\t//boolean valid = true;\n\n\t\twhile (i > 0 || j > 0) {\n\t\t\tint c = v[i + j * size];\n\t\t\tint delCost = i > 0 ? v[i - 1 + j * size] : Integer.MAX_VALUE;\n\t\t\tint insCost = j > 0 ? v[i + (j - 1) * size] : Integer.MAX_VALUE;\n\t\t\tint keepCost = j > 0 && i > 0 ? v[i - 1 + (j - 1) * size] : Integer.MAX_VALUE;\n\n\t\t\tif (keepCost <= delCost && keepCost <= insCost) {\n\t\t\t\tif (c - keepCost >= COMPARED_DISTINCT) {\n\t\t\t\t\tassert c - keepCost == COMPARED_DISTINCT;\n\t\t\t\t\t//System.out.printf(\"%d/%d rep %s -> %s%n\", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)), toString(elementRetriever.apply(listB, j - 1)));\n\t\t\t\t\tret[i - 1] = -1;\n\t\t\t\t} else {\n\t\t\t\t\t//System.out.printf(\"%d/%d eq %s - %s%n\", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)), toString(elementRetriever.apply(listB, j - 1)));\n\t\t\t\t\tret[i - 1] = j - 1;\n\n\t\t\t\t\t/*U e = elementRetriever.apply(listA, i - 1);\n\n\t\t\t\t\tif (e instanceof AbstractInsnNode\n\t\t\t\t\t\t\t&& ((AbstractInsnNode) e).getOpcode() != ((AbstractInsnNode) elementRetriever.apply(listB, j - 1)).getOpcode()) {\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t}*/\n\t\t\t\t}\n\n\t\t\t\ti--;\n\t\t\t\tj--;\n\t\t\t} else if (delCost < insCost) {\n\t\t\t\t//System.out.printf(\"%d/%d del %s%n\", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)));\n\t\t\t\tret[i - 1] = -1;\n\t\t\t\ti--;\n\t\t\t} else {\n\t\t\t\t//System.out.printf(\"%d/%d ins %s%n\", i-1, j-1, toString(elementRetriever.apply(listB, j - 1)));\n\t\t\t\tj--;\n\t\t\t}\n\t\t}\n\n\t\t/*if (!valid) {\n\t\t\tassert valid;\n\t\t}*/\n\n\t\treturn ret;\n\t}\n\n\tpublic interface ElementComparator<T> {\n\t\tint compare(T a, T b);\n\t}\n\n\tpublic static final int COMPARED_SIMILAR = 0;\n\tpublic static final int COMPARED_POSSIBLE = 1;\n\tpublic static final int COMPARED_DISTINCT = 2;\n\n\tprivate static String toString(Object node) {\n\t\tif (node instanceof AbstractInsnNode) {\n\t\t\tTextifier textifier = new Textifier();\n\t\t\tMethodVisitor visitor = new TraceMethodVisitor(textifier);\n\n\t\t\t((AbstractInsnNode) node).accept(visitor);\n\n\t\t\treturn textifier.getText().get(0).toString().trim();\n\t\t} else {\n\t\t\treturn Objects.toString(node);\n\t\t}\n\t}\n\n\tprivate interface ListElementRetriever<T, U> {\n\t\tU apply(T list, int pos);\n\t}\n\n\tprivate interface ListSizeRetriever<T> {\n\t\tint apply(T list);\n\t}\n\n\tpublic static <T extends Matchable<T>> List<RankResult<T>> rank(T src, T[] dsts, Collection<IClassifier<T>> classifiers, BiPredicate<T, T> potentialEqualityCheck, ClassEnvironment env, double maxMismatch) {\n\t\tList<RankResult<T>> ret = new ArrayList<>(dsts.length);\n\n\t\tfor (T dst : dsts) {\n\t\t\tRankResult<T> result = rank(src, dst, classifiers, potentialEqualityCheck, env, maxMismatch);\n\t\t\tif (result != null) ret.add(result);\n\t\t}\n\n\t\tret.sort(Comparator.<RankResult<T>, Double>comparing(RankResult::getScore).reversed());\n\n\t\treturn ret;\n\t}\n\n\tpublic static <T extends Matchable<T>> List<RankResult<T>> rankParallel(T src, T[] dsts, Collection<IClassifier<T>> classifiers, BiPredicate<T, T> potentialEqualityCheck, ClassEnvironment env, double maxMismatch) {\n\t\treturn Arrays.stream(dsts)\n\t\t\t\t.parallel()\n\t\t\t\t.map(dst -> rank(src, dst, classifiers, potentialEqualityCheck, env, maxMismatch))\n\t\t\t\t.filter(Objects::nonNull)\n\t\t\t\t.sorted(Comparator.<RankResult<T>, Double>comparing(RankResult::getScore).reversed())\n\t\t\t\t.collect(Collectors.toList());\n\t}\n\n\tprivate static <T extends Matchable<T>> RankResult<T> rank(T src, T dst, Collection<IClassifier<T>> classifiers, BiPredicate<T, T> potentialEqualityCheck, ClassEnvironment env, double maxMismatch) {\n\t\tassert src.getEnv() != dst.getEnv();\n\n\t\tif (!potentialEqualityCheck.test(src, dst)) return null;\n\n\t\tdouble score = 0;\n\t\tdouble mismatch = 0;\n\t\tList<ClassifierResult<T>> results = new ArrayList<>(classifiers.size());\n\n\t\tfor (IClassifier<T> classifier : classifiers) {\n\t\t\tdouble cScore = classifier.getScore(src, dst, env);\n\t\t\tassert cScore > -epsilon && cScore < 1 + epsilon : \"invalid score from \"+classifier.getName()+\": \"+cScore;\n\n\t\t\tdouble weight = classifier.getWeight();\n\t\t\tdouble weightedScore = cScore * weight;\n\n\t\t\tmismatch += weight - weightedScore;\n\t\t\tif (mismatch >= maxMismatch) return null;\n\n\t\t\tscore += weightedScore;\n\t\t\tresults.add(new ClassifierResult<>(classifier, cScore));\n\t\t}\n\n\t\treturn new RankResult<>(dst, score, results);\n\t}\n\n\tpublic static void extractStrings(InsnList il, Set<String> out) {\n\t\textractStrings(il.iterator(), out);\n\t}\n\n\tpublic static void extractStrings(Collection<AbstractInsnNode> il, Set<String> out) {\n\t\textractStrings(il.iterator(), out);\n\t}\n\n\tprivate static void extractStrings(Iterator<AbstractInsnNode> it, Set<String> out) {\n\t\twhile (it.hasNext()) {\n\t\t\tAbstractInsnNode aInsn = it.next();\n\n\t\t\tif (aInsn instanceof LdcInsnNode) {\n\t\t\t\tLdcInsnNode insn = (LdcInsnNode) aInsn;\n\n\t\t\t\tif (insn.cst instanceof String) {\n\t\t\t\t\tout.add((String) insn.cst);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void extractNumbers(MethodNode node, Set<Integer> ints, Set<Long> longs, Set<Float> floats, Set<Double> doubles) {\n\t\tfor (Iterator<AbstractInsnNode> it = node.instructions.iterator(); it.hasNext(); ) {\n\t\t\tAbstractInsnNode aInsn = it.next();\n\n\t\t\tif (aInsn instanceof LdcInsnNode) {\n\t\t\t\tLdcInsnNode insn = (LdcInsnNode) aInsn;\n\n\t\t\t\thandleNumberValue(insn.cst, ints, longs, floats, doubles);\n\t\t\t} else if (aInsn instanceof IntInsnNode) {\n\t\t\t\tIntInsnNode insn = (IntInsnNode) aInsn;\n\n\t\t\t\tints.add(insn.operand);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void handleNumberValue(Object number, Set<Integer> ints, Set<Long> longs, Set<Float> floats, Set<Double> doubles) {\n\t\tif (number == null) return;\n\n\t\tif (number instanceof Integer) {\n\t\t\tints.add((Integer) number);\n\t\t} else if (number instanceof Long) {\n\t\t\tlongs.add((Long) number);\n\t\t} else if (number instanceof Float) {\n\t\t\tfloats.add((Float) number);\n\t\t} else if (number instanceof Double) {\n\t\t\tdoubles.add((Double) number);\n\t\t}\n\t}\n\n\tpublic static <T extends Matchable<T>> double classifyPosition(T a, T b,\n\t\t\tToIntFunction<T> positionSupplier,\n\t\t\tBiFunction<T, Integer, T> siblingSupplier,\n\t\t\tFunction<T, T[]> siblingsSupplier) {\n\t\tint posA = positionSupplier.applyAsInt(a);\n\t\tint posB = positionSupplier.applyAsInt(b);\n\t\tT[] siblingsA = siblingsSupplier.apply(a);\n\t\tT[] siblingsB = siblingsSupplier.apply(b);\n\n\t\tif (posA == posB && siblingsA.length == siblingsB.length) return 1;\n\t\tif (posA == -1 || posB == -1) return posA == posB ? 1 : 0;\n\n\t\t// try to find the index range enclosed by other mapped members and compare relative to it\n\t\tint startPosA = 0;\n\t\tint startPosB = 0;\n\t\tint endPosA = siblingsA.length;\n\t\tint endPosB = siblingsB.length;\n\n\t\tif (posA > 0) {\n\t\t\tfor (int i = posA - 1; i >= 0; i--) {\n\t\t\t\tT c = siblingSupplier.apply(a, i);\n\t\t\t\tT match = c.getMatch();\n\n\t\t\t\tif (match != null) {\n\t\t\t\t\tstartPosA = i + 1;\n\t\t\t\t\tstartPosB = positionSupplier.applyAsInt(match) + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (posA < endPosA - 1) {\n\t\t\tfor (int i = posA + 1; i < endPosA; i++) {\n\t\t\t\tT c = siblingSupplier.apply(a, i);\n\t\t\t\tT match = c.getMatch();\n\n\t\t\t\tif (match != null) {\n\t\t\t\t\tendPosA = i;\n\t\t\t\t\tendPosB = positionSupplier.applyAsInt(match);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (startPosB >= endPosB || startPosB > posB || endPosB <= posB) {\n\t\t\tstartPosA = startPosB = 0;\n\t\t\tendPosA = siblingsA.length;\n\t\t\tendPosB = siblingsB.length;\n\t\t}\n\n\t\tdouble relPosA = getRelativePosition(posA - startPosA, endPosA - startPosA);\n\t\tassert relPosA >= 0 && relPosA <= 1;\n\t\tdouble relPosB = getRelativePosition(posB - startPosB, endPosB - startPosB);\n\t\tassert relPosB >= 0 && relPosB <= 1;\n\n\t\treturn 1 - Math.abs(relPosA - relPosB);\n\t}\n\n\tprivate static double getRelativePosition(int position, int size) {\n\t\tif (size == 1) return 0.5;\n\t\tassert size > 1;\n\n\t\treturn (double) position / (size - 1);\n\t}\n\n\tprivate static final double epsilon = 1e-6;\n\n\tprivate static final CacheToken<int[]> ilMapCacheToken = new CacheToken<>();\n}",
"public class MatchingCache {\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T, U extends Matchable<U>> T get(CacheToken<T> token, U a, U b) {\n\t\treturn (T) cache.get(new CacheKey<U>(token, a, b));\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T, U extends Matchable<U>> T compute(CacheToken<T> token, U a, U b, BiFunction<U, U, T> f) {\n\t\treturn (T) cache.computeIfAbsent(new CacheKey<U>(token, a, b), k -> f.apply((U) k.a, (U) k.b));\n\t}\n\n\tpublic void clear() {\n\t\tcache.clear();\n\t}\n\n\tpublic static final class CacheToken<t> {}\n\n\tprivate static class CacheKey<T extends Matchable<T>> {\n\t\tpublic CacheKey(CacheToken<?> token, T a, T b) {\n\t\t\tthis.token = token;\n\t\t\tthis.a = a;\n\t\t\tthis.b = b;\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn token.hashCode() ^ a.hashCode() ^ b.hashCode();\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (obj.getClass() != CacheKey.class) return false;\n\n\t\t\tCacheKey<?> o = (CacheKey<?>) obj;\n\n\t\t\treturn token == o.token && a == o.a && b == o.b;\n\t\t}\n\n\t\tfinal CacheToken<?> token;\n\t\tfinal T a;\n\t\tfinal T b;\n\t}\n\n\tprivate final Map<CacheKey<?>, Object> cache = new ConcurrentHashMap<>();\n}",
"public class ProjectConfig {\n\tpublic ProjectConfig() {\n\t\tthis(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), false, \"\", \"\", \"\", \"\");\n\t}\n\n\tProjectConfig(Preferences prefs) throws BackingStoreException {\n\t\tthis(Config.loadList(prefs, pathsAKey, Config::deserializePath),\n\t\t\t\tConfig.loadList(prefs, pathsBKey, Config::deserializePath),\n\t\t\t\tConfig.loadList(prefs, classPathAKey, Config::deserializePath),\n\t\t\t\tConfig.loadList(prefs, classPathBKey, Config::deserializePath),\n\t\t\t\tConfig.loadList(prefs, pathsSharedKey, Config::deserializePath),\n\t\t\t\tprefs.getBoolean(inputsBeforeClassPathKey, false),\n\t\t\t\tprefs.get(nonObfuscatedClassPatternAKey, \"\"),\n\t\t\t\tprefs.get(nonObfuscatedClassPatternBKey, \"\"),\n\t\t\t\tprefs.get(nonObfuscatedMemberPatternAKey, \"\"),\n\t\t\t\tprefs.get(nonObfuscatedMemberPatternBKey, \"\"));\n\t}\n\n\tpublic ProjectConfig(List<Path> pathsA, List<Path> pathsB, List<Path> classPathA, List<Path> classPathB, List<Path> sharedClassPath, boolean inputsBeforeClassPath,\n\t\t\tString nonObfuscatedClassesPatternA, String nonObfuscatedClassesPatternB, String nonObfuscatedMemberPatternA, String nonObfuscatedMemberPatternB) {\n\t\tthis.pathsA = pathsA;\n\t\tthis.pathsB = pathsB;\n\t\tthis.classPathA = classPathA;\n\t\tthis.classPathB = classPathB;\n\t\tthis.sharedClassPath = sharedClassPath;\n\t\tthis.inputsBeforeClassPath = inputsBeforeClassPath;\n\t\tthis.nonObfuscatedClassPatternA = nonObfuscatedClassesPatternA;\n\t\tthis.nonObfuscatedClassPatternB = nonObfuscatedClassesPatternB;\n\t\tthis.nonObfuscatedMemberPatternA = nonObfuscatedMemberPatternA;\n\t\tthis.nonObfuscatedMemberPatternB = nonObfuscatedMemberPatternB;\n\t}\n\n\tpublic List<Path> getPathsA() {\n\t\treturn pathsA;\n\t}\n\n\tpublic List<Path> getPathsB() {\n\t\treturn pathsB;\n\t}\n\n\tpublic List<Path> getClassPathA() {\n\t\treturn classPathA;\n\t}\n\n\tpublic List<Path> getClassPathB() {\n\t\treturn classPathB;\n\t}\n\n\tpublic List<Path> getSharedClassPath() {\n\t\treturn sharedClassPath;\n\t}\n\n\tpublic boolean hasInputsBeforeClassPath() {\n\t\treturn inputsBeforeClassPath;\n\t}\n\n\tpublic String getNonObfuscatedClassPatternA() {\n\t\treturn nonObfuscatedClassPatternA;\n\t}\n\n\tpublic String getNonObfuscatedClassPatternB() {\n\t\treturn nonObfuscatedClassPatternB;\n\t}\n\n\tpublic String getNonObfuscatedMemberPatternA() {\n\t\treturn nonObfuscatedMemberPatternA;\n\t}\n\n\tpublic String getNonObfuscatedMemberPatternB() {\n\t\treturn nonObfuscatedMemberPatternB;\n\t}\n\n\tpublic boolean isValid() {\n\t\treturn !pathsA.isEmpty()\n\t\t\t\t&& !pathsB.isEmpty()\n\t\t\t\t&& Collections.disjoint(pathsA, pathsB)\n\t\t\t\t&& Collections.disjoint(pathsA, sharedClassPath)\n\t\t\t\t&& Collections.disjoint(pathsB, sharedClassPath)\n\t\t\t\t//&& Collections.disjoint(classPathA, classPathB)\n\t\t\t\t&& Collections.disjoint(classPathA, pathsA)\n\t\t\t\t&& Collections.disjoint(classPathB, pathsA)\n\t\t\t\t&& Collections.disjoint(classPathA, pathsB)\n\t\t\t\t&& Collections.disjoint(classPathB, pathsB)\n\t\t\t\t&& Collections.disjoint(classPathA, sharedClassPath)\n\t\t\t\t&& Collections.disjoint(classPathB, sharedClassPath)\n\t\t\t\t&& tryCompilePattern(nonObfuscatedClassPatternA)\n\t\t\t\t&& tryCompilePattern(nonObfuscatedClassPatternB)\n\t\t\t\t&& tryCompilePattern(nonObfuscatedMemberPatternA)\n\t\t\t\t&& tryCompilePattern(nonObfuscatedMemberPatternB);\n\t}\n\n\tprivate static boolean tryCompilePattern(String regex) {\n\t\ttry {\n\t\t\tPattern.compile(regex);\n\t\t\treturn true;\n\t\t} catch (PatternSyntaxException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tvoid save(Preferences prefs) throws BackingStoreException {\n\t\tif (!isValid()) return;\n\n\t\tConfig.saveList(prefs.node(pathsAKey), pathsA);\n\t\tConfig.saveList(prefs.node(pathsBKey), pathsB);\n\t\tConfig.saveList(prefs.node(classPathAKey), classPathA);\n\t\tConfig.saveList(prefs.node(classPathBKey), classPathB);\n\t\tConfig.saveList(prefs.node(pathsSharedKey), sharedClassPath);\n\t\tprefs.putBoolean(inputsBeforeClassPathKey, inputsBeforeClassPath);\n\t\tprefs.put(nonObfuscatedClassPatternAKey, nonObfuscatedClassPatternA);\n\t\tprefs.put(nonObfuscatedClassPatternBKey, nonObfuscatedClassPatternB);\n\t\tprefs.put(nonObfuscatedMemberPatternAKey, nonObfuscatedMemberPatternA);\n\t\tprefs.put(nonObfuscatedMemberPatternBKey, nonObfuscatedMemberPatternB);\n\t}\n\n\tprivate static final String pathsAKey = \"paths-a\";\n\tprivate static final String pathsBKey = \"paths-b\";\n\tprivate static final String classPathAKey = \"class-path-a\";\n\tprivate static final String classPathBKey = \"class-path-b\";\n\tprivate static final String pathsSharedKey = \"paths-shared\";\n\tprivate static final String inputsBeforeClassPathKey = \"inputs-before-classpath\";\n\tprivate static final String nonObfuscatedClassPatternAKey = \"non-obfuscated-class-pattern-a\";\n\tprivate static final String nonObfuscatedClassPatternBKey = \"non-obfuscated-class-pattern-b\";\n\tprivate static final String nonObfuscatedMemberPatternAKey = \"non-obfuscated-member-pattern-a\";\n\tprivate static final String nonObfuscatedMemberPatternBKey = \"non-obfuscated-member-pattern-b\";\n\n\tprivate final List<Path> pathsA;\n\tprivate final List<Path> pathsB;\n\tprivate final List<Path> classPathA;\n\tprivate final List<Path> classPathB;\n\tprivate final List<Path> sharedClassPath;\n\tprivate final boolean inputsBeforeClassPath;\n\tprivate final String nonObfuscatedClassPatternA;\n\tprivate final String nonObfuscatedClassPatternB;\n\tprivate final String nonObfuscatedMemberPatternA;\n\tprivate final String nonObfuscatedMemberPatternB;\n}",
"public interface Decompiler {\n\tString decompile(ClassInstance cls, ClassFeatureExtractor extractor, NameType nameType);\n}",
"public static final class ClassSignature implements PotentialComparable<ClassSignature> {\n\tpublic static ClassSignature parse(String sig, ClassEnv env) {\n\t\t// [<TypeParameter+>] ClassTypeSignature ClassTypeSignature*\n\t\tClassSignature ret = new ClassSignature();\n\t\tMutableInt pos = new MutableInt();\n\n\t\tif (sig.startsWith(\"<\")) {\n\t\t\tpos.val++;\n\t\t\tret.typeParameters = new ArrayList<>();\n\n\t\t\tdo {\n\t\t\t\tret.typeParameters.add(TypeParameter.parse(sig, pos, env));\n\t\t\t} while (sig.charAt(pos.val) != '>');\n\n\t\t\tpos.val++;\n\t\t}\n\n\t\tret.superClassSignature = ClassTypeSignature.parse(sig, pos, env);\n\n\t\tif (pos.val < sig.length()) {\n\t\t\tret.superInterfaceSignatures = new ArrayList<>();\n\n\t\t\tdo {\n\t\t\t\tret.superInterfaceSignatures.add(ClassTypeSignature.parse(sig, pos, env));\n\t\t\t} while (pos.val < sig.length());\n\t\t}\n\n\t\tassert ret.toString().equals(sig);\n\n\t\treturn ret;\n\t}\n\n\tpublic String toString(NameType nameType) {\n\t\tStringBuilder ret = new StringBuilder();\n\n\t\tif (typeParameters != null) {\n\t\t\tret.append('<');\n\n\t\t\tfor (TypeParameter tp : typeParameters) {\n\t\t\t\tret.append(tp.toString(nameType));\n\t\t\t}\n\n\t\t\tret.append('>');\n\t\t}\n\n\t\tret.append(superClassSignature.toString(nameType));\n\n\t\tif (superInterfaceSignatures != null) {\n\t\t\tfor (ClassTypeSignature ts : superInterfaceSignatures) {\n\t\t\t\tret.append(ts.toString(nameType));\n\t\t\t}\n\t\t}\n\n\t\treturn ret.toString();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn toString(NameType.PLAIN);\n\t}\n\n\t@Override\n\tpublic boolean isPotentiallyEqual(ClassSignature o) {\n\t\treturn Signature.isPotentiallyEqual(typeParameters, o.typeParameters)\n\t\t\t\t&& superClassSignature.isPotentiallyEqual(o.superClassSignature)\n\t\t\t\t&& Signature.isPotentiallyEqual(superInterfaceSignatures, o.superInterfaceSignatures);\n\t}\n\n\t// [<\n\tList<TypeParameter> typeParameters;\n\t// >]\n\tClassTypeSignature superClassSignature;\n\tList<ClassTypeSignature> superInterfaceSignatures;\n}"
] | import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.DoubleConsumer;
import java.util.regex.Pattern;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InnerClassNode;
import org.objectweb.asm.tree.MethodNode;
import matcher.NameType;
import matcher.Util;
import matcher.classifier.ClassifierUtil;
import matcher.classifier.MatchingCache;
import matcher.config.ProjectConfig;
import matcher.srcprocess.Decompiler;
import matcher.type.Signature.ClassSignature; | }
}
if (!createUnknown) return null;
ClassInstance ret = new ClassInstance(id, this);
addSharedCls(ret);
return ret;
}
private Path getPath(URL url) {
URI uri = null;
try {
uri = url.toURI();
Path ret = Paths.get(uri);
if (uri.getScheme().equals("jrt") && !Files.exists(ret)) {
// workaround for https://bugs.openjdk.java.net/browse/JDK-8224946
ret = Paths.get(new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), "/modules".concat(uri.getPath()), uri.getQuery(), uri.getFragment()));
}
return ret;
} catch (URISyntaxException e) {
throw new RuntimeException(e);
} catch (FileSystemNotFoundException e) {
try {
addOpenFileSystem(FileSystems.newFileSystem(uri, Collections.emptyMap()));
return Paths.get(uri);
} catch (FileSystemNotFoundException e2) {
throw new RuntimeException("can't find fs for "+url, e2);
} catch (IOException e2) {
throw new UncheckedIOException(e2);
}
}
}
static URI getContainingUri(URI uri, String clsName) {
String path;
if (uri.getScheme().equals("jar")) {
path = uri.getSchemeSpecificPart();
int pos = path.lastIndexOf("!/");
if (pos > 0) {
try {
return new URI(path.substring(0, pos));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
} else {
throw new UnsupportedOperationException("jar uri without !/: "+uri);
}
} else {
path = uri.getPath();
}
if (path == null) {
throw new UnsupportedOperationException("uri without path: "+uri);
}
int rootPos = path.length() - ".class".length() - clsName.length();
if (rootPos <= 0 || !path.endsWith(".class") || !path.startsWith(clsName, rootPos)) {
throw new UnsupportedOperationException("unknown path format: "+uri);
}
path = path.substring(0, rootPos - 1);
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path, uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
static ClassNode readClass(Path path, boolean skipCode) {
try {
ClassReader reader = new ClassReader(Files.readAllBytes(path));
ClassNode cn = new ClassNode();
reader.accept(cn, ClassReader.EXPAND_FRAMES | (skipCode ? ClassReader.SKIP_CODE : 0));
return cn;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* 1st class processing pass, member+class hierarchy and signature initialization.
*
* Only the (known) classes are fully available at this point.
*/
static void processClassA(ClassInstance cls, Pattern nonObfuscatedMemberPattern) {
assert !cls.isInput() || !cls.isShared();
Set<String> strings = cls.strings;
for (ClassNode cn : cls.getAsmNodes()) {
if (cls.isInput() && cls.getSignature() == null && cn.signature != null) {
cls.setSignature(ClassSignature.parse(cn.signature, cls.getEnv()));
}
boolean isEnum = (cn.access & Opcodes.ACC_ENUM) != 0;
for (int i = 0; i < cn.methods.size(); i++) {
MethodNode mn = cn.methods.get(i);
if (cls.getMethod(mn.name, mn.desc) == null) {
boolean nameObfuscated = cls.isInput()
&& !mn.name.equals("<clinit>")
&& !mn.name.equals("<init>")
&& (!mn.name.equals("main") || !mn.desc.equals("([Ljava/lang/String;)V") || mn.access != (Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC))
&& (!isEnum || !isStandardEnumMethod(cn.name, mn))
&& (nonObfuscatedMemberPattern == null || !nonObfuscatedMemberPattern.matcher(cn.name+"/"+mn.name+mn.desc).matches());
cls.addMethod(new MethodInstance(cls, mn.name, mn.desc, mn, nameObfuscated, i));
| ClassifierUtil.extractStrings(mn.instructions, strings); | 2 |
caseydavenport/biermacht | src/com/biermacht/brews/xml/RecipeXmlWriter.java | [
"public class Fermentable extends Ingredient implements Parcelable {\n\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n // Name - Inherited\n // Version - Inherited\n private String type; // Grain, Extract, Adjunct\n private double yield; // Dry yeild / raw yield\n private double color; // Color in Lovibond (SRM)\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private boolean addAfterBoil; // True if added after boil\n private double maxInBatch; // Max reccomended in this batch\n\n // Custom Fields ==================================================\n // ================================================================\n private String description; // Description of fermentable\n\n // Static values =================================================\n // ===============================================================\n public static final String TYPE_GRAIN = \"Grain\";\n public static final String TYPE_EXTRACT = \"Extract\";\n public static final String TYPE_ADJUNCT = \"Adjunct\";\n public static final String TYPE_SUGAR = \"Sugar\";\n\n public Fermentable(String name) {\n super(name);\n this.type = TYPE_GRAIN;\n this.amount = 0;\n this.yield = 1;\n this.color = 0;\n this.addAfterBoil = false;\n this.setMaxInBatch(0);\n this.description = \"No description provided.\";\n }\n\n public Fermentable(Parcel p) {\n super(p);\n type = p.readString();\n yield = p.readDouble();\n color = p.readDouble();\n addAfterBoil = p.readInt() > 0;\n maxInBatch = p.readDouble();\n description = p.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n super.writeToParcel(p, flags);\n p.writeString(type); // Grain, Extract, Adjunct\n p.writeDouble(yield); // Dry yeild / raw yield\n p.writeDouble(color); // Color in Lovibond (SRM)\n p.writeInt(addAfterBoil ? 1 : 0); // True if added after boil\n p.writeDouble(maxInBatch); // Max reccomended in this batch\n p.writeString(description); // Description of fermentable\n }\n\n public static final Parcelable.Creator<Fermentable> CREATOR =\n new Parcelable.Creator<Fermentable>() {\n @Override\n public Fermentable createFromParcel(Parcel p) {\n return new Fermentable(p);\n }\n\n @Override\n public Fermentable[] newArray(int size) {\n return null;\n }\n };\n\n @Override\n public String getType() {\n return Ingredient.FERMENTABLE;\n }\n\n public double getLovibondColor() {\n color = (float) Math.round(color * 10) / 10;\n return color;\n }\n\n public void setLovibondColor(double color) {\n color = (float) Math.round(color * 10) / 10;\n this.color = color;\n }\n\n public double getGravity() {\n return yieldToGravity(yield);\n }\n\n public void setGravity(double gravity) {\n this.yield = gravityToYield(gravity);\n }\n\n public float getPpg() {\n return (float) (this.yield * 46) / 100;\n }\n\n public String getFermentableType() {\n return type;\n }\n\n public void setFermentableType(String type) {\n if (! Constants.FERMENTABLE_TYPES.contains(type)) {\n Log.e(\"Fermentable\", \"Setting invalid fermentable type: \" + type);\n }\n this.type = type;\n }\n\n @Override\n public double getDisplayAmount() {\n if (getDisplayUnits().equals(Units.POUNDS)) {\n return Units.kilosToPounds(this.amount);\n }\n else {\n return this.amount;\n }\n }\n\n @Override\n public double getBeerXmlStandardAmount() {\n return this.amount;\n }\n\n @Override\n public void setDisplayAmount(double amt) {\n if (getDisplayUnits().equals(Units.POUNDS)) {\n this.amount = Units.poundsToKilos(amt);\n }\n else {\n this.amount = amt;\n }\n }\n\n @Override\n public void setBeerXmlStandardAmount(double amt) {\n this.amount = amt;\n }\n\n @Override\n public int hashCode() {\n int hc = this.getName().hashCode();\n hc += this.getLovibondColor();\n hc |= (int) this.getGravity() * 1234;\n hc += (int) this.getBeerXmlStandardAmount();\n hc |= this.getType().hashCode();\n return hc;\n }\n\n @Override\n public String getDisplayUnits() {\n return Units.getFermentableUnits();\n }\n\n @Override\n public void setDisplayUnits(String s) {\n }\n\n @Override\n public String getBeerXmlStandardUnits() {\n return Units.KILOGRAMS;\n }\n\n /**\n * Evaluates equality of this Fermentable and the given Object.\n *\n * @param o\n * @return true if this Fermentable equals Object o, false otherwise.\n */\n @Override\n public boolean equals(Object o) {\n if (o instanceof Fermentable) {\n // Compare to other.\n return this.compareTo((Fermentable) o) == 0;\n }\n\n // Not a fermentable, and so is not equal.\n return false;\n }\n\n @Override\n public int getTime() {\n return time;\n }\n\n @Override\n public void setTime(int time) {\n this.time = time;\n }\n\n /**\n * @return the yield\n */\n public double getYield() {\n return yield;\n }\n\n /**\n * @param yield\n * the yield to set\n */\n public void setYield(double yield) {\n this.yield = yield;\n }\n\n /**\n * @return the addAfterBoil\n */\n public boolean isAddAfterBoil() {\n return addAfterBoil;\n }\n\n /**\n * @param addAfterBoil\n * the addAfterBoil to set\n */\n public void setAddAfterBoil(boolean addAfterBoil) {\n this.addAfterBoil = addAfterBoil;\n }\n\n @Override\n public void setShortDescription(String description) {\n this.description = description;\n }\n\n @Override\n public String getShortDescription() {\n return this.description;\n }\n\n /**\n * @return the maxInBatch\n */\n public double getMaxInBatch() {\n return maxInBatch;\n }\n\n @Override\n public String getUse() {\n if (this.getFermentableType().equals(TYPE_EXTRACT) ||\n this.getFermentableType().equals(TYPE_SUGAR)) {\n // Sugars and Extracts should be boiled.\n return Ingredient.USE_BOIL;\n }\n else {\n // Everything else should be mashed. Grains, Adjuncts.\n return Ingredient.USE_MASH;\n }\n }\n\n /**\n * @param maxInBatch\n * the maxInBatch to set\n */\n public void setMaxInBatch(double maxInBatch) {\n this.maxInBatch = maxInBatch;\n }\n\n /**\n * Turns given gravity into a yield\n *\n * @param gravity\n * @return\n */\n public double gravityToYield(double gravity) {\n double yield = 0;\n\n yield = gravity - 1;\n yield = yield * 1000;\n yield = yield * 100 / 46;\n\n return yield;\n }\n\n /**\n *\n * @return The gravity points contributed by this fermentable.\n */\n public double gravityPoints() {\n return this.getPpg() * Units.kilosToPounds(this.amount);\n }\n\n /**\n * turns given yield into a gravity\n *\n * @param yield\n * @return\n */\n public double yieldToGravity(double yield) {\n return 1 + (((yield * 46) / 100) / 1000);\n }\n\n /**\n * Compares the given Ingredient to this Fermentable and returns and indicator of (in)equality.\n *\n * @param other\n * The Ingredient with which to compare this Fermentable\n * @return 0 if argument is equal to this, < 0 if argument is greater than this, > 0 if argument\n * is less than this\n */\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type of Ingredient, sort based on Ingredient type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n Fermentable f = (Fermentable) other;\n\n // If they are both Fermentables, sort based on amount.\n int amountCompare = Double.compare(f.getBeerXmlStandardAmount(), this.getBeerXmlStandardAmount());\n if (amountCompare != 0) {\n return amountCompare;\n }\n\n // Sort based on name.\n int nameCompare = this.getName().compareTo(f.getName());\n if (nameCompare != 0) {\n return nameCompare;\n }\n\n // Sort based on color.\n int colorCompare = Double.compare(this.getLovibondColor(), f.getLovibondColor());\n if (colorCompare != 0) {\n return colorCompare;\n }\n\n // Sort based on gravity.\n int gravCompare = Double.compare(this.getGravity(), f.getGravity());\n if (gravCompare != 0) {\n return gravCompare;\n }\n\n // If all the above are equal, they are the same.\n return 0;\n }\n}",
"public class Hop extends Ingredient {\n\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n\n // Name - Inherited\n // Version - Inherited\n private double alpha; // Alpha in %\n private String use; // Boil, Dry Hop, etc\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private String type; // Bittering, Armoa, Both\n private String form; // Pellet, plug, whole\n private String origin; // Place of origin\n private ArrayList<String> substitutes; // Substitute options\n\n // Custom Fields ==================================================\n // ================================================================\n private String description; // Short description of flavor / use\n\n // Static values =================================================\n // ===============================================================\n public static final String FORM_PELLET = \"Pellet\";\n public static final String FORM_WHOLE = \"Whole\";\n public static final String FORM_PLUG = \"Plug\";\n\n // Hop types\n public static final String TYPE_BITTERING = \"Bittering\";\n public static final String TYPE_AROMA = \"Aromatic\";\n public static final String TYPE_BOTH = \"Bittering / Aromatic\";\n\n public Hop(String name) {\n super(name);\n this.amount = 0;\n this.alpha = 0;\n this.use = USE_BOIL;\n this.type = TYPE_BOTH;\n this.form = FORM_PELLET;\n this.origin = \"\";\n this.substitutes = new ArrayList<String>(); // TODO Get this from somewhere\n this.description = \"No description\";\n }\n\n public Hop(Parcel p) {\n super(p);\n this.substitutes = new ArrayList<String>();\n alpha = p.readDouble();\n use = p.readString();\n\n type = p.readString();\n form = p.readString();\n origin = p.readString();\n p.readStringList(this.substitutes);\n description = p.readString();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n super.writeToParcel(p, flags);\n\n // Required\n p.writeDouble(alpha);\n p.writeString(use);\n\n // Optional\n p.writeString(type);\n p.writeString(form);\n p.writeString(origin);\n p.writeStringList(substitutes);\n p.writeString(description);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<Hop> CREATOR =\n new Parcelable.Creator<Hop>() {\n @Override\n public Hop createFromParcel(Parcel p) {\n return new Hop(p);\n }\n\n @Override\n public Hop[] newArray(int size) {\n return null;\n }\n };\n\n @Override\n public String getType() {\n return Ingredient.HOP;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public double getAlphaAcidContent() {\n return alpha;\n }\n\n public void setAlphaAcidContent(double alpha) {\n this.alpha = alpha;\n }\n\n @Override\n public String getShortDescription() {\n return this.description;\n }\n\n @Override\n public double getDisplayAmount() {\n if (getDisplayUnits().equals(Units.OUNCES)) {\n return Units.kilosToOunces(this.amount);\n }\n else {\n return Units.kilosToGrams(this.amount);\n }\n }\n\n public int getDisplayTime() {\n if (this.getUse().equals(Hop.USE_DRY_HOP)) {\n return (int) Units.minutesToDays(this.time);\n }\n else {\n return this.time;\n }\n }\n\n public void setDisplayTime(int time) {\n if (this.getUse().equals(Hop.USE_DRY_HOP)) {\n this.time = (int) Units.daysToMinutes(time);\n }\n else {\n this.time = time;\n }\n }\n\n @Override\n public double getBeerXmlStandardAmount() {\n return this.amount;\n }\n\n @Override\n public void setDisplayAmount(double amt) {\n if (getDisplayUnits().equals(Units.OUNCES)) {\n this.amount = Units.ouncesToKilos(amt);\n }\n else {\n this.amount = Units.gramsToKilos(amt);\n }\n }\n\n @Override\n public void setBeerXmlStandardAmount(double amt) {\n this.amount = amt;\n }\n\n public String getForm() {\n return form;\n }\n\n public void setForm(String form) {\n this.form = form;\n }\n\n @Override\n public String getDisplayUnits() {\n return Units.getHopUnits();\n }\n\n public void setDisplayUnits(String s) {\n }\n\n @Override\n public String getBeerXmlStandardUnits() {\n return Units.KILOGRAMS;\n }\n\n @Override\n public int hashCode() {\n int hc = this.getName().hashCode();\n hc = hc ^ (int) (getAlphaAcidContent() * 1234);\n hc += this.getTime();\n hc += this.getUse().hashCode();\n hc += this.getType().hashCode();\n return hc;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o instanceof Hop) {\n return this.compareTo((Hop) o) == 0;\n }\n return false;\n }\n\n /**\n * @return the use\n */\n public String getUse() {\n return use;\n }\n\n /**\n * @param use\n * the use to set\n */\n public void setUse(String use) {\n this.use = use;\n }\n\n /**\n * @return the time\n */\n public int getBeerXmlStandardTime() {\n return time;\n }\n\n @Override\n public int getTime() {\n return this.getDisplayTime();\n }\n\n @Override\n public void setTime(int time) {\n setDisplayTime(time);\n }\n\n /**\n * @return the origin\n */\n public String getOrigin() {\n return origin;\n }\n\n /**\n * @param origin\n * the origin to set\n */\n public void setOrigin(String origin) {\n this.origin = origin;\n }\n\n /**\n * @return the substitutes\n */\n public ArrayList<String> getSubstitutes() {\n return substitutes;\n }\n\n /**\n * @param substitutes\n * the substitutes to set\n */\n public void setSubstitutes(ArrayList<String> substitutes) {\n this.substitutes = substitutes;\n }\n\n /**\n * @return the hopType\n */\n public String getHopType() {\n return type;\n }\n\n /**\n * @param type\n * the hopType to set\n */\n public void setHopType(String type) {\n this.type = type;\n }\n\n /**\n * @param time\n * the time to set\n */\n public void setBeerXmlStandardTime(int time) {\n this.time = time;\n }\n\n @Override\n public void setShortDescription(String description) {\n this.description = description;\n }\n\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type, sort based on type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n Hop h = (Hop) other;\n\n // If they are not the same use, sort based on use.\n if (! this.getUse().equals(other.getUse())) {\n return this.getUse().compareTo(other.getUse());\n }\n\n // Sort based on time.\n int timeCompare = Double.compare(h.getTime(), this.getTime());\n if (timeCompare != 0) {\n return timeCompare;\n }\n\n // Sort based on name.\n int nameCompare = this.getName().compareTo(h.getName());\n if (nameCompare != 0) {\n return nameCompare;\n }\n\n // Sort based on alpha acid.\n int alphaCompare = Double.compare(this.getAlphaAcidContent(), h.getAlphaAcidContent());\n if (alphaCompare != 0) {\n return alphaCompare;\n }\n\n // If all else is the same, they are equal.\n return 0;\n }\n}",
"public class Misc extends Ingredient {\n\n // Beer XML 1.0 Required Fields (To be inherited) =================\n // ================================================================\n private String miscType;\n private String use;\n private boolean amountIsWeight;\n private String useFor;\n private String notes;\n\n // Custom Fields ==================================================\n // ================================================================\n private String displayUnits;\n\n // Static values =================================================\n // ===============================================================\n public static String TYPE_SPICE = \"Spice\";\n public static String TYPE_FINING = \"Fining\";\n public static String TYPE_WATER_AGENT = \"Water Agent\";\n public static String TYPE_HERB = \"Herb\";\n public static String TYPE_FLAVOR = \"Flavor\";\n public static String TYPE_OTHER = \"Other\";\n\n public Misc(String name) {\n super(name);\n setDisplayUnits(\"\");\n setAmountIsWeight(false);\n setBeerXmlStandardAmount(0);\n setShortDescription(\"\");\n this.amount = 0;\n setUse(\"\");\n setVersion(1);\n setTime(0);\n setMiscType(TYPE_OTHER);\n }\n\n public Misc(Parcel p) {\n super(p);\n\n // Required\n this.miscType = p.readString();\n this.use = p.readString();\n this.amount = p.readDouble();\n this.amountIsWeight = p.readInt() > 0 ? true : false;\n this.useFor = p.readString();\n this.notes = p.readString();\n\n // Optional\n this.displayUnits = p.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n super.writeToParcel(p, flags);\n\n // Required\n p.writeString(this.miscType);\n p.writeString(this.use);\n p.writeDouble(this.amount);\n p.writeInt(amountIsWeight ? 1 : 0);\n p.writeString(this.useFor);\n p.writeString(this.notes);\n\n // Optional\n p.writeString(this.displayUnits);\n }\n\n public static final Parcelable.Creator<Misc> CREATOR =\n new Parcelable.Creator<Misc>() {\n @Override\n public Misc createFromParcel(Parcel p) {\n return new Misc(p);\n }\n\n @Override\n public Misc[] newArray(int size) {\n return null;\n }\n };\n\n @Override\n public String toString() {\n return this.getName();\n }\n\n public void setMiscType(String type) {\n this.miscType = type;\n }\n\n public String getMiscType() {\n if (! miscType.isEmpty() || this.miscType == null) {\n return this.miscType;\n }\n else {\n return Misc.TYPE_OTHER;\n }\n }\n\n public String getArrayAdapterDescription() {\n String s = this.getUse() + \", \";\n if (getTime() > 0) {\n s += this.getTime() + \" \" + this.getTimeUnits() + \", \";\n }\n s += getUseFor();\n return s;\n }\n\n public void setUse(String u) {\n this.use = u;\n }\n\n public String getUse() {\n return this.use;\n }\n\n public void setAmountIsWeight(boolean b) {\n this.amountIsWeight = b;\n }\n\n public boolean amountIsWeight() {\n return this.amountIsWeight;\n }\n\n public void setUseFor(String s) {\n this.useFor = s;\n }\n\n public String getUseFor() {\n return this.useFor;\n }\n\n @Override\n public String getType() {\n return Ingredient.MISC;\n }\n\n @Override\n public String getShortDescription() {\n return notes;\n }\n\n @Override\n public double getDisplayAmount() {\n\n String unit = this.getDisplayUnits();\n\n if (unit.equalsIgnoreCase(Units.GALLONS)) {\n return Units.litersToGallons(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.GRAMS)) {\n return Units.kilosToGrams(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.MILLIGRAMS)) {\n return Units.kilosToMilligrams(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.KILOGRAMS)) {\n return this.amount;\n }\n else if (unit.equalsIgnoreCase(Units.LITERS)) {\n return this.amount;\n }\n else if (unit.equalsIgnoreCase(Units.MILLILITERS)) {\n return Units.litersToMillis(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.TEASPOONS)) {\n return Units.litersToTeaspoons(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.TABLESPOONS)) {\n return Units.litersToTablespoons(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.OUNCES)) {\n if (this.amountIsWeight()) {\n return Units.kilosToOunces(this.amount);\n }\n else {\n return Units.litersToOunces(this.amount);\n }\n }\n else if (unit.equalsIgnoreCase(Units.POUNDS)) {\n return Units.kilosToPounds(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.QUARTS)) {\n return Units.litersToQuarts(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.PINTS)) {\n return Units.litersToPints(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.CUP) || unit.equalsIgnoreCase(Units.CUPS)) {\n return Units.litersToCups(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.ITEMS)) {\n return this.amount;\n }\n else if (unit.equalsIgnoreCase(Units.PACKAGES)) {\n return this.amount;\n }\n else {\n Log.e(\"Misc\", \"Failed to get display amount - bad units? \" + unit);\n return 0; // Should show that we couldn't compute\n }\n }\n\n @Override\n public double getBeerXmlStandardAmount() {\n return this.amount;\n }\n\n @Override\n public void setDisplayAmount(double amt) {\n // Not implemented - must use other method.\n // Get punished! (Can't throw exceptions here, but to make debugging\n // easier lets cause a problem!)\n int x = (Integer) null;\n x = x / 2;\n }\n\n public void setDisplayAmount(double amt, String unit) {\n Log.d(getName() + \"::setDisplayAmount\", \"Setting amt to: \" + amt + \" \" + unit);\n if (unit.equalsIgnoreCase(Units.GALLONS)) {\n this.amount = Units.gallonsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.GRAMS)) {\n this.amount = Units.gramsToKilos(amt);\n }\n else if (unit.equalsIgnoreCase(Units.MILLIGRAMS)) {\n this.amount = Units.milligramsToKilos(amt);\n }\n else if (unit.equalsIgnoreCase(Units.KILOGRAMS)) {\n this.amount = amt;\n }\n else if (unit.equalsIgnoreCase(Units.LITERS)) {\n this.amount = amt;\n this.amountIsWeight = false;\n }\n else if (unit.equalsIgnoreCase(Units.MILLILITERS)) {\n this.amount = Units.millisToLiters(amt);\n this.amountIsWeight = false;\n }\n else if (unit.equalsIgnoreCase(Units.TEASPOONS)) {\n this.amount = Units.teaspoonsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.TABLESPOONS)) {\n this.amount = Units.tablespoonsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.PINTS)) {\n this.amount = Units.pintsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.OUNCES)) {\n if (this.amountIsWeight()) {\n this.amount = Units.ouncesToKilos(amt);\n }\n else {\n this.amount = Units.ouncesToLiters(amt);\n }\n }\n else if (unit.equalsIgnoreCase(Units.POUNDS)) {\n this.amount = Units.poundsToKilos(amt);\n }\n else if (unit.equalsIgnoreCase(Units.CUP) || unit.equalsIgnoreCase(Units.CUPS)) {\n this.amount = Units.cupsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.ITEMS)) {\n this.amount = amt;\n }\n else if (unit.equalsIgnoreCase(Units.PACKAGES)) {\n this.amount = amt;\n }\n else {\n this.amount = - 1.0; // Should show that we couldn't compute\n }\n }\n\n @Override\n public void setBeerXmlStandardAmount(double amt) {\n this.amount = amt;\n }\n\n // This method is used when we want the value of the stored displayUnits\n // Not for use to determine the display units.\n public String getUnits() {\n return this.displayUnits;\n }\n\n @Override\n public String getDisplayUnits() {\n // If not, call the appropriate method based on which unit system the user has chosen\n if (Units.getUnitSystem().equals(Units.IMPERIAL)) {\n return getDisplayUnitsImperial();\n }\n else {\n return getDisplayUnitsMetric();\n }\n }\n\n // Called when preferred units are metric\n private String getDisplayUnitsMetric() {\n // First check if we have units specified\n if (! this.displayUnits.equals(\"\")) {\n return Units.getMetricEquivalent(this.displayUnits, this.amountIsWeight);\n }\n\n if (this.amountIsWeight()) {\n if (this.amount > 1) {\n return Units.KILOGRAMS;\n }\n else {\n return Units.GRAMS;\n }\n }\n else if (this.amount > .5) {\n return Units.LITERS;\n }\n else {\n return Units.MILLILITERS;\n }\n }\n\n // Called when preferred units are imperial\n private String getDisplayUnitsImperial() {\n // First check if we have units specified\n if (! this.displayUnits.equals(\"\")) {\n return this.displayUnits;\n }\n\n if (this.amountIsWeight()) {\n if (this.amount > .113)// .25lbs\n {\n return Units.POUNDS;\n }\n else {\n return Units.OUNCES;\n }\n }\n else if (this.amount > .946) // .25gal\n {\n return Units.GALLONS;\n }\n else {\n return Units.OUNCES;\n }\n }\n\n @Override\n public String getBeerXmlStandardUnits() {\n if (this.amountIsWeight()) {\n return Units.KILOGRAMS;\n }\n else {\n return Units.LITERS;\n }\n }\n\n @Override\n public int hashCode() {\n int hc = this.getName().hashCode();\n hc = hc ^ this.use.hashCode();\n hc = hc ^ this.miscType.hashCode();\n hc = hc + this.displayUnits.hashCode();\n hc = hc + this.getTime();\n return hc;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o instanceof Misc) {\n return this.compareTo((Misc) o) == 0;\n }\n return false;\n }\n\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type of Ingredient, sort based on Ingredient type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n Misc m = (Misc) other;\n\n // If they are both Misc, sort based on use.\n int useCompare = this.getUse().compareTo(m.getUse());\n if (useCompare != 0) {\n return useCompare;\n }\n\n // Sort based on time.\n int timeCompare = Double.compare(m.getTime(), this.getTime());\n if (timeCompare != 0) {\n return timeCompare;\n }\n\n // Sort based on name.\n int nameCompare = this.getName().compareTo(m.getName());\n if (nameCompare != 0) {\n return nameCompare;\n }\n\n // Sort based on type.\n int miscTypeCompare = this.getMiscType().compareTo(m.getMiscType());\n if (miscTypeCompare != 0) {\n return miscTypeCompare;\n }\n\n // Sort based on units.\n int unitCompare = this.getDisplayUnits().compareTo(m.getDisplayUnits());\n if (unitCompare != 0) {\n return unitCompare;\n }\n\n // Equal.\n return 0;\n }\n\n @Override\n public int getTime() {\n return time;\n }\n\n @Override\n public void setTime(int i) {\n this.time = i;\n }\n\n public String getTimeUnits() {\n if (use.equals(Misc.USE_PRIMARY) || use.equals(Misc.USE_SECONDARY)) {\n return Units.DAYS;\n }\n else if (use.equals(Misc.USE_BOIL) || use.equals(Misc.USE_MASH)) {\n return Units.MINUTES;\n }\n else {\n return Units.MINUTES;\n }\n }\n\n @Override\n public void setShortDescription(String description) {\n if (description.isEmpty()) {\n description = \"No description provided\";\n }\n this.notes = description;\n }\n\n @Override\n public void setDisplayUnits(String units) {\n this.displayUnits = units;\n }\n}",
"public class Water extends Ingredient {\n public Water(String name) {\n super(name);\n }\n\n public Water(Parcel p) {\n // TODO Implement this?\n this(\"New Water\");\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n\n }\n\n public static final Parcelable.Creator<Water> CREATOR =\n new Parcelable.Creator<Water>() {\n @Override\n public Water createFromParcel(Parcel p) {\n return new Water(p);\n }\n\n @Override\n public Water[] newArray(int size) {\n return new Water[]{};\n }\n };\n\n @Override\n public String getType() {\n return Ingredient.WATER;\n }\n\n @Override\n public String getShortDescription() {\n // TODO Auto-generated method stub\n return null;\n }\n\n public double getDisplayAmount() {\n // TODO: Implement this method\n return 0;\n }\n\n public double getBeerXmlStandardAmount() {\n // TODO: Implement this method\n return 0;\n }\n\n public void setDisplayAmount(double amt) {\n // TODO: Implement this method\n }\n\n public void setBeerXmlStandardAmount(double amt) {\n // TODO: Implement this method\n }\n\n @Override\n public String getDisplayUnits() {\n // TODO Auto-generated method stub\n return null;\n }\n\n @Override\n public void setDisplayUnits(String units) {\n // TODO Auto-generated method stub\n\n }\n\n public String getBeerXmlStandardUnits() {\n // TODO: Implement this method\n return Units.LITERS;\n }\n\n @Override\n public int hashCode() {\n // TODO Auto-generated method stub\n return 0;\n }\n\n @Override\n public boolean equals(Object o) {\n // TODO Auto-generated method stub\n return false;\n }\n\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type of Ingredient, sort based on Ingredient type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n\n // Equal.\n return 0;\n }\n\n @Override\n public int getTime() {\n // TODO Auto-generated method stub\n return 0;\n }\n\n @Override\n public void setTime(int i) {\n this.time = i;\n }\n\n @Override\n public void setShortDescription(String description) {\n // TODO Auto-generated method stub\n\n }\n}",
"public class Yeast extends Ingredient {\n\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n // Name - Inherited\n // Version - Inherited\n // Amount - Inherited\n private String type; // Ale, Lager, etc\n private String form; // Liquid, Dry, etc\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double minTemp;\n private double maxTemp;\n private double attenuation; // Percentage: x / 100\n private String notes;\n private String bestFor;\n private String productid;\n private String lab;\n\n // Custom Fields ==================================================\n // ================================================================\n\n // Static values =================================================\n // ===============================================================\n public static final String TYPE_ALE = \"Ale\";\n public static final String TYPE_LAGER = \"Lager\";\n public static final String TYPE_WHEAT = \"Wheat\";\n public static final String TYPE_WINE = \"Wine\";\n public static final String TYPE_CHAMPAGNE = \"Champagne\";\n\n public static final String FORM_LIQUID = \"Liquid\";\n public static final String FORM_DRY = \"Dry\";\n public static final String FORM_SLANT = \"Slant\";\n public static final String FORM_CULTURE = \"Culture\";\n\n public Yeast(String name) {\n super(name);\n this.type = TYPE_ALE;\n this.form = FORM_LIQUID;\n this.amount = 0;\n this.minTemp = 0;\n this.maxTemp = 0;\n this.attenuation = 75;\n this.notes = \"\";\n this.bestFor = \"\";\n this.productid = \"Unknown ID\";\n this.lab = \"Unknown lab\";\n }\n\n public Yeast(Parcel p) {\n super(p);\n type = p.readString();\n form = p.readString();\n minTemp = p.readDouble();\n maxTemp = p.readDouble();\n attenuation = p.readDouble();\n notes = p.readString();\n bestFor = p.readString();\n productid = p.readString();\n lab = p.readString();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n super.writeToParcel(p, flags);\n p.writeString(type); // Ale, Lager, etc\n p.writeString(form); // Liquid, Dry, etc\n p.writeDouble(minTemp);\n p.writeDouble(maxTemp);\n p.writeDouble(attenuation); // Percentage: x / 100\n p.writeString(notes);\n p.writeString(bestFor);\n p.writeString(productid);\n p.writeString(lab);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<Yeast> CREATOR =\n new Parcelable.Creator<Yeast>() {\n @Override\n public Yeast createFromParcel(Parcel p) {\n return new Yeast(p);\n }\n\n @Override\n public Yeast[] newArray(int size) {\n return null;\n }\n };\n\n @Override\n public String toString() {\n return this.getName();\n }\n\n @Override\n public String getType() {\n return Ingredient.YEAST;\n }\n\n @Override\n public String getShortDescription() {\n String s = this.getLaboratory();\n s += \" \" + this.getProductId();\n\n if (s.length() > 3) {\n s += \": \";\n }\n s += this.notes;\n return s;\n }\n\n public String getArrayAdapterDescription() {\n String s = getLaboratory() + \", \" + getProductId();\n\n if (s.length() < 3) {\n s = String.format(\"%2.2f\", this.getAttenuation()) + \"% attenuation\";\n }\n\n return s;\n }\n\n public String getBeerXmlStandardUnits() {\n return Units.LITERS;\n }\n\n public double getDisplayAmount() {\n // TODO: We just assume a single yeast pkg\n return 1;\n }\n\n public double getBeerXmlStandardAmount() {\n return this.amount;\n }\n\n public void setDisplayAmount(double amt) {\n this.amount = amt;\n }\n\n public void setBeerXmlStandardAmount(double amt) {\n this.amount = amt;\n }\n\n @Override\n public String getDisplayUnits() {\n return Units.PACKAGES;\n }\n\n @Override\n public int hashCode() {\n int hc = this.getName().hashCode();\n hc = hc ^ (int) (this.getAttenuation() * 1234);\n return hc;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o instanceof Yeast) {\n return this.compareTo((Yeast) o) == 0;\n }\n return false;\n }\n\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type of Ingredient, sort based on Ingredient type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n Yeast y = (Yeast) other;\n\n // If they are both Yeast, sort based on attenuation.\n int attnCompare = Double.compare(this.getAttenuation(), y.getAttenuation());\n if (attnCompare != 0) {\n return attnCompare;\n }\n\n // Sort based on name.\n int nameCompare = this.getName().compareTo(y.getName());\n if (nameCompare != 0) {\n return nameCompare;\n }\n\n // Equal.\n return 0;\n }\n\n @Override\n public int getTime() {\n return this.time;\n }\n\n @Override\n public void setTime(int time) {\n this.time = time;\n }\n\n @Override\n public void setShortDescription(String description) {\n this.notes = description;\n }\n\n @Override\n public void setDisplayUnits(String units) {\n\n }\n\n /**\n * @return the type\n */\n public String getYeastType() {\n return type;\n }\n\n /**\n * @param type\n * the type to set\n */\n public void setType(String type) {\n this.type = type;\n }\n\n /**\n * @return the form\n */\n public String getForm() {\n return form;\n }\n\n /**\n * @param form\n * the form to set\n */\n public void setForm(String form) {\n this.form = form;\n }\n\n /**\n * @return the minTemp\n */\n public double getMinTemp() {\n return minTemp;\n }\n\n /**\n * @param minTemp\n * the minTemp to set\n */\n public void setMinTemp(double minTemp) {\n this.minTemp = minTemp;\n }\n\n /**\n * @return the maxTemp\n */\n public double getMaxTemp() {\n return maxTemp;\n }\n\n /**\n * @param maxTemp\n * the maxTemp to set\n */\n public void setMaxTemp(double maxTemp) {\n this.maxTemp = maxTemp;\n }\n\n public int getBeerXmlStandardFermentationTemp() {\n return (int) ((maxTemp + minTemp) / 2);\n }\n\n public int getDisplayFermentationTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return (int) Units.celsiusToFahrenheit(((maxTemp + minTemp) / 2));\n }\n else {\n return (int) ((maxTemp + minTemp) / 2);\n }\n }\n\n /**\n * @return the attenuation\n */\n public double getAttenuation() {\n return attenuation;\n }\n\n /**\n * @param attenuation\n * the attenuation to set\n */\n public void setAttenuation(double attenuation) {\n this.attenuation = attenuation;\n }\n\n /**\n * @return the notes\n */\n public String getNotes() {\n return notes;\n }\n\n /**\n * @param notes\n * the notes to set\n */\n public void setNotes(String notes) {\n this.notes = notes;\n }\n\n /**\n * f\n *\n * @return the bestFor\n */\n public String getBestFor() {\n return bestFor;\n }\n\n /**\n * @param bestFor\n * the bestFor to set\n */\n public void setBestFor(String bestFor) {\n this.bestFor = bestFor;\n }\n\n public void setProductId(String s) {\n this.productid = s;\n }\n\n public void setLaboratory(String s) {\n this.lab = s;\n }\n\n public String getLaboratory() {\n return this.lab;\n }\n\n public String getProductId() {\n return this.productid;\n }\n}",
"public class BeerStyle implements Parcelable {\n\n // Categories based on beerXMl standard\n private String name;\n private String category;\n private Integer version;\n private String categoryNumber;\n private String styleLetter;\n private String styleGuide;\n private String type;\n private String notes;\n private String profile;\n private String ingredients;\n private String examples;\n\n // Reccomended values\n private double MinOg;\n private double MaxOg;\n private double MinFg;\n private double MaxFg;\n private double MinIbu;\n private double MaxIbu;\n private double minColor;\n private double maxColor;\n private double minAbv;\n private double maxAbv;\n\n // More\n private long ownerId;\n\n // Defines\n public static String TYPE_ALE = \"Ale\";\n public static String TYPE_LAGER = \"Lager\";\n public static String TYPE_MEAD = \"Mead\";\n public static String TYPE_WHEAT = \"Wheat\";\n public static String TYPE_MIXED = \"Mixed\";\n public static String TYPE_CIDER = \"Cider\";\n\n public BeerStyle(String name) {\n setName(name);\n setType(\"\");\n setCategory(\"\");\n setStyleLetter(\"\");\n setNotes(\"\");\n setExamples(\"\");\n setIngredients(\"\");\n setProfile(\"\");\n setStyleGuide(\"\");\n setCategoryNumber(\"\");\n setVersion(1);\n setOwnerId(- 1);\n\n this.MinOg = 1;\n this.MaxOg = 2;\n this.MinFg = 1;\n this.MaxFg = 2;\n this.MinIbu = 0;\n this.MaxIbu = 200;\n this.minColor = 0;\n this.maxColor = 100;\n this.minAbv = 0;\n this.maxAbv = 100;\n }\n\n public BeerStyle(Parcel p) {\n // Categories based on beerXMl standard\n name = p.readString();\n category = p.readString();\n version = p.readInt();\n categoryNumber = p.readString();\n styleLetter = p.readString();\n styleGuide = p.readString();\n type = p.readString();\n notes = p.readString();\n profile = p.readString();\n ingredients = p.readString();\n examples = p.readString();\n MinOg = p.readDouble();\n MaxOg = p.readDouble();\n MinFg = p.readDouble();\n MaxFg = p.readDouble();\n MinIbu = p.readDouble();\n MaxIbu = p.readDouble();\n minColor = p.readDouble();\n maxColor = p.readDouble();\n minAbv = p.readDouble();\n maxAbv = p.readDouble();\n ownerId = p.readLong();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n // Categories based on beerXMl standard\n p.writeString(name);\n p.writeString(category);\n p.writeInt(version);\n p.writeString(categoryNumber);\n p.writeString(styleLetter);\n p.writeString(styleGuide);\n p.writeString(type);\n p.writeString(notes);\n p.writeString(profile);\n p.writeString(ingredients);\n p.writeString(examples);\n p.writeDouble(MinOg);\n p.writeDouble(MaxOg);\n p.writeDouble(MinFg);\n p.writeDouble(MaxFg);\n p.writeDouble(MinIbu);\n p.writeDouble(MaxIbu);\n p.writeDouble(minColor);\n p.writeDouble(maxColor);\n p.writeDouble(minAbv);\n p.writeDouble(maxAbv);\n p.writeLong(ownerId);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<BeerStyle> CREATOR =\n new Parcelable.Creator<BeerStyle>() {\n @Override\n public BeerStyle createFromParcel(Parcel p) {\n return new BeerStyle(p);\n }\n\n @Override\n public BeerStyle[] newArray(int size) {\n return new BeerStyle[]{};\n }\n };\n\n @Override\n public boolean equals(Object o) {\n // Fist make sure its a BeerStyle\n if (! (o instanceof BeerStyle)) {\n return false;\n }\n\n // Based only off the name\n if (this.toString().equals(o.toString())) {\n return true;\n }\n else {\n return false;\n }\n\n }\n\n public String toString() {\n return name;\n }\n\n public void setOwnerId(long i) {\n this.ownerId = i;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setMinCarb(double d) {\n // TODO\n }\n\n public void setMaxCarb(double d) {\n // TODO\n }\n\n public void setName(String s) {\n this.name = s;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setType(String s) {\n this.type = s;\n }\n\n public void setCategory(String s) {\n this.category = s;\n }\n\n public void setStyleLetter(String s) {\n this.styleLetter = s;\n }\n\n public void setNotes(String s) {\n this.notes = s;\n }\n\n public void setExamples(String s) {\n this.examples = s;\n }\n\n public void setProfile(String s) {\n this.profile = s;\n }\n\n public void setCategoryNumber(String s) {\n this.categoryNumber = s;\n }\n\n public void setStyleGuide(String s) {\n this.styleGuide = s;\n }\n\n public void setIngredients(String s) {\n this.ingredients = s;\n }\n\n public void setVersion(int i) {\n this.version = i;\n }\n\n // Methods for getting individual mins and maxes\n public double getMinOg() {\n return MinOg;\n }\n\n public void setMinOg(double minGrav) {\n this.MinOg = minGrav;\n }\n\n public double getMaxOg() {\n return MaxOg;\n }\n\n public void setMaxOg(double maxGrav) {\n this.MaxOg = maxGrav;\n }\n\n public double getMinIbu() {\n return MinIbu;\n }\n\n public void setMinIbu(double MinIbu) {\n this.MinIbu = MinIbu;\n }\n\n public double getMaxIbu() {\n return MaxIbu;\n }\n\n public void setMaxIbu(double MaxIbu) {\n this.MaxIbu = MaxIbu;\n }\n\n public double getMinColor() {\n return minColor;\n }\n\n public void setMinColor(double minColor) {\n this.minColor = minColor;\n }\n\n public double getMaxColor() {\n return maxColor;\n }\n\n public void setMaxColor(double maxColor) {\n this.maxColor = maxColor;\n }\n\n public double getAverageColor() {\n return (this.minColor + this.maxColor) / 2;\n }\n\n public double getMinAbv() {\n return minAbv;\n }\n\n public void setMinAbv(double minAbv) {\n this.minAbv = minAbv;\n }\n\n public double getMaxAbv() {\n return maxAbv;\n }\n\n public void setMaxAbv(double maxAbv) {\n this.maxAbv = maxAbv;\n }\n\n public double getMaxFg() {\n return MaxFg;\n }\n\n public void setMaxFg(double MaxFg) {\n this.MaxFg = MaxFg;\n }\n\n public double getMinFg() {\n return MinFg;\n }\n\n public void setMinFg(double MinFg) {\n this.MinFg = MinFg;\n }\n\n public String getCategory() {\n return this.category;\n }\n\n public String getCatNum() {\n return this.categoryNumber;\n }\n\n public String getStyleLetter() {\n return this.styleLetter;\n }\n\n public String getStyleGuide() {\n return this.styleGuide;\n }\n\n public String getType() {\n return this.type;\n }\n\n public double getMinCarb() {\n return 0; // TODO\n }\n\n public double getMaxCarb() {\n return 0; // TODO\n }\n\n public String getNotes() {\n // Return the string without any newlines or tabs.\n return this.notes.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getProfile() {\n return this.profile.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getIngredients() {\n return this.ingredients.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getExamples() {\n return this.examples.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n}",
"public class MashProfile implements Parcelable {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // profile name\n private Integer version; // XML Version -- 1\n private double grainTemp; // Grain temp in C\n private ArrayList<MashStep> mashSteps; // List of steps\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double tunTemp; // TUN Temperature in C\n private double spargeTemp; // Sparge Temp in C\n private double pH; // pH of water\n private double tunWeight; // Weight of TUN in kG\n private double tunSpecificHeat; // Specific heat of TUN\n private String notes; // Notes\n private Boolean equipAdj; // Adjust for heating of equip?\n\n // Custom Fields ==================================================\n // ================================================================\n private long id; // id for use in database\n private long ownerId; // id for parent recipe\n private String mashType; // one of infusion, decoction, temperature\n private String spargeType; // one of batch, fly\n private Recipe recipe; // Recipe which owns this mash.\n\n // Static values =================================================\n // ===============================================================\n public static String MASH_TYPE_INFUSION = \"Infusion\";\n public static String MASH_TYPE_DECOCTION = \"Decoction\";\n public static String MASH_TYPE_TEMPERATURE = \"Temperature\";\n public static String MASH_TYPE_BIAB = \"BIAB\";\n public static String SPARGE_TYPE_BATCH = \"Batch\";\n public static String SPARGE_TYPE_FLY = \"Fly\";\n public static String SPARGE_TYPE_BIAB = \"BIAB\";\n\n // Basic Constructor\n public MashProfile(Recipe r) {\n this.setName(\"New Mash Profile\");\n this.setVersion(1);\n this.setBeerXmlStandardGrainTemp(20);\n this.mashSteps = new ArrayList<MashStep>();\n this.setBeerXmlStandardTunTemp(20);\n this.setBeerXmlStandardSpargeTemp(75.5555);\n this.setpH(7);\n this.setBeerXmlStandardTunWeight(0);\n this.setBeerXmlStandardTunSpecHeat(0);\n this.setEquipmentAdjust(false);\n this.setNotes(\"\");\n this.id = - 1;\n this.ownerId = - 1;\n this.mashType = MASH_TYPE_INFUSION;\n this.spargeType = SPARGE_TYPE_BATCH;\n this.recipe = r;\n }\n\n public MashProfile() {\n this(new Recipe());\n }\n\n public MashProfile(Parcel p) {\n name = p.readString();\n version = p.readInt();\n grainTemp = p.readDouble();\n\n mashSteps = new ArrayList<MashStep>();\n p.readTypedList(mashSteps, MashStep.CREATOR);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n tunTemp = p.readDouble();\n spargeTemp = p.readDouble();\n pH = p.readDouble();\n tunWeight = p.readDouble();\n tunSpecificHeat = p.readDouble();\n notes = p.readString();\n equipAdj = (p.readInt() > 0 ? true : false);\n\n // Custom Fields ==================================================\n // ================================================================\n id = p.readLong();\n ownerId = p.readLong();\n mashType = p.readString();\n spargeType = p.readString();\n // Don't read recipe because it recurses.\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n p.writeString(name); // profile name\n p.writeInt(version); // XML Version -- 1\n p.writeDouble(grainTemp); // Grain temp in C\n p.writeTypedList(mashSteps); // List of steps\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(tunTemp); // TUN Temperature in C\n p.writeDouble(spargeTemp); // Sparge Temp in C\n p.writeDouble(pH); // pH of water\n p.writeDouble(tunWeight); // Weight of TUN in kG\n p.writeDouble(tunSpecificHeat); // Specific heat of TUN\n p.writeString(notes); // Notes\n p.writeInt(equipAdj ? 1 : 0); // Adjust for heating of equip?\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(id); // id for use in database\n p.writeLong(ownerId); // id for parent recipe\n p.writeString(mashType);\n p.writeString(spargeType);\n // Don't write recipe because it recurses.\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<MashProfile> CREATOR =\n new Parcelable.Creator<MashProfile>() {\n @Override\n public MashProfile createFromParcel(Parcel p) {\n return new MashProfile(p);\n }\n\n @Override\n public MashProfile[] newArray(int size) {\n return new MashProfile[size];\n }\n };\n\n @Override\n public String toString() {\n return this.name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (! (o instanceof MashProfile)) {\n return false;\n }\n\n MashProfile other = (MashProfile) o;\n if (this.hashCode() != other.hashCode()) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int hc = this.name.hashCode();\n for (MashStep m : this.mashSteps) {\n hc ^= m.hashCode();\n }\n return hc;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setVersion(Integer v) {\n this.version = v;\n }\n\n public Integer getVersion() {\n return this.version;\n }\n\n public void setBeerXmlStandardGrainTemp(double temp) {\n this.grainTemp = temp;\n }\n\n public void setDisplayGrainTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.grainTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.grainTemp = temp;\n }\n }\n\n public double getBeerXmlStandardGrainTemp() {\n return this.grainTemp;\n }\n\n public double getDisplayGrainTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.grainTemp);\n }\n else {\n return this.grainTemp;\n }\n }\n\n public String getMashType() {\n return this.mashType;\n }\n\n public String getSpargeType() {\n return this.spargeType;\n }\n\n public void setMashType(String s) {\n this.mashType = s;\n }\n\n public void setSpargeType(String s) {\n Log.d(\"MashProfile\", \"Sparge type set: \" + s);\n this.spargeType = s;\n }\n\n public void setBeerXmlStandardTunTemp(double temp) {\n this.tunTemp = temp;\n }\n\n public void setDisplayTunTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.tunTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.tunTemp = temp;\n }\n }\n\n public double getBeerXmlStandardTunTemp() {\n return this.tunTemp;\n }\n\n public double getDisplayTunTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.tunTemp);\n }\n else {\n return this.tunTemp;\n }\n }\n\n public void setBeerXmlStandardSpargeTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.spargeTemp = temp;\n }\n }\n\n public void setDisplaySpargeTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.spargeTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.spargeTemp = temp;\n }\n }\n\n public double getDisplaySpargeTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.spargeTemp);\n }\n else {\n return this.spargeTemp;\n }\n }\n\n public double getBeerXmlStandardSpargeTemp() {\n return this.spargeTemp;\n }\n\n public void setpH(double pH) {\n this.pH = pH;\n }\n\n public double getpH() {\n return this.pH;\n }\n\n public void setBeerXmlStandardTunWeight(double weight) {\n this.tunWeight = weight;\n }\n\n public void setDisplayTunWeight(double weight) {\n if (Units.getWeightUnits().equals(Units.POUNDS)) {\n this.tunWeight = Units.poundsToKilos(weight);\n }\n else {\n this.tunWeight = weight;\n }\n }\n\n public double getBeerXmlStandardTunWeight() {\n return this.tunWeight;\n }\n\n public double getDisplayTunWeight() {\n if (Units.getWeightUnits().equals(Units.POUNDS)) {\n return Units.kilosToPounds(this.tunWeight);\n }\n else {\n return this.tunWeight;\n }\n }\n\n public void setBeerXmlStandardTunSpecHeat(double heat) {\n this.tunSpecificHeat = heat;\n }\n\n public double getBeerXmlStandardTunSpecHeat() {\n // Cal / (g * C)\n return this.tunSpecificHeat;\n }\n\n public void setEquipmentAdjust(boolean adj) {\n this.equipAdj = adj;\n }\n\n public Boolean getEquipmentAdjust() {\n return this.equipAdj;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public long getId() {\n return this.id;\n }\n\n public void setOwnerId(long id) {\n this.ownerId = id;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setNotes(String s) {\n this.notes = s;\n }\n\n public String getNotes() {\n return this.notes;\n }\n\n public int getNumberOfSteps() {\n return this.mashSteps.size();\n }\n\n public void setRecipe(Recipe r) {\n this.recipe = r;\n for (MashStep m : this.mashSteps) {\n m.setRecipe(this.recipe);\n }\n }\n\n public ArrayList<MashStep> getMashStepList() {\n return this.mashSteps;\n }\n\n public void clearMashSteps() {\n this.mashSteps = new ArrayList<MashStep>();\n }\n\n /**\n * Sets mash step list to given list. Assumes list is in the desired order and overrides orders\n * if reorder set to true\n *\n * @param list\n */\n public void setMashStepList(ArrayList<MashStep> list) {\n this.mashSteps = list;\n for (MashStep s : this.mashSteps) {\n s.setRecipe(this.recipe);\n }\n Collections.sort(this.mashSteps, new FromDatabaseMashStepComparator());\n }\n\n /**\n * Removes the given step, returns true if success\n *\n * @param step\n * @return\n */\n public boolean removeMashStep(MashStep step) {\n return this.mashSteps.remove(step);\n }\n\n public MashStep removeMashStep(int order) {\n return this.mashSteps.remove(order);\n }\n\n public void addMashStep(MashStep step) {\n step.setRecipe(this.recipe);\n this.mashSteps.add(step);\n }\n\n public void addMashStep(int order, MashStep step) {\n step.setRecipe(this.recipe);\n this.mashSteps.add(order, step);\n }\n\n public void save(Context c, long database) {\n Log.d(\"MashProfile\", \"Saving \" + name + \" to database \" + database);\n if (this.id < 0) {\n // We haven't yet saved this. Add it to the database.\n new DatabaseAPI(c).addMashProfile(database, this, this.getOwnerId());\n }\n else {\n // Already exists. Update it.\n new DatabaseAPI(c).updateMashProfile(this, this.getOwnerId(), database);\n }\n }\n\n public void delete(Context c, long database) {\n new DatabaseAPI(c).deleteMashProfileFromDatabase(this, database);\n }\n}",
"public class MashStep implements Parcelable {\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // profile name\n private int version; // XML Version -- 1\n private String type; // infusion, temp, decoc\n private double infuseAmount; // Amount\n private double stepTemp; // Temp for this step in C\n private double stepTime; // Time for this step\n\n // ================================================================\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double rampTime; // Time to ramp temp\n private double endTemp; // Final temp for long steps\n private String description; // Description of step\n private double waterToGrainRatio; // Water to grain ratio (L/kg)\n private double decoctAmount; // Amount of mash to decoct. (L)\n\n // ================================================================\n // Custom Fields ==================================================\n // ================================================================\n private long ownerId; // id for parent mash profile\n private long id; // id for use in database\n public int order; // Order in step list\n private double infuseTemp; // Temperature of infuse water\n private boolean calcInfuseTemp; // Auto calculate the infusion temperature if true.\n private boolean calcInfuseAmt; // Auto calculate the infusion amount if true.\n private boolean calcDecoctAmt; // Auto calculate the amount to decoct if true.\n private Recipe recipe; // Reference to the recipe that owns this mash.\n\n // ================================================================\n // Static values ==================================================\n // ================================================================\n public static String INFUSION = \"Infusion\";\n public static String TEMPERATURE = \"Temperature\";\n public static String DECOCTION = \"Decoction\";\n\n // Basic Constructor\n public MashStep(Recipe r) {\n this.setName(\"Mash Step (\" + (r.getMashProfile().getMashStepList().size() + 1) + \")\");\n this.setVersion(1);\n this.setType(MashStep.INFUSION);\n this.setDisplayInfuseAmount(0);\n this.setBeerXmlStandardStepTemp(65.555556);\n this.setStepTime(60);\n this.setRampTime(0);\n this.setBeerXmlStandardEndTemp(0.0);\n this.setDescription(\"\");\n this.setBeerXmlStandardWaterToGrainRatio(2.60793889);\n this.infuseTemp = 0.0;\n this.id = - 1;\n this.ownerId = - 1;\n this.order = 1;\n this.decoctAmount = 0;\n this.calcInfuseAmt = true;\n this.calcInfuseTemp = true;\n this.calcDecoctAmt = true;\n this.recipe = r;\n }\n\n // Only use this when we don't have a mash profile to\n // use!\n public MashStep() {\n this(new Recipe());\n }\n\n public MashStep(Parcel p) {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n name = p.readString();\n version = p.readInt();\n type = p.readString();\n infuseAmount = p.readDouble();\n stepTemp = p.readDouble();\n stepTime = p.readDouble();\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n rampTime = p.readDouble();\n endTemp = p.readDouble();\n description = p.readString();\n waterToGrainRatio = p.readDouble();\n decoctAmount = p.readDouble();\n\n // Custom Fields ==================================================\n // ================================================================\n ownerId = p.readLong();\n id = p.readLong();\n order = p.readInt();\n infuseTemp = p.readDouble();\n calcInfuseTemp = p.readInt() == 0 ? false : true;\n calcInfuseAmt = p.readInt() == 0 ? false : true;\n calcDecoctAmt = p.readInt() == 0 ? false : true;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n p.writeString(name); // profile name\n p.writeInt(version); // XML Version -- 1\n p.writeString(type); // infusion, temp, decoc\n p.writeDouble(infuseAmount); // Amount\n p.writeDouble(stepTemp); // Temp for this step in C\n p.writeDouble(stepTime); // Time for this step\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(rampTime); // Time to ramp temp\n p.writeDouble(endTemp); // Final temp for long steps\n p.writeString(description); // Description of step\n p.writeDouble(waterToGrainRatio); // Water to grain ratio (L/kg)\n p.writeDouble(decoctAmount); // Amount of water to decoct.\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(ownerId); // id for parent mash profile\n p.writeLong(id); // id for use in database\n p.writeInt(order); // Order in step list\n p.writeDouble(infuseTemp);\n p.writeInt(calcInfuseTemp ? 1 : 0);\n p.writeInt(calcInfuseAmt ? 1 : 0);\n p.writeInt(calcDecoctAmt ? 1 : 0);\n }\n\n public static final Parcelable.Creator<MashStep> CREATOR =\n new Parcelable.Creator<MashStep>() {\n @Override\n public MashStep createFromParcel(Parcel p) {\n return new MashStep(p);\n }\n\n @Override\n public MashStep[] newArray(int size) {\n return new MashStep[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public boolean equals(Object o) {\n // Non-MashStep objects cannot equal a MashStep.\n if (! (o instanceof MashStep)) {\n return false;\n }\n\n // Comparing to a MashStep - cast the given Object.\n MashStep other = (MashStep) o;\n\n // Both are MashStep objects - compare important fields.\n if (! this.getName().equals(other.getName())) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getName() + \" != \" + other.getName());\n return false;\n }\n else if (this.getStepTime() != other.getStepTime()) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getStepTime() + \" != \" + other.getStepTime());\n return false;\n }\n else if (this.getBeerXmlStandardStepTemp() != other.getBeerXmlStandardStepTemp()) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getBeerXmlStandardStepTemp() + \" != \" + other.getBeerXmlStandardStepTemp());\n return false;\n }\n else if (! this.getType().equals(other.getType())) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getType() + \" != \" + other.getType());\n return false;\n }\n\n // All index fields match - these objects are equal.\n return true;\n }\n\n @Override\n public String toString() {\n return this.name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public int getVersion() {\n return this.version;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getType() {\n return this.type;\n }\n\n public double getDisplayDecoctAmount() {\n // If we are autocalculating.\n if (this.calcDecoctAmt) {\n return this.calculateDecoctAmount();\n }\n\n // We're not auto-calculating.\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.decoctAmount);\n }\n else {\n return this.decoctAmount;\n }\n }\n\n public void setDisplayDecoctAmount(double amt) {\n Log.d(\"MashStep\", \"Setting display decoction amount: \" + amt);\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.decoctAmount = Units.gallonsToLiters(amt);\n }\n else {\n this.decoctAmount = amt;\n }\n }\n\n public void setBeerXmlDecoctAmount(double amt) {\n this.decoctAmount = amt;\n }\n\n public double getBeerXmlDecoctAmount() {\n return this.decoctAmount;\n }\n\n public void setDisplayInfuseAmount(double amt) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.infuseAmount = Units.gallonsToLiters(amt);\n }\n else {\n this.infuseAmount = amt;\n }\n }\n\n public double getDisplayAmount() {\n if (this.getType().equals(DECOCTION)) {\n Log.d(\"MashStep\", \"Returning display decoction amount: \" + this.getDisplayDecoctAmount());\n return this.getDisplayDecoctAmount();\n }\n else if (this.getType().equals(INFUSION)) {\n Log.d(\"MashStep\", \"Returning display infusion amount: \" + this.getDisplayInfuseAmount());\n return this.getDisplayInfuseAmount();\n }\n else if (this.getType().equals(TEMPERATURE)) {\n Log.d(\"MashStep\", \"Temperature mash, returning 0 for display amount\");\n return 0;\n }\n Log.d(\"MashStep\", \"Invalid type: \" + this.getType() + \". Returning -1 for display amount\");\n return - 1;\n }\n\n public double getDisplayInfuseAmount() {\n // No infuse amount for decoction steps. Ever.\n if (this.getType().equals(MashStep.DECOCTION)) {\n return 0;\n }\n\n // If we are autocalculating.\n if (this.calcInfuseAmt) {\n return this.calculateInfuseAmount();\n }\n\n // If we're not auto-calculating.\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.infuseAmount);\n }\n else {\n return this.infuseAmount;\n }\n }\n\n /* Calculates the infusion amount based on\n /* water to grain ratio, water temp, water to add,\n /* and the step temperature.\n /* Also sets this.infuseAmount to the correct value. */\n public double calculateInfuseAmount() {\n // We perform different calculations if this is the initial infusion.\n double amt = - 1;\n if (this.firstInList() &&\n ! this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n // Initial infusion for a non-biab mash. Water is constant * amount of grain.\n amt = this.getBeerXmlStandardWaterToGrainRatio() * this.getBeerXmlStandardMashWeight();\n }\n else if (this.firstInList() &&\n this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n // Initial infusion for a BIAB mash.\n // Water is boil volume + grain absorption.\n amt = this.recipe.getBeerXmlStandardBoilSize();\n\n // Estimate ~1 liter per kg absobtion.\n // TODO: Get this from equipment profile.\n amt += this.getBeerXmlStandardMashWeight();\n }\n else {\n // The actual temperature of the water being infused.\n double actualInfuseTemp = calcInfuseTemp ? calculateBXSInfuseTemp() : getBeerXmlStandardInfuseTemp();\n\n // Not initial infusion. Calculate water to add to reach appropriate temp.\n try {\n amt = (this.getBeerXmlStandardStepTemp() - getPreviousStep().getBeerXmlStandardStepTemp());\n } catch (Exception e) {\n e.printStackTrace();\n }\n amt = amt * (.41 * this.getBeerXmlStandardMashWeight() + this.getBXSTotalWaterInMash());\n amt = amt / (actualInfuseTemp - this.getBeerXmlStandardStepTemp());\n }\n\n // Set BXL amount so that database is consistent.\n this.infuseAmount = amt;\n\n // Use appropriate units.\n if (Units.getVolumeUnits().equals(Units.LITERS)) {\n return amt;\n }\n else {\n return Units.litersToGallons(amt);\n }\n }\n\n /* Calculates the decoction amount */\n public double calculateDecoctAmount() {\n Log.d(\"MashStep\", \"Auto-calculating decoct amount\");\n /**\n * F = (TS – TI) / (TB – TI – X)\n *\n * Where f is the fraction, TS is the target step temperature, TI is the initial (current) temperature,\n * TB is the temperature of the boiling mash and X is an equipment dependent parameter (typically 18F or 10C).\n */\n double target = this.getBeerXmlStandardStepTemp();\n double initial = 0;\n try {\n initial = this.getPreviousStep().getBeerXmlStandardStepTemp();\n } catch (Exception e) {\n // Attempted to calculate decoct amount for first step in MashProfile. This isn't\n // allowed (the first step must be an infusion step). Handle this\n // somewhat gracefully, as this can occur temporarily during recipe formulation.\n e.printStackTrace();\n return 0;\n }\n double boiling = 99; // Boiling temperature of mash (C).\n double X = 10; // TODO: Equipment factor - accounts for heat absorbtion of mash tun.\n double grainDensity = .43; // .43kg / 1L\n double waterVolume = getBXSTotalWaterInMash(); // L\n double grainMass = (waterVolume / waterToGrainRatio); // kg\n double grainVolume = grainMass / grainDensity; // L\n double totalVolume = waterVolume + grainVolume; // L\n\n // This calculates the ratio of \"mash to boil\" / \"mash to leave in tun\".\n double fraction = (target - initial) / (boiling - initial - X);\n\n // Convert this ratio to \"Mash to boil\" / \"Total Mash\"\n fraction = (fraction) / (1 + fraction);\n\n // Return the fraction of mash, adjusted for the selected units.\n if (Units.getUnitSystem().equals(Units.METRIC)) {\n return fraction * totalVolume; // Return Liters of mash.\n }\n else {\n return fraction * Units.litersToGallons(totalVolume); // Return Gallons of mash.\n }\n }\n\n /**\n * Calculates the infusion temperature for both initial infusion, and water adds.\n * http://www.howtobrew.com/section3/chapter16-3.html\n */\n public double calculateInfuseTemp() {\n // We perform different calculations if this is the initial infusion.\n double temp = 0;\n if (this.firstInList()) {\n // Initial infusion.\n // TODO: For now, we don't have equipment so we combine tun / grain temp for calculation.\n double tunTemp = .7 * this.recipe.getMashProfile().getBeerXmlStandardGrainTemp() +\n .3 * this.recipe.getMashProfile().getBeerXmlStandardTunTemp();\n temp = (.41) / (this.getBeerXmlStandardWaterToGrainRatio());\n temp = temp * (this.getBeerXmlStandardStepTemp() - tunTemp) + this.getBeerXmlStandardStepTemp();\n }\n else {\n // Not initial infusion. Assume boiling water to make\n // calculation easier. If the next step has a LOWER temperature,\n // use room temperature water (72F).\n try {\n if (getPreviousStep().getBeerXmlStandardStepTemp() < this.getBeerXmlStandardStepTemp()) {\n temp = 100;\n }\n else {\n temp = 22.2222;\n }\n } catch (Exception e) {\n temp = - 1;\n }\n }\n\n // Set the infuse temperature.\n this.infuseTemp = temp;\n\n // Use appropriate units.\n if (Units.getTemperatureUnits().equals(Units.CELSIUS)) {\n return temp;\n }\n else {\n return Units.celsiusToFahrenheit(temp);\n }\n }\n\n private double calculateBXSInfuseTemp() {\n if (Units.getTemperatureUnits().equals(Units.CELSIUS)) {\n return this.calculateInfuseTemp();\n }\n else {\n return Units.fahrenheitToCelsius(this.calculateInfuseTemp());\n }\n }\n\n public boolean firstInList() {\n return this.getOrder() == 0;\n }\n\n public void setBeerXmlStandardInfuseAmount(double amt) {\n this.infuseAmount = amt;\n }\n\n public double getBeerXmlStandardInfuseAmount() {\n if (this.calcInfuseAmt) {\n calculateInfuseAmount();\n }\n return this.infuseAmount;\n }\n\n public double getDisplayInfuseTemp() {\n if (this.calcInfuseTemp) {\n return Math.round(this.calculateInfuseTemp());\n }\n\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Math.round(Units.celsiusToFahrenheit(this.infuseTemp));\n }\n else {\n return Math.round(this.infuseTemp);\n }\n }\n\n public void setDisplayInfuseTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.infuseTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.infuseTemp = d;\n }\n }\n\n public double getBeerXmlStandardInfuseTemp() {\n return this.infuseTemp;\n }\n\n public void setBeerXmlStandardInfuseTemp(double d) {\n this.infuseTemp = d;\n }\n\n public void setAutoCalcInfuseTemp(boolean b) {\n this.calcInfuseTemp = b;\n }\n\n public void setAutoCalcInfuseAmt(boolean b) {\n this.calcInfuseAmt = b;\n }\n\n public void setAutoCalcDecoctAmt(boolean b) {\n this.calcDecoctAmt = b;\n }\n\n public boolean getAutoCalcDecoctAmt() {\n return this.calcDecoctAmt;\n }\n\n public boolean getAutoCalcInfuseTemp() {\n return this.calcInfuseTemp;\n }\n\n public boolean getAutoCalcInfuseAmt() {\n return this.calcInfuseAmt;\n }\n\n public void setDisplayStepTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.stepTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.stepTemp = temp;\n }\n }\n\n public double getDisplayStepTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.stepTemp);\n }\n else {\n return this.stepTemp;\n }\n }\n\n public void setBeerXmlStandardStepTemp(double temp) {\n this.stepTemp = temp;\n }\n\n public double getBeerXmlStandardStepTemp() {\n return this.stepTemp;\n }\n\n public double getBeerXmlStandardWaterToGrainRatio() {\n // If this is the first in the list, use the configured value.\n // Otherwise, we need to calculate it based on the water added.\n if (this.firstInList() && ! this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n return this.waterToGrainRatio;\n }\n return (this.getBeerXmlStandardInfuseAmount() + this.getBXSTotalWaterInMash()) / this.getBeerXmlStandardMashWeight();\n }\n\n public double getDisplayWaterToGrainRatio() {\n if (Units.getUnitSystem().equals(Units.IMPERIAL)) {\n return Units.LPKGtoQPLB(getBeerXmlStandardWaterToGrainRatio());\n }\n else {\n return getBeerXmlStandardWaterToGrainRatio();\n }\n }\n\n public void setBeerXmlStandardWaterToGrainRatio(double d) {\n // Don't update if less than 0. Impossible value.\n if (d <= 0) {\n return;\n }\n this.waterToGrainRatio = d;\n }\n\n public void setDisplayWaterToGrainRatio(double d) {\n if (d <= 0) {\n return;\n }\n if (Units.getUnitSystem().equals(Units.IMPERIAL)) {\n this.waterToGrainRatio = Units.QPLBtoLPKG(d);\n }\n else {\n this.waterToGrainRatio = d;\n }\n }\n\n public void setOrder(int i) {\n // Order is privately used for ordering mash steps\n // when they are received from the database. Once they\n // are out of the db, we use the order in the list as the order.\n // When saved, the orders will be updated in the database.\n this.order = i;\n }\n\n public int getOrder() {\n return this.recipe.getMashProfile().getMashStepList().indexOf(this);\n }\n\n public void setDescription(String s) {\n this.description = s;\n }\n\n public String getDescription() {\n return this.description;\n }\n\n public void setStepTime(double time) {\n this.stepTime = time;\n }\n\n public double getStepTime() {\n return this.stepTime;\n }\n\n public void setRampTime(double time) {\n this.rampTime = time;\n }\n\n public double getRampTime() {\n return this.rampTime;\n }\n\n public void setBeerXmlStandardEndTemp(double temp) {\n this.endTemp = temp;\n }\n\n public double getBeerXmlStandardEndTemp() {\n return this.endTemp;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public long getId() {\n return this.id;\n }\n\n public void setOwnerId(long id) {\n this.ownerId = id;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setRecipe(Recipe r) {\n this.recipe = r;\n }\n\n public Recipe getRecipe() {\n return this.recipe;\n }\n\n public double getBeerXmlStandardMashWeight() {\n // If there are no ingredients for this recipe yet, we need to use something!\n // Fake it, assume 12 pounds of grain by default.\n double weight = BrewCalculator.TotalBeerXmlMashWeight(this.recipe);\n return weight == 0 ? Units.poundsToKilos(12) : weight;\n }\n\n public MashStep getPreviousStep() throws Exception {\n if (this.firstInList()) {\n throw new Exception(); // TODO: This should throw a specific exception.\n }\n\n int idx = this.recipe.getMashProfile().getMashStepList().indexOf(this);\n return this.recipe.getMashProfile().getMashStepList().get(idx - 1);\n }\n\n public double getBXSTotalWaterInMash() {\n double amt = 0;\n\n for (MashStep step : this.recipe.getMashProfile().getMashStepList()) {\n if (step.equals(this)) {\n break;\n }\n amt += step.getBeerXmlStandardInfuseAmount();\n }\n Log.d(\"MashStep\", \"Step \" + this.getName() + \" has \" + Units.litersToGallons(amt) + \" gal in mash.\");\n return amt;\n }\n}",
"public class Recipe implements Parcelable {\n // ===============================================================\n // Static values =================================================\n // ===============================================================\n public static final String EXTRACT = \"Extract\";\n public static final String ALL_GRAIN = \"All Grain\";\n public static final String PARTIAL_MASH = \"Partial Mash\";\n public static final int STAGE_PRIMARY = 1;\n public static final int STAGE_SECONDARY = 2;\n public static final int STAGE_TERTIARY = 3;\n public static final Parcelable.Creator<Recipe> CREATOR =\n new Parcelable.Creator<Recipe>() {\n @Override\n public Recipe createFromParcel(Parcel p) {\n return new Recipe(p);\n }\n\n @Override\n public Recipe[] newArray(int size) {\n return new Recipe[]{};\n }\n };\n\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // Recipe name\n private int version; // XML Version -- 1\n private String type; // Extract, Grain, Mash\n private BeerStyle style; // Stout, Pilsner, etc.\n private String brewer; // Brewer's name\n private double batchSize; // Target size (L)\n private double boilSize; // Pre-boil vol (L)\n private int boilTime; // In Minutes\n private double efficiency; // 100 for extract\n private ArrayList<Hop> hops; // Hops used\n private ArrayList<Fermentable> fermentables; // Fermentables used\n private ArrayList<Yeast> yeasts; // Yeasts used\n private ArrayList<Misc> miscs; // Misc ingredients used\n private ArrayList<Water> waters; // Waters used\n private MashProfile mashProfile; // Mash profile for non-extracts\n\n // ================================================================\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double OG; // Original Gravity\n private double FG; // Final Gravity\n private int fermentationStages; // # of Fermentation stages\n private int primaryAge; // Time in primary in days\n private double primaryTemp; // Temp in primary in C\n private int secondaryAge; // Time in Secondary in days\n private double secondaryTemp; // Temp in secondary in C\n private int tertiaryAge; // Time in tertiary in days\n private double tertiaryTemp; // Temp in tertiary in C\n private String tasteNotes; // Taste notes\n private int tasteRating; // Taste score out of 50\n private int bottleAge; // Bottle age in days\n private double bottleTemp; // Bottle temp in C\n private boolean isForceCarbonated;// True if force carb is used\n private double carbonation; // Volumes of carbonation\n private String brewDate; // Date brewed\n private String primingSugarName; // Name of sugar for priming\n private double primingSugarEquiv; // Equivalent amount of priming sugar to be used\n private double kegPrimingFactor; // factor - use less sugar when kegging vs bottles\n private double carbonationTemp; // Carbonation temperature in C\n private int calories; // Calories (KiloCals)\n private String lastModified; // Date last modified in database.\n\n // ================================================================\n // Custom Fields ==================================================\n // ================================================================\n private long id; // id for use in database\n private String notes; // User input notes\n private int batchTime; // Total length in weeks\n private double ABV; // Alcohol by volume\n private double bitterness; // Bitterness in IBU\n private double color; // Color - SRM\n private InstructionGenerator instructionGenerator;\n private double measuredOG; // Brew day stat: measured OG\n private double measuredFG; // Brew stat: measured FG\n private double measuredVol; // Measured final volume (L) of batch.\n private double steepTemp; // Temperature to steep grains.\n\n // ================================================================\n // Fields for auto-calculation ====================================\n // ================================================================\n private boolean calculateBoilVolume; // Calculate the boil volume automatically\n private boolean calculateStrikeVolume; // Calculate strike vol automatically\n private boolean calculateStrikeTemp; // Calculate strike temp automatically\n\n // Public constructors\n public Recipe(String s) {\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n this.name = s;\n this.setVersion(1);\n this.setType(ALL_GRAIN);\n this.style = Constants.BEERSTYLE_OTHER;\n this.setBrewer(\"Unknown Brewer\");\n this.setDisplayBatchSize(5);\n this.setDisplayBoilSize(2.5);\n this.setBoilTime(60);\n this.setEfficiency(70);\n this.hops = new ArrayList<Hop>();\n this.fermentables = new ArrayList<Fermentable>();\n this.yeasts = new ArrayList<Yeast>();\n this.miscs = new ArrayList<Misc>();\n this.waters = new ArrayList<Water>();\n this.mashProfile = new MashProfile(this);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n this.OG = 1;\n this.setFG(1);\n this.setFermentationStages(1);\n this.primaryAge = 14;\n this.secondaryAge = 0;\n this.tertiaryAge = 0;\n this.primaryTemp = 21;\n this.secondaryTemp = 21;\n this.tertiaryTemp = 21;\n this.bottleAge = 14;\n this.brewDate = \"\";\n\n // Custom Fields ==================================================\n // ================================================================\n this.id = - 1;\n this.notes = \"\";\n this.tasteNotes = \"\";\n this.batchTime = 60;\n this.ABV = 0;\n this.bitterness = 0;\n this.color = 0;\n this.instructionGenerator = new InstructionGenerator(this);\n this.measuredOG = 0;\n this.measuredFG = 0;\n this.measuredVol = 0;\n this.steepTemp = Units.fahrenheitToCelsius(155);\n this.lastModified = new SimpleDateFormat(Constants.LAST_MODIFIED_DATE_FMT).format(new Date());\n\n // Fields for auto-calculation ====================================\n // ================================================================\n calculateBoilVolume = true;\n calculateStrikeVolume = false;\n calculateStrikeTemp = false;\n\n update();\n }\n\n // Constructor with no arguments!\n public Recipe() {\n this(\"New Recipe\");\n }\n\n public Recipe(Parcel p) {\n hops = new ArrayList<Hop>();\n fermentables = new ArrayList<Fermentable>();\n yeasts = new ArrayList<Yeast>();\n miscs = new ArrayList<Misc>();\n waters = new ArrayList<Water>();\n\n name = p.readString(); // Recipe name\n version = p.readInt(); // XML Version -- 1\n type = p.readString(); // Extract, Grain, Mash\n style = p.readParcelable(BeerStyle.class.getClassLoader()); // Stout, Pilsner, etc.\n brewer = p.readString(); // Brewer's name\n batchSize = p.readDouble();\n boilSize = p.readDouble();\n boilTime = p.readInt(); // In Minutes\n efficiency = p.readDouble(); // 100 for extract\n p.readTypedList(hops, Hop.CREATOR); // Hops used\n p.readTypedList(fermentables, Fermentable.CREATOR); // Fermentables used\n p.readTypedList(yeasts, Yeast.CREATOR); // Yeasts used\n p.readTypedList(miscs, Misc.CREATOR); // Misc ingredients used\n p.readTypedList(waters, Water.CREATOR); // Waters used\n mashProfile = p.readParcelable(MashProfile.class.getClassLoader()); // Mash profile for non-extracts\n mashProfile.setRecipe(this);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n OG = p.readDouble(); // Original Gravity\n FG = p.readDouble(); // Final Gravity\n fermentationStages = p.readInt(); // # of Fermentation stages\n primaryAge = p.readInt(); // Time in primary in days\n primaryTemp = p.readDouble(); // Temp in primary in C\n secondaryAge = p.readInt(); // Time in Secondary in days\n secondaryTemp = p.readDouble(); // Temp in secondary in C\n tertiaryAge = p.readInt(); // Time in tertiary in days\n tertiaryTemp = p.readDouble(); // Temp in tertiary in C\n tasteNotes = p.readString(); // Taste notes\n tasteRating = p.readInt(); // Taste score out of 50\n bottleAge = p.readInt(); // Bottle age in days\n bottleTemp = p.readDouble(); // Bottle temp in C\n isForceCarbonated = p.readInt() > 0; // True if force carb is used\n carbonation = p.readDouble(); // Volumes of carbonation\n brewDate = p.readString(); // Date brewed\n primingSugarName = p.readString(); // Name of sugar for priming\n primingSugarEquiv = p.readDouble(); // Equivalent amount of priming sugar to be used\n kegPrimingFactor = p.readDouble(); // factor - use less sugar when kegging vs bottles\n carbonationTemp = p.readDouble(); // Carbonation temperature in C\n calories = p.readInt();\n lastModified = p.readString();\n\n // Custom Fields ==================================================\n // ================================================================\n id = p.readLong(); // id for use in database\n notes = p.readString(); // User input notes\n batchTime = p.readInt(); // Total length in weeks\n ABV = p.readDouble(); // Alcohol by volume\n bitterness = p.readDouble(); // Bitterness in IBU\n color = p.readDouble(); // Color - SRM\n // Instruction generator not included in parcel\n measuredOG = p.readDouble(); // Brew day stat: measured OG\n measuredFG = p.readDouble(); // Brew stat: measured FG\n measuredVol = p.readDouble(); // Brew stat: measured volume\n steepTemp = p.readDouble(); // Temperature to steep grains for extract recipes.\n\n // Fields for auto-calculation ====================================\n // ================================================================\n calculateBoilVolume = p.readInt() > 0;\n calculateStrikeVolume = p.readInt() > 0;\n calculateStrikeTemp = p.readInt() > 0;\n\n // Create instruction generator\n instructionGenerator = new InstructionGenerator(this);\n update();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n p.writeString(name); // Recipe name\n p.writeInt(version); // XML Version -- 1\n p.writeString(type); // Extract, Grain, Mash\n p.writeParcelable(style, flags); // Stout, Pilsner, etc.\n p.writeString(brewer); // Brewer's name\n p.writeDouble(batchSize); // Target size (L)\n p.writeDouble(boilSize); // Pre-boil vol (L)\n p.writeInt(boilTime); // In Minutes\n p.writeDouble(efficiency); // 100 for extract\n p.writeTypedList(hops); // Hops used\n p.writeTypedList(fermentables); // Fermentables used\n p.writeTypedList(yeasts); // Yeasts used\n p.writeTypedList(miscs); // Misc ingredients used\n p.writeTypedList(waters); // Waters used\n p.writeParcelable(mashProfile, flags); // Mash profile for non-extracts\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(OG); // Original Gravity\n p.writeDouble(FG); // Final Gravity\n p.writeInt(fermentationStages); // # of Fermentation stages\n p.writeInt(primaryAge); // Time in primary in days\n p.writeDouble(primaryTemp); // Temp in primary in C\n p.writeInt(secondaryAge); // Time in Secondary in days\n p.writeDouble(secondaryTemp); // Temp in secondary in C\n p.writeInt(tertiaryAge); // Time in tertiary in days\n p.writeDouble(tertiaryTemp); // Temp in tertiary in C\n p.writeString(tasteNotes); // Taste notes\n p.writeInt(tasteRating); // Taste score out of 50\n p.writeInt(bottleAge); // Bottle age in days\n p.writeDouble(bottleTemp); // Bottle temp in C\n p.writeInt(isForceCarbonated ? 1 : 0); // True if force carb is used\n p.writeDouble(carbonation); // Volumes of carbonation\n p.writeString(brewDate); // Date brewed\n p.writeString(primingSugarName); // Name of sugar for priming\n p.writeDouble(primingSugarEquiv); // Equivalent amount of priming sugar to be used\n p.writeDouble(kegPrimingFactor); // factor - use less sugar when kegging vs bottles\n p.writeDouble(carbonationTemp); // Carbonation temperature in C\n p.writeInt(calories); // Calories (KiloCals)\n p.writeString(lastModified);\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(id); // id for use in database\n p.writeString(notes); // User input notes\n p.writeInt(batchTime); // Total length in weeks\n p.writeDouble(ABV); // Alcohol by volume\n p.writeDouble(bitterness); // Bitterness in IBU\n p.writeDouble(color); // Color - SRM\n // Instruction generator not included in parcel\n p.writeDouble(measuredOG); // Brew day stat: measured OG\n p.writeDouble(measuredFG); // Brew stat: measured FG\n p.writeDouble(measuredVol); // Brew stat: measured volume\n p.writeDouble(steepTemp); // Steep temperature for extract recipes.\n\n // Fields for auto-calculation ====================================\n // ================================================================\n p.writeInt(calculateBoilVolume ? 1 : 0);\n p.writeInt(calculateStrikeVolume ? 1 : 0);\n p.writeInt(calculateStrikeTemp ? 1 : 0);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n /**\n * Recipe objects are identified by the recipe name and the recipe's ID, as used when stored in\n * the database. If a recipe has not been stored in the database, it will not necessarily have a\n * unique ID.\n */\n @Override\n public boolean equals(Object o) {\n // If the given object is not a Recipe, it cannot be equal.\n if (! (o instanceof Recipe)) {\n return false;\n }\n\n // The given object is a recipe - cast it.\n Recipe other = (Recipe) o;\n\n // Check index fields.\n if (! other.getRecipeName().equals(this.getRecipeName())) {\n // If the given recipe does not have the same name, it is not equal.\n return false;\n }\n else if (other.getId() != this.getId()) {\n // If the given recipe does not have the same ID, it is not equal.\n return false;\n }\n\n // Otherwise, the two recipes are equal.\n return true;\n }\n\n @Override\n public String toString() {\n return this.getRecipeName();\n }\n\n // Public methods\n public void update() {\n setColor(BrewCalculator.Color(this));\n setOG(BrewCalculator.OriginalGravity(this));\n setBitterness(BrewCalculator.Bitterness(this));\n setFG(BrewCalculator.FinalGravity(this));\n setABV(BrewCalculator.AlcoholByVolume(this));\n this.instructionGenerator.generate();\n }\n\n public String getRecipeName() {\n return this.name;\n }\n\n public void setRecipeName(String name) {\n this.name = name;\n }\n\n public void addIngredient(Ingredient i) {\n Log.d(getRecipeName() + \"::addIngredient\", \"Adding ingredient: \" + i.getName());\n if (i.getType().equals(Ingredient.HOP)) {\n addHop(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n addFermentable(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n addMisc(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n addYeast(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n addWater(i);\n }\n\n update();\n }\n\n public void removeIngredientWithId(long id) {\n for (Ingredient i : getIngredientList()) {\n if (i.getId() == id) {\n Log.d(\"Recipe\", \"Removing ingredient \" + i.getName());\n removeIngredient(i);\n }\n }\n }\n\n public void removeIngredient(Ingredient i) {\n if (i.getType().equals(Ingredient.HOP)) {\n hops.remove(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n fermentables.remove(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n miscs.remove(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n yeasts.remove(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n waters.remove(i);\n }\n\n if (getIngredientList().contains(i)) {\n Log.d(\"Recipe\", \"Failed to remove ingredient\");\n }\n else {\n Log.d(\"Recipe\", \"Successfully removed ingredient\");\n }\n\n update();\n }\n\n public MashProfile getMashProfile() {\n return this.mashProfile;\n }\n\n public void setMashProfile(MashProfile profile) {\n this.mashProfile = profile;\n this.mashProfile.setRecipe(this);\n update();\n }\n\n public String getNotes() {\n return notes;\n }\n\n public void setNotes(String notes) {\n this.notes = notes;\n }\n\n public BeerStyle getStyle() {\n return style;\n }\n\n public void setStyle(BeerStyle beerStyle) {\n this.style = beerStyle;\n }\n\n public ArrayList<Ingredient> getIngredientList() {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n list.addAll(hops);\n list.addAll(fermentables);\n list.addAll(yeasts);\n list.addAll(miscs);\n list.addAll(waters);\n\n Collections.sort(list, new RecipeIngredientsComparator());\n return list;\n }\n\n public void setIngredientsList(ArrayList<Ingredient> ingredientsList) {\n\n for (Ingredient i : ingredientsList) {\n if (i.getType().equals(Ingredient.HOP)) {\n addHop(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n addFermentable(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n addMisc(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n addYeast(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n addWater(i);\n }\n }\n\n update();\n }\n\n private void addWater(Ingredient i) {\n Water w = (Water) i;\n waters.add(w);\n }\n\n private void addYeast(Ingredient i) {\n Yeast y = (Yeast) i;\n yeasts.add(y);\n }\n\n private void addMisc(Ingredient i) {\n Misc m = (Misc) i;\n miscs.add(m);\n }\n\n private void addFermentable(Ingredient i) {\n Log.d(getRecipeName() + \"::addFermentable\", \"Adding fermentable: \" + i.getName());\n Fermentable f = (Fermentable) i;\n this.fermentables.add(f);\n }\n\n private void addHop(Ingredient i) {\n Hop h = (Hop) i;\n this.hops.add(h);\n }\n\n public ArrayList<Instruction> getInstructionList() {\n return this.instructionGenerator.getInstructions();\n }\n\n public double getOG() {\n return OG;\n }\n\n public void setOG(double gravity) {\n gravity = (double) Math.round(gravity * 1000) / 1000;\n this.OG = gravity;\n }\n\n public double getBitterness() {\n bitterness = (double) Math.round(bitterness * 10) / 10;\n return bitterness;\n }\n\n public void setBitterness(double bitterness) {\n bitterness = (double) Math.round(bitterness * 10) / 10;\n this.bitterness = bitterness;\n }\n\n public double getColor() {\n color = (double) Math.round(color * 10) / 10;\n return color;\n }\n\n public void setColor(double color) {\n color = (double) Math.round(color * 10) / 10;\n this.color = color;\n }\n\n public double getABV() {\n ABV = (double) Math.round(ABV * 10) / 10;\n return ABV;\n }\n\n public void setABV(double aBV) {\n ABV = (double) Math.round(ABV * 10) / 10;\n ABV = aBV;\n }\n\n public int getBatchTime() {\n return batchTime;\n }\n\n public void setBatchTime(int batchTime) {\n this.batchTime = batchTime;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getVolumeUnits() {\n return Units.getVolumeUnits();\n }\n\n public double getDisplayBatchSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.batchSize);\n }\n else {\n return this.batchSize;\n }\n }\n\n public void setDisplayBatchSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.batchSize = Units.gallonsToLiters(size);\n }\n else {\n this.batchSize = size;\n }\n }\n\n public double getDisplayMeasuredBatchSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.measuredVol);\n }\n else {\n return this.measuredVol;\n }\n }\n\n public void setDisplayMeasuredBatchSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.measuredVol = Units.gallonsToLiters(size);\n }\n else {\n this.measuredVol = size;\n }\n }\n\n public double getBeerXmlStandardBatchSize() {\n return this.batchSize;\n }\n\n public void setBeerXmlStandardBatchSize(double v) {\n this.batchSize = v;\n }\n\n public double getBeerXmlMeasuredBatchSize() {\n return this.measuredVol;\n }\n\n public void setBeerXmlMeasuredBatchSize(double d) {\n this.measuredVol = d;\n }\n\n public int getBoilTime() {\n return boilTime;\n }\n\n public void setBoilTime(int boilTime) {\n this.boilTime = boilTime;\n }\n\n public double getEfficiency() {\n if (this.getType().equals(EXTRACT)) {\n return 100;\n }\n return efficiency;\n }\n\n public void setEfficiency(double efficiency) {\n this.efficiency = efficiency;\n }\n\n public String getBrewer() {\n return brewer;\n }\n\n public void setBrewer(String brewer) {\n this.brewer = brewer;\n }\n\n public double getDisplayBoilSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n if (this.calculateBoilVolume) {\n return Units.litersToGallons(calculateBoilVolume());\n }\n else {\n return Units.litersToGallons(this.boilSize);\n }\n }\n else {\n if (this.calculateBoilVolume) {\n return calculateBoilVolume();\n }\n else {\n return this.boilSize;\n }\n }\n }\n\n public void setDisplayBoilSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.boilSize = Units.gallonsToLiters(size);\n }\n else {\n this.boilSize = size;\n }\n }\n\n private double calculateBoilVolume() {\n // TODO: Get parameters from equipment profile.\n double TRUB_LOSS = Units.gallonsToLiters(.3); // Liters lost\n double SHRINKAGE = .04; // Percent lost\n double EVAP_LOSS = Units.gallonsToLiters(1.5); // Evaporation loss (L/hr)\n\n if (this.type.equals(Recipe.ALL_GRAIN)) {\n return batchSize * (1 + SHRINKAGE) + TRUB_LOSS + (EVAP_LOSS * Units.minutesToHours(boilTime));\n }\n else {\n return (batchSize / 3) * (1 + SHRINKAGE) + TRUB_LOSS + (EVAP_LOSS * Units.minutesToHours\n (boilTime));\n }\n }\n\n public double getBeerXmlStandardBoilSize() {\n return boilSize;\n }\n\n public void setBeerXmlStandardBoilSize(double boilSize) {\n this.boilSize = boilSize;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public double getFG() {\n this.FG = (double) Math.round(FG * 1000) / 1000;\n return this.FG;\n }\n\n public void setFG(double fG) {\n fG = (double) Math.round(fG * 1000) / 1000;\n this.FG = fG;\n }\n\n public int getFermentationStages() {\n return fermentationStages;\n }\n\n public void setFermentationStages(int fermentationStages) {\n this.fermentationStages = fermentationStages;\n }\n\n public int getTotalFermentationDays() {\n return this.primaryAge + this.secondaryAge + this.tertiaryAge;\n }\n\n public int getVersion() {\n return version;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public ArrayList<Misc> getMiscList() {\n return miscs;\n }\n\n public ArrayList<Fermentable> getFermentablesList() {\n return fermentables;\n }\n\n public ArrayList<Hop> getHopsList() {\n return hops;\n }\n\n public ArrayList<Yeast> getYeastsList() {\n return yeasts;\n }\n\n public ArrayList<Water> getWatersList() {\n return waters;\n }\n\n /**\n * Generates a list of hops in this recipe with the given use.\n *\n * @param use\n * One of Ingredient.USE_*\n * @return An ArrayList of Ingredients.\n */\n public ArrayList<Ingredient> getHops(String use) {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n for (Hop h : this.getHopsList()) {\n if (h.getUse().equals(use)) {\n list.add(h);\n }\n }\n return list;\n }\n\n public double getMeasuredOG() {\n return this.measuredOG;\n }\n\n public void setMeasuredOG(double d) {\n this.measuredOG = d;\n }\n\n public double getMeasuredFG() {\n return this.measuredFG;\n }\n\n public void setMeasuredFG(double d) {\n this.measuredFG = d;\n }\n\n public int getDisplayCoolToFermentationTemp() {\n // Metric - imperial conversion is performed in Yeast\n for (Yeast y : this.getYeastsList()) {\n return y.getDisplayFermentationTemp();\n }\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return 65;\n }\n else {\n return (int) Units.fahrenheitToCelsius(65);\n }\n }\n\n public double getDisplaySteepTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(steepTemp);\n }\n else {\n return steepTemp;\n }\n }\n\n public void setDisplaySteepTemp(double t) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.steepTemp = Units.fahrenheitToCelsius(t);\n }\n else {\n this.steepTemp = t;\n }\n }\n\n public void setNumberFermentationStages(int stages) {\n this.fermentationStages = stages;\n }\n\n public void setFermentationAge(int stage, int age) {\n switch (stage) {\n case STAGE_PRIMARY:\n this.primaryAge = age;\n case STAGE_SECONDARY:\n this.secondaryAge = age;\n case STAGE_TERTIARY:\n this.tertiaryAge = age;\n }\n }\n\n public int getFermentationAge(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n return this.primaryAge;\n case STAGE_SECONDARY:\n return this.secondaryAge;\n case STAGE_TERTIARY:\n return this.tertiaryAge;\n default:\n return 7;\n }\n }\n\n public void setBeerXmlStandardFermentationTemp(int stage, double temp) {\n switch (stage) {\n case STAGE_PRIMARY:\n this.primaryTemp = temp;\n case STAGE_SECONDARY:\n this.secondaryTemp = temp;\n case STAGE_TERTIARY:\n this.tertiaryTemp = temp;\n }\n }\n\n public double getBeerXmlStandardFermentationTemp(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n return this.primaryTemp;\n case STAGE_SECONDARY:\n return this.secondaryTemp;\n case STAGE_TERTIARY:\n return this.tertiaryTemp;\n default:\n return 21;\n }\n }\n\n public void setDisplayFermentationTemp(int stage, double temp) {\n switch (stage) {\n case STAGE_PRIMARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.primaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.primaryTemp = temp;\n }\n break;\n\n case STAGE_SECONDARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.secondaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.secondaryTemp = temp;\n }\n break;\n\n case STAGE_TERTIARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.tertiaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.secondaryTemp = temp;\n }\n break;\n }\n }\n\n public double getDisplayFermentationTemp(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.primaryTemp);\n }\n else {\n return this.primaryTemp;\n }\n\n case STAGE_SECONDARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.secondaryTemp);\n }\n else {\n return this.secondaryTemp;\n }\n\n case STAGE_TERTIARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.tertiaryTemp);\n }\n else {\n return this.tertiaryTemp;\n }\n\n default:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(21);\n }\n else {\n return 21;\n }\n }\n }\n\n public String getTasteNotes() {\n if (this.tasteNotes == null) {\n this.tasteNotes = \"\";\n }\n return this.tasteNotes;\n }\n\n public void setTasteNotes(String s) {\n this.tasteNotes = s;\n }\n\n public int getTasteRating() {\n return this.tasteRating;\n }\n\n public void setTasteRating(int i) {\n this.tasteRating = i;\n }\n\n public int getBottleAge() {\n return this.bottleAge;\n }\n\n public void setBottleAge(int i) {\n this.bottleAge = i;\n }\n\n public double getBeerXmlStandardBottleTemp() {\n return this.bottleTemp;\n }\n\n public void setBeerXmlStandardBottleTemp(double d) {\n this.bottleTemp = d;\n }\n\n public double getDisplayBottleTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.bottleTemp);\n }\n else {\n return this.bottleTemp;\n }\n }\n\n public void setDisplayBottleTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.bottleTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.bottleTemp = d;\n }\n }\n\n public boolean isForceCarbonated() {\n return this.isForceCarbonated;\n }\n\n public void setIsForceCarbonated(boolean b) {\n this.isForceCarbonated = b;\n }\n\n public double getCarbonation() {\n return this.carbonation;\n }\n\n public void setCarbonation(double d) {\n this.carbonation = d;\n }\n\n public void setLastModified(String s) {\n this.lastModified = s;\n }\n\n public Date getLastModified() {\n try {\n Date d = new SimpleDateFormat(Constants.LAST_MODIFIED_DATE_FMT).parse(this.lastModified);\n Log.d(\"Recipe\", this.toString() + \" was last modified \" + d.toString());\n return d;\n } catch (ParseException e) {\n Log.w(\"Recipe\", \"Failed to parse lastModified: \" + this.lastModified);\n return new Date();\n } catch (NullPointerException e) {\n // No modified date was ever set - likely a recipe from before this\n // feature existed.\n Log.w(\"Recipe\", \"No last modified for recipe: \" + this.toString());\n return new Date();\n }\n }\n\n public String getBrewDate() {\n if (this.brewDate == null) {\n this.brewDate = \"\";\n }\n return this.brewDate;\n }\n\n public void setBrewDate(String s) {\n this.brewDate = s;\n }\n\n /* There is no standardized date format in beerXML. Thus, we need\n * to try and parse as many formats as possible. This method takes the given raw\n * date string and returns the best effort Date object. If not we're unable to parse\n * the date, then this method returns today's date.\n */\n public Date getBrewDateDate() {\n // First, try the common date formats to speed things up. We'll resort to a full search\n // of known formats if these fail.\n String d = this.getBrewDate();\n\n // This format is common for BeerSmith recipes.\n try {\n return new SimpleDateFormat(\"MM/dd/yyyy\").parse(d);\n } catch (ParseException e) {\n // Do nothing.\n }\n\n // This format is used by Biermacht.\n try {\n return new SimpleDateFormat(\"dd MMM yyyy\").parse(d);\n } catch (ParseException e) {\n // Do nothing.\n }\n\n // This takes a long time, so only do it as a last resort.\n // Look through a bunch of known formats to figure out what it is.\n String fmt = DateUtil.determineDateFormat(d);\n if (fmt == null) {\n Log.w(\"Recipe\", \"Failed to parse date: \" + d);\n return new Date();\n }\n try {\n return new SimpleDateFormat(fmt).parse(d);\n } catch (ParseException e) {\n Log.e(\"Recipe\", \"Failed to parse date: \" + d);\n e.printStackTrace();\n return new Date();\n }\n }\n\n public String getPrimingSugarName() {\n return this.primingSugarName;\n }\n\n public void setPrimingSugarName(String s) {\n this.primingSugarName = s;\n }\n\n public double getPrimingSugarEquiv() {\n // TODO\n return 0.0;\n }\n\n public void setPrimingSugarEquiv(double d) {\n this.primingSugarEquiv = d;\n }\n\n public double getBeerXmlStandardCarbonationTemp() {\n return this.carbonationTemp;\n }\n\n public void setBeerXmlStandardCarbonationTemp(double d) {\n this.carbonationTemp = d;\n }\n\n public double getDisplayCarbonationTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.carbonationTemp);\n }\n else {\n return this.carbonationTemp;\n }\n }\n\n public void setDisplayCarbonationTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.carbonationTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.carbonationTemp = d;\n }\n }\n\n public double getKegPrimingFactor() {\n return this.kegPrimingFactor;\n }\n\n public void setKegPrimingFactor(double d) {\n this.kegPrimingFactor = d;\n }\n\n public int getCalories() {\n return this.calories;\n }\n\n public void setCalories(int i) {\n this.calories = i;\n }\n\n public boolean getCalculateBoilVolume() {\n return this.calculateBoilVolume;\n }\n\n public void setCalculateBoilVolume(boolean b) {\n this.calculateBoilVolume = b;\n }\n\n public boolean getCalculateStrikeVolume() {\n return this.calculateStrikeVolume;\n }\n\n public void setCalculateStrikeVolume(boolean b) {\n this.calculateStrikeVolume = b;\n }\n\n public boolean getCalculateStrikeTemp() {\n return this.calculateStrikeTemp;\n }\n\n public void setCalculateStrikeTemp(boolean b) {\n this.calculateStrikeTemp = b;\n }\n\n public double getMeasuredABV() {\n if (this.getMeasuredFG() > 0 && this.getMeasuredOG() > this.getMeasuredFG()) {\n return (this.getMeasuredOG() - this.getMeasuredFG()) * 131;\n }\n else {\n return 0;\n }\n }\n\n public double getMeasuredEfficiency() {\n double potGravP, measGravP;\n double eff = 100;\n double measBatchSize = this.getBeerXmlMeasuredBatchSize();\n\n // If the user hasn't input a measured batch size, assume the recipe went as planned\n // and that the target final batch size was hit.\n if (measBatchSize == 0) {\n Log.d(\"Recipe\", \"No measured batch size, try using recipe batch size\");\n measBatchSize = this.getBeerXmlStandardBatchSize();\n }\n\n if (! this.getType().equals(Recipe.EXTRACT)) {\n eff = getEfficiency();\n }\n\n // Computation only valid if measured gravity is greater than 1, and batch size is non-zero.\n // Theoretically, measured gravity could be less than 1, but we don't support that yet.\n if ((this.getMeasuredOG() > 1) && (batchSize > 0)) {\n // Calculate potential milli-gravity points. Adjust the value returned by the\n // brew calculator, because it takes the expected efficiency into account (which\n // we don't want here).\n potGravP = (BrewCalculator.OriginalGravity(this) - 1) / (eff / 100);\n\n // Adjust potential gravity points to account for measured batch size.\n potGravP = potGravP * (getBeerXmlStandardBatchSize() / measBatchSize);\n\n // Calculate the measured milli-gravity points.\n measGravP = this.getMeasuredOG() - 1;\n\n // Return the efficiency.\n return 100 * measGravP / potGravP;\n }\n else {\n return 0;\n }\n }\n\n public void save(Context c) {\n Log.d(getRecipeName() + \"::save\", \"Saving with id: \" + this.getId());\n new DatabaseAPI(c).updateRecipe(this);\n }\n}"
] | import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.biermacht.brews.ingredient.Fermentable;
import com.biermacht.brews.ingredient.Hop;
import com.biermacht.brews.ingredient.Misc;
import com.biermacht.brews.ingredient.Water;
import com.biermacht.brews.ingredient.Yeast;
import com.biermacht.brews.recipe.BeerStyle;
import com.biermacht.brews.recipe.MashProfile;
import com.biermacht.brews.recipe.MashStep;
import com.biermacht.brews.recipe.Recipe;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; | Element versionElement = d.createElement("VERSION");
Element typeElement = d.createElement("TYPE");
Element amountElement = d.createElement("AMOUNT");
Element yieldElement = d.createElement("YIELD");
Element colorElement = d.createElement("COLOR");
Element addAfterBoilElement = d.createElement("ADD_AFTER_BOIL");
// Assign values
nameElement.setTextContent(f.getName());
versionElement.setTextContent(f.getVersion() + "");
typeElement.setTextContent(f.getFermentableType());
amountElement.setTextContent(f.getBeerXmlStandardAmount() + "");
yieldElement.setTextContent(f.getYield() + "");
colorElement.setTextContent(f.getLovibondColor() + "");
addAfterBoilElement.setTextContent(f.isAddAfterBoil() + "");
// Attach to element.
fermentableElement.appendChild(nameElement);
fermentableElement.appendChild(versionElement);
fermentableElement.appendChild(typeElement);
fermentableElement.appendChild(amountElement);
fermentableElement.appendChild(yieldElement);
fermentableElement.appendChild(colorElement);
fermentableElement.appendChild(addAfterBoilElement);
// Attach to list of elements.
fermentablesElement.appendChild(fermentableElement);
}
return fermentablesElement;
}
public Element getMiscsChild(Document d, ArrayList<Misc> l) {
// Create the element.
Element miscsElement = d.createElement("MISCS");
for (Misc m : l) {
miscsElement.appendChild(this.getMiscChild(d, m));
}
return miscsElement;
}
public Element getMiscChild(Document d, Misc m) {
// Create the element.
Element rootElement = d.createElement("MISC");
// Create a mapping of name -> value
Map<String, String> map = new HashMap<String, String>();
map.put("NAME", m.getName());
map.put("VERSION", m.getVersion() + "");
map.put("TYPE", m.getType());
map.put("USE", m.getUse());
map.put("AMOUNT", String.format("%2.8f", m.getBeerXmlStandardAmount()));
map.put("DISPLAY_AMOUNT", m.getDisplayAmount() + " " + m.getDisplayUnits());
map.put("DISPLAY_TIME", m.getTime() + " " + m.getTimeUnits());
map.put("AMOUNT_IS_WEIGHT", m.amountIsWeight() ? "true" : "false");
map.put("NOTES", m.getShortDescription());
map.put("USE_FOR", m.getUseFor());
for (Map.Entry<String, String> e : map.entrySet()) {
String fieldName = e.getKey();
String fieldValue = e.getValue();
Element element = d.createElement(fieldName);
element.setTextContent(fieldValue);
rootElement.appendChild(element);
}
return rootElement;
}
public Element getYeastsChild(Document d, ArrayList<Yeast> l) {
// Create the element.
Element yeastsElement = d.createElement("YEASTS");
for (Yeast y : l) {
Element yeastElement = d.createElement("YEAST");
// Create fields of element
Element nameElement = d.createElement("NAME");
Element versionElement = d.createElement("VERSION");
Element typeElement = d.createElement("TYPE");
Element formElement = d.createElement("FORM");
Element amountElement = d.createElement("AMOUNT");
Element laboratoryElement = d.createElement("LABORATORY");
Element productIdElement = d.createElement("PRODUCT_ID");
Element minTempElement = d.createElement("MIN_TEMPERATURE");
Element maxTempElement = d.createElement("MAX_TEMPERATURE");
Element attenuationElement = d.createElement("ATTENUATION");
// Assign values
nameElement.setTextContent(y.getName());
versionElement.setTextContent(y.getVersion() + "");
typeElement.setTextContent(y.getType());
formElement.setTextContent(y.getForm());
amountElement.setTextContent(y.getBeerXmlStandardAmount() + "");
laboratoryElement.setTextContent(y.getLaboratory());
productIdElement.setTextContent(y.getProductId());
minTempElement.setTextContent(y.getBeerXmlStandardFermentationTemp() + "");
maxTempElement.setTextContent(y.getBeerXmlStandardFermentationTemp() + "");
attenuationElement.setTextContent(y.getAttenuation() + "");
// Attach to element.
yeastElement.appendChild(nameElement);
yeastElement.appendChild(versionElement);
yeastElement.appendChild(typeElement);
yeastElement.appendChild(amountElement);
yeastElement.appendChild(laboratoryElement);
yeastElement.appendChild(productIdElement);
yeastElement.appendChild(minTempElement);
yeastElement.appendChild(maxTempElement);
yeastElement.appendChild(attenuationElement);
// Attach to list of elements.
yeastsElement.appendChild(yeastElement);
}
return yeastsElement;
}
| public Element getWatersChild(Document d, ArrayList<Water> l) { | 3 |
junicorn/roo | src/main/java/social/roo/controller/auth/GithubController.java | [
"public enum UserRole {\n\n GUEST(0, \"游客\"),\n MEMBER(1, \"注册会员-所有注册用户自动属于该角色\"),\n VIP(2, \"VIP会员-没有特殊权限,只是一个身份象征\"),\n MODERATOR(3, \"版主-可以管理若干个话题下的帖子\"),\n SUPER_MODERATOR(4, \"超级版主-可以管理所有话题下的帖子和所有会员\"),\n ADMIN(5, \"管理员-享有论坛的最高权限,可以管理整个论坛,设置整个论坛的参数\");\n\n @Getter\n private Integer id;\n @Getter\n private String description;\n\n UserRole(Integer id, String description) {\n this.id = id;\n this.description = description;\n }\n\n public String role(){\n return this.toString().toLowerCase();\n }\n\n}",
"public class Auth {\n\n public static boolean check() {\n return true;\n }\n\n /**\n * 验证某个操作的频率\n *\n * @param seconds 最近的多少秒内允许操作\n * @return 返回是否在允许的范围内\n */\n public static boolean checkFrequency(long seconds) {\n Date lastUpdated = Auth.loginUser().getUpdated();\n Date current = new Date();\n long diff = current.getTime() - lastUpdated.getTime();\n long diffSeconds = diff / 1000;\n if (seconds <= diffSeconds) {\n return true;\n }\n return false;\n }\n\n public static User loginUser() {\n User user = WebContext.request().session().attribute(RooConst.LOGIN_SESSION_KEY);\n return user;\n }\n\n public static void saveToSession(User user) {\n WebContext.request().session().attribute(RooConst.LOGIN_SESSION_KEY, user);\n }\n\n public static User getUserByCookie() {\n String hash = WebContext.request().cookie(RooConst.LOGIN_COOKIE_KEY, \"\");\n if (StringKit.isNotBlank(hash)) {\n Long uid = RooUtils.decodeId(hash);\n return new User().find(uid);\n }\n return null;\n }\n\n public static void saveToCookie(Long uid) {\n String hash = RooUtils.encodeId(uid);\n WebContext.response().cookie(RooConst.LOGIN_COOKIE_KEY, hash, 3600 * 7);\n }\n\n public static void logout() {\n WebContext.request().session().removeAttribute(LOGIN_SESSION_KEY);\n WebContext.response().removeCookie(RooConst.LOGIN_COOKIE_KEY);\n WebContext.response().redirect(\"/\");\n }\n\n}",
"@Data\npublic class GithubUser {\n\n private String avatar_url;\n private String login;\n private String email;\n\n}",
"@Table(value = \"roo_platform_user\")\n@Data\npublic class PlatformUser extends ActiveRecord {\n private Integer id;\n private String appType;\n private String username;\n private Long uid;\n private Date created;\n}",
"@Data\n@Table(value = \"roo_profile\", pk = \"uid\")\npublic class Profile extends ActiveRecord {\n\n /**\n * 用户id\n */\n private Long uid;\n /**\n * 用户名\n */\n private String username;\n /**\n * 发布的帖子数\n */\n private Integer topics;\n /**\n * 评论的帖子数\n */\n private Integer comments;\n /**\n * 收藏数\n */\n private Integer favorites;\n /**\n * 粉丝数\n */\n private Integer followers;\n /**\n * 所在位置\n */\n private String location;\n /**\n * 个人主页\n */\n private String website;\n /**\n * github账号\n */\n private String github;\n /**\n * 微博账号\n */\n private String weibo;\n /**\n * 个性签名\n */\n private String signature;\n\n}",
"@Table(value = \"roo_user\", pk = \"uid\")\n@Data\npublic class User extends ActiveRecord {\n\n /**\n * 用户id\n */\n private Long uid;\n /**\n *用户名\n */\n private String username;\n /**\n * 用户密码\n */\n private String password;\n /**\n * 用户邮箱\n */\n private String email;\n /**\n *\n */\n private String avatar;\n /**\n * 角色\n */\n private String role;\n /**\n * 注册时间\n */\n private Date created;\n /**\n * 最后一次操作时间\n */\n private Date updated;\n /**\n * 最后一次登录时间\n */\n private Date logined;\n /**\n * 用户状态 0:未激活 1:正常 2:停用 3:注销\n */\n private Integer state;\n\n}",
"@Bean\npublic class AccountService {\n\n public RestResponse<Boolean> register(SignupParam signupParam) {\n String vcode = WebContext.request().session().attribute(\"vcode\");\n// if (!signupParam.getVcode().equals(vcode)) {\n// return RestResponse.fail(\"验证码输入错误\");\n// }\n if (!signupParam.getPassword().equals(signupParam.getRepassword())) {\n return RestResponse.fail(\"密码输入不一致\");\n }\n long count = new User().where(\"username\", signupParam.getUsername())\n .and(\"state\", 1).count();\n if (count > 0) {\n return RestResponse.fail(\"用户名已存在\");\n }\n count = new User().where(\"email\", signupParam.getUsername())\n .and(\"state\", 1).count();\n if (count > 0) {\n return RestResponse.fail(\"邮箱已被注册\");\n }\n\n String pwd = EncryptKit.md5(signupParam.getUsername() + signupParam.getPassword());\n\n LocalDateTime now = LocalDateTime.now();\n\n User user = new User();\n user.setUsername(signupParam.getUsername());\n user.setPassword(pwd);\n user.setEmail(signupParam.getEmail());\n user.setState(0);\n user.setCreated(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));\n user.setUpdated(user.getCreated());\n user.setRole(UserRole.MEMBER.role());\n Long uid = user.save();\n\n String code = UUID.UU64();\n String activeLink = Roo.me().getSiteUrl() + \"/active?code=\" + code;\n\n signupParam.setLink(activeLink);\n\n Actived actived = new Actived();\n actived.setCode(code);\n actived.setUid(uid);\n actived.setUsername(signupParam.getUsername());\n actived.setEmail(signupParam.getEmail());\n actived.setCreated(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));\n // 有效期2小时\n actived.setExpired(Date.from(now.plusHours(2).atZone(ZoneId.systemDefault()).toInstant()));\n actived.setState(0);\n actived.save();\n\n // 发送注册邮件\n EmailUtils.sendRegister(signupParam);\n return RestResponse.ok();\n }\n\n public User getUserById(Long uid) {\n return new User().find(uid);\n }\n\n public RestResponse<User> login(SigninParam signinParam) {\n User user = new User();\n User u1 = user.where(\"username\", signinParam.getUsername()).find();\n User u2 = user.where(\"email\", signinParam.getUsername()).find();\n if (null == u1 && null == u2) {\n return RestResponse.fail(\"不存在该用户\");\n }\n if (null != u1) {\n if (!u1.getPassword().equals(EncryptKit.md5(u1.getUsername() + signinParam.getPassword()))) {\n return RestResponse.fail(\"用户名或密码错误\");\n }\n return RestResponse.ok(u1);\n }\n if (null != u2) {\n if (!u2.getPassword().equals(EncryptKit.md5(u2.getUsername() + signinParam.getPassword()))) {\n return RestResponse.fail(\"用户名或密码错误\");\n }\n return RestResponse.ok(u2);\n }\n return null;\n }\n\n public void active(Actived actived) {\n Base.atomic(() -> {\n Actived temp = new Actived();\n temp.setState(1);\n temp.update(actived.getId());\n\n Profile profile = new Profile();\n profile.setUid(actived.getUid());\n profile.setUsername(actived.getUsername());\n profile.save();\n\n // set user state is ok\n User user = new User();\n user.setState(1);\n user.setUpdated(new Date());\n user.update(actived.getUid());\n\n // settings user count +1\n Setting setting = new Setting();\n setting.setSkey(RooConst.SETTING_KEY_USERS);\n Setting users = setting.find();\n users.setSvalue(String.valueOf(Integer.parseInt(users.getSvalue()) + 1));\n users.update();\n\n // refresh settings\n Roo.me().refreshSettings();\n return true;\n });\n }\n\n public Profile getProfile(String username) {\n return new Profile().where(\"username\", username).find();\n }\n\n}",
"@Bean\npublic class PlatformService {\n\n public PlatformUser getPlatformUser(String username) {\n PlatformUser platformUser = new PlatformUser().where(\"username\", username).find();\n return platformUser;\n }\n\n}"
] | import com.blade.ioc.annotation.Inject;
import com.blade.kit.JsonKit;
import com.blade.mvc.WebContext;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.Param;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.http.Session;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import lombok.extern.slf4j.Slf4j;
import social.roo.enums.UserRole;
import social.roo.model.dto.Auth;
import social.roo.model.dto.GithubUser;
import social.roo.model.entity.PlatformUser;
import social.roo.model.entity.Profile;
import social.roo.model.entity.User;
import social.roo.service.AccountService;
import social.roo.service.PlatformService;
import java.util.Date;
import static social.roo.RooConst.LOGIN_SESSION_KEY; | package social.roo.controller.auth;
/**
* Github认证控制器
*
* @author biezhi
* @date 2017/10/9
*/
@Slf4j
@Path("auth/github")
public class GithubController {
@Inject
private OAuth20Service githubService;
@Inject
private PlatformService platformService;
@Inject
private AccountService accountService;
private static final String PROTECTED_RESOURCE_URL = "https://api.github.com/user";
@GetRoute("signin")
public void signin(com.blade.mvc.http.Response response) {
String authorizationUrl = githubService.getAuthorizationUrl();
log.info("authorizationUrl: {}", authorizationUrl);
response.redirect(authorizationUrl);
}
@GetRoute("callback")
public void callback(@Param String code, Session session, com.blade.mvc.http.Response response) throws Exception {
log.info("Code: {}", code);
final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
final Response res = execute(code, request);
String body = res.getBody();
GithubUser githubUser = JsonKit.formJson(body, GithubUser.class);
PlatformUser platformUser = platformService.getPlatformUser(githubUser.getLogin());
if (null != platformUser) {
// 直接登录
User user = accountService.getUserById(platformUser.getUid());
Auth.saveToSession(user);
Auth.saveToCookie(user.getUid());
log.info("登录成功");
} else {
// 判断当前是否已经登录
User loginUser = session.attribute(LOGIN_SESSION_KEY);
PlatformUser temp = new PlatformUser();
temp.setAppType("github");
temp.setCreated(new Date());
temp.setUsername(githubUser.getLogin());
Profile profile = new Profile();
if (null != loginUser) {
temp.setUid(loginUser.getUid());
profile.setUid(loginUser.getUid());
profile.setUsername(githubUser.getLogin());
profile.setGithub(githubUser.getLogin());
profile.save();
Auth.saveToSession(loginUser);
Auth.saveToCookie(loginUser.getUid());
} else {
// 创建新用户
User user = new User();
user.setUsername(githubUser.getLogin());
user.setPassword("");
user.setEmail(githubUser.getEmail());
user.setState(1);
user.setAvatar(githubUser.getAvatar_url());
user.setCreated(new Date());
user.setUpdated(new Date()); | user.setRole(UserRole.MEMBER.role()); | 0 |
1014277960/DailyReader | app/src/main/java/com/wulinpeng/daiylreader/bookdetail/presenter/BookDetailPresenterImpl.java | [
"public interface IBookDetailPresenter extends IBaseContract.IBasePresenter {\n\n public void getBookDetail();\n\n public boolean checkSelf();\n\n public void removeFromSelf();\n\n public void addToSelf();\n}",
"public interface IBookDetailView extends IBaseContract.IBaseView {\n\n public void onBookDetailFinish(BookDetail bookDetail);\n\n public void onError(String msg);\n}",
"public class CollectionChangeEvent {\n}",
"public class BookCollection {\n\n private List<BookDetail> books;\n\n public List<BookDetail> getBooks() {\n return books;\n }\n\n public void setBooks(List<BookDetail> books) {\n this.books = books;\n }\n\n @Override\n public String toString() {\n return \"BookCollection{\" +\n \"books=\" + books +\n '}';\n }\n}",
"public class BookDetail {\n /**\n * {\n \"_id\": \"565f903c433ac3f5197257f1\",\n \"title\": \"邪恶女神立志传\",\n \"author\": \"路人a\",\n \"longIntro\": \"他们,为了贯彻自己的原则、价值观,可以抛却一切,他们是最忠诚的狂信者,不屈的卫道士,他们是与世俗进行不懈斗争的真正英雄,解放陈规旧条的革命烈士,世人用充满敬畏的态度称呼这些有着不灭英魂的战士--变态。主角是个披着女神外皮的变态,很有爱的变态。剧情需要,人物和原版可能有所出入,认真你就输了。绝不tj,越后越精彩。变身百合小说,不喜勿入,免污贵眼。想看主角雄霸天下一身绝世神兵世所无敌谈笑间樯橹灰飞烟灭拯救世界的\",\n \"cover\": \"/agent/http://bj.bs.baidu.com/wise-novel-authority-logo/d9a36f4846fc0ce5c6972c15d22379ff.jpg\",\n \"cat\": \"其它\",\n \"majorCate\": \"其它\",\n \"minorCate\": \"\",\n \"_le\": true,\n \"allowMonthly\": false,\n \"allowVoucher\": true,\n \"allowBeanVoucher\": false,\n \"hasCp\": false,\n \"postCount\": 4,\n \"latelyFollower\": 2745,\n \"latelyFollowerBase\": 0,\n \"followerCount\": 0,\n \"wordCount\": 0,\n \"serializeWordCount\": -1,\n \"minRetentionRatio\": 0,\n \"retentionRatio\": \"7.11\",\n \"updated\": \"2015-12-03T00:43:40.598Z\",\n \"isSerial\": false,\n \"chaptersCount\": 280,\n \"lastChapter\": \"134 再会(end)(梅芙篇)\",\n \"gender\": [\"male\"],\n \"tags\": [\"玄幻\"],\n \"donate\": false\n }\n */\n\n private String _id;\n private String title;\n private String author;\n private String longIntro;\n private String cover;\n private String cat;\n private String majorCate;\n private String minorCate;\n private boolean _le;\n private boolean allowMonthly;\n private boolean allowVoucher;\n private boolean allowBeanVoucher;\n private boolean hasCp;\n private int postCount;\n private int latelyFollower;\n private int latelyFollowerBase;\n private int followerCount;\n private long wordCount;\n private int serializeWordCount;\n private int minRetentionRatio;\n private String retentionRatio;\n private String updated;\n private boolean isSerial;\n private int chaptersCount;\n private String lastChapter;\n private List<String> gender;\n private List<String> tags;\n private boolean donate;\n\n public String get_id() {\n return _id;\n }\n\n public void set_id(String _id) {\n this._id = _id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getAuthor() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n public String getLongIntro() {\n return longIntro;\n }\n\n public void setLongIntro(String longIntro) {\n this.longIntro = longIntro;\n }\n\n public String getCover() {\n return cover;\n }\n\n public void setCover(String cover) {\n this.cover = cover;\n }\n\n public String getCat() {\n return cat;\n }\n\n public void setCat(String cat) {\n this.cat = cat;\n }\n\n public String getMajorCate() {\n return majorCate;\n }\n\n public void setMajorCate(String majorCate) {\n this.majorCate = majorCate;\n }\n\n public String getMinorCate() {\n return minorCate;\n }\n\n public void setMinorCate(String minorCate) {\n this.minorCate = minorCate;\n }\n\n public boolean is_le() {\n return _le;\n }\n\n public void set_le(boolean _le) {\n this._le = _le;\n }\n\n public boolean isAllowMonthly() {\n return allowMonthly;\n }\n\n public void setAllowMonthly(boolean allowMonthly) {\n this.allowMonthly = allowMonthly;\n }\n\n public boolean isAllowVoucher() {\n return allowVoucher;\n }\n\n public void setAllowVoucher(boolean allowVoucher) {\n this.allowVoucher = allowVoucher;\n }\n\n public boolean isAllowBeanVoucher() {\n return allowBeanVoucher;\n }\n\n public void setAllowBeanVoucher(boolean allowBeanVoucher) {\n this.allowBeanVoucher = allowBeanVoucher;\n }\n\n public boolean isHasCp() {\n return hasCp;\n }\n\n public void setHasCp(boolean hasCp) {\n this.hasCp = hasCp;\n }\n\n public int getPostCount() {\n return postCount;\n }\n\n public void setPostCount(int postCount) {\n this.postCount = postCount;\n }\n\n public int getLatelyFollower() {\n return latelyFollower;\n }\n\n public void setLatelyFollower(int latelyFollower) {\n this.latelyFollower = latelyFollower;\n }\n\n public int getLatelyFollowerBase() {\n return latelyFollowerBase;\n }\n\n public void setLatelyFollowerBase(int latelyFollowerBase) {\n this.latelyFollowerBase = latelyFollowerBase;\n }\n\n public int getFollowerCount() {\n return followerCount;\n }\n\n public void setFollowerCount(int followerCount) {\n this.followerCount = followerCount;\n }\n\n public long getWordCount() {\n return wordCount;\n }\n\n public void setWordCount(long wordCount) {\n this.wordCount = wordCount;\n }\n\n public int getSerializeWordCount() {\n return serializeWordCount;\n }\n\n public void setSerializeWordCount(int serializeWordCount) {\n this.serializeWordCount = serializeWordCount;\n }\n\n public int getMinRetentionRatio() {\n return minRetentionRatio;\n }\n\n public void setMinRetentionRatio(int minRetentionRatio) {\n this.minRetentionRatio = minRetentionRatio;\n }\n\n public String getRetentionRatio() {\n return retentionRatio;\n }\n\n public void setRetentionRatio(String retentionRatio) {\n this.retentionRatio = retentionRatio;\n }\n\n public String getUpdated() {\n return updated;\n }\n\n public void setUpdated(String updated) {\n this.updated = updated;\n }\n\n public boolean isSerial() {\n return isSerial;\n }\n\n public void setSerial(boolean serial) {\n isSerial = serial;\n }\n\n public int getChaptersCount() {\n return chaptersCount;\n }\n\n public void setChaptersCount(int chaptersCount) {\n this.chaptersCount = chaptersCount;\n }\n\n public String getLastChapter() {\n return lastChapter;\n }\n\n public void setLastChapter(String lastChapter) {\n this.lastChapter = lastChapter;\n }\n\n public List<String> getGender() {\n return gender;\n }\n\n public void setGender(List<String> gender) {\n this.gender = gender;\n }\n\n public List<String> getTags() {\n return tags;\n }\n\n public void setTags(List<String> tags) {\n this.tags = tags;\n }\n\n public boolean isDonate() {\n return donate;\n }\n\n public void setDonate(boolean donate) {\n this.donate = donate;\n }\n\n @Override\n public String toString() {\n return \"BookDetail{\" +\n \"_id='\" + _id + '\\'' +\n \", title='\" + title + '\\'' +\n \", author='\" + author + '\\'' +\n \", longIntro='\" + longIntro + '\\'' +\n \", cover='\" + cover + '\\'' +\n \", cat='\" + cat + '\\'' +\n \", majorCate='\" + majorCate + '\\'' +\n \", minorCate='\" + minorCate + '\\'' +\n \", _le=\" + _le +\n \", allowMonthly=\" + allowMonthly +\n \", allowVoucher=\" + allowVoucher +\n \", allowBeanVoucher=\" + allowBeanVoucher +\n \", hasCp=\" + hasCp +\n \", postCount=\" + postCount +\n \", latelyFollower=\" + latelyFollower +\n \", latelyFollowerBase=\" + latelyFollowerBase +\n \", followerCount=\" + followerCount +\n \", wordCount=\" + wordCount +\n \", serializeWordCount=\" + serializeWordCount +\n \", minRetentionRatio=\" + minRetentionRatio +\n \", retentionRatio='\" + retentionRatio + '\\'' +\n \", updated='\" + updated + '\\'' +\n \", isSerial=\" + isSerial +\n \", chaptersCount=\" + chaptersCount +\n \", lastChapter='\" + lastChapter + '\\'' +\n \", gender=\" + gender +\n \", tags=\" + tags +\n \", donate=\" + donate +\n '}';\n }\n}",
"public class CacheManager {\n\n private static volatile CacheManager mInstance;\n\n private CacheHelper mCacheHelper;\n\n public CacheManager() {\n mCacheHelper = CacheHelper.getInstance();\n }\n\n public static CacheManager getInstance() {\n if (mInstance == null) {\n synchronized (CacheManager.class) {\n if (mInstance == null) {\n mInstance = new CacheManager();\n }\n }\n }\n return mInstance;\n }\n\n /**\n * =============================================================\n * ================== 收藏书籍 ========================\n * =============================================================\n */\n\n public void saveCollection(BookCollection collection) {\n mCacheHelper.saveObject(\"collection\", collection);\n }\n\n public BookCollection getCollection() {\n return mCacheHelper.getObject(\"collection\", BookCollection.class);\n }\n\n /**\n * =============================================================\n * ================== 书本章节列表 ========================\n * =============================================================\n */\n\n /**\n * 返回某一本书籍的全部信息缓存路径\n * @param bookId\n * @return\n */\n private File getBookDir(String bookId) {\n File file = new File(mCacheHelper.getRootFile(), \"book\");\n if (!file.exists()) {\n file.mkdir();\n }\n File bookDir = new File(file, bookId);\n if (!bookDir.exists()) {\n bookDir.mkdir();\n }\n return bookDir;\n }\n\n public void saveChapters(ChaptersResponse.MixToc toc) {\n File book = new File(getBookDir(toc.getBook()), \"chapters\");\n try {\n book.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n mCacheHelper.saveObject(book, toc);\n }\n\n public ChaptersResponse.MixToc getChapters(String bookId) {\n File chapters = new File(getBookDir(bookId), \"chapters\");\n if (!chapters.exists()) {\n return null;\n }\n return mCacheHelper.getObject(chapters, ChaptersResponse.MixToc.class);\n }\n\n /**\n * =============================================================\n * ================== 书本章节内容 ========================\n * =============================================================\n */\n\n public void saveChapter(String bookId, int index, ChapterDetailResponse.Chapter chapter) {\n File chapterFile = new File(getBookDir(bookId), \"chapter\" + index);\n try {\n chapterFile.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n mCacheHelper.saveString(chapterFile, chapter.getBody());\n }\n\n public ChapterDetailResponse.Chapter getChapter(String bookId, int index) {\n File chapterFile = new File(getBookDir(bookId), \"chapter\" + index);\n if (!chapterFile.exists()) {\n return null;\n }\n return mCacheHelper.getObject(chapterFile, ChapterDetailResponse.Chapter.class);\n }\n\n public File getChapterFile(String bookId, int index) {\n File chapterFile = new File(getBookDir(bookId), \"chapter\" + index);\n if (!chapterFile.exists()) {\n return null;\n }\n return chapterFile;\n }\n\n}",
"public class RxUtil {\n\n public static <T> Observable.Transformer<T, T> rxScheduler() {\n return observable -> observable\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread());\n }\n}"
] | import android.content.Context;
import com.wulinpeng.daiylreader.net.ReaderApiManager;
import com.wulinpeng.daiylreader.bookdetail.contract.IBookDetailPresenter;
import com.wulinpeng.daiylreader.bookdetail.contract.IBookDetailView;
import com.wulinpeng.daiylreader.bookdetail.event.CollectionChangeEvent;
import com.wulinpeng.daiylreader.bean.BookCollection;
import com.wulinpeng.daiylreader.bean.BookDetail;
import com.wulinpeng.daiylreader.manager.CacheManager;
import com.wulinpeng.daiylreader.util.RxUtil;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import wulinpeng.com.framework.base.mvp.BasePresenter; | package com.wulinpeng.daiylreader.bookdetail.presenter;
/**
* @author wulinpeng
* @datetime: 17/2/20 下午7:59
* @description:
*/
public class BookDetailPresenterImpl extends BasePresenter<IBookDetailView> implements IBookDetailPresenter {
private Context context;
private String bookId;
private BookDetail bookDetail;
public BookDetailPresenterImpl(Context context, IBookDetailView rootView, String bookId) {
super(rootView);
this.context = context;
this.bookId = bookId;
}
@Override
public void getBookDetail() {
ReaderApiManager.INSTANCE.getBookDetail(bookId) | .compose(RxUtil.rxScheduler()) | 6 |
aschaetzle/Sempala | sempala-loader/src/main/java/de/uni_freiburg/informatik/dbis/sempala/loader/run/Main.java | [
"public final class ExtVPLoader extends Loader {\n\n\t/** The constructor */\n\tpublic ExtVPLoader(Impala wrapper, String hdfsLocation) {\n\t\tsuper(wrapper, hdfsLocation);\n\t\ttablename_output = \"extvp\";\n\t}\n\n\tprivate ArrayList<String> ExtVPTypes = new ArrayList<String>();\n\tprivate ArrayList<String> ListOfPredicates = new ArrayList<>();\n\t\n\t//Default values for threshold, triple table and initial predicate\n\tprivate double SF = 1;\n\tprivate String TT = tablename_triple_table;\n\tprivate int FirstPredicate = 0;\n\tprivate int LastPredicate = 0;\n\t\n\t/**\n\t * Creates Extended Vertical Partitioning tables from a triple table.\n\t *\n\t * The input table has to be in triple table format. The output will be a\n\t * set of tables in format described in 'S2RDF: RDF Querying with\n\t * SPARQL on Spark'.\n\t *\n\t * @throws SQLException\n\t */\n\t@Override\n\tpublic void load() throws SQLException {\n\t\t// Get value of threshold\n\t\tsetThreshold(threshold,EvaluationMode);\n\n\t\t// Specify ExtVP types to be calculated\n\t\tsetExtVPTypes(extvp_types_selected);\n\n\t\t// Set the first predicate from which to start ExtVP calculation\n\t\tFirstPredicate = GetCompletedPredicate(1);\n\t\t\n\t\t// Load the triple table\n\t\tif (FirstPredicate == 0) {\n\t\t\tlong timestampTT = System.currentTimeMillis();\n\t\t\tbuildTripleTable();\n\t\t\tAddStats(\"BUILD TRIPLETABLE\", \" TIME\", \"\", \"Time\", 0, 0,\n\t\t\t\t\t(double) (System.currentTimeMillis() - timestampTT) / 1000,0);\n\t\t}\n\t\t\n\t\t// Get list of predicates given by user\n\t\tsetListOfPredicates(TT);\n\t\t\n\t\t//Get the last predicate if loading is partitioned\n\t\tLastPredicate = GetLastPredicate(Predicate_Partition);\n\t\t\n\t\t//Create ExtVP tables\n\t\tSystem.out.print(String.format(\"Creating %s from '%s' \\n\", \"ExtVps\", TT));\n\t\tlong timestamptotal = System.currentTimeMillis();\n\t\tfor (int i = FirstPredicate; i < LastPredicate; i++) {\n\t\t\tString p1 = ListOfPredicates.get(i);\n\t\t\tSelectStatement leftstmt = SelectPartition(TT, p1);\n\t\t\tfor (int j = i; j < ListOfPredicates.size(); j++) {\n\t\t\t\tString p2 = ListOfPredicates.get(j);\n\t\t\t\tSelectStatement rightstmt = SelectPartition(TT, p2);\n\t\t\t\tdouble PartitionSizeP1 = TableSize(TT,p1);\n\t\t\t\tdouble PartitionSizeP2 = TableSize(TT,p2);\n\t\t\t\tif (!ExtVPTypes.isEmpty()) {\n\t\t\t\t\tif (ExtVPTypes.contains(\"so\") && ExtVPTypes.contains(\"os\")) {\n\t\t\t\t\t\tCompute_SOandOS(TT, p1, p2, SF, leftstmt, rightstmt, PartitionSizeP1, PartitionSizeP2);\n\t\t\t\t\t} else if (ExtVPTypes.contains(\"so\") && !ExtVPTypes.contains(\"os\")) {\n\t\t\t\t\t\tCompute_SO(TT, p1, p2, SF, leftstmt, rightstmt, PartitionSizeP1, PartitionSizeP2);\n\t\t\t\t\t} else if (!ExtVPTypes.contains(\"so\") && ExtVPTypes.contains(\"os\")) {\n\t\t\t\t\t\tCompute_OS(TT, p1, p2, SF, leftstmt, rightstmt, PartitionSizeP1, PartitionSizeP2);\n\t\t\t\t\t} else {\n\t\t\t\t\t}\n\t\t\t\t\tif (ExtVPTypes.contains(\"ss\")) {\n\t\t\t\t\t\tCompute_SS(TT, p1, p2, SF, leftstmt, rightstmt, PartitionSizeP1, PartitionSizeP2);\n\t\t\t\t\t}\n\t\t\t\t\tif (ExtVPTypes.contains(\"oo\")) {\n\t\t\t\t\t\tCompute_OO(TT, p1, p2, SF, leftstmt, rightstmt, PartitionSizeP1, PartitionSizeP2);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tSystem.out.println(\"ExtVPTypes is empty\");\n\t\t\t\t}\n\t\t\t\tPhaseCompleted(i, p1, j, p2);\n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float) (System.currentTimeMillis() - timestamptotal) / 1000));\n\t\tAddStats(\"Complete_EXTVP_TABLES\",String.valueOf(FirstPredicate)+\"-\"+String.valueOf(LastPredicate),\"\",\"Time\",0,0, (double) (System.currentTimeMillis() - timestamptotal) / 1000,0);\n\t\t\n\t\t//Store statistic files in HDFS\n\t\ttry {\n\t\t\tStoreInHdfs(hdfs_input_directory);\n\t\t} catch (IllegalArgumentException | IOException e1) {\n\t\t\te1.printStackTrace();\n\t\t}\n\t\t\n\t\t// Sleep 10 seconds to give impala some time to calm down\n\t\ttry {\n\t\t\tThread.sleep(10000);\n\t\t} catch (InterruptedException e1) {\n\t\t\te1.printStackTrace();\n\t\t}\n\t\t\n\t\t//Create tables of statistics\n\t\tSystem.out.print(String.format(\"Creating %s \\n\", \"ExtVp Statistic Tables\"));\n\t\tlong timestampStats = System.currentTimeMillis();\n\t\ttry {\n\t\t\tCreateStatsTables(\"SS\",hdfs_input_directory,HdfsUserPath);\n\t\t\tCreateStatsTables(\"SO\",hdfs_input_directory,HdfsUserPath);\n\t\t\tCreateStatsTables(\"OS\",hdfs_input_directory,HdfsUserPath);\n\t\t\tCreateStatsTables(\"OO\",hdfs_input_directory,HdfsUserPath);\n\t\t\tCreateStatsTables(\"TIME\",hdfs_input_directory,HdfsUserPath);\n\t\t\tCreateStatsTables(\"EMPTY\",hdfs_input_directory,HdfsUserPath);\n\t\t} catch (IllegalArgumentException | IOException e) {\n\t\t\tSystem.out.println(\"Stats tables could not be created. \");\n\t\t\te.printStackTrace();\n\t\t}\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float) (System.currentTimeMillis() - timestampStats) / 1000));\n\t\t\n\t\tSystem.exit(-1);\n\t}\n\n\t/**\n\t * Read value of threshold from CLI.\n\t */\n\tprivate void setThreshold(String threshold, boolean evaluation_mode) {\n\t\tif (evaluation_mode)\n\t\t\tSF = 1.01;\n\t\telse {\n\t\t\ttry {\n\t\t\t\tSF = Double.parseDouble(threshold);\n\t\t\t\tif (SF <= 0)\n\t\t\t\t\tthrow new IllegalArgumentException();\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.print(String.format(\"Threshold '%s' is not a proper value as threshold\", threshold));\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read types of ExtVP from CLI.\n\t */\n\tprivate void setExtVPTypes(String SelectedTypes) {\n\t\tString[] ExtVPTypesSelected;\n\t\tif (SelectedTypes != \"\\\\n\") {\n\t\t\ttry {\n\t\t\t\tExtVPTypesSelected = SelectedTypes.toLowerCase().split(\"[/.,\\\\s\\\\-:\\\\?]\");\n\t\t\t\tfor (int i = 0; i < ExtVPTypesSelected.length; i++) {\n\t\t\t\t\tif (ExtVPTypesSelected[i].length() != 2\n\t\t\t\t\t\t\t|| (!ExtVPTypesSelected[i].contains(\"s\") && !ExtVPTypesSelected[i].contains(\"o\")))\n\t\t\t\t\t\tthrow new IllegalArgumentException();\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (!ExtVPTypes.contains(ExtVPTypesSelected[i]))\n\t\t\t\t\t\t\tExtVPTypes.add(ExtVPTypesSelected[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.print(String.format(\"'%s' is not a proper format of ExtVP types\", SelectedTypes));\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t} else {\n\t\t\tExtVPTypes.add(\"ss\");\n\t\t\tExtVPTypes.add(\"so\");\n\t\t\tExtVPTypes.add(\"os\");\n\t\t\tExtVPTypes.add(\"oo\");\n\t\t}\n\t}\n\n\t/**\n\t * Set the list of predicates for which the ExtVP tables will be calculated,\n\t * if list of predicates is given, that list is used.\n\t * \n\t * @param TripleTable - Table containing all triples.\n\t * \n\t * @throws IllegalArgumentException\n\t * @throws SQLException\n\t */\n\tprivate void setListOfPredicates(String TripleTable) throws IllegalArgumentException, SQLException {\n\t\tif (path_of_list_of_predicates != \"\\\\n\") {\n\t\t\tSystem.out.println(String.format(\"Path for list of predicates is given: %s\", path_of_list_of_predicates));\n\t\t\ttry {\n\t\t\t\tBufferedReader br = new BufferedReader(new FileReader(path_of_list_of_predicates));\n\t\t\t\tfor (String line; (line = br.readLine()) != null;) {\n\t\t\t\t\tListOfPredicates.add(line);\n\t\t\t\t}\n\t\t\t\tbr.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"[ERROR] Could not open list of predicates file. Reason: \" + e.getMessage());\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t} else {\n\t\t\tSystem.out.println(\"Get All predicates\");\n\t\t\tResultSet DataSet = impala.select(column_name_predicate).distinct().from(TripleTable).execute();\n\t\t\twhile (DataSet.next()) {\n\t\t\t\tListOfPredicates.add(DataSet.getString(column_name_predicate));\n\t\t\t}\n\t\t}\t\n\t\tjava.util.Collections.sort(ListOfPredicates);\n\t}\n\n\t/**\n\t * Compute ExtVP table of type SO, OS, SS and OO for given predicates.\n\t * \n\t * @param TT - Triple table.\n\t * @param p1 - First predicate.\n\t * @param p2 - Second predicate.\n\t * @param SF - Selectivity threshold.\n\t * @param leftstmt - Left statement of SemiJoin.\n\t * @param rightstmt - Right statement of SemiJoin.\n\t * @param PartitionSizeP1 - Partition size with predicate equal to first predicate.\n\t * @param PartitionSizeP2 - Partition size with predicate equal to second predicate.\n\t * \n\t * @throws IllegalArgumentException\n\t * @throws SQLException\n\t */\n\tprivate void Compute_SO(String TT, String p1, String p2, double SF, SelectStatement leftstmt, SelectStatement rightstmt, double PartitionSizeP1, double PartitionSizeP2) throws IllegalArgumentException, SQLException {\n\t\tString ExtVPFormat = \"so\";\n\t\tString TableName_p1p2_SO = TableName(p1, p2, ExtVPFormat);\n\t\tString TableName_p2p1_SO = TableName(p2, p1, ExtVPFormat);\n\t\tdouble Time = 0;\n\t\t\n\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p1p2_SO, TT));\n\t\tlong timestamp = System.currentTimeMillis();\n\n\t\tSelectStatement mainstmt = impala.select(String.format(\"t1.%s\", column_name_subject));\n\t\tmainstmt.addProjection(String.format(\"t1.%s\", column_name_object));\n\t\tmainstmt.from(String.format(\"(%s) t1\", leftstmt));\n\t\tmainstmt.leftSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_subject, \"t2\", column_name_object), false);\n\t\t\n\t\tCreateStatement cstmtSO = CreateTable(p1, p2, ExtVPFormat, mainstmt);\n\t\tcstmtSO.execute();\n\t\tTime = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\t\t\n\t\tif (!isEmpty(TableName_p1p2_SO)) {\n\t\t\timpala.computeStats(TableName_p1p2_SO);\n\t\t\tdouble ExtVPSize = TableSize(TableName_p1p2_SO);\n\t\t\tdouble Selectivity = ExtVPSize/PartitionSizeP1;\n\t\t\tAddStats(TableName_p1p2_SO,p1, p2, ExtVPFormat, ExtVPSize, PartitionSizeP1, Selectivity, Time);\n\t\t\tif (Selectivity >= SF)\n\t\t\t\timpala.dropTable(TableName_p1p2_SO);\n\t\t} \n\t\telse {\n\t\t\timpala.dropTable(TableName_p1p2_SO);\n\t\t\tStoreEmptyTables(TableName_p1p2_SO);\n\t\t}\n\n\t\tif (p1 != p2) {\n\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p2p1_SO, TT));\n\t\t\ttimestamp = System.currentTimeMillis();\n\n\t\t\tSelectStatement mainstmt2 = impala.select(String.format(\"t2.%s\", column_name_subject));\n\t\t\tmainstmt2.addProjection(String.format(\"t2.%s\", column_name_object));\n\t\t\tmainstmt2.from(String.format(\"(%s) t1\", leftstmt));\n\t\t\tmainstmt2.rightSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_object, \"t2\", column_name_subject), false);\n\t\t\t\n\t\t\tCreateStatement cstmtSO2 = CreateTable(p2, p1, ExtVPFormat, mainstmt2);\n\t\t\tcstmtSO2.execute();\n\t\t\tTime = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\n\t\t\tif (!isEmpty(TableName_p2p1_SO)) {\n\t\t\t\timpala.computeStats(TableName_p2p1_SO);\n\t\t\t\tdouble ExtVPSize = TableSize(TableName_p2p1_SO);\n\t\t\t\tdouble Selectivity = ExtVPSize/PartitionSizeP2;\n\t\t\t\tAddStats(TableName_p2p1_SO,p2, p1, ExtVPFormat, ExtVPSize, PartitionSizeP2, Selectivity, Time);\n\t\t\t\tif (TableSize(TableName_p2p1_SO) / TableSize(TT, p2) >= SF)\n\t\t\t\t\timpala.dropTable(TableName_p2p1_SO);\n\t\t\t} else {\n\t\t\t\timpala.dropTable(TableName_p2p1_SO);\n\t\t\t\tStoreEmptyTables(TableName_p2p1_SO);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void Compute_OS(String TT, String p1, String p2, double SF, SelectStatement leftstmt, SelectStatement rightstmt, double PartitionSizeP1, double PartitionSizeP2) throws IllegalArgumentException, SQLException {\n\t\tString ExtVPFormat = \"os\";\n\t\tString TableName_p1p2_OS = TableName(p1, p2, ExtVPFormat);\n\t\tString TableName_p2p1_OS = TableName(p2, p1, ExtVPFormat);\n\t\tdouble Time = 0;\n\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p1p2_OS, TT));\n\t\tlong timestamp = System.currentTimeMillis();\n\t\t\n\t\tSelectStatement mainstm = impala.select(String.format(\"t1.%s\", column_name_subject));\n\t\tmainstm.addProjection(String.format(\"t1.%s\", column_name_object));\n\t\tmainstm.from(String.format(\"(%s) t1\", leftstmt));\n\t\tmainstm.leftSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_object, \"t2\", column_name_subject), false);\n\n\t\tCreateStatement cstmt = CreateTable(p1, p2, ExtVPFormat, mainstm);\n\t\tcstmt.execute();\n\t\tTime = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\t\t\n\t\tif (!isEmpty(TableName_p1p2_OS)) {\n\t\t\timpala.computeStats(TableName_p1p2_OS);\n\t\t\tdouble ExtVPSize = TableSize(TableName_p1p2_OS);\n\t\t\tdouble PartitionSize = TableSize(TT, p1);\n\t\t\tdouble Selectivity = ExtVPSize/PartitionSize;\n\t\t\tAddStats(TableName_p1p2_OS,p1, p2, ExtVPFormat, ExtVPSize, PartitionSize, Selectivity, Time);\n\t\t\tif (Selectivity >= SF)\n\t\t\t\timpala.dropTable(TableName_p1p2_OS);\n\t\t} else {\n\t\t\timpala.dropTable(TableName_p1p2_OS);\n\t\t\tStoreEmptyTables(TableName_p1p2_OS);\n\t\t}\n\n\t\tif (p1 != p2) {\n\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p2p1_OS, TT));\n\t\t\ttimestamp = System.currentTimeMillis();\n\n\t\t\tSelectStatement mainstm2 = impala.select(String.format(\"t2.%s\", column_name_subject));\n\t\t\tmainstm2.addProjection(String.format(\"t2.%s\", column_name_object));\n\t\t\tmainstm2.from(String.format(\"(%s) t1\", leftstmt));\n\t\t\tmainstm2.rightSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_subject, \"t2\", column_name_object), false);\n\t\t\t\n\t\t\tCreateStatement cstmt2 = CreateTable(p2, p1, ExtVPFormat, mainstm2);\n\t\t\tcstmt2.execute();\n\t\t\tTime = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\n\t\t\tif (!isEmpty(TableName_p2p1_OS)) {\n\t\t\t\timpala.computeStats(TableName_p2p1_OS);\n\t\t\t\tdouble ExtVPSize = TableSize(TableName_p2p1_OS);\n\t\t\t\tdouble PartitionSize = TableSize(TT, p2);\n\t\t\t\tdouble Selectivity = ExtVPSize/PartitionSize;\n\t\t\t\tAddStats(TableName_p2p1_OS,p2, p1, ExtVPFormat, ExtVPSize, PartitionSize, Selectivity, Time);\n\t\t\t\tif (Selectivity >= SF)\n\t\t\t\t\timpala.dropTable(TableName_p2p1_OS);\n\t\t\t} else {\n\t\t\t\timpala.dropTable(TableName_p2p1_OS);\n\t\t\t\tStoreEmptyTables(TableName_p2p1_OS);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void Compute_SS(String TT, String p1, String p2, double SF, SelectStatement leftstmt, SelectStatement rightstmt, double PartitionSizeP1, double PartitionSizeP2) throws IllegalArgumentException, SQLException {\n\t\tString ExtVPFormat = \"ss\";\n\t\tString TableName_p1p2_SS = TableName(p1, p2, ExtVPFormat);\n\t\tString TableName_p2p1_SS = TableName(p2, p1, ExtVPFormat);\n\t\tdouble Time = 0;\n\t\tdouble Time2 = 0;\n\t\tif (p1 != p2) {\n\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p1p2_SS, TT));\n\t\t\tlong timestamp = System.currentTimeMillis();\n\t\t\t\n\t\t\tSelectStatement mainstm = impala.select(String.format(\"t1.%s\", column_name_subject));\n\t\t\tmainstm.addProjection(String.format(\"t1.%s\", column_name_object));\n\t\t\tmainstm.from(String.format(\"(%s) t1\", leftstmt));\n\t\t\tmainstm.leftSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_subject, \"t2\", column_name_subject), false);\n\n\t\t\tCreateStatement cstmtSS = CreateTable(p1, p2, ExtVPFormat, mainstm);\n\t\t\tcstmtSS.execute();\n\t\t\tTime = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\t\t\t\n\t\t\tif (!isEmpty(TableName_p1p2_SS)) {\n\t\t\t\timpala.computeStats(TableName_p1p2_SS);\n\t\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p2p1_SS, TT));\n\t\t\t\ttimestamp = System.currentTimeMillis();\n\n\t\t\t\tSelectStatement mainstm2 = impala.select(String.format(\"t2.%s\", column_name_subject));\n\t\t\t\tmainstm2.addProjection(String.format(\"t2.%s\", column_name_object));\n\t\t\t\tmainstm2.from(String.format(\"%s t1\", TableName_p1p2_SS));\n\t\t\t\tmainstm2.rightSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_subject, \"t2\", column_name_subject), false);\n\n\t\t\t\tCreateStatement cstmtSS2 = CreateTable(p2, p1, ExtVPFormat, mainstm2);\n\t\t\t\tcstmtSS2.execute();\n\t\t\t\tTime2 = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\t\t\t\timpala.computeStats(TableName_p2p1_SS);\n\t\t\t\t\n\t\t\t\tdouble ExtVPSize = TableSize(TableName_p1p2_SS);\n\t\t\t\tdouble PartitionSize = TableSize(TT, p1);\n\t\t\t\tdouble Selectivity = ExtVPSize/PartitionSize;\n\t\t\t\tAddStats(TableName_p1p2_SS,p1, p2, ExtVPFormat, ExtVPSize, PartitionSize, Selectivity, Time);\n\t\t\t\tif (Selectivity >= SF)\n\t\t\t\t\timpala.dropTable(TableName_p1p2_SS);\n\t\t\t\t\n\t\t\t\tExtVPSize = TableSize(TableName_p2p1_SS);\n\t\t\t\tPartitionSize = TableSize(TT, p2);\n\t\t\t\tSelectivity = ExtVPSize/PartitionSize;\n\t\t\t\tAddStats(TableName_p2p1_SS,p2, p1, ExtVPFormat, ExtVPSize, PartitionSize, Selectivity, Time2);\n\t\t\t\tif (Selectivity >= SF)\n\t\t\t\t\timpala.dropTable(TableName_p2p1_SS);\n\n\t\t\t} else {\n\t\t\t\timpala.dropTable(TableName_p1p2_SS);\n\t\t\t\tStoreEmptyTables(TableName_p1p2_SS);\n\t\t\t\tStoreEmptyTables(TableName_p2p1_SS);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void Compute_OO(String TT, String p1, String p2, double SF, SelectStatement leftstmt, SelectStatement rightstmt, double PartitionSizeP1, double PartitionSizeP2) throws IllegalArgumentException, SQLException {\n\t\tString ExtVPFormat = \"oo\";\n\t\tString TableName_p1p2_OO = TableName(p1, p2, ExtVPFormat);\n\t\tString TableName_p2p1_OO = TableName(p2, p1, ExtVPFormat);\n\t\tdouble Time = 0;\n\t\tdouble Time2 = 0;\n\t\tif (p1 != p2) {\n\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p1p2_OO, TT));\n\t\t\tlong timestamp = System.currentTimeMillis();\n\n\t\t\tSelectStatement mainstm = impala.select(String.format(\"t1.%s\", column_name_subject));\n\t\t\tmainstm.addProjection(String.format(\"t1.%s\", column_name_object));\n\t\t\tmainstm.from(String.format(\"(%s) t1\", leftstmt));\n\t\t\tmainstm.leftSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_object, \"t2\", column_name_object), false);\n\n\t\t\tCreateStatement cstmtOO = CreateTable(p1, p2, ExtVPFormat, mainstm);\n\t\t\tcstmtOO.execute();\n\t\t\tTime = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\t\t\t\n\t\t\tif (!isEmpty(TableName_p1p2_OO)) {\n\t\t\t\timpala.computeStats(TableName_p1p2_OO);\n\t\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p2p1_OO, TT));\n\t\t\t\ttimestamp = System.currentTimeMillis();\n\n\t\t\t\tSelectStatement mainstm2 = impala.select(String.format(\"t2.%s\", column_name_subject));\n\t\t\t\tmainstm2.addProjection(String.format(\"t2.%s\", column_name_object));\n\t\t\t\tmainstm2.from(String.format(\"%s t1\", TableName_p1p2_OO));\n\t\t\t\tmainstm2.rightSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_object, \"t2\", column_name_object), false);\n\n\t\t\t\tCreateStatement cstmtOO2 = CreateTable(p2, p1, ExtVPFormat, mainstm2);\n\t\t\t\tcstmtOO2.execute();\n\t\t\t\tTime2 = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time2));\n\t\t\t\timpala.computeStats(TableName_p2p1_OO);\n\n\t\t\t\tdouble ExtVPSize = TableSize(TableName_p1p2_OO);\n\t\t\t\tdouble PartitionSize = TableSize(TT, p1);\n\t\t\t\tdouble Selectivity = ExtVPSize/PartitionSize;\n\t\t\t\tAddStats(TableName_p1p2_OO,p1, p2, ExtVPFormat, ExtVPSize, PartitionSize, Selectivity, Time);\n\t\t\t\tif (Selectivity >= SF)\n\t\t\t\t\timpala.dropTable(TableName_p1p2_OO);\n\t\t\t\t\n\t\t\t\tExtVPSize = TableSize(TableName_p2p1_OO);\n\t\t\t\tPartitionSize = TableSize(TT, p2);\n\t\t\t\tSelectivity = ExtVPSize/PartitionSize;\n\t\t\t\tAddStats(TableName_p2p1_OO,p2, p1, ExtVPFormat, ExtVPSize, PartitionSize, Selectivity, Time2);\n\t\t\t\tif (Selectivity >= SF)\n\t\t\t\t\timpala.dropTable(TableName_p2p1_OO);\n\n\t\t\t} else {\n\t\t\t\timpala.dropTable(TableName_p1p2_OO);\n\t\t\t\tStoreEmptyTables(TableName_p1p2_OO);\n\t\t\t\tStoreEmptyTables(TableName_p2p1_OO);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void Compute_SOandOS(String TT, String p1, String p2, double SF, SelectStatement leftstmt, SelectStatement rightstmt, double PartitionSizeP1, double PartitionSizeP2) throws IllegalArgumentException, SQLException {\n\t\tString ExtVPFormatSO = \"so\";\n\t\tString ExtVPFormatOS = \"os\";\n\t\tString TableName_p1p2_SO = TableName(p1, p2, ExtVPFormatSO);\n\t\tString TableName_p2p1_OS = TableName(p2, p1, ExtVPFormatOS);\n\t\tString TableName_p1p2_OS = TableName(p1, p2, ExtVPFormatOS);\n\t\tString TableName_p2p1_SO = TableName(p2, p1, ExtVPFormatSO);\n\t\tdouble Time = 0;\n\t\tdouble Time2 = 0;\n\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p1p2_SO, TT));\n\t\tlong timestamp = System.currentTimeMillis();\t\t\n\t\t\n\t\tSelectStatement mainstm = impala.select(String.format(\"t1.%s\", column_name_subject));\n\t\tmainstm.addProjection(String.format(\"t1.%s\", column_name_object));\n\t\tmainstm.from(String.format(\"(%s) t1\", leftstmt));\n\t\tmainstm.leftSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_subject, \"t2\", column_name_object), false);\n\t\t\n\t\tCreateStatement cstmtSO = CreateTable(p1, p2, ExtVPFormatSO, mainstm);\n\t\tcstmtSO.execute();\n\t\tTime = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\t\t\n\n\t\tif (!isEmpty(TableName_p1p2_SO)) {\n\t\t\timpala.computeStats(TableName_p1p2_SO);\n\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p2p1_OS, TT));\n\t\t\ttimestamp = System.currentTimeMillis();\n\n\t\t\tSelectStatement mainstm2 = impala.select(String.format(\"t2.%s\", column_name_subject));\n\t\t\tmainstm2.addProjection(String.format(\"t2.%s\", column_name_object));\n\t\t\tmainstm2.from(String.format(\"%s t1\", TableName_p1p2_SO));\n\t\t\tmainstm2.rightSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_subject, \"t2\", column_name_object), false);\n\n\t\t\tCreateStatement cstmtOS = CreateTable(p2, p1, ExtVPFormatOS, mainstm2);\n\t\t\tcstmtOS.execute();\n\t\t\tTime2 = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time2));\n\t\t\timpala.computeStats(TableName_p2p1_OS);\n\n\t\t\tdouble ExtVPSize = TableSize(TableName_p1p2_SO);\n\t\t\tdouble PartitionSize = TableSize(TT, p1);\n\t\t\tdouble Selectivity = ExtVPSize/PartitionSize;\n\t\t\tAddStats(TableName_p1p2_SO, p1, p2, ExtVPFormatSO, ExtVPSize, PartitionSize, Selectivity, Time);\n\t\t\tif (Selectivity >= SF)\n\t\t\t\timpala.dropTable(TableName_p1p2_SO);\n\n\t\t\tExtVPSize = TableSize(TableName_p2p1_OS);\n\t\t\tPartitionSize = TableSize(TT, p2);\n\t\t\tSelectivity = ExtVPSize/PartitionSize;\n\t\t\tAddStats(TableName_p2p1_OS,p2, p1, ExtVPFormatOS, ExtVPSize, PartitionSize, Selectivity, Time2);\n\t\t\tif (Selectivity >= SF)\n\t\t\t\timpala.dropTable(TableName_p2p1_OS);\n\n\t\t} else {\n\t\t\timpala.dropTable(TableName_p1p2_SO);\n\t\t\tStoreEmptyTables(TableName_p1p2_SO);\n\t\t\tStoreEmptyTables(TableName_p2p1_OS);\n\t\t}\n\t\tif (p1 != p2) {\n\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p1p2_OS, TT));\n\t\t\ttimestamp = System.currentTimeMillis();\n\n\t\t\tSelectStatement mainstm3 = impala.select(String.format(\"t1.%s\", column_name_subject));\n\t\t\tmainstm3.addProjection(String.format(\"t1.%s\", column_name_object));\n\t\t\tmainstm3.from(String.format(\"(%s) t1\", leftstmt));\n\t\t\tmainstm3.leftSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_object, \"t2\", column_name_subject), false);\n\t\t\t\n\t\t\tCreateStatement cstmtOS2 = CreateTable(p1, p2, ExtVPFormatOS, mainstm3);\n\t\t\tcstmtOS2.execute();\n\t\t\tTime = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time));\n\n\n\t\t\tif (!isEmpty(TableName_p1p2_OS)) {\n\t\t\t\timpala.computeStats(TableName_p1p2_OS);\n\t\t\t\tSystem.out.print(String.format(\"Creating %s from '%s'\", TableName_p2p1_SO, TT));\n\t\t\t\ttimestamp = System.currentTimeMillis();\n\n\n\t\t\t\tSelectStatement mainstm4 = impala.select(String.format(\"t2.%s\", column_name_subject));\n\t\t\t\tmainstm4.addProjection(String.format(\"t2.%s\", column_name_object));\n\t\t\t\tmainstm4.from(String.format(\"%s t1\", TableName_p1p2_OS));\n\t\t\t\tmainstm4.rightSemiJoin(String.format(\"(%s) t2\", rightstmt),\n\t\t\t\t\t\tString.format(\"%s.%s = %s.%s\", \"t1\", column_name_object, \"t2\", column_name_subject), false);\n\n\t\t\t\tCreateStatement cstmtSO2 = CreateTable(p2, p1, ExtVPFormatSO, mainstm4);\n\t\t\t\tcstmtSO2.execute();\n\t\t\t\tTime2 = (float) (System.currentTimeMillis() - timestamp) / 1000;\n\t\t\t\tSystem.out.println(String.format(\" [%.3fs]\", Time2));\n\t\t\t\timpala.computeStats(TableName_p2p1_SO);\n\n\t\t\t\tdouble ExtVPSize = TableSize(TableName_p1p2_OS);\n\t\t\t\tdouble PartitionSize = TableSize(TT, p1);\n\t\t\t\tdouble Selectivity = ExtVPSize/PartitionSize;\n\t\t\t\tAddStats(TableName_p1p2_OS, p1, p2, ExtVPFormatOS, ExtVPSize, PartitionSize, Selectivity, Time);\n\t\t\t\tif (TableSize(TableName_p1p2_OS) / TableSize(TT, p1) >= SF)\n\t\t\t\t\timpala.dropTable(TableName_p1p2_OS);\n\n\t\t\t\tExtVPSize = TableSize(TableName_p2p1_SO);\n\t\t\t\tPartitionSize = TableSize(TT, p2);\n\t\t\t\tSelectivity = ExtVPSize/PartitionSize;\n\t\t\t\tAddStats(TableName_p2p1_SO,p2, p1, ExtVPFormatSO, ExtVPSize, PartitionSize, Selectivity, Time2);\n\t\t\t\tif (Selectivity >= SF)\n\t\t\t\t\timpala.dropTable(TableName_p2p1_SO);\n\n\t\t\t} else {\n\t\t\t\timpala.dropTable(TableName_p1p2_OS);\n\t\t\t\tStoreEmptyTables(TableName_p1p2_OS);\n\t\t\t\tStoreEmptyTables(TableName_p2p1_SO);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Check if a given table is empty.\n\t * \n\t * @param Tablename - Name of the table which is checked\n\t * @return true if table is empty.\n\t * \n\t * @throws IllegalArgumentException\n\t * @throws SQLException\n\t */\n\tprivate boolean isEmpty(String Tablename) throws IllegalArgumentException, SQLException {\n\t\tResultSet DataSet = impala.select().addProjection(\"Count(*) AS NrTuples\").from(Tablename).execute();\n\t\tboolean Empty = true;\n\t\tDataSet.next();\n\t\tif (Double.parseDouble(DataSet.getString(\"NrTuples\")) != 0) {\n\t\t\tEmpty = false;\n\t\t} else {\n\t\t\tEmpty = true;\n\t\t}\n\t\treturn Empty;\n\t}\n\n\t/**\n\t * Get the size of a given table, or the size of a partition inside the given table based on \n\t * predicate.\n\t * \n\t * @param Tablename - Name of the table.\n\t * @param Predicate - Specified predicate.\n\t * @return table size.\n\t * \n\t * @throws IllegalArgumentException\n\t * @throws SQLException\n\t */\n\tprivate double TableSize(String Tablename, String Predicate) throws IllegalArgumentException, SQLException {\n\t\tResultSet DataSet = impala.select().addProjection(\"Count(*) AS NrTuples\").from(Tablename)\n\t\t\t\t.where(String.format(\"%s='%s'\", column_name_predicate, Predicate)).execute();\n\t\tdouble Nrtuples = 0;\n\t\tDataSet.next();\n\t\tNrtuples = Double.parseDouble(DataSet.getString(\"NrTuples\"));\n\t\treturn Nrtuples * 1.0000;\n\t}\n\tprivate double TableSize(String Tablename) throws IllegalArgumentException, SQLException {\n\t\tResultSet DataSet = impala.select().addProjection(\"Count(*) AS NrTuples\").from(Tablename).execute();\n\t\tdouble Nrtuples = 0;\n\t\tDataSet.next();\n\t\tNrtuples = Double.parseDouble(DataSet.getString(\"NrTuples\"));\n\t\treturn Nrtuples * 1.000;\n\t}\n\n\t/**\n\t * Select a specified partition inside a table based on predicate.\n\t * \n\t * @param TableName - Name of the table\n\t * @param Predicate - Specified predicate\n\t * @return Select statement for the partition.\n\t */\n\tprivate SelectStatement SelectPartition(String TableName, String Predicate) {\n\t\tSelectStatement result = impala.select(column_name_subject);\n\t\tresult.addProjection(column_name_object);\n\t\tresult.from(String.format(\"%s\", TableName));\n\t\tresult.where(String.format(\"%s='%s'\", column_name_predicate, Predicate));\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * Create empty ExtVP table based on predicates and format, without data.\n\t * \n\t * @param Predicate1 - First predicate.\n\t * @param Predicate2 - Second predicate.\n\t * @param ExtVPFormat - ExtVP Format.\n\t * @return Create statement for the ExtVP table.\n\t */\n\tprivate CreateStatement CreateTable(String Predicate1, String Predicate2, String ExtVPFormat, SelectStatement stmt) {\n\t\tCreateStatement cstmt = impala.createTable(TableName(Predicate1, Predicate2, ExtVPFormat)).ifNotExists();\n\t\tcstmt.storedAs(FileFormat.PARQUET);\n\t\tcstmt.asSelect(stmt);\n\t\treturn cstmt;\n\t}\n\n\t/**\n\t * Set the name of the ExtVP table based on predicates and format.\n\t * \n\t * @param Predicate1 - First predicate.\n\t * @param Predicate2 - Second predicate.\n\t * @param ExtVPFormat - ExtVP Format.\n\t * @return Name of the table.\n\t */\n\tprivate String TableName(String Predicate1, String Predicate2, String ExtVPFormat) {\n\t\tPredicate1 = RenamePredicates(Predicate1);\n\t\tPredicate2 = RenamePredicates(Predicate2);\n\t\treturn String.format(\"%s_%s_%s_%s\", tablename_output, Predicate1, Predicate2, ExtVPFormat);\n\t}\n\t\n\t/**\n\t * Rename the predicate by replacing restricted characters for table names.\n\t * \n\t * @param Predicate - Predicate to be modified.\n\t * \n\t * @return New predicate with replaced characters.\n\t */\n\tprivate String RenamePredicates(String Predicate) {\n\t\t// NOT ALLOWED < > : // - / . , | # @ ` ~\n\t\tString RenamedPredicate = Predicate.replaceAll(\"[<>/.`~#,\\\\s\\\\-:\\\\?]\", \"_\");\n\t\treturn RenamedPredicate;\n\t}\n\n\t/**\n\t * Store empty ExtVP tables in a .txt file.\n\t * \n\t * @param EmptyTable\n\t * \n\t * @throws IllegalArgumentException\n\t * @throws SQLException\n\t */\n\tprivate void StoreEmptyTables(String EmptyTable)\n\t\t\tthrows IllegalArgumentException, SQLException {\n\n\t\ttry (FileWriter fw = new FileWriter(\"./EmptyTables_\"+String.valueOf(FirstPredicate)+\".txt\", true);\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\t\t\t\tPrintWriter Append = new PrintWriter(bw)) {\n\t\t\tAppend.println(EmptyTable);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\t/**\n\t * Store the predicate up to which the ExtVP tables are completed.\n\t * \n\t * @param Pred1Possition - Position of first predicate of ExtVP table in the list of predicates.\n\t * @param Predicate1 - First predicate.\n\t * @param Pred2Possition - Position of second predicate of ExtVP table in the list of predicates.\n\t * @param Predicate2 - Second predicate.\n\t * \n\t * @throws IllegalArgumentException\n\t * @throws SQLException\n\t */\n\tprivate void PhaseCompleted(int Pred1Possition, String Predicate1, int Pred2Possition, String Predicate2) throws IllegalArgumentException, SQLException {\n\t\ttry (FileWriter fw = new FileWriter(\"./ExtVpCompleted.txt\");\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\t\t\t\tPrintWriter Append = new PrintWriter(bw)) {\n\t\t\tAppend.println(String.format(\"%d,='%s',%d,='%s'\", Pred1Possition, Predicate1, Pred2Possition, Predicate2));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * In case loader for ExtVP is executed in several executions, \n\t * then get the last predicate for which the ExtVP tables have been calculated\n\t * in previous execution. \n\t * @param PredicatOrder\n\t * @return\n\t */\n\tprivate int GetCompletedPredicate(int PredicatOrder){\n\t\tif (Predicate_Partition != \"All\") {\n\t\t\tString[] Position = Predicate_Partition.split(\",\");\n\t\t\treturn Integer.parseInt(Position[0]);\n\t\t} \n\t\telse {\n\t\t\tint i = 0;\n\t\t\tint result = 0;\n\t\t\tif (PredicatOrder == 2)\n\t\t\t\ti = 2;\n\t\t\ttry {\n\t\t\t\tBufferedReader br = new BufferedReader(new FileReader(\"./ExtVpCompleted.txt\"));\n\t\t\t\tString line = br.readLine();\n\t\t\t\tString[] CompletedPredicates = line.toLowerCase().split(\"[,]\");\n\t\t\t\tresult = Integer.parseInt(CompletedPredicates[i]);\n\t\t\t\tbr.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\n\t\t\t\t\t\t\"ExtVpCompleted.txt does not exist or it could not be opened. ExtVPs will start from beginning\");\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t}\n\t\n\t/**\n\t * In case loader for ExtVP is executed in separated mode, \n\t * then get the last predicate for which the ExtVP tables have been to be calculated. \n\t * @param PredicatePartition\n\t * @return\n\t */\n\tprivate int GetLastPredicate(String PredicatePartition){\n\t\tif (PredicatePartition != \"All\") {\n\t\t\tString[] Position = Predicate_Partition.split(\",\");\n\t\t\ttry {\n\t\t\t\treturn Integer.parseInt(Position[1]);\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn ListOfPredicates.size();\n\t\t\t}\n\t\t\t\n\t\t}\n\t\telse\n\t\t\treturn ListOfPredicates.size();\n\t}\n\t\n\t/**\n\t * Store statistics of ExtVP table in .txt files.\n\t * \n\t * @param TableName - Name of ExtVP table.\n\t * @param p1 - First predicate.\n\t * @param p2 - Second predicate.\n\t * @param ExtVPformat - ExtVP format.\n\t * @param ExtVPSize - ExtVP table size.\n\t * @param VPSize - Partition size based on first predicate.\n\t * @param Selectivity - Selectivity of ExtVP table size compared to partition size.\n\t */\n\tprivate void AddStats(String TableName, String p1, String p2, String ExtVPformat, double ExtVPSize, double VPSize, double Selectivity, double Time){\n\t\ttry (FileWriter fw = new FileWriter(String.format(\"./ExtVpStats_%s_%d.txt\", ExtVPformat, FirstPredicate), true);\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\t\t\t\tPrintWriter Append = new PrintWriter(bw)) {\n\t\t\tAppend.println(String.format(\"%s\\t%s_%s\\t%f\\t%f\\t%f\\t%f\",TableName, p1, p2, ExtVPSize, VPSize, Selectivity, Time));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\t/**\n\t * Put the statistic files into hdfs directories\n\t * \n\t * @param DataSetName - Name of Dataset used to create the directory in Stats with the same name\n\t * @throws IllegalArgumentException\n\t * @throws IOException\n\t */\n\tprivate void StoreInHdfs(String DataSetName) throws IllegalArgumentException, IOException{\t\n\t\tint index = DataSetName.lastIndexOf(\"/\");\n\t\tString HdfsFolderName = DataSetName.substring(index);\n\t\t\n\t\tRuntime rt; \n\n\t\ttry {\n\t\t\tThread.sleep(10000);\n\t\t\trt = Runtime.getRuntime();\n\t\t\trt.exec(\"hdfs dfs -mkdir ./Stats\");\n\t\t\tThread.sleep(2000);\n\t\t\trt = Runtime.getRuntime();\n\t\t\trt.exec(\"hdfs dfs -mkdir ./Stats\" + HdfsFolderName);\n\t\t\tThread.sleep(2000);\n\t\t\trt = Runtime.getRuntime();\n\t\t\trt.exec(\"hdfs dfs -mkdir ./Stats\" + HdfsFolderName + \"/Empty\");\n\t\t\tThread.sleep(2000);\n\t\t\trt = Runtime.getRuntime();\n\t\t\trt.exec(\"hdfs dfs -mkdir ./Stats\" + HdfsFolderName + \"/Time\");\n\t\t\tThread.sleep(2000);\n\t\t\trt = Runtime.getRuntime();\n\t\t\trt.exec(\"hdfs dfs -mkdir ./Stats\" + HdfsFolderName + \"/SS\");\n\t\t\tThread.sleep(2000);\n\t\t\trt = Runtime.getRuntime();\n\t\t\trt.exec(\"hdfs dfs -mkdir ./Stats\" + HdfsFolderName + \"/SO\");\n\t\t\tThread.sleep(2000);\n\t\t\trt = Runtime.getRuntime();\n\t\t\trt.exec(\"hdfs dfs -mkdir ./Stats\" + HdfsFolderName + \"/OS\");\n\t\t\tThread.sleep(2000);\n\t\t\trt = Runtime.getRuntime();\n\t\t\trt.exec(\"hdfs dfs -mkdir ./Stats\" + HdfsFolderName + \"/OO\");\n\t\t\tThread.sleep(10000);\n\n\t\t\trt.exec(\"hadoop fs -chmod 777 ./Stats\" + HdfsFolderName + \"/OO\");\n\t\t\trt.exec(\"hadoop fs -chmod 777 ./Stats\" + HdfsFolderName + \"/OS\");\n\t\t\trt.exec(\"hadoop fs -chmod 777 ./Stats\" + HdfsFolderName + \"/SO\");\n\t\t\trt.exec(\"hadoop fs -chmod 777 ./Stats\" + HdfsFolderName + \"/SS\");\n\t\t\trt.exec(\"hadoop fs -chmod 777 ./Stats\" + HdfsFolderName + \"/Time\");\n\t\t\trt.exec(\"hadoop fs -chmod 777 ./Stats\" + HdfsFolderName + \"/Empty\");\n\t\t\trt.exec(\"hadoop fs -chmod 777 ./Stats\" + HdfsFolderName);\n\t\t\trt.exec(\"hadoop fs -chmod 777 ./Stats\");\n\n\t\t\trt.exec(\"hdfs dfs -put ./EmptyTables_\"+String.valueOf(FirstPredicate)+\".txt ./Stats\" + HdfsFolderName + \"/Empty\");\n\t\t\trt.exec(\"hdfs dfs -put ./ExtVpStats_Time_\"+String.valueOf(FirstPredicate)+\".txt ./Stats\" + HdfsFolderName + \"/Time\");\n\t\t\trt.exec(\"hdfs dfs -put ./ExtVpStats_ss_\"+String.valueOf(FirstPredicate)+\".txt ./Stats\" + HdfsFolderName + \"/SS\");\n\t\t\trt.exec(\"hdfs dfs -put ./ExtVpStats_so_\"+String.valueOf(FirstPredicate)+\".txt ./Stats\" + HdfsFolderName + \"/SO\");\n\t\t\trt.exec(\"hdfs dfs -put ./ExtVpStats_os_\"+String.valueOf(FirstPredicate)+\".txt ./Stats\" + HdfsFolderName + \"/OS\");\n\t\t\trt.exec(\"hdfs dfs -put ./ExtVpStats_oo_\"+String.valueOf(FirstPredicate)+\".txt ./Stats\" + HdfsFolderName + \"/OO\");\n\t\t\tThread.sleep(2000);\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\t\n\t/**\n\t * Store the ExtVP Loader phase statistics and ExtVP table statistics as a table.\n\t * \n\t * @param ExtVPType - Type of statistic (SO, OS, SS, OO, TIME, EMPTY).\n\t * \n\t * @throws FileNotFoundException\n\t * @throws IOException\n\t * @throws IllegalArgumentException\n\t * @throws SQLException\n\t */\n\tprivate void CreateStatsTables(String ExtVPType, String DataSetName, String UsersDirectory) throws FileNotFoundException, IOException, IllegalArgumentException, SQLException{\n\t\tint index = DataSetName.lastIndexOf(\"/\");\n\t\tString HdfsFolderName = DataSetName.substring(index);\t\n\n\t\tif(ExtVPType==\"TIME\"){\n\t\t\timpala.createTable(\"external_extvp_tableofstats_time\").ifNotExists()\n\t\t\t.external()\n\t\t\t.addColumnDefinition(\"Operation_Name\", DataType.STRING)\n\t\t\t.addColumnDefinition(\"Description\", DataType.STRING)\n\t\t\t.addColumnDefinition(\"Time\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"Measured\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"Seconds\", DataType.DOUBLE)\n\t\t\t.fieldTermintor(field_terminator)\n\t\t\t.lineTermintor(line_terminator)\n\t\t\t.location(UsersDirectory+\"/Stats\"+HdfsFolderName+\"/Time/\")\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala.createTable(\"extvp_tableofstats_time\").ifNotExists()\n\t\t\t.storedAs(FileFormat.PARQUET)\n\t\t\t.addColumnDefinition(\"Operation_Name\", DataType.STRING)\n\t\t\t.addColumnDefinition(\"Description\", DataType.STRING)\n\t\t\t.addColumnDefinition(\"Time\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"Measured\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"Seconds\", DataType.DOUBLE)\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala\n\t\t\t.insertOverwrite(\"extvp_tableofstats_time\")\n\t\t\t.selectStatement(impala.select(\"Operation_Name\")\n\t\t\t.addProjection(\"Description\")\n\t\t\t.addProjection(\"Time\") \n\t\t\t.addProjection(\"Measured\") \n\t\t\t.addProjection(\"Seconds\") \n\t\t\t.from(\"external_extvp_tableofstats_time\"))\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala.computeStats(\"extvp_tableofstats_time\");\n\t\t\t\n\t\t\timpala.dropTable(\"external_extvp_tableofstats_time\");\n\t\t}\n\t\telse if(ExtVPType==\"EMPTY\"){\n\t\t\timpala.createTable(\"external_extvp_tableofstats_emptytable\").ifNotExists()\n\t\t\t.external()\n\t\t\t.addColumnDefinition(\"ExtVPTable_Name\", DataType.STRING)\n\t\t\t.lineTermintor(line_terminator)\n\t\t\t.location(UsersDirectory+\"/Stats\"+HdfsFolderName+\"/Empty/\")\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala.createTable(\"extvp_tableofstats_emptytable\").ifNotExists()\n\t\t\t.storedAs(FileFormat.PARQUET)\n\t\t\t.addColumnDefinition(\"ExtVPTable_Name\", DataType.STRING)\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala\n\t\t\t.insertOverwrite(\"extvp_tableofstats_emptytable\")\n\t\t\t.selectStatement(impala.select(\"ExtVPTable_Name\")\n\t\t\t.from(\"external_extvp_tableofstats_emptytable\"))\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala.computeStats(\"extvp_tableofstats_emptytable\");\n\t\t\t\n\t\t\timpala.dropTable(\"external_extvp_tableofstats_emptytable\");\n\t\t}\n\t\telse{\n\t\t\timpala.createTable(\"external_extvp_tableofstats_\"+ExtVPType).ifNotExists()\n\t\t\t.external()\n\t\t\t.addColumnDefinition(\"ExtVPTable_Name\", DataType.STRING)\n\t\t\t.addColumnDefinition(\"ExtVPTable_Predicates\", DataType.STRING)\n\t\t\t.addColumnDefinition(\"ExtVPTable_Nr_Tuples\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"Partition_Nr_Tuples\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"ExtVPTable_SF\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"ExtVPTable_Time\", DataType.DOUBLE)\n\t\t\t.fieldTermintor(field_terminator)\n\t\t\t.lineTermintor(line_terminator)\n\t\t\t.location(UsersDirectory+\"/Stats\"+HdfsFolderName+\"/\"+ExtVPType+\"/\")\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala.createTable(\"extvp_tableofstats_\"+ExtVPType)\n\t\t\t.ifNotExists()\n\t\t\t.storedAs(FileFormat.PARQUET)\n\t\t\t.addColumnDefinition(\"ExtVPTable_Name\", DataType.STRING)\n\t\t\t.addColumnDefinition(\"ExtVPTable_Predicates\", DataType.STRING)\n\t\t\t.addColumnDefinition(\"ExtVPTable_Nr_Tuples\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"Partition_Nr_Tuples\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"ExtVPTable_SF\", DataType.DOUBLE)\n\t\t\t.addColumnDefinition(\"ExtVPTable_Time\", DataType.DOUBLE)\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala\n\t\t\t.insertOverwrite(\"extvp_tableofstats_\"+ExtVPType)\n\t\t\t.selectStatement(impala.select(\"ExtVPTable_Name\")\n\t\t\t.addProjection(\"ExtVPTable_Predicates\")\n\t\t\t.addProjection(\"ExtVPTable_Nr_Tuples\") \n\t\t\t.addProjection(\"Partition_Nr_Tuples\") \n\t\t\t.addProjection(\"ExtVPTable_SF\") \n\t\t\t.addProjection(\"ExtVPTable_Time\")\n\t\t\t.from(\"external_extvp_tableofstats_\"+ExtVPType))\n\t\t\t.execute();\n\t\t\t\n\t\t\timpala.computeStats(\"extvp_tableofstats_\"+ExtVPType);\n\t\t\t\n\t\t\timpala.dropTable(\"external_extvp_tableofstats_\"+ExtVPType);\n\t\t}\n\t}\n}",
"public abstract class Loader {\n\t\n\t/** The impala wrapper */\n\tprotected Impala impala;\n\n\t/*\n\t * Input configurations \n\t */\n\t\n\t/** The location of the input data */\n\tprotected String hdfs_input_directory;\n\t\n\t/** The map containing the prefixes */\n\tpublic String prefix_file;\n\t\n\t/** Indicates if dot at the end of the line is to be stripped */\n\tpublic boolean strip_dot;\n\n\t/** Indicates if duplicates in the input are to be ignored */\n\tpublic boolean unique;\n\n\t/** The separator of the fields in the rdf data */\n\tpublic String field_terminator = \"\\\\t\";\n\n\t/** The separator of the lines in the rdf data */\n\tpublic String line_terminator = \"\\\\n\";\n\t\n\t\n\t/*\n\t * Triplestore configurations \n\t */\n\t\n\t/** The table name of the triple table */\n\tprotected static final String tablename_triple_table = \"tripletable\";\n\t\n\t/** The name used for RDF subject columns */\n\tpublic String column_name_subject = \"s\";\n\n\t/** The name used for RDF predicate columns */\n\tpublic String column_name_predicate = \"p\";\n\n\t/** The name used for RDF object columns */\n\tpublic String column_name_object = \"o\";\n\n\t/*\n\t * Output configurations \n\t */\n\t\t\n\t/** The name of the output table */\n\tpublic String tablename_output;\n\n\t/** Indicates if shuffle strategy should be used for join operations */\n\tpublic boolean shuffle;\n\t\n\t/** Indicates if temporary tables must not dropped */\n\tpublic boolean keep;\n\n\t/** The location of the list of predicates */\n\tpublic String path_of_list_of_predicates = \"\\\\n\";\n\t\n\t/** The types of ExtVP tables*/\n\tpublic String extvp_types_selected = \"\\\\n\";\n\n\t/** The value of threshold*/\n\tpublic String threshold;\n\t\n\t/** Indicates if Sempala should run in Evaluation Mode */\n\tpublic boolean EvaluationMode;\n\t\n\t/** Absolut path of users folder in Hdfs */\n\tpublic String HdfsUserPath;\n\t\n\t/** The value of threshold*/\n\tpublic String Predicate_Partition = \"All\";\n\t\n\t/** The constructor */\n\tpublic Loader(Impala wrapper, String hdfsLocation) {\n\t\timpala = wrapper;\n\t\thdfs_input_directory = hdfsLocation;\n\t}\n\t\t\n\t/**\n\t * Loads RDF data into an impala parquet table.\n\t *\n\t * The input data has to be in N-Triple format and reside in a readable HDFS\n\t * directory. The output will be parquet encoded in a raw triple table\n\t * with the given name. If a prefix file is given, the matching prefixes in\n\t * the RDF data set will be replaced.\n\t * \n\t * @throws SQLException\n\t */\n\tprotected void buildTripleTable() throws SQLException {\n\n\t\tfinal String tablename_external_tripletable = \"external_tripletable\";\n\n\t\t// Import the table from hdfs into impala\n\t\tSystem.out.println(String.format(\"Creating external table '%s' from hdfs data\", tablename_external_tripletable));\n\t\timpala\n\t\t.createTable(tablename_external_tripletable)\n\t\t.external()\n\t\t.addColumnDefinition(column_name_subject, DataType.STRING)\n\t\t.addColumnDefinition(column_name_predicate, DataType.STRING)\n\t\t.addColumnDefinition(column_name_object, DataType.STRING)\n\t\t.fieldTermintor(field_terminator)\n\t\t.lineTermintor(line_terminator)\n\t\t.location(hdfs_input_directory)\n\t\t.execute();\n\t\timpala.computeStats(tablename_external_tripletable);\n\n\t\t\n\t\t// Read the prefix file if there is one\n\t\tMap<String, String> prefix_map = null;\n\t\tif (prefix_file != null) {\n\t\t\t// Get the prefixes and remove braces from long format\n\t\t\tprefix_map = new HashMap<String, String>();\n\t\t\ttry {\n\t\t\t\tBufferedReader br = new BufferedReader(new FileReader(prefix_file));\n\t\t\t\tfor (String line; (line = br.readLine()) != null;) {\n\t\t\t\t\tString[] splited = line.split(\"\\\\s+\");\n\t\t\t\t\tif (splited.length < 2){\n\t\t\t\t\t\tSystem.out.printf(\"Line in prefix file has invalid format. Skip. ('%s')\\n\", line);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tprefix_map.put(splited[1].substring(1, splited[1].length() - 1), splited[0]);\n\t\t\t\t}\n\t\t\t\tbr.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"[ERROR] Could not open prefix file. Reason: \" + e.getMessage());\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t}\n\n\t\t// Create a new parquet table, partitioned by predicate\");\n\t\tSystem.out.print(String.format(\"Creating internal partitioned table '%s' from '%s'\", tablename_triple_table, tablename_external_tripletable));\n\t\t\n\t\tlong timestamp = System.currentTimeMillis();\n\t\timpala\n\t\t.createTable(tablename_triple_table)\n\t\t.ifNotExists()\n\t\t.storedAs(FileFormat.PARQUET)\n\t\t.addColumnDefinition(column_name_subject, DataType.STRING)\n\t\t.addColumnDefinition(column_name_object, DataType.STRING)\n\t\t.addPartitionDefinition(column_name_predicate, DataType.STRING)\n\t\t.execute();\n\n\t\t// First create a select statement for the INSERT statement.\n\t\tSelectStatement ss;\n\n\t\t// Strip point if necessary (four slashes: one escape for java one for sql\n\t\tString column_name_object_dot_stripped = (strip_dot)\n\t\t\t\t? String.format(\"regexp_replace(%s, '\\\\\\\\s*\\\\\\\\.\\\\\\\\s*$', '')\", column_name_object)\n\t\t\t\t: column_name_object;\n\n\t\t// Replace prefixes\n\t\tif (prefix_map != null) {\n\t\t\t// Build a select statement _WITH_ prefix replaced values\n\t\t\tss = impala\n\t\t\t\t\t.select(prefixHelper(column_name_subject, prefix_map))\n\t\t\t\t\t.addProjection(prefixHelper(column_name_object_dot_stripped, prefix_map))\n\t\t\t\t\t.addProjection(prefixHelper(column_name_predicate, prefix_map));\n\t\t} else {\n\t\t\t// Build a select statement _WITH_OUT_ prefix replaced values\n\t\t\tss = impala\n\t\t\t\t\t.select(column_name_subject)\n\t\t\t\t\t.addProjection(column_name_object_dot_stripped)\n\t\t\t\t\t.addProjection(column_name_predicate);\n\t\t}\n\t\tif (unique)\n\t\t\tss.distinct();\n\t\tss.from(tablename_external_tripletable);\n\n\t\t// Now insert the data into the new table\n\t\timpala\n\t\t.insertOverwrite(tablename_triple_table)\n\t\t.addPartition(column_name_predicate)\n\t\t.selectStatement(ss)\n\t\t.execute();\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(System.currentTimeMillis() - timestamp)/1000));\n\t\timpala.computeStats(tablename_triple_table);\n\n\t\t// Drop intermediate tables\n\t\tif (!keep)\n\t\t\timpala.dropTable(tablename_external_tripletable);\n\t}\n\n\t/**\n\t * Creates the enormous prefix replace case statements for\n\t * buildTripleStoreTable.\n\t *\n\t * buildTripleStoreTable makes use of regex_replace in its select clause\n\t * which is dynamically created for each column. This function takes over\n\t * this part to not violate DRY principle.\n\t *\n\t * Note: Replace this with lambdas in Java 8.\n\t *\n\t * @param column_name The column name for which to create the case statement\n\t * \n\t * @return The complete CASE statement for this column\n\t */\n\tprivate static String prefixHelper(String column_name, Map<String, String> prefix_map) {\n\t\t// For each prefix append a case with a regex_replace stmt\n\t\tStringBuilder case_clause_builder = new StringBuilder();\n\t\tfor (Map.Entry<String, String> entry : prefix_map.entrySet()) {\n\t\t\tcase_clause_builder.append(String.format(\n\t\t\t\t\t\"\\n\\t WHEN %1$s LIKE '<%2$s%%'\" + \"\\n\\t THEN regexp_replace(translate(%1$s, '<>', ''), '%2$s', '%3$s')\",\n\t\t\t\t\tcolumn_name, entry.getKey(), entry.getValue()));\n\t\t}\n\t\treturn String.format(\"CASE %s \\n\\tELSE %s\\n\\tEND\", case_clause_builder.toString(), column_name);\n\t}\n\t\n\t/**\n\t * Makes the string conform to the requirements for impala column names.\n\t * I.e. remove braces, replace non word characters, trim spaces.\n\t * @param The string to make impala conform\n\t * @return The impala conform string\n\t */\n\tprotected static String toImpalaColumnName(String s) {\n\t\t// Space is a nonword character so trim before replacing chars.\n\t\treturn s.replaceAll(\"[<>]\", \"\").trim().replaceAll(\"[[^\\\\w]+]\", \"_\");\n\t}\n\n\t/** Abstract method that has to be implemented */\n\tpublic abstract void load() throws SQLException;\n}",
"public final class SimplePropertyTableLoader extends Loader {\n\t\n\t/** The name of the intermediate table of distinct subjects */\n\tprivate final String tablename_distinct_subjects = \"distinct_subjects\";\n\n\t/** The constructor */\n\tpublic SimplePropertyTableLoader(Impala wrapper, String hdfsLocation){\n\t\tsuper(wrapper, hdfsLocation);\t\n\t\ttablename_output = \"propertytable\";\t\n\t}\n\n\t/**\n\t * Creates a new property table from a triple table.\n\t *\n\t * The input table has to be in triple table format. The output will be a\n\t * table in format described in 'Sempala: Interactive SPARQL Query\n\t * Processing on Hadoop'.\n\t *\n\t * @throws SQLException\n\t */\n\t@Override\n\tpublic void load() throws SQLException {\n\t\t// Load the triple table\n\t\tbuildTripleTable();\n\t\t\n\t\t// Build a table containing distinct subjects\n\t\tSystem.out.print(String.format(\"Creating table containing distinct subjects (%s)\", tablename_distinct_subjects));\n\t\tlong timestamp = System.currentTimeMillis();\n\t\timpala\n\t\t.createTable(tablename_distinct_subjects)\n\t\t.storedAs(FileFormat.PARQUET)\n\t\t.asSelect(\n\t\t\t\timpala\n\t\t\t\t.select(column_name_subject)\n\t\t\t\t.distinct()\n\t\t\t\t.from(tablename_triple_table)\n\t\t\t\t)\n\t\t.execute();\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(System.currentTimeMillis() - timestamp)/1000));\n\t\timpala.computeStats(tablename_distinct_subjects);\n\n\t\tSystem.out.print(String.format(\"Creating property table (%s)\", tablename_output));\n\t\ttimestamp = System.currentTimeMillis();\n\t\t\n\t\t// Get properties\n\t\tResultSet resultSet = impala\n\t\t\t\t.select(column_name_predicate)\n\t\t\t\t.distinct()\n\t\t\t\t.from(tablename_triple_table)\n\t\t\t\t.execute();\n\n\t\t// Convert the result set to a list\n\t\tArrayList<String> predicates = new ArrayList<String>();\n\t\twhile (resultSet.next())\n\t\t\tpredicates.add(resultSet.getString(column_name_predicate));\n\n\t\t// Build a select stmt for the Insert-as-select statement\n\t\tSelectStatement sstmt = impala.select();\n\n\t\t// Add the subject column\n\t\tsstmt.addProjection(String.format(\"subjects.%s\", column_name_subject));\n\n\t\t// Add the property columns to select clause (\", t<x>.object AS <predicate>\")\n \t for (int i = 0; i < predicates.size(); i++)\n\t\t\tsstmt.addProjection(String.format(\"t%d.%s AS %s\", i, column_name_object, toImpalaColumnName(predicates.get(i))));\n\n\t\t// Add distinct subjects table reference\n\t\tsstmt.from(String.format(\"%s subjects\", tablename_distinct_subjects));\n\n\t\t// Append the properties via join\n\t\t// \"LEFT JOIN <tablename_internal_parquet> t<x> ON (t1.subject =\n\t\t// t<x>.subject AND t<x>.predicate = <predicate>)\" to from clause\n\t\tfor (int i = 0; i < predicates.size(); i++)\n \t \tsstmt.leftJoin(\n \t \t\t\tString.format(\"%s t%d\", tablename_triple_table, i),\n \t \t\t\tString.format(\"subjects.%2$s = t%1$d.%2$s AND t%1$d.%3$s = '%4$s'\",\n \t \t\t\t\t\ti, column_name_subject,\n \t \t\t\t\t\tcolumn_name_predicate, predicates.get(i)),\n \t \t\t\tshuffle);\n\n\t\t// Create the property table \"s, p, o[, p1, ...]\"\n\t\tCreateStatement cstmt = impala.createTable(tablename_output).ifNotExists();\n\t\tcstmt.addColumnDefinition(column_name_subject, DataType.STRING);\n\t\tfor (String pred : predicates)\n\t\t\tcstmt.addColumnDefinition(toImpalaColumnName(pred), DataType.STRING);\n\t\tcstmt.storedAs(FileFormat.PARQUET);\n\t\tcstmt.execute();\n\t\t\n\t\t// Insert data into the single table using the built select stmt\n\t\timpala\n\t\t.insertOverwrite(tablename_output)\n\t\t.selectStatement(sstmt)\n\t\t.execute();\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(System.currentTimeMillis() - timestamp)/1000));\n\t\timpala.computeStats(tablename_output);\n\t\t\n\t\t// Drop intermediate tables\n\t\tif (!keep){\n\t\t\timpala.dropTable(tablename_triple_table);\n\t\t\timpala.dropTable(tablename_distinct_subjects);\n\t\t}\n\t}\n}",
"public final class SingleTableLoader extends Loader {\n\t\n\t/** The name of the intermediate table of distinct subject predicate relations */\n\tprivate final String tablename_distinct_sp_relations = \"distinct_sp_relations\";\n\n\t/** The name of the intermediate table of distinct object predicate relations */\n\tprivate final String tablename_distinct_op_relations = \"distinct_op_relations\";\n\t\n\t/** The constructor */\n\tpublic SingleTableLoader(Impala wrapper, String hdfsLocation){\n\t\tsuper(wrapper, hdfsLocation);\n\t\ttablename_output = \"singletable\";\n\t}\n\n\t/**\n\t * Creates a new singletable from a triple table.\n\t *\n\t * The input table has to be in triple table format. The output will be a\n\t * table in format described in 'Master's Thesis: S2RDF, Skilevic Simon'\n\t *\n\t * @throws SQLException\n\t */\n\t@Override\n\tpublic void load() throws SQLException {\n\t\t// Load the triple table\n\t\tbuildTripleTable();\n\n\t\t/*\n\t\t * Create a table for the distinct subject-predicate tuples (not partitioned)\n\t\t */\n\t\t\n\t\tSystem.out.print(String.format(\"Creating table '%s'\", tablename_distinct_sp_relations));\n\t\tlong timestamp = System.currentTimeMillis();\n\t\timpala\n\t\t.createTable(tablename_distinct_sp_relations)\n\t\t.storedAs(FileFormat.PARQUET)\n\t\t.asSelect(\n\t\t\t\timpala\n\t\t\t\t.select(column_name_subject)\n\t\t\t\t.addProjection(column_name_predicate)\n\t\t\t\t.distinct()\n\t\t\t\t.from(tablename_triple_table))\n\t\t.execute();\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(System.currentTimeMillis() - timestamp)/1000));\n\t\timpala.computeStats(tablename_distinct_sp_relations);\n\n\t\t/*\n\t\t * Create a table for the distinct object-predicate tuples (not partitioned)\n\t\t */\n\n\t\tSystem.out.print(String.format(\"Creating table '%s'\", tablename_distinct_op_relations));\n\t\ttimestamp = System.currentTimeMillis();\n\t\timpala\n\t\t.createTable(tablename_distinct_op_relations)\n\t\t.storedAs(FileFormat.PARQUET)\n\t\t.ifNotExists()\n\t\t.asSelect(\n\t\t\t\timpala\n\t\t\t\t.select(column_name_object)\n\t\t\t\t.addProjection(column_name_predicate)\n\t\t\t\t.distinct()\n\t\t\t\t.from(tablename_triple_table))\n\t\t.execute();\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(System.currentTimeMillis() - timestamp)/1000));\n\t\timpala.computeStats(tablename_distinct_op_relations);\n\n\t\t/*\n\t\t * Create the single table\n\t\t */\n\t\tSystem.out.println(String.format(\"Starting the iterative creation of the singletable '%s'\", tablename_output));\n\t\ttimestamp = System.currentTimeMillis();\n\t\t\n\t\t// Get a list of all predicates\n\t\tArrayList<String> predicates = new ArrayList<String>();\n\t\tResultSet resultSet = impala.select(column_name_predicate).distinct().from(tablename_triple_table).execute();\n\t\twhile (resultSet.next())\n\t\t\tpredicates.add(resultSet.getString(column_name_predicate));\n\t\t\n\t\t// Create the new single table \"s, p, o, [ss_p1, so_p1, os_p1], ...\"\n\t\tCreateStatement cstmt = impala\n\t\t\t\t.createTable(tablename_output)\n\t\t\t\t.addColumnDefinition(column_name_subject, DataType.STRING)\n\t\t\t\t.addPartitionDefinition(column_name_predicate, DataType.STRING)\n\t\t\t\t.addColumnDefinition(column_name_object, DataType.STRING);\n\t\tfor (String pred : predicates){\n\t\t\tString impalaConformPred = toImpalaColumnName(pred);\n\t\t\tcstmt.addColumnDefinition(String.format(\"ss_%s\", impalaConformPred), DataType.BOOLEAN);\n\t\t\tcstmt.addColumnDefinition(String.format(\"so_%s\", impalaConformPred), DataType.BOOLEAN);\n\t\t\tcstmt.addColumnDefinition(String.format(\"os_%s\", impalaConformPred), DataType.BOOLEAN);\n\t\t}\n\t\tcstmt.storedAs(FileFormat.PARQUET);\n\t\tcstmt.execute();\n\n\t\t/*\n\t\t * Fill the single table\n\t\t */\n\n\t\t// Sets containing existing relations \n\t\tHashSet<String> SS_relations = new HashSet<String>();\n\t\tHashSet<String> SO_relations = new HashSet<String>();\n\t\tHashSet<String> OS_relations = new HashSet<String>();\n\t\t\n\t\tfor (String predicate : predicates){\n\n\t\t\tSystem.out.print(String.format(\"Processing '%s'\", predicate));\n\t\t\tlong localtimestamp = System.currentTimeMillis();\n\t\t\t\n\t\t\t// Reset existing relations \n\t\t\tSS_relations.clear(); \n\t\t\tSO_relations.clear(); \n\t\t\tOS_relations.clear();\n\t\t\t\n\t\t\t// Get all predicates that are in a SS relation to any triples in this partition (predicate)\n\t\t\tresultSet =\n\t\t\t\t\timpala\n\t\t\t\t\t.select(column_name_predicate).distinct()\n\t\t\t\t\t.from(String.format(\"%s sp\", tablename_distinct_sp_relations))\n\t\t\t\t\t.leftSemiJoin(\n\t\t\t\t\t\t\tString.format(\"%s tt\", tablename_triple_table),\n\t\t\t\t\t\t\tString.format(\"tt.%s=sp.%s AND tt.%s='%s'\",\n\t\t\t\t\t\t\t\t\tcolumn_name_subject, column_name_subject, column_name_predicate, predicate),\n\t\t\t\t\t\t\tshuffle)\n\t\t\t\t\t.execute();\n\t\t\twhile (resultSet.next())\n\t\t\t\tSS_relations.add(resultSet.getString(column_name_predicate));\n\t\t\t\n \t\t// Get all predicates that are in a SO relation to any triples in this partition (predicate)\n\t\t\tresultSet = impala.select(column_name_predicate).distinct()\n\t\t\t\t\t.from(String.format(\"%s op\", tablename_distinct_op_relations))\n\t\t\t\t\t.leftSemiJoin(\n\t\t\t\t\t\t\tString.format(\"%s tt\", tablename_triple_table),\n\t\t\t\t\t\t\tString.format(\"tt.%s=op.%s AND tt.%s='%s'\",\n\t\t\t\t\t\t\t\t\tcolumn_name_subject, column_name_object, column_name_predicate, predicate),\n\t\t\t\t\t\t\tshuffle)\n\t\t\t\t\t.execute();\n\t\t\twhile (resultSet.next())\n\t\t\t\tSO_relations.add(resultSet.getString(column_name_predicate));\n\t\t\t\n\t\t\t// Get all predicates that are in a OS relation to any triples in this partition (predicate)\n\t\t\tresultSet =\n\t\t\t\t\timpala\n\t\t\t\t\t.select(column_name_predicate).distinct()\n\t\t\t\t\t.from(String.format(\"%s sp\", tablename_distinct_sp_relations))\n\t\t\t\t\t.leftSemiJoin(\n\t\t\t\t\t\t\tString.format(\"%s tt\", tablename_triple_table),\n\t\t\t\t\t\t\tString.format(\"tt.%s=sp.%s AND tt.%s='%s'\",\n\t\t\t\t\t\t\t\t\tcolumn_name_object, column_name_subject, column_name_predicate, predicate),\n\t\t\t\t\t\t\tshuffle)\n\t\t\t\t\t.execute();\n\t\t\twhile (resultSet.next())\n\t\t\t\tOS_relations.add(resultSet.getString(column_name_predicate));\n\n\t\t\t// Build a select stmt for the Insert-as-select statement\n\t\t\tSelectStatement ss = impala.select();\n\n\t\t\t// Build the huge select clause\n\t\t\tss.addProjection(String.format(\"tt.%s\", column_name_subject));\n\t\t\tss.addProjection(String.format(\"tt.%s\", column_name_object));\n\t\t\tss.from(String.format(\"%s tt\", tablename_triple_table));\n\t\t\t\n\t\t\tfor (String p : predicates){\n\t\t\t\tString impalaConformPredicate = toImpalaColumnName(p);\n\t\t\t\t\n\t\t\t\t// SS_p_i\n\t\t\t\tif (SS_relations.contains(p)){\n\t\t\t\t\tss.addProjection(String.format(\"CASE WHEN %s.%s IS NULL THEN false ELSE true END AS %s\",\n\t\t\t\t\t\t\tString.format(\"tss_%s\", impalaConformPredicate),\n\t\t\t\t\t\t\tcolumn_name_subject,\n\t\t\t\t\t\t\tString.format(\"ss_%s\", impalaConformPredicate)));\n\t\t\t\t\tss.leftJoin(\n\t\t\t\t\t\t\t// Table reference e.g. \"LEFT JOIN subjects tss_p1\"\n\t\t\t\t\t\t\tString.format(\"%s tss_%s\", tablename_distinct_sp_relations, impalaConformPredicate),\n\t\t\t\t\t\t\t// On clause e.g. \"ON tt.id=tss_p1.id AND tss_p1.predicate='wsdbm:friendOf'\"\n\t\t\t\t\t\t\tString.format(\"tt.%1$s=tss_%3$s.%1$s AND tss_%3$s.%2$s='%4$s'\",\n\t\t\t\t\t\t\t\t\tcolumn_name_subject,\n\t\t\t\t\t\t\t\t\tcolumn_name_predicate,\n\t\t\t\t\t\t\t\t\timpalaConformPredicate,\n\t\t\t\t\t\t\t\t\tp),\n\t\t \t \t\t\tshuffle);\n\t\t\t\t} else {\n\t\t\t\t\tss.addProjection(\"false\");\n\t\t\t\t}\n\n\t\t\t\t// SO_pi\n\t\t\t\tif (SO_relations.contains(p)){\n\t\t\t\t\tss.addProjection(String.format(\"CASE WHEN %s.%s IS NULL THEN false ELSE true END AS %s\",\n\t\t\t\t\t\t\tString.format(\"tso_%s\", impalaConformPredicate),\n\t\t\t\t\t\t\tcolumn_name_object,\n\t\t\t\t\t\t\tString.format(\"so_%s\", impalaConformPredicate)));\n\t\t\t\t\tss.leftJoin(\n\t\t\t\t\t\t\t// Table reference e.g. \"LEFT JOIN objects tso_p1\"\n\t\t\t\t\t\t\tString.format(\"%s tso_%s\", tablename_distinct_op_relations, impalaConformPredicate),\n\t\t\t\t\t\t\t// On clause e.g. \"ON tt.id=tso_p1.object AND tso_p1.predicate='wsdbm:friendOf'\"\n\t\t\t\t\t\t\tString.format(\"tt.%1$s=tso_%4$s.%3$s AND tso_%4$s.%2$s='%5$s'\",\n\t\t\t\t\t\t\t\t\tcolumn_name_subject,\n\t\t\t\t\t\t\t\t\tcolumn_name_predicate,\n\t\t\t\t\t\t\t\t\tcolumn_name_object,\n\t\t\t\t\t\t\t\t\timpalaConformPredicate,\n\t\t\t\t\t\t\t\t\tp),\n\t\t \t \t\t\tshuffle);\n\t\t\t\t} else {\n\t\t\t\t\tss.addProjection(\"false\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (OS_relations.contains(p)){\n\t\t\t\t\tss.addProjection(String.format(\"CASE WHEN %s.%s IS NULL THEN false ELSE true END AS %s\",\n\t\t\t\t\t\t\tString.format(\"tos_%s\", impalaConformPredicate),\n\t\t\t\t\t\t\tcolumn_name_subject,\n\t\t\t\t\t\t\tString.format(\"os_%s\", impalaConformPredicate)));\n\t\t\t\t\tss.leftJoin(\n\t\t\t\t\t\t\t// Table reference e.g. \"LEFT JOIN subjects tos_p1\"\n\t\t\t\t\t\t\tString.format(\"%s tos_%s\", tablename_distinct_sp_relations, impalaConformPredicate),\n\t\t\t\t\t\t\t// On clause e.g. \"ON tt.object=tos_p1.id AND tos_p1.predicate='wsdbm:friendOf'\"\n\t\t\t\t\t\t\tString.format(\"tt.%3$s=tos_%4$s.%1$s AND tos_%4$s.%2$s='%5$s'\",\n\t\t\t\t\t\t\t\t\tcolumn_name_subject,\n\t\t\t\t\t\t\t\t\tcolumn_name_predicate,\n\t\t\t\t\t\t\t\t\tcolumn_name_object,\n\t\t\t\t\t\t\t\t\timpalaConformPredicate,\n\t\t\t\t\t\t\t\t\tp),\n\t\t \t \t\t\tshuffle);\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tss.addProjection(\"false\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Partition column at last (impala requirement)\n\t\t\tss.addProjection(String.format(\"tt.%s\", column_name_predicate));\n\t\t\tss.where(String.format(\"tt.%s='%s'\", column_name_predicate, predicate));\n\t\t\t\n\t\t\t// Insert data into the single table using the built select stmt\n\t\t\timpala\n\t\t\t.insertInto(tablename_output)\n\t\t\t.addPartition(column_name_predicate)\n\t\t\t.selectStatement(ss)\n\t\t\t.execute();\n\t\t\t\n\t\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(System.currentTimeMillis() - localtimestamp)/1000));\n\t\t}\n\t\tSystem.out.println(String.format(\"Singletable created in [%.3fs]\", (float)(System.currentTimeMillis() - timestamp)/1000));\n\t\timpala.computeStats(tablename_output);\n\t\t\n\t\t// Drop intermediate tables\n\t\tif (!keep){\n\t\t\timpala.dropTable(tablename_triple_table);\n\t\t\timpala.dropTable(tablename_distinct_sp_relations);\n\t\t\timpala.dropTable(tablename_distinct_op_relations);\n\t\t}\n\t}\n}",
"public class ComplexPropertyTableLoader {\n\n\t/** The location of the input data. */\n\tprotected String hdfs_input_directory;\n\n\t/** The file containing the prefixes. */\n\tpublic String prefix_file;\n\n\t/** A map containing the prefixes **/\n\tprivate Map<String, String> prefix_map;\n\n\t/** Indicates if dot at the end of the line is to be stripped. */\n\tpublic boolean strip_dot;\n\n\t/** Indicates if duplicates in the input are to be ignored. */\n\tpublic boolean unique;\n\n\t/** The separator of the fields in the rdf data. */\n\tpublic String field_terminator = \"\\\\t\";\n\n\t/** The separator of the lines in the rdf data. */\n\tpublic String line_terminator = \"\\\\n\";\n\n\t/*\n\t * Triplestore configurations\n\t */\n\n\t/**\n\t * The table name of the table that contains all rdf triples. The scheme of\n\t * the table is (s:STRING, p:STRING, o:OBJECT). All prefixes if a file with\n\t * prefixes is given are replaced in the table.\n\t */\n\tprotected static final String tablename_triple_table = \"tripletable\";\n\n\t/**\n\t * The name of the table that stores all properties/predicates and their\n\t * type - are they simple or complex. The scheme of the table is (p :\n\t * STRING, is_complex : BOOLEAN). There is a row for each predicate.\n\t */\n\tprotected static final String tablename_properties = \"properties\";\n\n\t/**\n\t * The name of the table that stores the transformed triple table into a\n\t * complex property table (the result of this loader). If we have a list of\n\t * predicates/properties p1, ... , pN, then the scheme of the table is (s:\n\t * STRING, p1: LIST<STRING> OR STRING, ..., pN: LIST<STRING> OR STRING).\n\t * Column s contains subjects. For each subject , there is only one row in\n\t * the table. Each predicate can be of complex or simple type. If a\n\t * predicate is of simple type means that there is no subject which has more\n\t * than one triple containing this property/predicate. Then the predicate\n\t * column is of type STRING. Otherwise, if a predicate is of complex type\n\t * which means that there exists at least one subject which has more than\n\t * one triple containing this property/predicate. Then the predicate column\n\t * is of type LIST<STRING>.\n\t */\n\tprotected static final String tablename_complex_property_table = \"complex_property_table\";\n\n\t/** The name used for RDF subject columns. */\n\tpublic String column_name_subject = \"s\";\n\n\t/** The name used for RDF predicate columns. */\n\tpublic String column_name_predicate = \"p\";\n\n\t/** The name used for RDF object columns. */\n\tpublic String column_name_object = \"o\";\n\t\n\t/** Separator used to distinguish two values in the same string */\n\tpublic String columns_separator = \"\\\\$%\";\n\n\t/**\n\t * The name used for an properties table column which indicates if a\n\t * property is simple or complex.\n\t */\n\tprotected static final String column_name_is_complex = \"is_complex\";\n\n\t/**\n\t * The format in which the tables in Spark are stored especially the result\n\t * table of this loader.\n\t */\n\tprotected static final String table_format_parquet = \"parquet\";\n\n\t/** Indicates if temporary tables must not dropped. */\n\tpublic boolean keep;\n\n\t/** Spark connection used for executing queries. */\n\tprivate Spark connection;\n\n\t/** Hive context of a Spark connection. */\n\tprivate HiveContext hiveContext;\n\n\tpublic ComplexPropertyTableLoader(Spark connection, String hdfsLocation) {\n\t\tthis.connection = connection;\n\t\tthis.hiveContext = connection.getHiveContext();\n\t\tthis.hdfs_input_directory = hdfsLocation;\n\t\tthis.strip_dot = false;\n\t\tthis.keep = false;\n\t}\n\n\t/**\n\t * Build a table that contains all rdf triples. If a file with prefixes is\n\t * given, they will be replaced. See\n\t * {@link ComplexPropertyTableLoader#tablename_triple_table}.\n\t */\n\tpublic void buildTripleTable() {\n\n\t\tString createTripleTable = String.format(\n\t\t\t\t\"CREATE EXTERNAL TABLE %s(%s STRING, %s STRING, %s STRING) ROW FORMAT DELIMITED\"\n\t\t\t\t\t\t+ \" FIELDS TERMINATED BY '%s' LINES TERMINATED BY '%s' LOCATION '%s'\",\n\t\t\t\t\t\ttablename_triple_table, column_name_subject, column_name_predicate, column_name_object,\n\t\t\t\tfield_terminator, line_terminator, hdfs_input_directory);\n\n\t\tthis.hiveContext.sql(createTripleTable);\n\n\t}\n\n\t/**\n\t * Create \"properties\" table. See:\n\t * {@link ComplexPropertyTableLoader#tablename_properties}.\n\t */\n\tpublic void savePropertiesIntoTable() {\n\t\t// return rows of format <predicate, is_complex>\n\t\t// is_complex can be 1 or 0\n\t\t// 1 for multivalued predicate, 0 for single predicate\n\n\t\t// select the properties that are complex\n\t\tDataFrame multivaluedProperties = this.hiveContext.sql(String.format(\n\t\t\t\t\"SELECT DISTINCT(%1$s) AS %1$s FROM (SELECT %2$s, %1$s, COUNT(*) AS rc FROM %3$s GROUP BY %2$s, %1$s HAVING rc > 1) AS grouped\",\n\t\t\t\tcolumn_name_predicate, column_name_subject, tablename_triple_table));\n\n\t\t// select all the properties\n\t\tDataFrame allProperties = this.hiveContext.sql(String.format(\"SELECT DISTINCT(%1$s) AS %1$s FROM %2$s\",\n\t\t\t\tcolumn_name_predicate, tablename_triple_table));\n\n\t\t// select the properties that are not complex\n\t\tDataFrame singledValueProperties = allProperties.except(multivaluedProperties);\n\n\t\t// combine them\n\t\tDataFrame combinedProperties = singledValueProperties\n\t\t\t\t.selectExpr(column_name_predicate, \"0 AS \" + column_name_is_complex)\n\t\t\t\t.unionAll(multivaluedProperties.selectExpr(column_name_predicate, \"1 AS \" + column_name_is_complex));\n\t\t\n\t\t// remove '<' and '>', convert the characters\n\t\tDataFrame cleanedProperties = combinedProperties.withColumn(\"p\", functions.regexp_replace(functions.translate(combinedProperties.col(\"p\"), \"<>\", \"\"), \n\t\t\t\t\"[[^\\\\w]+]\", \"_\"));\n\t\t\n\t\t// write the result\n\t\tcleanedProperties.write().mode(SaveMode.Overwrite).saveAsTable(tablename_properties);\n\t}\n\n\t/**\n\t * Create the final property table, allProperties contains the list of all\n\t * possible properties isComplexProperty contains (in the same order used by\n\t * allProperties) the boolean value that indicates if that property is\n\t * complex (called also multi valued) or simple.\n\t */\n\tpublic void buildComplexPropertyTable(String[] allProperties, Boolean[] isComplexProperty) {\n\n\t\t// create a new aggregation environment\n\t\tPropertiesAggregateFunction aggregator = new PropertiesAggregateFunction(allProperties, columns_separator);\n\n\t\tString predicateObjectColumn = \"po\";\n\t\tString groupColumn = \"group\";\n\n\t\t// get the compressed table\n\t\tDataFrame compressedTriples = this.hiveContext.sql(String.format(\"SELECT %s, CONCAT(%s, '%s', %s) AS po FROM %s\",\n\t\t\t\tcolumn_name_subject, column_name_predicate, columns_separator, column_name_object, tablename_triple_table));\n\n\t\t// group by the subject and get all the data\n\t\tDataFrame grouped = compressedTriples.groupBy(column_name_subject)\n\t\t\t\t.agg(aggregator.apply(compressedTriples.col(predicateObjectColumn)).alias(groupColumn));\n\n\t\t// build the query to extract the property from the array\n\t\tString[] selectProperties = new String[allProperties.length + 1];\n\t\tselectProperties[0] = column_name_subject;\n\t\tfor (int i = 0; i < allProperties.length; i++) {\n\t\t\t\n\t\t\t// if property is a full URI, remove the < at the beginning end > at the end\n\t\t\tString rawProperty = allProperties[i].startsWith(\"<\") && allProperties[i].endsWith(\">\") ? \n\t\t\t\t\tallProperties[i].substring(1, allProperties[i].length() - 1) : allProperties[i];\n\t\t\t// if is not a complex type, extract the value\n\t\t\tString newProperty = isComplexProperty[i]\n\t\t\t\t\t? \" \" + groupColumn + \"[\" + String.valueOf(i) + \"] AS \" + getValidColumnName(rawProperty)\n\t\t\t\t\t: \" \" + groupColumn + \"[\" + String.valueOf(i) + \"][0] AS \" + getValidColumnName(rawProperty);\n\t\t\tselectProperties[i + 1] = newProperty;\n\t\t}\n\n\t\tDataFrame propertyTable = grouped.selectExpr(selectProperties);\n\n\t\t// write the final one\n\t\tpropertyTable.write().mode(SaveMode.Overwrite).format(table_format_parquet)\n\t\t\t\t.saveAsTable(tablename_complex_property_table);\n\t}\n\n\t/**\n\t * Replace all not allowed characters of a DB column name by an\n\t * underscore(\"_\") and return a valid DB column name.\n\t * \n\t * @param columnName\n\t * column name that will be validated and fixed\n\t * @return name of a DB column\n\t */\n\tprivate String getValidColumnName(String columnName) {\n\t\treturn columnName.replaceAll(\"[^a-zA-Z0-9_]\", \"_\");\n\t}\n\t\n\n\n\t/**\n\t * Method that contains the full process of creating of complex property\n\t * table. Initially, from the rdf triples a table is created. If a file with\n\t * prefixes is given, they are replaced. Information of this table is\n\t * collected and move to another table named complex_property_table. It\n\t * contains one row for each subject and a list of list of its predicates.\n\t * Besides a table containing all extracted predicates and their type is\n\t * also created and it is named \"properties\". Finally, the initial triple\n\t * table could be deleted if intermediate results are discarded. For more\n\t * information about the created and used tables see: TRIPLE TABLE:\n\t * {@link ComplexPropertyTableLoader#tablename_triple_table}, PROPERTIES\n\t * TABLE: {@link ComplexPropertyTableLoader#tablename_properties}, COMPLEX\n\t * PROPERTY TABLE:\n\t * {@link ComplexPropertyTableLoader#tablename_complex_property_table}.\n\t */\n\tpublic void load() {\n\n\t\tbuildPrefixMap();\n\t\t\n\t\tbuildTripleTable();\n\n\t\t// create properties table\n\t\tsavePropertiesIntoTable();\n\n\t\t// collect information for all properties\n\t\tRow[] props = this.hiveContext.sql(String.format(\"SELECT * FROM %s\", tablename_properties)).collect();\n\t\tString[] allProperties = new String[props.length];\n\t\tBoolean[] isComplexProperty = new Boolean[props.length];\n\t\tfor (int i = 0; i < props.length; i++) {\n\t\t\tallProperties[i] = props[i].getString(0);\n\t\t\tisComplexProperty[i] = props[i].getInt(1) == 1;\n\t\t}\n\n\t\t// create complex property table\n\t\tbuildComplexPropertyTable(allProperties, isComplexProperty);\n\n\t\t// Drop intermediate tables\n\t\tif (!keep) {\n\t\t\tdropTables(tablename_triple_table);\n\t\t}\n\t}\n\n\t/**\n\t * Creates the enormous prefix replace case statements.\n\t *\n\t * buildTripleStoreTable makes use of regex_replace in its select clause\n\t * which is dynamically created for each column.\n\t *\n\t * Note: Replace this with lambdas in Java 8.\n\t *\n\t * @param column_name\n\t * The column name for which to create the case statement\n\t * \n\t * @return The complete CASE statement for this column\n\t */\n\n\tprivate static String prefixHelper(String column_name, Map<String, String> prefix_map) {\n\t\t// For each prefix append a case with a regex_replace stmt\n\t\tStringBuilder case_clause_builder = new StringBuilder();\n\t\tfor (Map.Entry<String, String> entry : prefix_map.entrySet()) {\n\t\t\tcase_clause_builder.append(String.format(\n\t\t\t\t\t\"\\n\\t WHEN %1$s LIKE '%2$s%%'\"\n\t\t\t\t\t\t\t+ \"\\n\\t THEN regexp_replace(translate(%1$s, '<>', ''), '%2$s', '%3$s')\",\n\t\t\t\t\tcolumn_name, entry.getKey(), entry.getValue()));\n\t\t}\n\t\treturn String.format(\"CASE %s \\n\\tELSE %s\\n\\tEND\", case_clause_builder.toString(), column_name);\n\t}\n\t\n\t/**\n\t * create the map containing the prefixes, if they are used\n\t */\n\tprivate void buildPrefixMap() {\n\t\t// Read the prefix file if there is one\n\t\tthis.prefix_map = null;\n\t\tif (prefix_file != null) {\n\t\t\t// Get the prefixes and remove braces from long format\n\t\t\tprefix_map = new HashMap<String, String>();\n\t\t\ttry {\n\t\t\t\tBufferedReader br = new BufferedReader(new FileReader(prefix_file));\n\t\t\t\tfor (String line; (line = br.readLine()) != null;) {\n\t\t\t\t\tString[] splited = line.split(\"\\\\s+\");\n\t\t\t\t\tif (splited.length < 2) {\n\t\t\t\t\t\tSystem.out.printf(\"Line in prefix file has invalid format. Skip. ('%s')\\n\", line);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tprefix_map.put(splited[1].substring(1, splited[1].length() - 1), splited[0]);\n\t\t\t\t}\n\t\t\t\tbr.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"[ERROR] Could not open prefix file. Reason: \" + e.getMessage());\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Drop tables.\n\t * \n\t * @param tableNames\n\t * list of table names that will be dropped\n\t */\n\tpublic void dropTables(String... tableNames) {\n\t\tfor (String tb : tableNames)\n\t\t\tthis.hiveContext.sql(\"DROP TABLE \" + tb);\n\t}\n\n}",
"public class Spark {\n\n\tprivate SparkConf sparkConfiguration;\n\tprivate JavaSparkContext javaContext;\n\tprivate HiveContext hiveContext;\n\n\t/**\n\t * Initializes a Spark connection. Use it afterwards for execution of Spark\n\t * SQL queries.\n\t * \n\t * @param appName\n\t * the name of the app that will be used with this Spark\n\t * connection\n\t * @param database\n\t * name of the database that will be used with this Spark\n\t * connection\n\t */\n\tpublic Spark(String appName, String database) {\n\n\t\t// TODO check what will happen if there is already in use the same app\n\t\t// name\n\t\tthis.sparkConfiguration = new SparkConf().setAppName(appName);\n\t\tthis.javaContext = new JavaSparkContext(sparkConfiguration);\n\t\tthis.hiveContext = new HiveContext(javaContext);\n\t\t// TODO check what kind of exception can be thrown here if there is a\n\t\t// problem with spark connection\n\n\t\tthis.hiveContext.sql(String.format(\"CREATE DATABASE %s\", database));\n\t\t// TODO check what kind of exception is thrown if database already\n\n\t\t// use the created database\n\t\tthis.hiveContext.sql((String.format(\"USE %s\", database)));\n\t}\n\n\t/**\n\t * Get Hive context.\n\t * \n\t * @return {@link HiveContext}\n\t */\n\tpublic HiveContext getHiveContext() {\n\t\treturn hiveContext;\n\t}\n}",
"public final class Impala {\n\n\t/** An enumertation of the query options supported by impala 2.2 */\n\tpublic enum QueryOption {\n\t\tABORT_ON_DEFAULT_LIMIT_EXCEEDED,\n\t\tABORT_ON_ERROR,\n\t\tALLOW_UNSUPPORTED_FORMATS,\n\t\tAPPX_COUNT_DISTINCT,\n\t\tBATCH_SIZE,\n\t\tCOMPRESSION_CODEC,\n\t\tDEBUG_ACTION,\n\t\tDEFAULT_ORDER_BY_LIMIT,\n\t\tDISABLE_CODEGEN,\n\t\tDISABLE_UNSAFE_SPILLS,\n\t\tEXEC_SINGLE_NODE_ROWS_THRESHOLD,\n\t\tEXPLAIN_LEVEL,\n\t\tHBASE_CACHE_BLOCKS,\n\t\tHBASE_CACHING,\n\t\tMAX_ERRORS,\n\t\tMAX_IO_BUFFERS,\n\t\tMAX_SCAN_RANGE_LENGTH,\n\t\tMEM_LIMIT,\n\t\tNUM_NODES,\n\t\tNUM_SCANNER_THREADS,\n\t\tPARQUET_COMPRESSION_CODEC,\n\t\tPARQUET_FILE_SIZE,\n\t\tQUERY_TIMEOUT_S,\n\t\tREQUEST_POOL,\n\t\tRESERVATION_REQUEST_TIMEOUT,\n\t\tSUPPORT_START_OVER,\n\t\tSYNC_DDL,\n\t\tV_CPU_CORES\n\t}\n\n\t/** The connection to the impala daemon */\n private Connection connection = null;\n\n /** Creates an instance of the impala wrapper. */\n\tpublic Impala(String host, String port, String database) throws SQLException {\n // Dynamically load the impala driver // Why is this not necessary?\n//\t\ttry {\n//\t \tClass.forName(\"com.cloudera.impala.jdbc41.Driver\");\n//\t\t} catch (ClassNotFoundException e) {\n//\t\t\tSystem.out.println(\"Where is your JDBC Driver?\");\n//\t\t\te.printStackTrace();\n//\t\t\treturn;\n//\t\t}\n//\t Enumeration<Driver> d = DriverManager.getDrivers();\n//\t\twhile (d.hasMoreElements()) {\n//\t\t\tSystem.out.println(d.nextElement());\n//\t\t}\n\n \t// Establish the connection to impalad\n\t\tString impalad_url = String.format(\"jdbc:impala://%s:%s/\", host, port);\n\t\tSystem.out.println(String.format(\"Connecting to impalad (%s)\", impalad_url));\n\t\tconnection = DriverManager.getConnection(impalad_url);\n\t\ttry {\n\t\t\t// Try to create the database\n\t\t\tconnection.createStatement().executeUpdate(String.format(\"CREATE DATABASE %s\", database));\n\t\t} catch (SQLException e) {\n\t\t\t// TODO: Make sure this is the exception we expect (database exists)\n\t\t\t// Ask which action should be taken\n\t\t\tinputloop: while (true) {\n\t\t\t\tSystem.out.printf(\"Database '%s' exists. (D)rop it, (u)se it, (a)bort? [d/u/a]: \", database);\n\t\t\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\t\tString input = null;\n\t\t\t\ttry {\n\t\t\t\t\tinput = br.readLine().toLowerCase();\n\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\tSystem.exit(1);\n\t\t\t\t}\n\t\t\t\tswitch (input) {\n\t\t\t\tcase \"d\":\n\t\t\t\t\tconnection.createStatement().executeUpdate(String.format(\"DROP DATABASE %s CASCADE\", database));\n\t\t\t\t\tconnection.createStatement().executeUpdate(String.format(\"CREATE DATABASE IF NOT EXISTS %s\", database));\n\t\t\t\t\tbreak inputloop;\n\t\t\t\tcase \"u\":\n\t\t\t\t\tbreak inputloop;\n\t\t\t\tcase \"a\":\n\t\t\t\t\tSystem.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconnection.createStatement().executeUpdate(String.format(\"USE %s\", database));\n }\n\n @Override\n protected void finalize() throws Throwable {\n \tconnection.close();\n \tconnection=null;\n \tsuper.finalize();\n }\n\n /**\n * Creates a handy builder for the CREATE statement.\n *\n * @param tablename The name of the table you want to create.\n * @return The builder for the CREATE statement.\n */\n public CreateStatement createTable(String tablename){\n \treturn new CreateStatement(connection, tablename);\n }\n\n /**\n * Creates a handy builder for the CREATE statement.\n *\n * Convenience function for {@link createTable}. This function returns a\n * statement with the external flag initially set.\n *\n * @param tablename The name of the table you want to create.\n * @return The builder for the CREATE statement.\n */\n public CreateStatement createTable(){\n \treturn new CreateStatement(connection);\n }\n\n /**\n * Creates a handy builder for the INSERT statement.\n *\n * @param tablename The name of the table you want to insert into.\n * @return The builder for the INSERT statement.\n */\n public InsertStatement insertInto(String tablename){\n \treturn new InsertStatement(connection, tablename);\n }\n\n /**\n * Creates a handy builder for the INSERT statement.\n *\n * Convenience function for {@link insertTable}. This function returns a\n * statement with the overwrite flag initially set.\n *\n * @param tablename The name of the table you want to create.\n * @return The builder for the INSERT statement.\n */\n public InsertStatement insertOverwrite(String tablename){\n \treturn this.insertInto(tablename).overwrite();\n }\n\n /**\n * Creates a handy builder for the SELECT statement.\n *\n * @param tablename The projection expression of your query\n * @return The builder for the SELECT statement.\n */\n public SelectStatement select(){\n \treturn new SelectStatement(connection);\n }\n\n /**\n * Creates a handy builder for the SELECT statement.\n *\n * @param tablename The projection expression of your query\n * @return The builder for the SELECT statement.\n */\n public SelectStatement select(String expression){\n \treturn new SelectStatement(connection, expression);\n }\n\n /**\n * Drops a table instantly.\n *\n * @param tablename The table to drop.\n * @throws SQLException\n */\n public void dropTable(String tablename) throws SQLException {\n\t\tSystem.out.print(String.format(\"Dropping table '%s'\", tablename));\n\t\tlong startTime = System.currentTimeMillis();\n\t\tconnection.createStatement().executeUpdate(String.format(\"DROP TABLE %s;\", tablename));\n\t\tlong endTime = System.currentTimeMillis();\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(endTime - startTime)/1000));\n }\n\n /**\n * Computes stats for a table (optimization)\n *\n * Gathers information about volume and distribution of data in a table and\n * all associated columns and partitions. The information is stored in the\n * metastore database, and used by Impala to help optimize queries.\n *\n * http://www.cloudera.com/content/www/en-us/documentation/enterprise/latest/topics/impala_perf_stats.html?scroll=perf_stats\n *\n * @param tablename\n * @throws SQLException\n */\n public void computeStats(String tablename) throws SQLException {\n\t\tSystem.out.print(String.format(\"Precomputing optimization stats for '%s'\", tablename));\n\t\tlong startTime = System.currentTimeMillis();\n\t\tconnection.createStatement().executeUpdate(String.format(\"COMPUTE STATS %s;\", tablename));\n\t\tlong endTime = System.currentTimeMillis();\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(endTime - startTime)/1000));\n }\n\n /**\n * Sets an impala query option\n *\n * http://www.cloudera.com/content/www/en-us/documentation/archive/impala/2-x/2-1-x/topics/impala_query_options.html?scroll=query_options\n *\n * @param option The option to set.\n * @param value The value of the option to set.\n * @throws SQLException\n */\n public void set(QueryOption option, String value) throws SQLException {\n\t\tSystem.out.print(String.format(\"Setting impala query option '%s' to '%s'\", option.name(), value));\n\t\tlong startTime = System.currentTimeMillis();\n\t\tconnection.createStatement().executeUpdate(String.format(\"SET %s=%s;\", option.name(), value));\n\t\tlong endTime = System.currentTimeMillis();\n\t\tSystem.out.println(String.format(\" [%.3fs]\", (float)(endTime - startTime)/1000));\n }\n}",
"public enum QueryOption {\n\tABORT_ON_DEFAULT_LIMIT_EXCEEDED,\n\tABORT_ON_ERROR,\n\tALLOW_UNSUPPORTED_FORMATS,\n\tAPPX_COUNT_DISTINCT,\n\tBATCH_SIZE,\n\tCOMPRESSION_CODEC,\n\tDEBUG_ACTION,\n\tDEFAULT_ORDER_BY_LIMIT,\n\tDISABLE_CODEGEN,\n\tDISABLE_UNSAFE_SPILLS,\n\tEXEC_SINGLE_NODE_ROWS_THRESHOLD,\n\tEXPLAIN_LEVEL,\n\tHBASE_CACHE_BLOCKS,\n\tHBASE_CACHING,\n\tMAX_ERRORS,\n\tMAX_IO_BUFFERS,\n\tMAX_SCAN_RANGE_LENGTH,\n\tMEM_LIMIT,\n\tNUM_NODES,\n\tNUM_SCANNER_THREADS,\n\tPARQUET_COMPRESSION_CODEC,\n\tPARQUET_FILE_SIZE,\n\tQUERY_TIMEOUT_S,\n\tREQUEST_POOL,\n\tRESERVATION_REQUEST_TIMEOUT,\n\tSUPPORT_START_OVER,\n\tSYNC_DDL,\n\tV_CPU_CORES\n}"
] | import java.sql.SQLException;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import de.uni_freiburg.informatik.dbis.sempala.loader.ExtVPLoader;
import de.uni_freiburg.informatik.dbis.sempala.loader.Loader;
import de.uni_freiburg.informatik.dbis.sempala.loader.SimplePropertyTableLoader;
import de.uni_freiburg.informatik.dbis.sempala.loader.SingleTableLoader;
import de.uni_freiburg.informatik.dbis.sempala.loader.spark.ComplexPropertyTableLoader;
import de.uni_freiburg.informatik.dbis.sempala.loader.spark.Spark;
import de.uni_freiburg.informatik.dbis.sempala.loader.sql.Impala;
import de.uni_freiburg.informatik.dbis.sempala.loader.sql.Impala.QueryOption; | package de.uni_freiburg.informatik.dbis.sempala.loader.run;
/**
*
* @author Manuel Schneider <[email protected]>
*
*/
public class Main {
/**
* The main routine.
*
* @param args
* The arguments passed to the program
*/
public static void main(String[] args) {
// Parse command line
Options options = buildOptions();
CommandLine commandLine = null;
CommandLineParser parser = new BasicParser();
try {
commandLine = parser.parse(options, args);
} catch (ParseException e) {
// Commons CLI is poorly designed and uses exceptions for missing
// required options. Therefore we can not print help without
// throwing
// an exception. We'll just print it on every exception.
System.err.println(e.getLocalizedMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(100);
formatter.printHelp("sempala-loader", options, true);
System.exit(1);
}
// parse the format of the table that will be built
String format = commandLine.getOptionValue(OptionNames.FORMAT.toString());
String database = commandLine.getOptionValue(OptionNames.DATABASE.toString());
Impala impala = null;
Spark spark = null;
if (format.equals(Format.EXTVP.toString()) || format.equals(Format.SIMPLE_PROPERTY_TABLE.toString()) || format.equals(Format.SINGLE_TABLE.toString())) {
// Connect to the impala daemon
if(!commandLine.hasOption(OptionNames.USER_HDFS_DIRECTORY.toString())){
System.err.println("For ExtVP format user's absolut path of HDFS direcotry -ud is also required.");
System.exit(1);
}
try {
String host = commandLine.getOptionValue(OptionNames.HOST.toString());
String port = commandLine.getOptionValue(OptionNames.PORT.toString(), "21050");
impala = new Impala(host, port, database);
// Set compression codec to snappy | impala.set(QueryOption.COMPRESSION_CODEC, "SNAPPY"); | 7 |
terzerm/hover-raft | src/main/java/org/tools4j/hoverraft/command/Command.java | [
"public interface DirectPayload {\n\n int byteLength();\n\n int offset();\n\n DirectBuffer readBufferOrNull();\n\n MutableDirectBuffer writeBufferOrNull();\n\n void wrap(DirectBuffer buffer, int offset);\n\n void wrap(MutableDirectBuffer buffer, int offset);\n\n void unwrap();\n\n default boolean isWrapped() {\n return readBufferOrNull() != null || writeBufferOrNull() != null;\n }\n}",
"public interface Event {\n Transition accept(ServerContext serverContext, EventHandler eventHandler);\n}",
"public interface EventHandler {\n default Transition onTransition(ServerContext serverContext, Transition transition) {return Transition.STEADY;}\n default Transition onCommand(ServerContext serverContext, Command command) {return Transition.STEADY;}\n default Transition onVoteRequest(ServerContext serverContext, VoteRequest voteRequest) {return Transition.STEADY;}\n default Transition onVoteResponse(ServerContext serverContext, VoteResponse voteResponse) {return Transition.STEADY;}\n default Transition onAppendRequest(ServerContext serverContext, AppendRequest appendRequest) {return Transition.STEADY;}\n default Transition onAppendResponse(ServerContext serverContext, AppendResponse appendResponse) {return Transition.STEADY;}\n default Transition onTimeoutNow(ServerContext serverContext, TimeoutNow timeoutNow) {return Transition.STEADY;}\n default Transition onTimerEvent(ServerContext serverContext, TimerEvent timerEvent) {return Transition.STEADY;};\n}",
"public interface ServerContext {\n\n ServerConfig serverConfig();\n\n ConsensusConfig consensusConfig();\n\n Connections<Message> connections();\n\n DirectFactory directFactory();\n\n StateMachine stateMachine();\n\n Timer timer();\n\n ResendStrategy resendStrategy();\n\n void perform();\n\n default int id() {\n return serverConfig().id();\n }\n}",
"public enum Transition implements Event {\n STEADY(null, false),\n TO_FOLLOWER(Role.FOLLOWER, true),\n TO_CANDIDATE(Role.CANDIDATE, false),\n TO_LEADER(Role.LEADER, false);\n\n private final Role targetRole;\n private final boolean replayEvent;\n\n Transition(final Role targetRole, final boolean replayEvent) {\n this.targetRole = targetRole;//nullable\n this.replayEvent = replayEvent;\n }\n\n public final Role targetRole(final Role currentRole) {\n return this == STEADY ? currentRole : targetRole;\n }\n\n public final boolean replayEvent() {\n return replayEvent;\n }\n\n @Override\n public Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {\n return eventHandler.onTransition(serverContext, this);\n }\n\n public static Transition startWith(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {\n return event.accept(serverContext, eventHandler);\n }\n public final Transition ifSteadyThen(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {\n if (this == STEADY) {\n return event.accept(serverContext, eventHandler);\n }\n return this;\n }\n}"
] | import org.tools4j.hoverraft.direct.DirectPayload;
import org.tools4j.hoverraft.event.Event;
import org.tools4j.hoverraft.event.EventHandler;
import org.tools4j.hoverraft.server.ServerContext;
import org.tools4j.hoverraft.state.Transition; | /**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* 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 org.tools4j.hoverraft.command;
public interface Command extends DirectPayload, Event {
CommandKey commandKey();
CommandPayload commandPayload();
default Command sourceId(final int sourceId) {
commandKey().sourceId(sourceId);
return this;
}
default Command commandIndex(final long commandIndex) {
commandKey().commandIndex(commandIndex);
return this;
}
default void copyFrom(final Command command) {
writeBufferOrNull().putBytes(offset(), command.readBufferOrNull(), command.offset(), command.byteLength());
}
@Override | default Transition accept(final ServerContext serverContext, final EventHandler eventHandler) { | 2 |
ilmila/J2EEScan | src/main/java/burp/J2EELFIRetriever.java | [
"public static boolean isApacheStrutsConfigFile(byte[] response, IExtensionHelpers helpers) {\n final byte[] STRUTS_PATTERN = \"<struts\".getBytes();\n List<int[]> matchesStruts = getMatches(response, STRUTS_PATTERN, helpers);\n\n return (matchesStruts.size() > 0);\n}",
"public static boolean isEtcPasswdFile(byte[] response, IExtensionHelpers helpers) {\n final byte[] PASSWD_PATTERN_1 = \"root:\".getBytes();\n final byte[] PASSWD_PATTERN_2 = \"bin/\".getBytes();\n List<int[]> matchesPasswd1 = getMatches(response, PASSWD_PATTERN_1, helpers);\n\n if (matchesPasswd1.size() > 0) {\n List<int[]> matchesPasswd2 = getMatches(response, PASSWD_PATTERN_2, helpers);\n if (matchesPasswd2.size() > 0) {\n return true;\n }\n }\n\n return false;\n}",
"public static boolean isEtcShadowFile(byte[] response, IExtensionHelpers helpers) {\n final byte[] SHADOW_PATTERN = \"root:\".getBytes();\n List<int[]> matchesShadow = getMatches(response, SHADOW_PATTERN, helpers);\n\n return (matchesShadow.size() > 0);\n}",
"public static boolean isIBMWSBinding(byte[] response, IExtensionHelpers helpers) {\n final byte[] IBMWEB_PATTERN = \"<webservices-bnd\".getBytes();\n List<int[]> matchesIbmweb = getMatches(response, IBMWEB_PATTERN, helpers);\n\n return (matchesIbmweb.size() > 0);\n}",
"public static boolean isSpringContextConfigFile(byte[] response, IExtensionHelpers helpers) {\n final byte[] SPRING_PATTERN = \"<beans\".getBytes();\n List<int[]> matchesStruts = getMatches(response, SPRING_PATTERN, helpers);\n\n return (matchesStruts.size() > 0);\n}",
"public class CustomScanIssue implements IScanIssue {\n\n private IHttpService httpService;\n private URL url;\n private IHttpRequestResponse httpMessages;\n private String name;\n private String detail;\n private Risk severity;\n private String remedy;\n private Confidence confidence = Confidence.Certain;\n \n public CustomScanIssue(\n IHttpService httpService,\n URL url,\n IHttpRequestResponse httpMessages,\n String name,\n String detail,\n String remedy,\n Risk severity,\n Confidence confidence) {\n this.httpService = httpService;\n this.url = url;\n this.httpMessages = httpMessages;\n this.name = \"J2EEScan - \" + name;\n this.detail = detail;\n this.remedy = remedy;\n this.severity = severity;\n this.confidence = confidence;\n } \n \n\n @Override\n public URL getUrl() {\n return url;\n }\n\n @Override\n public String getIssueName() {\n return name;\n }\n\n @Override\n public int getIssueType() {\n return 0;\n }\n\n @Override\n public String getSeverity() {\n return severity.toString();\n }\n\n @Override\n // \"Certain\", \"Firm\" or \"Tentative\"\n public String getConfidence() {\n return confidence.toString();\n }\n\n @Override\n public String getIssueBackground() {\n return null;\n }\n\n @Override\n public String getRemediationBackground() {\n return null;\n }\n\n @Override\n public String getIssueDetail() {\n return detail;\n }\n\n @Override\n public String getRemediationDetail() {\n return remedy;\n }\n\n @Override\n public IHttpRequestResponse[] getHttpMessages() {\n return new IHttpRequestResponse[]{httpMessages};\n }\n\n @Override\n public IHttpService getHttpService() {\n return httpService;\n }\n\n}"
] | import static burp.HTTPMatcher.isApacheStrutsConfigFile;
import static burp.HTTPMatcher.isEtcPasswdFile;
import static burp.HTTPMatcher.isEtcShadowFile;
import static burp.HTTPMatcher.isIBMWSBinding;
import static burp.HTTPMatcher.isSpringContextConfigFile;
import burp.j2ee.Confidence;
import burp.j2ee.CustomScanIssue;
import burp.j2ee.Risk;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List; | IHttpRequestResponse ibmwebRequestResponse = cb.makeHttpRequest(
baseRequestResponse.getHttpService(), helpers.stringToBytes(ibmwebLFIRequest));
byte[] ibmwebResponse = ibmwebRequestResponse.getResponse();
if (HTTPMatcher.isIBMWebExtFileWAS7(ibmwebResponse, helpers)) {
cb.addScanIssue(new CustomScanIssue(
baseRequestResponse.getHttpService(),
requestInfo.getUrl(),
ibmwebRequestResponse,
"Local File Include - ibm-web-ext.xml Retrieved",
"J2EEScan was able tor retrieve the IBM Application Server ibm-web-ext.xml resource through the LFI vulnerability.",
LFI_REMEDY,
Risk.Low,
Confidence.Certain
));
}
} catch (Exception ex) {
ex.printStackTrace(stderr);
}
// Try to retrieve /ibm-web-ext.xmi file
try {
//
String ibmwebLFIRequest = requestToString.replace(baseConfigFile, "ibm-web-ext.xmi");
IHttpRequestResponse ibmwebRequestResponse = cb.makeHttpRequest(
baseRequestResponse.getHttpService(), helpers.stringToBytes(ibmwebLFIRequest));
byte[] ibmwebResponse = ibmwebRequestResponse.getResponse();
if (HTTPMatcher.isIBMWebExtFileWAS6(ibmwebResponse, helpers)) {
cb.addScanIssue(new CustomScanIssue(
baseRequestResponse.getHttpService(),
requestInfo.getUrl(),
ibmwebRequestResponse,
"Local File Include - ibm-web-ext.xmi Retrieved",
"J2EEScan was able tor retrieve the IBM Application Server ibm-web-ext.xmi resource through the LFI vulnerability.",
LFI_REMEDY,
Risk.Low,
Confidence.Certain
));
}
} catch (Exception ex) {
ex.printStackTrace(stderr);
}
// Try to retrieve ibm-ws-bnd.xml file
try {
// http://www-01.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.wlp.nd.doc/ae/twlp_sec_ws_basicauth.html?cp=SSAW57_8.5.5%2F1-3-11-0-4-9-0-1
String ibmwebLFIRequest = requestToString.replace(baseConfigFile, "ibm-ws-bnd.xml");
IHttpRequestResponse ibmwebRequestResponse = cb.makeHttpRequest(
baseRequestResponse.getHttpService(), helpers.stringToBytes(ibmwebLFIRequest));
byte[] ibmwebResponse = ibmwebRequestResponse.getResponse();
if (isIBMWSBinding(ibmwebResponse, helpers)) {
cb.addScanIssue(new CustomScanIssue(
baseRequestResponse.getHttpService(),
requestInfo.getUrl(),
ibmwebRequestResponse,
"Local File Include - ibm-ws-bnd.xml Retrieved",
"J2EEScan was able tor retrieve the IBM Application Server ibm-ws-bnd.xml resource through the LFI vulnerability.",
LFI_REMEDY,
Risk.Low,
Confidence.Certain
));
}
} catch (Exception ex) {
ex.printStackTrace(stderr);
}
// Try to retrieve weblogic.xml file
try {
String weblogicLFIRequest = requestToString.replace(baseConfigFile, "weblogic.xml");
IHttpRequestResponse weblogicRequestResponse = cb.makeHttpRequest(
baseRequestResponse.getHttpService(), helpers.stringToBytes(weblogicLFIRequest));
byte[] weblogicResponse = weblogicRequestResponse.getResponse();
if (HTTPMatcher.isWebLogicFile(weblogicResponse, helpers)) {
cb.addScanIssue(new CustomScanIssue(
baseRequestResponse.getHttpService(),
requestInfo.getUrl(),
weblogicRequestResponse,
"Local File Include - weblogic.xml Retrieved",
"J2EEScan was able tor retrieve the weblogic.xml resource through the LFI vulnerability.",
LFI_REMEDY,
Risk.High,
Confidence.Certain
));
}
} catch (Exception ex) {
ex.printStackTrace(stderr);
}
// Try to retrieve the struts configuration file
try {
// Possibile paths:
// /WEB-INF/classes/struts.xml
// /WEB-INF/struts-config.xml
// /WEB-INF/struts.xml
final List<String> STRUTS_PATHS = Arrays.asList(
helpers.urlEncode("classes/struts.xml"),
"struts-config.xml",
"struts.xml"
);
for (String STRUT_PATH : STRUTS_PATHS) {
String strutLFIRequest = requestToString.replace(baseConfigFile, STRUT_PATH);
IHttpRequestResponse strutsRequestResponse = cb.makeHttpRequest(
baseRequestResponse.getHttpService(), helpers.stringToBytes(strutLFIRequest));
byte[] strutsResponse = strutsRequestResponse.getResponse();
| if (isApacheStrutsConfigFile(strutsResponse, helpers)) { | 0 |
apache/geronimo-gshell | gshell-core/src/main/java/org/apache/geronimo/gshell/builtins/SourceCommand.java | [
"public abstract class CommandSupport\n implements Command\n{\n protected Log log;\n\n private String name;\n\n private CommandContext context;\n\n protected CommandSupport(final String name) {\n setName(name);\n }\n\n /**\n * Sub-class <b>must</b> call {@link #setName(String)}.\n */\n protected CommandSupport() {\n super();\n }\n\n public void setName(final String name) {\n if (name == null) {\n throw new NullArgumentException(\"name\");\n }\n if (name.trim().length() == 0) {\n throw new IllegalArgumentException(\"Name is empty\");\n }\n\n this.name = name;\n }\n\n public String getName() {\n if (name == null) {\n throw new IllegalStateException(\"Name was not set\");\n }\n\n return name;\n }\n\n //\n // Life-cycle\n //\n\n private void dump(final Variables vars) {\n Iterator<String> iter = vars.names();\n\n if (iter.hasNext()) {\n log.debug(\"Variables:\");\n }\n\n while (iter.hasNext()) {\n String name = iter.next();\n\n log.debug(\" \" + name + \"=\" + vars.get(name));\n }\n }\n\n public final void init(final CommandContext context) {\n if (this.context != null) {\n throw new IllegalStateException(\"Command already initalized\");\n }\n\n // Initialize logging with command name\n log = LogFactory.getLog(this.getClass().getName() + \".\" + getName());\n\n log.debug(\"Initializing\");\n\n this.context = context;\n\n if (log.isDebugEnabled()) {\n dump(context.getVariables());\n }\n\n try {\n doInit();\n }\n catch (Exception e) {\n log.error(\"Initialization failed\", e);\n\n //\n // HACK: Need to handle or descide to ignore this exception\n //\n\n throw new RuntimeException(\"Command initialization failed\", e);\n }\n\n log.debug(\"Initialized\");\n }\n\n protected void doInit() throws Exception {\n // Sub-class should override to provide custom initialization\n }\n\n private void ensureInitialized() {\n if (context == null) {\n throw new IllegalStateException(\"Command has not been initialized\");\n }\n }\n\n public final void destroy() {\n if (this.context == null) {\n throw new IllegalStateException(\"Command already destroyed (or never initialized)\");\n }\n\n log.debug(\"Destroying\");\n\n if (log.isDebugEnabled()) {\n dump(context.getVariables());\n }\n\n try {\n doDestroy();\n }\n catch (Exception e) {\n log.error(\"Destruction failed\", e);\n\n //\n // HACK: Need to handle or descide to ignore this exception\n //\n\n throw new RuntimeException(\"Command destruction failed\", e);\n }\n\n this.context = null;\n\n log.debug(\"Destroyed\");\n }\n\n protected void doDestroy() throws Exception {\n // Sub-class should override to provide custom cleanup\n }\n\n public void abort() {\n // Sub-calss should override to allow for custom abort functionality\n }\n\n //\n // Context Helpers\n //\n\n protected CommandContext getCommandContext() {\n if (context == null) {\n throw new IllegalStateException(\"Not initialized; missing command context\");\n }\n\n return context;\n }\n\n protected Variables getVariables() {\n return getCommandContext().getVariables();\n }\n\n protected IO getIO() {\n return getCommandContext().getIO();\n }\n\n protected MessageSource getMessageSource() {\n return getCommandContext().getMessageSource();\n }\n\n //\n // Execute Helpers\n //\n\n public Object execute(final Object... args) throws Exception {\n assert args != null;\n\n // Make sure that we have been initialized before we go any further\n ensureInitialized();\n\n boolean info = log.isInfoEnabled();\n\n if (info) {\n log.info(\"Executing w/arguments: \" + Arguments.asString(args));\n }\n\n Object result;\n\n try {\n // Handle the command-line\n Options options = getOptions();\n CommandLineParser parser = new PosixParser();\n CommandLine line = parser.parse(options, Arguments.toStringArray(args));\n\n // First check for help flags\n boolean usage = line.hasOption('h');\n\n // Custom command-line processing\n if (!usage) {\n usage = processCommandLine(line);\n }\n\n // Default command-line processing\n if (usage) {\n displayHelp(options);\n\n return Command.SUCCESS;\n }\n\n // Execute with the remaining arguments post-processing\n result = doExecute(line.getArgs());\n }\n catch (Exception e) {\n log.error(e.getMessage());\n if (log.isDebugEnabled()) {\n log.debug(\"Exception details\", e);\n }\n\n result = Command.FAILURE;\n }\n catch (Notification n) {\n //\n // Always rethrow notifications\n //\n throw n;\n }\n catch (Error e) {\n log.error(e.getMessage());\n\n if (log.isDebugEnabled()) {\n log.debug(\"Error details\", e);\n }\n\n result = Command.FAILURE;\n }\n finally {\n // Be sure to flush the commands outputs\n getIO().flush();\n }\n\n if (info) {\n log.info(\"Command exited with result: \" + result);\n }\n\n return result;\n }\n\n /**\n * Sub-class should override to perform custom execution.\n *\n * @param args Post-command-line parsed options.\n * @return\n *\n * @throws Exception\n */\n protected abstract Object doExecute(final Object[] args) throws Exception;\n\n //\n // CLI Fluff\n //\n\n /**\n * Process the command-line.\n *\n * <p>\n * The default is to provide no additional processing.\n *\n * @param line The command-line to process.\n * @return True to display help and exit; else false to continue.\n *\n * @throws CommandException\n */\n protected boolean processCommandLine(final CommandLine line) throws CommandException {\n return false;\n }\n\n /**\n * Get the command-line options to process.\n *\n * <p>\n * The default is to provide --help and -h support.\n *\n * @return The command-line options; never null;\n */\n protected Options getOptions() {\n MessageSource messages = getMessageSource();\n\n Options options = new Options();\n\n options.addOption(OptionBuilder.withLongOpt(\"help\")\n .withDescription(messages.getMessage(\"cli.option.help\"))\n .create('h'));\n\n return options;\n }\n\n /**\n * Returns the command-line usage.\n *\n * @return The command-line usage.\n */\n protected String getUsage() {\n return \"[options]\";\n }\n\n protected void displayHelp(final Options options) {\n MessageSource messages = getMessageSource();\n IO io = getIO();\n\n io.out.print(getName());\n io.out.print(\" -- \");\n io.out.println(messages.getMessage(\"cli.usage.description\"));\n io.out.println();\n\n HelpFormatter formatter = new HelpFormatter();\n formatter.printHelp(\n io.out,\n 80, // width (FIXME: Should pull from gshell.columns variable)\n getName() + \" \" + getUsage(),\n \"\",\n options,\n 4, // left pad\n 4, // desc pad\n \"\",\n false); // auto usage\n\n io.out.println();\n\n String footer = messages.getMessage(\"cli.usage.footer\");\n if (footer.trim().length() != 0) {\n io.out.println(footer);\n io.out.println();\n }\n }\n}",
"public class CommandException\n extends Exception\n{\n ///CLOVER:OFF\n \n public CommandException(String msg) {\n super(msg);\n }\n\n public CommandException(String msg, Throwable cause) {\n super(msg, cause);\n }\n\n public CommandException(Throwable cause) {\n super(cause);\n }\n\n public CommandException() {\n super();\n }\n}",
"public interface MessageSource\n{\n String getMessage(String code);\n\n String getMessage(String code, Object... args);\n}",
"public interface Command\n{\n /** Standard command success status code. */\n int SUCCESS = 0;\n\n /** Standard command failure status code. */\n int FAILURE = -1;\n\n String getName();\n\n void init(CommandContext context); // throws Exception ?\n\n Object execute(Object... args) throws Exception;\n \n void abort(); // throws Exception ?\n \n void destroy(); // throws Exception ?\n\n //\n // 'help' command helpers to allow external inspection of command help\n //\n\n // String usage() // single line used to render help page\n\n // String about() // single line to describe the command\n\n // String help() // full help page (includes usage + about + command line options)\n}",
"public class IO\n{\n /**\n * Raw input stream.\n *\n * @see #in\n */\n public final InputStream inputStream;\n\n /**\n * Raw output stream.\n *\n * @see #out\n */\n public final OutputStream outputStream;\n\n /**\n * Raw error output stream.\n *\n * @see #err\n */\n public final OutputStream errorStream;\n\n /**\n * Prefered input reader.\n */\n public final Reader in;\n\n /**\n * Prefered output writer.\n */\n public final PrintWriter out;\n\n /**\n * Prefered error output writer.\n */\n public final PrintWriter err;\n\n /**\n * Construct a new IO container.\n *\n * @param in The input steam; must not be null\n * @param out The output stream; must not be null\n * @param err The error output stream; must not be null\n */\n public IO(final InputStream in, final OutputStream out, final OutputStream err) {\n if (in == null) {\n throw new NullArgumentException(\"in\");\n }\n if (out == null) {\n throw new NullArgumentException(\"out\");\n }\n if (err == null) {\n throw new NullArgumentException(\"err\");\n }\n\n this.inputStream = in;\n this.outputStream = out;\n this.errorStream = err;\n\n this.in = new InputStreamReader(in);\n this.out = new PrintWriter(out, true);\n this.err = new PrintWriter(err, true);\n }\n\n /**\n * Construct a new IO container.\n *\n * @param in The input steam; must not be null\n * @param out The output stream and error stream; must not be null\n */\n public IO(final InputStream in, final OutputStream out) {\n this(in, out, out);\n }\n\n /**\n * Helper which uses current values from {@link System}.\n */\n public IO() {\n this(System.in, System.out, System.err);\n }\n\n /**\n * Flush both output streams.\n */\n public void flush() {\n out.flush();\n err.flush();\n }\n\n public void close() throws IOException {\n in.close();\n out.close();\n err.close();\n }\n}",
"public class Shell\n{\n //\n // TODO: Introduce Shell interface?\n //\n\n private static final Log log = LogFactory.getLog(Shell.class);\n\n private final IO io;\n\n private final ShellContainer shellContainer = new ShellContainer();\n\n private final CommandManager commandManager;\n\n private final CommandLineBuilder commandLineBuilder;\n\n private final Variables variables = new VariablesImpl();\n\n public Shell(final IO io) throws CommandException {\n if (io == null) {\n throw new NullArgumentException(\"io\");\n }\n\n this.io = io;\n\n shellContainer.registerComponentInstance(this);\n shellContainer.registerComponentImplementation(CommandManagerImpl.class);\n shellContainer.registerComponentImplementation(CommandLineBuilder.class);\n\n //\n // TODO: Refactor to use the container, now that we have one\n //\n\n this.commandManager = (CommandManager) shellContainer.getComponentInstanceOfType(CommandManager.class);\n this.commandLineBuilder = (CommandLineBuilder) shellContainer.getComponentInstanceOfType(CommandLineBuilder.class);\n\n //\n // HACK: Set some default variables\n //\n\n variables.set(StandardVariables.PROMPT, \"> \");\n }\n\n public Shell() throws CommandException {\n this(new IO());\n }\n\n public Variables getVariables() {\n return variables;\n }\n\n public IO getIO() {\n return io;\n }\n\n public CommandManager getCommandManager() {\n return commandManager;\n }\n\n public Object execute(final String commandLine) throws Exception {\n assert commandLine != null;\n\n if (log.isInfoEnabled()) {\n log.info(\"Executing (String): \" + commandLine);\n }\n\n CommandLine cl = commandLineBuilder.create(commandLine);\n return cl.execute();\n }\n\n //\n // CommandExecutor\n //\n\n private void dump(final Variables vars) {\n Iterator<String> iter = vars.names();\n\n if (iter.hasNext()) {\n log.debug(\"Variables:\");\n }\n\n while (iter.hasNext()) {\n String name = iter.next();\n\n log.debug(\" \" + name + \"=\" + vars.get(name));\n }\n }\n\n public Object execute(final String commandName, final Object[] args) throws Exception {\n assert commandName != null;\n assert args != null;\n\n boolean debug = log.isDebugEnabled();\n\n if (log.isInfoEnabled()) {\n log.info(\"Executing (\" + commandName + \"): \" + Arguments.asString(args));\n }\n\n // Setup the command container\n ShellContainer container = new ShellContainer(shellContainer);\n\n final CommandDefinition def = commandManager.getCommandDefinition(commandName);\n final Class type = def.loadClass();\n\n //\n // TODO: Pass the command instance the name it was registered with?, could be an alias\n //\n\n container.registerComponentInstance(def);\n container.registerComponentImplementation(type);\n\n // container.start() ?\n\n Command cmd = (Command) container.getComponentInstanceOfType(Command.class);\n\n //\n // TODO: DI all bits if we can, then free up \"context\" to replace \"category\" as a term\n //\n\n final Variables vars = new VariablesImpl(getVariables());\n\n cmd.init(new CommandContext() {\n public IO getIO() {\n return io;\n }\n\n public Variables getVariables() {\n return vars;\n }\n\n MessageSource messageSource;\n\n public MessageSource getMessageSource() {\n // Lazy init the messages, commands many not need them\n if (messageSource == null) {\n messageSource = new MessageSourceImpl(type.getName() + \"Messages\");\n }\n\n return messageSource;\n }\n });\n\n // Setup command timings\n StopWatch watch = null;\n if (debug) {\n watch = new StopWatch();\n watch.start();\n }\n\n Object result;\n try {\n result = cmd.execute(args);\n\n if (debug) {\n log.debug(\"Command completed in \" + watch);\n }\n }\n finally {\n cmd.destroy();\n\n shellContainer.removeChildContainer(container);\n // container.stop() container.dispose() ?\n }\n\n return result;\n }\n\n public Object execute(final Object... args) throws Exception {\n assert args != null;\n assert args.length > 1;\n\n if (log.isInfoEnabled()) {\n log.info(\"Executing (Object...): \" + Arguments.asString(args));\n }\n\n return execute(String.valueOf(args[0]), Arguments.shift(args));\n }\n}"
] | import org.apache.geronimo.gshell.command.CommandException;
import org.apache.geronimo.gshell.command.MessageSource;
import org.apache.geronimo.gshell.command.Command;
import org.apache.geronimo.gshell.console.IO;
import org.apache.geronimo.gshell.Shell;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import org.apache.commons.cli.CommandLine;
import org.apache.geronimo.gshell.command.CommandSupport; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.gshell.builtins;
/**
* Read and execute commands from a file/url in the current shell environment.
*
* @version $Rev$ $Date$
*/
public class SourceCommand
extends CommandSupport
{
private Shell shell;
public SourceCommand(final Shell shell) {
super("source");
this.shell = shell;
}
protected String getUsage() {
return super.getUsage() + " <file|url>";
}
protected boolean processCommandLine(final CommandLine line) throws CommandException {
assert line != null;
String[] args = line.getArgs();
| IO io = getIO(); | 4 |
searchisko/elasticsearch-river-sysinfo | src/main/java/org/jboss/elasticsearch/river/sysinfo/SysinfoRiverPlugin.java | [
"public class JRLifecycleAction extends\n\t\tClusterAction<JRLifecycleRequest, JRLifecycleResponse, JRLifecycleRequestBuilder> {\n\n\tpublic static final JRLifecycleAction INSTANCE = new JRLifecycleAction();\n\tpublic static final String NAME = \"sysinfo_river/lifecycle\";\n\n\tprotected JRLifecycleAction() {\n\t\tsuper(NAME);\n\t}\n\n\t@Override\n\tpublic JRLifecycleRequestBuilder newRequestBuilder(ClusterAdminClient client) {\n\t\treturn new JRLifecycleRequestBuilder(client);\n\t}\n\n\t@Override\n\tpublic JRLifecycleResponse newResponse() {\n\t\treturn new JRLifecycleResponse();\n\t}\n\n}",
"public class RestJRLifecycleAction extends RestJRMgmBaseAction {\n\n\t@Inject\n\tprotected RestJRLifecycleAction(Settings settings, Client client, RestController controller) {\n\t\tsuper(settings, client, controller);\n\t\tString baseUrl = baseRestMgmUrl();\n\t\tcontroller.registerHandler(org.elasticsearch.rest.RestRequest.Method.POST, baseUrl + \"stop\", this);\n\t\tcontroller.registerHandler(org.elasticsearch.rest.RestRequest.Method.POST, baseUrl + \"restart\", this);\n\t}\n\n\t@Override\n\tpublic void handleRequest(final RestRequest restRequest, final RestChannel restChannel, Client client) {\n\n\t\tJRLifecycleCommand command = JRLifecycleCommand.RESTART;\n\t\tif (restRequest.path().endsWith(\"stop\"))\n\t\t\tcommand = JRLifecycleCommand.STOP;\n\n\t\tJRLifecycleRequest actionRequest = new JRLifecycleRequest(restRequest.param(\"riverName\"), command);\n\n\t\tclient\n\t\t\t\t.admin()\n\t\t\t\t.cluster()\n\t\t\t\t.execute(\n\t\t\t\t\t\tJRLifecycleAction.INSTANCE,\n\t\t\t\t\t\tactionRequest,\n\t\t\t\t\t\tnew JRMgmBaseActionListener<JRLifecycleRequest, JRLifecycleResponse, NodeJRLifecycleResponse>(\n\t\t\t\t\t\t\t\tactionRequest, restRequest, restChannel) {\n\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tprotected void handleRiverResponse(NodeJRLifecycleResponse nodeInfo) throws Exception {\n\t\t\t\t\t\t\t\trestChannel.sendResponse(new BytesRestResponse(OK, buildMessageDocument(restRequest,\n\t\t\t\t\t\t\t\t\t\t\"Command successful\")));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t});\n\t}\n}",
"public class TransportJRLifecycleAction extends\n\t\tTransportJRMgmBaseAction<JRLifecycleRequest, JRLifecycleResponse, NodeJRLifecycleRequest, NodeJRLifecycleResponse> {\n\n\t@Inject\n\tpublic TransportJRLifecycleAction(Settings settings, ClusterName clusterName, ThreadPool threadPool,\n\t\t\tClusterService clusterService, TransportService transportService, ActionFilters actionFilters) {\n\t\tsuper(settings, JRLifecycleAction.NAME, clusterName, threadPool, clusterService, transportService, actionFilters);\n\t}\n\n\t@Override\n\tprotected NodeJRLifecycleResponse performOperationOnRiver(IRiverMgm river, JRLifecycleRequest req, DiscoveryNode node)\n\t\t\tthrows Exception {\n\t\tJRLifecycleCommand command = req.getCommand();\n\t\tlogger.debug(\"Go to perform lifecycle command {} on river '{}'\", command, req.getRiverName());\n\t\tswitch (command) {\n\t\tcase STOP:\n\t\t\triver.stop();\n\t\t\tbreak;\n\t\tcase RESTART:\n\t\t\triver.restart();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new UnsupportedOperationException(\"Command \" + command + \" is not supported\");\n\t\t}\n\n\t\treturn new NodeJRLifecycleResponse(node, true);\n\t}\n\n\t@Override\n\tprotected JRLifecycleRequest newRequest() {\n\t\treturn new JRLifecycleRequest();\n\t}\n\n\t@Override\n\tprotected NodeJRLifecycleRequest newNodeRequest() {\n\t\treturn new NodeJRLifecycleRequest();\n\t}\n\n\t@Override\n\tprotected NodeJRLifecycleRequest newNodeRequest(String nodeId, JRLifecycleRequest request) {\n\t\treturn new NodeJRLifecycleRequest(nodeId, request);\n\t}\n\n\t@Override\n\tprotected NodeJRLifecycleResponse newNodeResponse() {\n\t\treturn new NodeJRLifecycleResponse(clusterService.localNode());\n\t}\n\n\t@Override\n\tprotected NodeJRLifecycleResponse[] newNodeResponseArray(int len) {\n\t\treturn new NodeJRLifecycleResponse[len];\n\t}\n\n\t@Override\n\tprotected JRLifecycleResponse newResponse(ClusterName clusterName, NodeJRLifecycleResponse[] array) {\n\t\treturn new JRLifecycleResponse(clusterName, array);\n\t}\n\n}",
"public class JRPeriodAction extends ClusterAction<JRPeriodRequest, JRPeriodResponse, JRPeriodRequestBuilder> {\n\n\tpublic static final JRPeriodAction INSTANCE = new JRPeriodAction();\n\tpublic static final String NAME = \"sysinfo_river/period\";\n\n\tprotected JRPeriodAction() {\n\t\tsuper(NAME);\n\t}\n\n\t@Override\n\tpublic JRPeriodRequestBuilder newRequestBuilder(ClusterAdminClient client) {\n\t\treturn new JRPeriodRequestBuilder(client);\n\t}\n\n\t@Override\n\tpublic JRPeriodResponse newResponse() {\n\t\treturn new JRPeriodResponse();\n\t}\n\n}",
"public class RestJRPeriodAction extends RestJRMgmBaseAction {\n\n\t@Inject\n\tprotected RestJRPeriodAction(Settings settings, Client client, RestController controller) {\n\t\tsuper(settings, client, controller);\n\t\tString baseUrl = baseRestMgmUrl();\n\t\tcontroller.registerHandler(org.elasticsearch.rest.RestRequest.Method.POST, baseUrl\n\t\t\t\t+ \"{indexerName}/period/{period}\", this);\n\t}\n\n\t@Override\n\tpublic void handleRequest(final RestRequest restRequest, final RestChannel restChannel, Client client) {\n\n\t\tfinal String indexerNames = restRequest.param(\"indexerName\");\n\t\tfinal long period = Utils.parseTimeValue(restRequest.params(), \"period\", 1, TimeUnit.MINUTES);\n\t\tJRPeriodRequest actionRequest = new JRPeriodRequest(restRequest.param(\"riverName\"),\n\t\t\t\tsplitIndexerNames(indexerNames), period);\n\n\t\tclient\n\t\t\t\t.admin()\n\t\t\t\t.cluster()\n\t\t\t\t.execute(\n\t\t\t\t\t\tJRPeriodAction.INSTANCE,\n\t\t\t\t\t\tactionRequest,\n\t\t\t\t\t\tnew JRMgmBaseActionListener<JRPeriodRequest, JRPeriodResponse, NodeJRPeriodResponse>(actionRequest,\n\t\t\t\t\t\t\t\trestRequest, restChannel) {\n\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tprotected void handleRiverResponse(NodeJRPeriodResponse nodeInfo) throws Exception {\n\t\t\t\t\t\t\t\tif (nodeInfo.indexerFound) {\n\t\t\t\t\t\t\t\t\trestChannel.sendResponse(new BytesRestResponse(OK, buildMessageDocument(restRequest,\n\t\t\t\t\t\t\t\t\t\t\t\"Period changed to \" + period + \"[ms] for at least one of defined indexers\")));\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trestChannel.sendResponse(new BytesRestResponse(RestStatus.NOT_FOUND, buildMessageDocument(\n\t\t\t\t\t\t\t\t\t\t\trestRequest, \"No any of defined indexers '\" + indexerNames + \"' found\")));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t});\n\t}\n\n\tpublic static String[] splitIndexerNames(String namesParam) {\n\t\tif (Utils.isEmpty(namesParam)) {\n\t\t\treturn Strings.EMPTY_ARRAY;\n\t\t}\n\t\treturn Strings.splitStringByCommaToArray(namesParam);\n\t}\n}",
"public class TransportJRPeriodAction extends\n\t\tTransportJRMgmBaseAction<JRPeriodRequest, JRPeriodResponse, NodeJRPeriodRequest, NodeJRPeriodResponse> {\n\n\t@Inject\n\tpublic TransportJRPeriodAction(Settings settings, ClusterName clusterName, ThreadPool threadPool,\n\t\t\tClusterService clusterService, TransportService transportService, ActionFilters actionFilters) {\n\t\tsuper(settings, JRPeriodAction.NAME, clusterName, threadPool, clusterService, transportService, actionFilters);\n\t}\n\n\t@Override\n\tprotected NodeJRPeriodResponse performOperationOnRiver(IRiverMgm river, JRPeriodRequest req, DiscoveryNode node)\n\t\t\tthrows Exception {\n\t\tlogger.debug(\"Go to perform period change to {} for indexers {} on river '{}'\", req.period, req.indexerNames,\n\t\t\t\treq.getRiverName());\n\t\tboolean ret = river.changeIndexerPeriod(req.indexerNames, req.period);\n\t\treturn new NodeJRPeriodResponse(node, true, ret);\n\t}\n\n\t@Override\n\tprotected JRPeriodRequest newRequest() {\n\t\treturn new JRPeriodRequest();\n\t}\n\n\t@Override\n\tprotected NodeJRPeriodRequest newNodeRequest() {\n\t\treturn new NodeJRPeriodRequest();\n\t}\n\n\t@Override\n\tprotected NodeJRPeriodRequest newNodeRequest(String nodeId, JRPeriodRequest request) {\n\t\treturn new NodeJRPeriodRequest(nodeId, request);\n\t}\n\n\t@Override\n\tprotected NodeJRPeriodResponse newNodeResponse() {\n\t\treturn new NodeJRPeriodResponse(clusterService.localNode());\n\t}\n\n\t@Override\n\tprotected NodeJRPeriodResponse[] newNodeResponseArray(int len) {\n\t\treturn new NodeJRPeriodResponse[len];\n\t}\n\n\t@Override\n\tprotected JRPeriodResponse newResponse(ClusterName clusterName, NodeJRPeriodResponse[] array) {\n\t\treturn new JRPeriodResponse(clusterName, array);\n\t}\n\n}",
"public class ListRiversAction extends ClusterAction<ListRiversRequest, ListRiversResponse, ListRiversRequestBuilder> {\n\n\tpublic static final ListRiversAction INSTANCE = new ListRiversAction();\n\tpublic static final String NAME = \"sysinfo_river/list_river_names\";\n\n\tprotected ListRiversAction() {\n\t\tsuper(NAME);\n\t}\n\n\t@Override\n\tpublic ListRiversRequestBuilder newRequestBuilder(ClusterAdminClient client) {\n\t\treturn new ListRiversRequestBuilder(client);\n\t}\n\n\t@Override\n\tpublic ListRiversResponse newResponse() {\n\t\treturn new ListRiversResponse();\n\t}\n\n}",
"public class RestListRiversAction extends RestJRMgmBaseAction {\n\n\t@Inject\n\tprotected RestListRiversAction(Settings settings, Client client, RestController controller) {\n\t\tsuper(settings, client, controller);\n\t\tcontroller.registerHandler(org.elasticsearch.rest.RestRequest.Method.GET, \"/_sysinfo_river/list\", this);\n\t}\n\n\t@Override\n\tpublic void handleRequest(final RestRequest restRequest, final RestChannel restChannel, Client client) {\n\n\t\tListRiversRequest actionRequest = new ListRiversRequest();\n\n\t\tlogger.debug(\"Go to look for Sysinfo rivers in cluster\");\n\t\tclient.admin().cluster()\n\t\t\t\t.execute(ListRiversAction.INSTANCE, actionRequest, new ActionListener<ListRiversResponse>() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onResponse(ListRiversResponse response) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tSet<String> allRivers = new HashSet<String>();\n\t\t\t\t\t\t\tfor (NodeListRiversResponse node : response.getNodes()) {\n\t\t\t\t\t\t\t\tif (node.riverNames != null) {\n\t\t\t\t\t\t\t\t\tallRivers.addAll(node.riverNames);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tXContentBuilder builder = RestXContentBuilder.restContentBuilder(restRequest);\n\t\t\t\t\t\t\tbuilder.startObject();\n\t\t\t\t\t\t\tbuilder.field(\"sysinfo_river_names\", allRivers);\n\t\t\t\t\t\t\tbuilder.endObject();\n\t\t\t\t\t\t\trestChannel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\tonFailure(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onFailure(Throwable e) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trestChannel.sendResponse(new BytesRestResponse(restChannel, e));\n\t\t\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\t\t\tlogger.error(\"Failed to send failure response\", e1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t});\n\t}\n}",
"@SuppressWarnings(\"rawtypes\")\npublic class TransportListRiversAction extends\n\t\tTransportNodesOperationAction<ListRiversRequest, ListRiversResponse, NodeListRiversRequest, NodeListRiversResponse> {\n\n\tprotected final static ESLogger logger = Loggers.getLogger(TransportListRiversAction.class);\n\n\t@Inject\n\tpublic TransportListRiversAction(Settings settings, ClusterName clusterName, ThreadPool threadPool,\n\t\t\tClusterService clusterService, TransportService transportService, ActionFilters actionFilters) {\n\t\tsuper(settings, ListRiversAction.NAME, clusterName, threadPool, clusterService, transportService, actionFilters);\n\t}\n\n\t@Override\n\tprotected String executor() {\n\t\treturn ThreadPool.Names.MANAGEMENT;\n\t}\n\n\t@Override\n\tprotected ListRiversResponse newResponse(ListRiversRequest request, AtomicReferenceArray responses) {\n\t\tfinal List<NodeListRiversResponse> nodesInfos = new ArrayList<NodeListRiversResponse>();\n\t\tfor (int i = 0; i < responses.length(); i++) {\n\t\t\tObject resp = responses.get(i);\n\t\t\tif (resp instanceof NodeListRiversResponse) {\n\t\t\t\tnodesInfos.add((NodeListRiversResponse) resp);\n\t\t\t}\n\t\t}\n\t\treturn new ListRiversResponse(clusterName, nodesInfos.toArray(new NodeListRiversResponse[nodesInfos.size()]));\n\t}\n\n\t@Override\n\tprotected boolean accumulateExceptions() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected NodeListRiversResponse nodeOperation(NodeListRiversRequest nodeRequest) throws ElasticsearchException {\n\t\tlogger.debug(\"Go to look for Sysinfo rivers on this node\");\n\t\treturn new NodeListRiversResponse(clusterService.localNode(), SysinfoRiver.getRunningInstances());\n\t}\n\n\t@Override\n\tprotected ListRiversRequest newRequest() {\n\t\treturn new ListRiversRequest();\n\t}\n\n\t@Override\n\tprotected NodeListRiversRequest newNodeRequest() {\n\t\treturn new NodeListRiversRequest();\n\t}\n\n\t@Override\n\tprotected NodeListRiversRequest newNodeRequest(String nodeId, ListRiversRequest request) {\n\t\treturn new NodeListRiversRequest(nodeId, request);\n\t}\n\n\t@Override\n\tprotected NodeListRiversResponse newNodeResponse() {\n\t\treturn new NodeListRiversResponse(clusterService.localNode());\n\t}\n\n}"
] | import org.elasticsearch.action.ActionModule;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.plugins.AbstractPlugin;
import org.elasticsearch.rest.RestModule;
import org.elasticsearch.river.RiversModule;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.JRLifecycleAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.RestJRLifecycleAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.TransportJRLifecycleAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.period.JRPeriodAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.period.RestJRPeriodAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.period.TransportJRPeriodAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.riverslist.ListRiversAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.riverslist.RestListRiversAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.riverslist.TransportListRiversAction; | /*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*/
package org.jboss.elasticsearch.river.sysinfo;
/**
* System Info River ElasticSearch Plugin class.
*
* @author Vlastimil Elias (velias at redhat dot com)
*/
public class SysinfoRiverPlugin extends AbstractPlugin {
@Inject
public SysinfoRiverPlugin() {
}
@Override
public String name() {
return "river-sysinfo";
}
@Override
public String description() {
return "River Sysinfo Plugin";
}
public void onModule(RiversModule module) {
module.registerRiver("sysinfo", SysinfoRiverModule.class);
}
public void onModule(RestModule module) {
module.addRestAction(RestListRiversAction.class);
module.addRestAction(RestJRLifecycleAction.class);
module.addRestAction(RestJRPeriodAction.class);
}
public void onModule(ActionModule module) {
module.registerAction(ListRiversAction.INSTANCE, TransportListRiversAction.class);
module.registerAction(JRLifecycleAction.INSTANCE, TransportJRLifecycleAction.class); | module.registerAction(JRPeriodAction.INSTANCE, TransportJRPeriodAction.class); | 5 |