hexsha
stringlengths
40
40
repo
stringlengths
4
114
path
stringlengths
6
369
license
sequence
language
stringclasses
1 value
identifier
stringlengths
1
123
original_docstring
stringlengths
8
49.2k
docstring
stringlengths
5
8.63k
docstring_tokens
sequence
code
stringlengths
25
988k
code_tokens
sequence
short_docstring
stringlengths
0
6.18k
short_docstring_tokens
sequence
comment
sequence
parameters
list
docstring_params
dict
334065db85bce5cdab84298717a3beb05cc98165
javagraphics/main
src/main/java/com/bric/io/location/LocationFactory.java
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
Java
LocationFactory
/** A factory for common <code>IOLocations</code>. */
A factory for common IOLocations.
[ "A", "factory", "for", "common", "IOLocations", "." ]
public class LocationFactory { private static LocationFactory factory = new LocationFactory(); public synchronized static LocationFactory get() { return factory; } public synchronized static void set(LocationFactory f) { if(f==null) throw new NullPointerException(); factory = f; } protected boolean zipNavigation = true; protected boolean tarNavigation = true; protected SuffixIOLocationFilter zipFilter = new SuffixIOLocationFilter(false, false, true, "jar", "zip"); protected SuffixIOLocationFilter tarFilter = new SuffixIOLocationFilter(false, false, true, "tar"); public boolean isZipArchiveNavigable() { return zipNavigation; } public boolean isTarArchiveNavigable() { return tarNavigation; } public void setTarArchiveNavigable(boolean b) { tarNavigation = b; } public void setZipArchiveNavigable(boolean b) { zipNavigation = b; } /** Create an <code>IOLocation</code> based on a <code>File</code>. * This factory may not return a <code>FileLocation</code>. (For * example: it might return a <code>ZipArchiveLocation</code>, or * a special subclass of <code>FileLocation</code>.) * @param file * @return a new IOLocation based on a File. */ public IOLocation create(File file) { if(file==null) throw new NullPointerException(); FileLocation fileLoc = createFileLocation(file); return filter(fileLoc); } /** Create a <code>FileLocation</code> based on a <code>File</code>. * This is not recommended unless you explicitly need * a <code>FileLocation</code>. * * @param file * @return a new FileLocation based on a File. * @see #create(File) */ public FileLocation createFileLocation(File file) { if(file==null) throw new NullPointerException(); return new FileLocation(file); } /** Create a <code>URLLocation</code> based on a <code>URL</code>. * This is not recommended unless you explicitly need * a <code>URLLocation</code>. * * @param url * @return a new URLLocation based on a URL * @see #create(URL) */ public URLLocation createURLLocation(URL url) { if(url==null) throw new NullPointerException(); return new URLLocation(url); } /** @return an <code>IOLocation</code> based on a <code>URL</code>. * This factory may not return a <code>URLLocation</code>. (For * example: it might return a <code>FileLocation</code>, a <code>ZipArchiveLocation</code>, or * a special subclass of <code>URLLocation</code>.) * @param url the url this is based on. */ public IOLocation create(URL url) { if(url==null) throw new NullPointerException(); URLLocation urlLoc = createURLLocation(url); return filter(urlLoc); } public IOLocation[] getRoots() { File[] files; if(JVM.isMac) { files = (new File("/Volumes/")).listFiles(); } else { files = File.listRoots(); } List<IOLocation> list = new ArrayList<IOLocation>(files.length); for(File f : files) { list.add( create(f) ); } return list.toArray(new IOLocation[list.size()]); } protected IOLocation filter(IOLocation loc) { if(loc==null) throw new NullPointerException(); if(loc instanceof URLLocation) { String url = loc.getURL().toString(); //TODO: look at queries/fragments/etc if(url.toLowerCase().startsWith("file:")) { String path = url.substring("file:".length()); path = path.replace("/", File.separator); //TODO: improve this path = path.replace("%20", " "); File file = new File(path); return create(file); } } /* TODO: consider making public, and let users navigate zips inside zips? * */ //TODO: test queries/fragments/etc if( zipFilter.filter(loc)!=null && (!(loc instanceof ZipArchiveLocation))) { return filter(new ZipArchiveLocation(loc)); } else if( tarFilter.filter(loc)!=null && (!(loc instanceof TarArchiveLocation))) { return filter(new TarArchiveLocation(loc)); } return loc; } }
[ "public", "class", "LocationFactory", "{", "private", "static", "LocationFactory", "factory", "=", "new", "LocationFactory", "(", ")", ";", "public", "synchronized", "static", "LocationFactory", "get", "(", ")", "{", "return", "factory", ";", "}", "public", "synchronized", "static", "void", "set", "(", "LocationFactory", "f", ")", "{", "if", "(", "f", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "factory", "=", "f", ";", "}", "protected", "boolean", "zipNavigation", "=", "true", ";", "protected", "boolean", "tarNavigation", "=", "true", ";", "protected", "SuffixIOLocationFilter", "zipFilter", "=", "new", "SuffixIOLocationFilter", "(", "false", ",", "false", ",", "true", ",", "\"", "jar", "\"", ",", "\"", "zip", "\"", ")", ";", "protected", "SuffixIOLocationFilter", "tarFilter", "=", "new", "SuffixIOLocationFilter", "(", "false", ",", "false", ",", "true", ",", "\"", "tar", "\"", ")", ";", "public", "boolean", "isZipArchiveNavigable", "(", ")", "{", "return", "zipNavigation", ";", "}", "public", "boolean", "isTarArchiveNavigable", "(", ")", "{", "return", "tarNavigation", ";", "}", "public", "void", "setTarArchiveNavigable", "(", "boolean", "b", ")", "{", "tarNavigation", "=", "b", ";", "}", "public", "void", "setZipArchiveNavigable", "(", "boolean", "b", ")", "{", "zipNavigation", "=", "b", ";", "}", "/** Create an <code>IOLocation</code> based on a <code>File</code>.\n\t * This factory may not return a <code>FileLocation</code>. (For\n\t * example: it might return a <code>ZipArchiveLocation</code>, or\n\t * a special subclass of <code>FileLocation</code>.)\n\t * @param file\n\t * @return a new IOLocation based on a File.\n\t */", "public", "IOLocation", "create", "(", "File", "file", ")", "{", "if", "(", "file", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "FileLocation", "fileLoc", "=", "createFileLocation", "(", "file", ")", ";", "return", "filter", "(", "fileLoc", ")", ";", "}", "/** Create a <code>FileLocation</code> based on a <code>File</code>. \n\t * This is not recommended unless you explicitly need\n\t * a <code>FileLocation</code>.\n\t * \n\t * @param file\n\t * @return a new FileLocation based on a File.\n\t * @see #create(File)\n\t */", "public", "FileLocation", "createFileLocation", "(", "File", "file", ")", "{", "if", "(", "file", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "return", "new", "FileLocation", "(", "file", ")", ";", "}", "/** Create a <code>URLLocation</code> based on a <code>URL</code>. \n\t * This is not recommended unless you explicitly need\n\t * a <code>URLLocation</code>.\n\t * \n\t * @param url\n\t * @return a new URLLocation based on a URL\n\t * @see #create(URL)\n\t */", "public", "URLLocation", "createURLLocation", "(", "URL", "url", ")", "{", "if", "(", "url", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "return", "new", "URLLocation", "(", "url", ")", ";", "}", "/** @return an <code>IOLocation</code> based on a <code>URL</code>.\n\t * This factory may not return a <code>URLLocation</code>. (For\n\t * example: it might return a <code>FileLocation</code>, a <code>ZipArchiveLocation</code>, or\n\t * a special subclass of <code>URLLocation</code>.)\n\t * @param url the url this is based on.\n\t */", "public", "IOLocation", "create", "(", "URL", "url", ")", "{", "if", "(", "url", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "URLLocation", "urlLoc", "=", "createURLLocation", "(", "url", ")", ";", "return", "filter", "(", "urlLoc", ")", ";", "}", "public", "IOLocation", "[", "]", "getRoots", "(", ")", "{", "File", "[", "]", "files", ";", "if", "(", "JVM", ".", "isMac", ")", "{", "files", "=", "(", "new", "File", "(", "\"", "/Volumes/", "\"", ")", ")", ".", "listFiles", "(", ")", ";", "}", "else", "{", "files", "=", "File", ".", "listRoots", "(", ")", ";", "}", "List", "<", "IOLocation", ">", "list", "=", "new", "ArrayList", "<", "IOLocation", ">", "(", "files", ".", "length", ")", ";", "for", "(", "File", "f", ":", "files", ")", "{", "list", ".", "add", "(", "create", "(", "f", ")", ")", ";", "}", "return", "list", ".", "toArray", "(", "new", "IOLocation", "[", "list", ".", "size", "(", ")", "]", ")", ";", "}", "protected", "IOLocation", "filter", "(", "IOLocation", "loc", ")", "{", "if", "(", "loc", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "if", "(", "loc", "instanceof", "URLLocation", ")", "{", "String", "url", "=", "loc", ".", "getURL", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "url", ".", "toLowerCase", "(", ")", ".", "startsWith", "(", "\"", "file:", "\"", ")", ")", "{", "String", "path", "=", "url", ".", "substring", "(", "\"", "file:", "\"", ".", "length", "(", ")", ")", ";", "path", "=", "path", ".", "replace", "(", "\"", "/", "\"", ",", "File", ".", "separator", ")", ";", "path", "=", "path", ".", "replace", "(", "\"", "%20", "\"", ",", "\"", " ", "\"", ")", ";", "File", "file", "=", "new", "File", "(", "path", ")", ";", "return", "create", "(", "file", ")", ";", "}", "}", "/* TODO: consider making public, and let users navigate zips inside zips?\n\t\t * \n\t\t */", "if", "(", "zipFilter", ".", "filter", "(", "loc", ")", "!=", "null", "&&", "(", "!", "(", "loc", "instanceof", "ZipArchiveLocation", ")", ")", ")", "{", "return", "filter", "(", "new", "ZipArchiveLocation", "(", "loc", ")", ")", ";", "}", "else", "if", "(", "tarFilter", ".", "filter", "(", "loc", ")", "!=", "null", "&&", "(", "!", "(", "loc", "instanceof", "TarArchiveLocation", ")", ")", ")", "{", "return", "filter", "(", "new", "TarArchiveLocation", "(", "loc", ")", ")", ";", "}", "return", "loc", ";", "}", "}" ]
A factory for common <code>IOLocations</code>.
[ "A", "factory", "for", "common", "<code", ">", "IOLocations<", "/", "code", ">", "." ]
[ "//TODO: look at queries/fragments/etc", "//TODO: improve this", "//TODO: test queries/fragments/etc" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
3341e33b46f37a75dceab51ed3766492d5b67c24
adambirse/innovation-funding-service
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/transactional/ApplicationInnovationAreaServiceImpl.java
[ "MIT" ]
Java
ApplicationInnovationAreaServiceImpl
/** * Transactional service implementation for linking an {@link Application} to an {@link InnovationArea}. */
Transactional service implementation for linking an Application to an InnovationArea.
[ "Transactional", "service", "implementation", "for", "linking", "an", "Application", "to", "an", "InnovationArea", "." ]
@Service public class ApplicationInnovationAreaServiceImpl extends BaseTransactionalService implements ApplicationInnovationAreaService { @Autowired private ApplicationMapper applicationMapper; @Autowired private InnovationAreaMapper innovationAreaMapper; @Override @Transactional public ServiceResult<ApplicationResource> setInnovationArea(Long applicationId, Long innovationAreaId) { return find(application(applicationId)) .andOnSuccess(application -> findInnovationAreaInAllowedList(application, innovationAreaId) .andOnSuccess(innovationArea -> saveApplicationWithInnovationArea(application, innovationArea))) .andOnSuccess(application -> serviceSuccess(applicationMapper.mapToResource(application))); } @Override @Transactional public ServiceResult<ApplicationResource> setNoInnovationAreaApplies(Long applicationId) { return find(application(applicationId)).andOnSuccess(this::saveWithNoInnovationAreaApplies) .andOnSuccess(application -> serviceSuccess(applicationMapper.mapToResource(application))); } @Override public ServiceResult<List<InnovationAreaResource>> getAvailableInnovationAreas(Long applicationId) { return find(application(applicationId)).andOnSuccess(this::getAllowedInnovationAreas) .andOnSuccess(areas -> serviceSuccess(innovationAreaMapper.mapToResource(areas))); } private ServiceResult<InnovationArea> findInnovationAreaInAllowedList(Application application, Long innovationAreaId) { return getAllowedInnovationAreas(application).andOnSuccess(areas -> findInnovationAreaInList(areas, innovationAreaId)); } private ServiceResult<List<InnovationArea>> getAllowedInnovationAreas(Application application) { if (application.getCompetition() !=null && application.getCompetition().getInnovationSector() !=null && application.getCompetition().getInnovationSector().getChildren() !=null) { return serviceSuccess(application.getCompetition().getInnovationAreas() .stream() .sorted(comparing(InnovationArea::getName)) .collect(toList())); } else { return serviceFailure(GENERAL_NOT_FOUND); } } private ServiceResult<InnovationArea> findInnovationAreaInList(List<InnovationArea> innovationAreasList, Long innovationAreaId) { Optional<InnovationArea> allowedInnovationArea = innovationAreasList .stream() .filter(area -> area .getId() .equals(innovationAreaId)) .findAny(); return allowedInnovationArea .map(ServiceResult::serviceSuccess) .orElseGet(() -> serviceFailure(GENERAL_FORBIDDEN)); } private ServiceResult<Application> saveWithNoInnovationAreaApplies(Application application) { application.setInnovationArea(null); application.setNoInnovationAreaApplicable(true); return serviceSuccess(applicationRepository.save(application)); } private ServiceResult<Application> saveApplicationWithInnovationArea(Application application, InnovationArea innovationArea) { application.setNoInnovationAreaApplicable(false); application.setInnovationArea(innovationArea); return serviceSuccess(applicationRepository.save(application)); } }
[ "@", "Service", "public", "class", "ApplicationInnovationAreaServiceImpl", "extends", "BaseTransactionalService", "implements", "ApplicationInnovationAreaService", "{", "@", "Autowired", "private", "ApplicationMapper", "applicationMapper", ";", "@", "Autowired", "private", "InnovationAreaMapper", "innovationAreaMapper", ";", "@", "Override", "@", "Transactional", "public", "ServiceResult", "<", "ApplicationResource", ">", "setInnovationArea", "(", "Long", "applicationId", ",", "Long", "innovationAreaId", ")", "{", "return", "find", "(", "application", "(", "applicationId", ")", ")", ".", "andOnSuccess", "(", "application", "->", "findInnovationAreaInAllowedList", "(", "application", ",", "innovationAreaId", ")", ".", "andOnSuccess", "(", "innovationArea", "->", "saveApplicationWithInnovationArea", "(", "application", ",", "innovationArea", ")", ")", ")", ".", "andOnSuccess", "(", "application", "->", "serviceSuccess", "(", "applicationMapper", ".", "mapToResource", "(", "application", ")", ")", ")", ";", "}", "@", "Override", "@", "Transactional", "public", "ServiceResult", "<", "ApplicationResource", ">", "setNoInnovationAreaApplies", "(", "Long", "applicationId", ")", "{", "return", "find", "(", "application", "(", "applicationId", ")", ")", ".", "andOnSuccess", "(", "this", "::", "saveWithNoInnovationAreaApplies", ")", ".", "andOnSuccess", "(", "application", "->", "serviceSuccess", "(", "applicationMapper", ".", "mapToResource", "(", "application", ")", ")", ")", ";", "}", "@", "Override", "public", "ServiceResult", "<", "List", "<", "InnovationAreaResource", ">", ">", "getAvailableInnovationAreas", "(", "Long", "applicationId", ")", "{", "return", "find", "(", "application", "(", "applicationId", ")", ")", ".", "andOnSuccess", "(", "this", "::", "getAllowedInnovationAreas", ")", ".", "andOnSuccess", "(", "areas", "->", "serviceSuccess", "(", "innovationAreaMapper", ".", "mapToResource", "(", "areas", ")", ")", ")", ";", "}", "private", "ServiceResult", "<", "InnovationArea", ">", "findInnovationAreaInAllowedList", "(", "Application", "application", ",", "Long", "innovationAreaId", ")", "{", "return", "getAllowedInnovationAreas", "(", "application", ")", ".", "andOnSuccess", "(", "areas", "->", "findInnovationAreaInList", "(", "areas", ",", "innovationAreaId", ")", ")", ";", "}", "private", "ServiceResult", "<", "List", "<", "InnovationArea", ">", ">", "getAllowedInnovationAreas", "(", "Application", "application", ")", "{", "if", "(", "application", ".", "getCompetition", "(", ")", "!=", "null", "&&", "application", ".", "getCompetition", "(", ")", ".", "getInnovationSector", "(", ")", "!=", "null", "&&", "application", ".", "getCompetition", "(", ")", ".", "getInnovationSector", "(", ")", ".", "getChildren", "(", ")", "!=", "null", ")", "{", "return", "serviceSuccess", "(", "application", ".", "getCompetition", "(", ")", ".", "getInnovationAreas", "(", ")", ".", "stream", "(", ")", ".", "sorted", "(", "comparing", "(", "InnovationArea", "::", "getName", ")", ")", ".", "collect", "(", "toList", "(", ")", ")", ")", ";", "}", "else", "{", "return", "serviceFailure", "(", "GENERAL_NOT_FOUND", ")", ";", "}", "}", "private", "ServiceResult", "<", "InnovationArea", ">", "findInnovationAreaInList", "(", "List", "<", "InnovationArea", ">", "innovationAreasList", ",", "Long", "innovationAreaId", ")", "{", "Optional", "<", "InnovationArea", ">", "allowedInnovationArea", "=", "innovationAreasList", ".", "stream", "(", ")", ".", "filter", "(", "area", "->", "area", ".", "getId", "(", ")", ".", "equals", "(", "innovationAreaId", ")", ")", ".", "findAny", "(", ")", ";", "return", "allowedInnovationArea", ".", "map", "(", "ServiceResult", "::", "serviceSuccess", ")", ".", "orElseGet", "(", "(", ")", "->", "serviceFailure", "(", "GENERAL_FORBIDDEN", ")", ")", ";", "}", "private", "ServiceResult", "<", "Application", ">", "saveWithNoInnovationAreaApplies", "(", "Application", "application", ")", "{", "application", ".", "setInnovationArea", "(", "null", ")", ";", "application", ".", "setNoInnovationAreaApplicable", "(", "true", ")", ";", "return", "serviceSuccess", "(", "applicationRepository", ".", "save", "(", "application", ")", ")", ";", "}", "private", "ServiceResult", "<", "Application", ">", "saveApplicationWithInnovationArea", "(", "Application", "application", ",", "InnovationArea", "innovationArea", ")", "{", "application", ".", "setNoInnovationAreaApplicable", "(", "false", ")", ";", "application", ".", "setInnovationArea", "(", "innovationArea", ")", ";", "return", "serviceSuccess", "(", "applicationRepository", ".", "save", "(", "application", ")", ")", ";", "}", "}" ]
Transactional service implementation for linking an {@link Application} to an {@link InnovationArea}.
[ "Transactional", "service", "implementation", "for", "linking", "an", "{", "@link", "Application", "}", "to", "an", "{", "@link", "InnovationArea", "}", "." ]
[]
[ { "param": "BaseTransactionalService", "type": null }, { "param": "ApplicationInnovationAreaService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseTransactionalService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ApplicationInnovationAreaService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33433876f15b841574446018e7ff44e7cf08b717
randallk/rocksplicator
cluster_management/src/main/java/com/pinterest/rocksplicator/ClientShardMapAgent.java
[ "Apache-2.0" ]
Java
ClientShardMapAgent
/** * A Java agent deployed as side-car along with the clients or application that needs routing * data downloaded from the zk, as published by the zk based publisher. * * It can watch multiple cluster's shard_map data. The clusters can be either provided as a static * comman separated list or as JSON_ARRAY formatted file. If the names of clusters to fetch * shard_map data for is provided through file, the agent will watch for any changes in file * and corresponding to that it will either starting watching any new clusters added or stop * watching any clusters that are removed from the file. * * This can also be used as a tool to manually download a cluster's latest shard_map and dump it * to the specified directory. by running command as * * java -cp cluster_management/target/cluster_management-0.0.1-SNAPSHOT-jar-with-dependencies.jar \\ * com.pinterest.rocksplicator.ShardMapAgent \\ * --shardMapZkSvr zookeeper-server:2181 \\ * --clusters=rocksplicator-cluster-name \\ * --shardMapDownloadDir=directory_where_shard_maps_are_downloaded */
A Java agent deployed as side-car along with the clients or application that needs routing data downloaded from the zk, as published by the zk based publisher. It can watch multiple cluster's shard_map data. The clusters can be either provided as a static comman separated list or as JSON_ARRAY formatted file. If the names of clusters to fetch shard_map data for is provided through file, the agent will watch for any changes in file and corresponding to that it will either starting watching any new clusters added or stop watching any clusters that are removed from the file. This can also be used as a tool to manually download a cluster's latest shard_map and dump it to the specified directory. by running command as
[ "A", "Java", "agent", "deployed", "as", "side", "-", "car", "along", "with", "the", "clients", "or", "application", "that", "needs", "routing", "data", "downloaded", "from", "the", "zk", "as", "published", "by", "the", "zk", "based", "publisher", ".", "It", "can", "watch", "multiple", "cluster", "'", "s", "shard_map", "data", ".", "The", "clusters", "can", "be", "either", "provided", "as", "a", "static", "comman", "separated", "list", "or", "as", "JSON_ARRAY", "formatted", "file", ".", "If", "the", "names", "of", "clusters", "to", "fetch", "shard_map", "data", "for", "is", "provided", "through", "file", "the", "agent", "will", "watch", "for", "any", "changes", "in", "file", "and", "corresponding", "to", "that", "it", "will", "either", "starting", "watching", "any", "new", "clusters", "added", "or", "stop", "watching", "any", "clusters", "that", "are", "removed", "from", "the", "file", ".", "This", "can", "also", "be", "used", "as", "a", "tool", "to", "manually", "download", "a", "cluster", "'", "s", "latest", "shard_map", "and", "dump", "it", "to", "the", "specified", "directory", ".", "by", "running", "command", "as" ]
public class ClientShardMapAgent { private static final Logger LOG = LoggerFactory.getLogger(ClientShardMapAgent.class); private static final String shardMapZkSvrArg = "shardMapZkSvr"; private static final String clustersArg = "clusters"; private static final String clustersFileArg = "clustersFile"; private static final String shardMapDownloadDirArg = "shardMapDownloadDir"; private static final String disableSharingZkClientArg = "disableSharingZkClient"; private static Options constructCommandLineOptions() { Option shardMapZkSvrOption = OptionBuilder.withLongOpt(shardMapZkSvrArg) .withDescription("Provide zk server connect string hosting the shard_maps [Required]") .create(); shardMapZkSvrOption.setArgs(1); shardMapZkSvrOption.setRequired(true); shardMapZkSvrOption.setArgName(shardMapZkSvrArg); Option clustersOption = OptionBuilder .withLongOpt(clustersArg) .withDescription("Provide comma separated clusters to download shard_map for [Optional]") .create(); clustersOption.setArgs(1); clustersOption.setRequired(false); clustersOption.setArgName(clustersArg); Option clustersFileOption = OptionBuilder .withLongOpt(clustersFileArg) .withDescription("Provide file path containing clusters to download shard_maps [Optional," + " at least one of clusters or clustersFile argument must be provided ]").create(); clustersFileOption.setArgs(1); clustersFileOption.setRequired(false); clustersFileOption.setArgName(clustersFileArg); Option shardMapDownloadDirOption = OptionBuilder .withLongOpt(shardMapDownloadDirArg) .withDescription("Provide directory to download shardMap for each cluster").create(); shardMapDownloadDirOption.setArgs(1); shardMapDownloadDirOption.setRequired(true); shardMapDownloadDirOption.setArgName(shardMapDownloadDirArg); Option disableSharingZkClientOption = OptionBuilder .withLongOpt(disableSharingZkClientArg) .withDescription("Explicitly disable sharing zk connection for watching multiple clusters") .create(); disableSharingZkClientOption.setArgs(0); disableSharingZkClientOption.setRequired(false); disableSharingZkClientOption.setArgName(disableSharingZkClientArg); Options options = new Options(); options.addOption(shardMapZkSvrOption) .addOption(clustersOption) .addOption(clustersFileOption) .addOption(shardMapDownloadDirOption) .addOption(disableSharingZkClientOption); return options; } private static CommandLine processCommandLineArgs(String[] cliArgs) throws ParseException { CommandLineParser cliParser = new GnuParser(); Options cliOptions = constructCommandLineOptions(); return cliParser.parse(cliOptions, cliArgs); } public static void main(String[] args) throws Exception { org.apache.log4j.Logger.getRootLogger().setLevel(Level.INFO); BasicConfigurator.configure(new ConsoleAppender( new PatternLayout("%d{HH:mm:ss.SSS} [%t] %-5p %30.30c - %m%n") )); CommandLine cmd = processCommandLineArgs(args); final String zkConnectString = cmd.getOptionValue(shardMapZkSvrArg); final String shardMapDownloadDir = cmd.getOptionValue(shardMapDownloadDirArg); final String csClusters = cmd.getOptionValue(clustersArg, ""); final String clustersFile = cmd.getOptionValue(clustersFileArg, ""); final boolean disableSharingZkClient = cmd.hasOption(disableSharingZkClientArg); Preconditions.checkArgument(!(csClusters.isEmpty() && clustersFile.isEmpty())); Supplier<Set<String>> clustersSupplier = null; if (!csClusters.isEmpty()) { final Set<String> clusters = new HashSet<>(); String[] clustersArray = csClusters.split(","); Preconditions.checkNotNull(clustersArray); Preconditions.checkArgument(clustersArray.length > 0); for (String cluster : clustersArray) { Preconditions.checkNotNull(cluster); Preconditions.checkArgument(!cluster.isEmpty()); clusters.add(cluster); } Preconditions.checkArgument(!clusters.isEmpty()); final ImmutableSet<String> immutableClusters = ImmutableSet.copyOf(clusters); clustersSupplier = new Supplier<Set<String>>() { @Override public Set<String> get() { return immutableClusters; } }; } else { final ConfigStore<Set<String>> configStore = new ConfigStore<Set<String>>( ConfigCodecs.getDecoder( ConfigCodecEnum.JSON_ARRAY), clustersFile); clustersSupplier = new Supplier<Set<String>>() { @Override public Set<String> get() { return configStore.get(); } }; } CuratorFramework localZkShardMapClient = null; if (!disableSharingZkClient) { localZkShardMapClient = CuratorFrameworkFactory .newClient(zkConnectString, new BoundedExponentialBackoffRetry( 250, 10000, 60)); localZkShardMapClient.start(); try { localZkShardMapClient.blockUntilConnected(120, TimeUnit.SECONDS); } catch (InterruptedException e) { localZkShardMapClient.close(); throw new RuntimeException(); } } final CuratorFramework zkShardMapClient = localZkShardMapClient; ClusterShardMapAgentManager handler = new ClusterShardMapAgentManager(zkConnectString, zkShardMapClient, shardMapDownloadDir, clustersSupplier); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { handler.close(); } catch (IOException e) { e.printStackTrace(); } if (zkShardMapClient != null) { zkShardMapClient.close(); } } }); LOG.error("ShardMapAgent running"); Thread.currentThread().join(); } }
[ "public", "class", "ClientShardMapAgent", "{", "private", "static", "final", "Logger", "LOG", "=", "LoggerFactory", ".", "getLogger", "(", "ClientShardMapAgent", ".", "class", ")", ";", "private", "static", "final", "String", "shardMapZkSvrArg", "=", "\"", "shardMapZkSvr", "\"", ";", "private", "static", "final", "String", "clustersArg", "=", "\"", "clusters", "\"", ";", "private", "static", "final", "String", "clustersFileArg", "=", "\"", "clustersFile", "\"", ";", "private", "static", "final", "String", "shardMapDownloadDirArg", "=", "\"", "shardMapDownloadDir", "\"", ";", "private", "static", "final", "String", "disableSharingZkClientArg", "=", "\"", "disableSharingZkClient", "\"", ";", "private", "static", "Options", "constructCommandLineOptions", "(", ")", "{", "Option", "shardMapZkSvrOption", "=", "OptionBuilder", ".", "withLongOpt", "(", "shardMapZkSvrArg", ")", ".", "withDescription", "(", "\"", "Provide zk server connect string hosting the shard_maps [Required]", "\"", ")", ".", "create", "(", ")", ";", "shardMapZkSvrOption", ".", "setArgs", "(", "1", ")", ";", "shardMapZkSvrOption", ".", "setRequired", "(", "true", ")", ";", "shardMapZkSvrOption", ".", "setArgName", "(", "shardMapZkSvrArg", ")", ";", "Option", "clustersOption", "=", "OptionBuilder", ".", "withLongOpt", "(", "clustersArg", ")", ".", "withDescription", "(", "\"", "Provide comma separated clusters to download shard_map for [Optional]", "\"", ")", ".", "create", "(", ")", ";", "clustersOption", ".", "setArgs", "(", "1", ")", ";", "clustersOption", ".", "setRequired", "(", "false", ")", ";", "clustersOption", ".", "setArgName", "(", "clustersArg", ")", ";", "Option", "clustersFileOption", "=", "OptionBuilder", ".", "withLongOpt", "(", "clustersFileArg", ")", ".", "withDescription", "(", "\"", "Provide file path containing clusters to download shard_maps [Optional,", "\"", "+", "\"", " at least one of clusters or clustersFile argument must be provided ]", "\"", ")", ".", "create", "(", ")", ";", "clustersFileOption", ".", "setArgs", "(", "1", ")", ";", "clustersFileOption", ".", "setRequired", "(", "false", ")", ";", "clustersFileOption", ".", "setArgName", "(", "clustersFileArg", ")", ";", "Option", "shardMapDownloadDirOption", "=", "OptionBuilder", ".", "withLongOpt", "(", "shardMapDownloadDirArg", ")", ".", "withDescription", "(", "\"", "Provide directory to download shardMap for each cluster", "\"", ")", ".", "create", "(", ")", ";", "shardMapDownloadDirOption", ".", "setArgs", "(", "1", ")", ";", "shardMapDownloadDirOption", ".", "setRequired", "(", "true", ")", ";", "shardMapDownloadDirOption", ".", "setArgName", "(", "shardMapDownloadDirArg", ")", ";", "Option", "disableSharingZkClientOption", "=", "OptionBuilder", ".", "withLongOpt", "(", "disableSharingZkClientArg", ")", ".", "withDescription", "(", "\"", "Explicitly disable sharing zk connection for watching multiple clusters", "\"", ")", ".", "create", "(", ")", ";", "disableSharingZkClientOption", ".", "setArgs", "(", "0", ")", ";", "disableSharingZkClientOption", ".", "setRequired", "(", "false", ")", ";", "disableSharingZkClientOption", ".", "setArgName", "(", "disableSharingZkClientArg", ")", ";", "Options", "options", "=", "new", "Options", "(", ")", ";", "options", ".", "addOption", "(", "shardMapZkSvrOption", ")", ".", "addOption", "(", "clustersOption", ")", ".", "addOption", "(", "clustersFileOption", ")", ".", "addOption", "(", "shardMapDownloadDirOption", ")", ".", "addOption", "(", "disableSharingZkClientOption", ")", ";", "return", "options", ";", "}", "private", "static", "CommandLine", "processCommandLineArgs", "(", "String", "[", "]", "cliArgs", ")", "throws", "ParseException", "{", "CommandLineParser", "cliParser", "=", "new", "GnuParser", "(", ")", ";", "Options", "cliOptions", "=", "constructCommandLineOptions", "(", ")", ";", "return", "cliParser", ".", "parse", "(", "cliOptions", ",", "cliArgs", ")", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "org", ".", "apache", ".", "log4j", ".", "Logger", ".", "getRootLogger", "(", ")", ".", "setLevel", "(", "Level", ".", "INFO", ")", ";", "BasicConfigurator", ".", "configure", "(", "new", "ConsoleAppender", "(", "new", "PatternLayout", "(", "\"", "%d{HH:mm:ss.SSS} [%t] %-5p %30.30c - %m%n", "\"", ")", ")", ")", ";", "CommandLine", "cmd", "=", "processCommandLineArgs", "(", "args", ")", ";", "final", "String", "zkConnectString", "=", "cmd", ".", "getOptionValue", "(", "shardMapZkSvrArg", ")", ";", "final", "String", "shardMapDownloadDir", "=", "cmd", ".", "getOptionValue", "(", "shardMapDownloadDirArg", ")", ";", "final", "String", "csClusters", "=", "cmd", ".", "getOptionValue", "(", "clustersArg", ",", "\"", "\"", ")", ";", "final", "String", "clustersFile", "=", "cmd", ".", "getOptionValue", "(", "clustersFileArg", ",", "\"", "\"", ")", ";", "final", "boolean", "disableSharingZkClient", "=", "cmd", ".", "hasOption", "(", "disableSharingZkClientArg", ")", ";", "Preconditions", ".", "checkArgument", "(", "!", "(", "csClusters", ".", "isEmpty", "(", ")", "&&", "clustersFile", ".", "isEmpty", "(", ")", ")", ")", ";", "Supplier", "<", "Set", "<", "String", ">", ">", "clustersSupplier", "=", "null", ";", "if", "(", "!", "csClusters", ".", "isEmpty", "(", ")", ")", "{", "final", "Set", "<", "String", ">", "clusters", "=", "new", "HashSet", "<", ">", "(", ")", ";", "String", "[", "]", "clustersArray", "=", "csClusters", ".", "split", "(", "\"", ",", "\"", ")", ";", "Preconditions", ".", "checkNotNull", "(", "clustersArray", ")", ";", "Preconditions", ".", "checkArgument", "(", "clustersArray", ".", "length", ">", "0", ")", ";", "for", "(", "String", "cluster", ":", "clustersArray", ")", "{", "Preconditions", ".", "checkNotNull", "(", "cluster", ")", ";", "Preconditions", ".", "checkArgument", "(", "!", "cluster", ".", "isEmpty", "(", ")", ")", ";", "clusters", ".", "add", "(", "cluster", ")", ";", "}", "Preconditions", ".", "checkArgument", "(", "!", "clusters", ".", "isEmpty", "(", ")", ")", ";", "final", "ImmutableSet", "<", "String", ">", "immutableClusters", "=", "ImmutableSet", ".", "copyOf", "(", "clusters", ")", ";", "clustersSupplier", "=", "new", "Supplier", "<", "Set", "<", "String", ">", ">", "(", ")", "{", "@", "Override", "public", "Set", "<", "String", ">", "get", "(", ")", "{", "return", "immutableClusters", ";", "}", "}", ";", "}", "else", "{", "final", "ConfigStore", "<", "Set", "<", "String", ">", ">", "configStore", "=", "new", "ConfigStore", "<", "Set", "<", "String", ">", ">", "(", "ConfigCodecs", ".", "getDecoder", "(", "ConfigCodecEnum", ".", "JSON_ARRAY", ")", ",", "clustersFile", ")", ";", "clustersSupplier", "=", "new", "Supplier", "<", "Set", "<", "String", ">", ">", "(", ")", "{", "@", "Override", "public", "Set", "<", "String", ">", "get", "(", ")", "{", "return", "configStore", ".", "get", "(", ")", ";", "}", "}", ";", "}", "CuratorFramework", "localZkShardMapClient", "=", "null", ";", "if", "(", "!", "disableSharingZkClient", ")", "{", "localZkShardMapClient", "=", "CuratorFrameworkFactory", ".", "newClient", "(", "zkConnectString", ",", "new", "BoundedExponentialBackoffRetry", "(", "250", ",", "10000", ",", "60", ")", ")", ";", "localZkShardMapClient", ".", "start", "(", ")", ";", "try", "{", "localZkShardMapClient", ".", "blockUntilConnected", "(", "120", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "localZkShardMapClient", ".", "close", "(", ")", ";", "throw", "new", "RuntimeException", "(", ")", ";", "}", "}", "final", "CuratorFramework", "zkShardMapClient", "=", "localZkShardMapClient", ";", "ClusterShardMapAgentManager", "handler", "=", "new", "ClusterShardMapAgentManager", "(", "zkConnectString", ",", "zkShardMapClient", ",", "shardMapDownloadDir", ",", "clustersSupplier", ")", ";", "Runtime", ".", "getRuntime", "(", ")", ".", "addShutdownHook", "(", "new", "Thread", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "handler", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "if", "(", "zkShardMapClient", "!=", "null", ")", "{", "zkShardMapClient", ".", "close", "(", ")", ";", "}", "}", "}", ")", ";", "LOG", ".", "error", "(", "\"", "ShardMapAgent running", "\"", ")", ";", "Thread", ".", "currentThread", "(", ")", ".", "join", "(", ")", ";", "}", "}" ]
A Java agent deployed as side-car along with the clients or application that needs routing data downloaded from the zk, as published by the zk based publisher.
[ "A", "Java", "agent", "deployed", "as", "side", "-", "car", "along", "with", "the", "clients", "or", "application", "that", "needs", "routing", "data", "downloaded", "from", "the", "zk", "as", "published", "by", "the", "zk", "based", "publisher", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
3344dc191eb5a22802aeeb937ada2610a2e06a12
muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices
JavaSimulator/lib/frodo2/src/frodo2/algorithms/AbstractDCOPsolver.java
[ "MIT" ]
Java
AbstractDCOPsolver
/** An abstract convenient class for solving DCOP instances * @author Thomas Leaute * @param <V> type used for variable values * @param <U> type used for utility values * @param <S> type used for the solution */
An abstract convenient class for solving DCOP instances @author Thomas Leaute @param type used for variable values @param type used for utility values @param type used for the solution
[ "An", "abstract", "convenient", "class", "for", "solving", "DCOP", "instances", "@author", "Thomas", "Leaute", "@param", "type", "used", "for", "variable", "values", "@param", "type", "used", "for", "utility", "values", "@param", "type", "used", "for", "the", "solution" ]
public abstract class AbstractDCOPsolver < V extends Addable<V>, U extends Addable<U>, S extends Solution<V, U> > extends AbstractSolver<DCOPProblemInterface<V, U>, V, U, S> { /** Solves a problem and writes statistics to a file * @param args [algoName, solverClassName, agentConfigFile, problemFile, timeout in seconds, outputFile] * @throws Exception if an error occurs */ public static void main (String[] args) throws Exception { // Parse the input arguments String algoName = args[0]; String solverClassName = args[1]; Document agentConfig = XCSPparser.parse(args[2], false); Document problemFile = XCSPparser.parse(args[3], false); Long timeout = 1000 * Long.parseLong(args[4]); // *1000 to get it in ms String outputFilePath = args[5]; // Instantiate the solver @SuppressWarnings("unchecked") Class<? extends AbstractDCOPsolver<?, ?, ?>> solverClass = (Class<? extends AbstractDCOPsolver<?, ?, ?>>) Class.forName(solverClassName); @SuppressWarnings("unchecked") AbstractDCOPsolver< ?, ?, Solution<?, ?> > solver = (AbstractDCOPsolver<?, ?, Solution<?, ?>>) solverClass.getConstructor(Document.class).newInstance(agentConfig); // Write a first "timeout" line to the output file that will be overwritten after the algorithm terminates (if it does) File outputFile = new File (outputFilePath); boolean newFile = ! outputFile.exists(); BufferedWriter writer = new BufferedWriter (new FileWriter (outputFile, true)); if (newFile) writer.append(solver.getFileHeader(problemFile)).append("\n"); writer.append(solver.getTimeoutLine(algoName, problemFile)).append("\n").flush(); // Solve and record the stats Solution<?, ?> sol = solver.solve(problemFile, false, timeout); if (sol != null) { writer.append(algoName); writer.append("\t0"); // 0 = no timeout; 1 = timeout // First write statistics about the problem instance writer.append(solver.getProbStats(problemFile)); // Write the statistics about the solution found writer.append(sol.toLineString()).append("\n"); } writer.close(); } /** Returns the header for the output CSV file * @param problemFile the problem file * @return the titles of the columns in the output CSV file */ protected String getFileHeader(Document problemFile) { StringBuffer buf = new StringBuffer ("algorithm"); buf.append("\ttimed out"); // 0 if the algorithm terminated, 1 if it timed out buf.append("\tproblem instance"); // the name of the problem instance, assumed unique // Write statistics about the problem instance, added by the problem generator to the XCSP file Element presElmt = problemFile.getRootElement().getChild("presentation"); TreeSet<String> stats = new TreeSet<String> (); for (Element child : presElmt.getChildren()) stats.add(child.getAttributeValue("name")); for (String name : stats) buf.append("\t").append(name); // Continue with the statistics about the solution buf.append("\tNCCCs"); buf.append("\tsimulated time (in ms)"); buf.append("\tnumber of messages"); buf.append("\ttotal message size (in bytes)"); buf.append("\tmaximum message size (in bytes)"); buf.append("\tinduced treewidth"); if (Boolean.parseBoolean(presElmt.getAttributeValue("maximize"))) buf.append("\treported utility").append("\ttrue utility"); else buf.append("\treported cost").append("\ttrue cost"); return buf.toString(); } /** Parses the statistics about the problem instance * @param problemFile the problem instance * @return the statistics */ protected String getProbStats (Document problemFile) { StringBuffer buf = new StringBuffer (); // Write the name of this problem instance (assuming it is unique) Element presElmt = problemFile.getRootElement().getChild("presentation"); buf.append("\t").append(presElmt.getAttributeValue("name")); // Write statistics about the problem instance TreeMap<String, String> stats = new TreeMap<String, String> (); for (Element child : presElmt.getChildren()) stats.put(child.getAttributeValue("name"), child.getText()); for (String value : stats.values()) buf.append("\t").append(value); return buf.toString(); } /** Returns a timeout line for the output CSV file * @param algoName the name of the algorithm * @param problemFile the problem instance * @return a line in the output CSV file that corresponds to a timeout */ protected String getTimeoutLine(String algoName, Document problemFile) { StringBuffer buf = new StringBuffer (algoName); buf.append("\t1"); // 0 = no timeout; 1 = timeout buf.append(this.getProbStats(problemFile)); // Continue with statistics about the solution buf.append("\t").append(Long.MAX_VALUE); // NCCCs buf.append("\t").append(Long.MAX_VALUE); // runtime buf.append("\t").append(Integer.MAX_VALUE); // nbrMessages buf.append("\t").append(Long.MAX_VALUE); // total msg size buf.append("\t").append(Long.MAX_VALUE); // max msg size buf.append("\t").append(Integer.MAX_VALUE); // treewidth buf.append("\tNaN"); // reported util buf.append("\tNaN"); // true util return buf.toString(); } /** * Dummy constructor */ protected AbstractDCOPsolver() { super(); this.overrideMsgTypes(); } /** Constructor from an agent configuration file * @param agentDescFile the agent configuration file */ protected AbstractDCOPsolver (String agentDescFile) { super (agentDescFile); this.overrideMsgTypes(); } /** Constructor from an agent configuration file * @param agentDescFile the agent configuration file * @param useTCP Whether to use TCP pipes or shared memory pipes * @warning Using TCP pipes automatically disables simulated time. */ protected AbstractDCOPsolver (String agentDescFile, boolean useTCP) { super (agentDescFile, useTCP); this.overrideMsgTypes(); } /** Constructor * @param agentDesc a JDOM Document for the agent description */ protected AbstractDCOPsolver (Document agentDesc) { super(agentDesc); this.overrideMsgTypes(); } /** Constructor * @param agentDesc a JDOM Document for the agent description * @param useTCP Whether to use TCP pipes or shared memory pipes * @warning Using TCP pipes automatically disables simulated time. */ protected AbstractDCOPsolver (Document agentDesc, boolean useTCP) { super (agentDesc, useTCP); this.overrideMsgTypes(); } /** Constructor * @param agentDesc The agent description * @param parserClass The class of the parser to be used */ protected AbstractDCOPsolver (Document agentDesc, Class< ? extends XCSPparser<V, U> > parserClass) { super(agentDesc, parserClass); this.overrideMsgTypes(); } /** Constructor * @param agentDesc The agent description * @param parserClass The class of the parser to be used * @param useTCP Whether to use TCP pipes or shared memory pipes * @warning Using TCP pipes automatically disables simulated time. */ protected AbstractDCOPsolver (Document agentDesc, Class< ? extends XCSPparser<V, U> > parserClass, boolean useTCP) { super(agentDesc, parserClass, useTCP); this.overrideMsgTypes(); } /** @see AbstractSolver#solve(org.jdom2.Document, int, boolean, java.lang.Long, boolean) */ @Override public S solve (Document problem, int nbrElectionRounds, boolean measureMsgs, Long timeout, boolean cleanAfterwards) { agentDesc.getRootElement().setAttribute("measureMsgs", Boolean.toString(measureMsgs)); this.setNbrElectionRounds(nbrElectionRounds); return this.solve(problem, cleanAfterwards, timeout); } /** @see AbstractSolver#solve(frodo2.solutionSpaces.ProblemInterface, int, boolean, java.lang.Long, boolean) */ @Override public S solve (DCOPProblemInterface<V, U> problem, int nbrElectionRounds, boolean measureMsgs, Long timeout, boolean cleanAfterwards) { agentDesc.getRootElement().setAttribute("measureMsgs", Boolean.toString(measureMsgs)); this.setNbrElectionRounds(nbrElectionRounds); return this.solve(problem, cleanAfterwards, timeout); } /** Sets the number of rounds of VariableElection * @param nbrElectionRounds the number of rounds of VariableElection (must be greater than the diameter of the constraint graph) */ protected void setNbrElectionRounds (int nbrElectionRounds) { for (Element module : (List<Element>) agentDesc.getRootElement().getChild("modules").getChildren()) if (module.getAttributeValue("className").equals(VariableElection.class.getName())) module.setAttribute("nbrSteps", Integer.toString(nbrElectionRounds)); } /** Overrides message types if necessary */ @SuppressWarnings("unchecked") private void overrideMsgTypes() { Element modsElmt = agentDesc.getRootElement().getChild("modules"); try { if (modsElmt != null) { for (Element moduleElmt : (List<Element>) modsElmt.getChildren()) { String className = moduleElmt.getAttributeValue("className"); Class< MessageListener<String> > moduleClass = (Class< MessageListener<String> >) Class.forName(className); Element allMsgsElmt = moduleElmt.getChild("messages"); if (allMsgsElmt != null) { for (Element msgElmt : (List<Element>) allMsgsElmt.getChildren()) { // Look up the new value for the message type String newType = msgElmt.getAttributeValue("value"); String ownerClassName = msgElmt.getAttributeValue("ownerClass"); if (ownerClassName != null) { // the attribute "value" actually refers to a field in a class Class<?> ownerClass = Class.forName(ownerClassName); try { Field field = ownerClass.getDeclaredField(newType); newType = (String) field.get(newType); } catch (NoSuchFieldException e) { System.err.println("Unable to read the value of the field " + ownerClass.getName() + "." + newType); e.printStackTrace(); } } // Set the message type to its new value try { SingleQueueAgent.setMsgType(moduleClass, msgElmt.getAttributeValue("name"), newType); } catch (NoSuchFieldException e) { System.err.println("Unable to find the field " + moduleClass.getName() + "." + msgElmt.getAttributeValue("name")); e.printStackTrace(); } } } } } } catch (Exception e) { e.printStackTrace(); } } }
[ "public", "abstract", "class", "AbstractDCOPsolver", "<", "V", "extends", "Addable", "<", "V", ">", ",", "U", "extends", "Addable", "<", "U", ">", ",", "S", "extends", "Solution", "<", "V", ",", "U", ">", ">", "extends", "AbstractSolver", "<", "DCOPProblemInterface", "<", "V", ",", "U", ">", ",", "V", ",", "U", ",", "S", ">", "{", "/** Solves a problem and writes statistics to a file\n\t * @param args \t[algoName, solverClassName, agentConfigFile, problemFile, timeout in seconds, outputFile]\n\t * @throws Exception if an error occurs\n\t */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "String", "algoName", "=", "args", "[", "0", "]", ";", "String", "solverClassName", "=", "args", "[", "1", "]", ";", "Document", "agentConfig", "=", "XCSPparser", ".", "parse", "(", "args", "[", "2", "]", ",", "false", ")", ";", "Document", "problemFile", "=", "XCSPparser", ".", "parse", "(", "args", "[", "3", "]", ",", "false", ")", ";", "Long", "timeout", "=", "1000", "*", "Long", ".", "parseLong", "(", "args", "[", "4", "]", ")", ";", "String", "outputFilePath", "=", "args", "[", "5", "]", ";", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "Class", "<", "?", "extends", "AbstractDCOPsolver", "<", "?", ",", "?", ",", "?", ">", ">", "solverClass", "=", "(", "Class", "<", "?", "extends", "AbstractDCOPsolver", "<", "?", ",", "?", ",", "?", ">", ">", ")", "Class", ".", "forName", "(", "solverClassName", ")", ";", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "AbstractDCOPsolver", "<", "?", ",", "?", ",", "Solution", "<", "?", ",", "?", ">", ">", "solver", "=", "(", "AbstractDCOPsolver", "<", "?", ",", "?", ",", "Solution", "<", "?", ",", "?", ">", ">", ")", "solverClass", ".", "getConstructor", "(", "Document", ".", "class", ")", ".", "newInstance", "(", "agentConfig", ")", ";", "File", "outputFile", "=", "new", "File", "(", "outputFilePath", ")", ";", "boolean", "newFile", "=", "!", "outputFile", ".", "exists", "(", ")", ";", "BufferedWriter", "writer", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "outputFile", ",", "true", ")", ")", ";", "if", "(", "newFile", ")", "writer", ".", "append", "(", "solver", ".", "getFileHeader", "(", "problemFile", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "writer", ".", "append", "(", "solver", ".", "getTimeoutLine", "(", "algoName", ",", "problemFile", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ".", "flush", "(", ")", ";", "Solution", "<", "?", ",", "?", ">", "sol", "=", "solver", ".", "solve", "(", "problemFile", ",", "false", ",", "timeout", ")", ";", "if", "(", "sol", "!=", "null", ")", "{", "writer", ".", "append", "(", "algoName", ")", ";", "writer", ".", "append", "(", "\"", "\\t", "0", "\"", ")", ";", "writer", ".", "append", "(", "solver", ".", "getProbStats", "(", "problemFile", ")", ")", ";", "writer", ".", "append", "(", "sol", ".", "toLineString", "(", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "}", "writer", ".", "close", "(", ")", ";", "}", "/** Returns the header for the output CSV file\n\t * @param problemFile \tthe problem file\n\t * @return the titles of the columns in the output CSV file \n\t */", "protected", "String", "getFileHeader", "(", "Document", "problemFile", ")", "{", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", "\"", "algorithm", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "timed out", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "problem instance", "\"", ")", ";", "Element", "presElmt", "=", "problemFile", ".", "getRootElement", "(", ")", ".", "getChild", "(", "\"", "presentation", "\"", ")", ";", "TreeSet", "<", "String", ">", "stats", "=", "new", "TreeSet", "<", "String", ">", "(", ")", ";", "for", "(", "Element", "child", ":", "presElmt", ".", "getChildren", "(", ")", ")", "stats", ".", "add", "(", "child", ".", "getAttributeValue", "(", "\"", "name", "\"", ")", ")", ";", "for", "(", "String", "name", ":", "stats", ")", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "name", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "NCCCs", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "simulated time (in ms)", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "number of messages", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "total message size (in bytes)", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "maximum message size (in bytes)", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "induced treewidth", "\"", ")", ";", "if", "(", "Boolean", ".", "parseBoolean", "(", "presElmt", ".", "getAttributeValue", "(", "\"", "maximize", "\"", ")", ")", ")", "buf", ".", "append", "(", "\"", "\\t", "reported utility", "\"", ")", ".", "append", "(", "\"", "\\t", "true utility", "\"", ")", ";", "else", "buf", ".", "append", "(", "\"", "\\t", "reported cost", "\"", ")", ".", "append", "(", "\"", "\\t", "true cost", "\"", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}", "/** Parses the statistics about the problem instance\n\t * @param problemFile \tthe problem instance\n\t * @return the statistics\n\t */", "protected", "String", "getProbStats", "(", "Document", "problemFile", ")", "{", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", ")", ";", "Element", "presElmt", "=", "problemFile", ".", "getRootElement", "(", ")", ".", "getChild", "(", "\"", "presentation", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "presElmt", ".", "getAttributeValue", "(", "\"", "name", "\"", ")", ")", ";", "TreeMap", "<", "String", ",", "String", ">", "stats", "=", "new", "TreeMap", "<", "String", ",", "String", ">", "(", ")", ";", "for", "(", "Element", "child", ":", "presElmt", ".", "getChildren", "(", ")", ")", "stats", ".", "put", "(", "child", ".", "getAttributeValue", "(", "\"", "name", "\"", ")", ",", "child", ".", "getText", "(", ")", ")", ";", "for", "(", "String", "value", ":", "stats", ".", "values", "(", ")", ")", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "value", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}", "/** Returns a timeout line for the output CSV file\n\t * @param algoName \t\tthe name of the algorithm\n\t * @param problemFile \tthe problem instance\n\t * @return a line in the output CSV file that corresponds to a timeout \n\t */", "protected", "String", "getTimeoutLine", "(", "String", "algoName", ",", "Document", "problemFile", ")", "{", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", "algoName", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "1", "\"", ")", ";", "buf", ".", "append", "(", "this", ".", "getProbStats", "(", "problemFile", ")", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "Long", ".", "MAX_VALUE", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "Long", ".", "MAX_VALUE", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "Integer", ".", "MAX_VALUE", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "Long", ".", "MAX_VALUE", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "Long", ".", "MAX_VALUE", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "Integer", ".", "MAX_VALUE", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "NaN", "\"", ")", ";", "buf", ".", "append", "(", "\"", "\\t", "NaN", "\"", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}", "/**\n\t * Dummy constructor\n\t */", "protected", "AbstractDCOPsolver", "(", ")", "{", "super", "(", ")", ";", "this", ".", "overrideMsgTypes", "(", ")", ";", "}", "/** Constructor from an agent configuration file\n\t * @param agentDescFile \tthe agent configuration file\n\t */", "protected", "AbstractDCOPsolver", "(", "String", "agentDescFile", ")", "{", "super", "(", "agentDescFile", ")", ";", "this", ".", "overrideMsgTypes", "(", ")", ";", "}", "/** Constructor from an agent configuration file\n\t * @param agentDescFile \tthe agent configuration file\n\t * @param useTCP \t\t\tWhether to use TCP pipes or shared memory pipes\n\t * @warning Using TCP pipes automatically disables simulated time. \n\t */", "protected", "AbstractDCOPsolver", "(", "String", "agentDescFile", ",", "boolean", "useTCP", ")", "{", "super", "(", "agentDescFile", ",", "useTCP", ")", ";", "this", ".", "overrideMsgTypes", "(", ")", ";", "}", "/** Constructor\n\t * @param agentDesc \ta JDOM Document for the agent description\n\t */", "protected", "AbstractDCOPsolver", "(", "Document", "agentDesc", ")", "{", "super", "(", "agentDesc", ")", ";", "this", ".", "overrideMsgTypes", "(", ")", ";", "}", "/** Constructor\n\t * @param agentDesc \ta JDOM Document for the agent description\n\t * @param useTCP \t\tWhether to use TCP pipes or shared memory pipes\n\t * @warning Using TCP pipes automatically disables simulated time. \n\t */", "protected", "AbstractDCOPsolver", "(", "Document", "agentDesc", ",", "boolean", "useTCP", ")", "{", "super", "(", "agentDesc", ",", "useTCP", ")", ";", "this", ".", "overrideMsgTypes", "(", ")", ";", "}", "/** Constructor\n\t * @param agentDesc \tThe agent description\n\t * @param parserClass \tThe class of the parser to be used\n\t */", "protected", "AbstractDCOPsolver", "(", "Document", "agentDesc", ",", "Class", "<", "?", "extends", "XCSPparser", "<", "V", ",", "U", ">", ">", "parserClass", ")", "{", "super", "(", "agentDesc", ",", "parserClass", ")", ";", "this", ".", "overrideMsgTypes", "(", ")", ";", "}", "/** Constructor\n\t * @param agentDesc \tThe agent description\n\t * @param parserClass \tThe class of the parser to be used\n\t * @param useTCP \t\tWhether to use TCP pipes or shared memory pipes\n\t * @warning Using TCP pipes automatically disables simulated time. \n\t */", "protected", "AbstractDCOPsolver", "(", "Document", "agentDesc", ",", "Class", "<", "?", "extends", "XCSPparser", "<", "V", ",", "U", ">", ">", "parserClass", ",", "boolean", "useTCP", ")", "{", "super", "(", "agentDesc", ",", "parserClass", ",", "useTCP", ")", ";", "this", ".", "overrideMsgTypes", "(", ")", ";", "}", "/** @see AbstractSolver#solve(org.jdom2.Document, int, boolean, java.lang.Long, boolean) */", "@", "Override", "public", "S", "solve", "(", "Document", "problem", ",", "int", "nbrElectionRounds", ",", "boolean", "measureMsgs", ",", "Long", "timeout", ",", "boolean", "cleanAfterwards", ")", "{", "agentDesc", ".", "getRootElement", "(", ")", ".", "setAttribute", "(", "\"", "measureMsgs", "\"", ",", "Boolean", ".", "toString", "(", "measureMsgs", ")", ")", ";", "this", ".", "setNbrElectionRounds", "(", "nbrElectionRounds", ")", ";", "return", "this", ".", "solve", "(", "problem", ",", "cleanAfterwards", ",", "timeout", ")", ";", "}", "/** @see AbstractSolver#solve(frodo2.solutionSpaces.ProblemInterface, int, boolean, java.lang.Long, boolean) */", "@", "Override", "public", "S", "solve", "(", "DCOPProblemInterface", "<", "V", ",", "U", ">", "problem", ",", "int", "nbrElectionRounds", ",", "boolean", "measureMsgs", ",", "Long", "timeout", ",", "boolean", "cleanAfterwards", ")", "{", "agentDesc", ".", "getRootElement", "(", ")", ".", "setAttribute", "(", "\"", "measureMsgs", "\"", ",", "Boolean", ".", "toString", "(", "measureMsgs", ")", ")", ";", "this", ".", "setNbrElectionRounds", "(", "nbrElectionRounds", ")", ";", "return", "this", ".", "solve", "(", "problem", ",", "cleanAfterwards", ",", "timeout", ")", ";", "}", "/** Sets the number of rounds of VariableElection\n\t * @param nbrElectionRounds \tthe number of rounds of VariableElection (must be greater than the diameter of the constraint graph)\n\t */", "protected", "void", "setNbrElectionRounds", "(", "int", "nbrElectionRounds", ")", "{", "for", "(", "Element", "module", ":", "(", "List", "<", "Element", ">", ")", "agentDesc", ".", "getRootElement", "(", ")", ".", "getChild", "(", "\"", "modules", "\"", ")", ".", "getChildren", "(", ")", ")", "if", "(", "module", ".", "getAttributeValue", "(", "\"", "className", "\"", ")", ".", "equals", "(", "VariableElection", ".", "class", ".", "getName", "(", ")", ")", ")", "module", ".", "setAttribute", "(", "\"", "nbrSteps", "\"", ",", "Integer", ".", "toString", "(", "nbrElectionRounds", ")", ")", ";", "}", "/** Overrides message types if necessary */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "private", "void", "overrideMsgTypes", "(", ")", "{", "Element", "modsElmt", "=", "agentDesc", ".", "getRootElement", "(", ")", ".", "getChild", "(", "\"", "modules", "\"", ")", ";", "try", "{", "if", "(", "modsElmt", "!=", "null", ")", "{", "for", "(", "Element", "moduleElmt", ":", "(", "List", "<", "Element", ">", ")", "modsElmt", ".", "getChildren", "(", ")", ")", "{", "String", "className", "=", "moduleElmt", ".", "getAttributeValue", "(", "\"", "className", "\"", ")", ";", "Class", "<", "MessageListener", "<", "String", ">", ">", "moduleClass", "=", "(", "Class", "<", "MessageListener", "<", "String", ">", ">", ")", "Class", ".", "forName", "(", "className", ")", ";", "Element", "allMsgsElmt", "=", "moduleElmt", ".", "getChild", "(", "\"", "messages", "\"", ")", ";", "if", "(", "allMsgsElmt", "!=", "null", ")", "{", "for", "(", "Element", "msgElmt", ":", "(", "List", "<", "Element", ">", ")", "allMsgsElmt", ".", "getChildren", "(", ")", ")", "{", "String", "newType", "=", "msgElmt", ".", "getAttributeValue", "(", "\"", "value", "\"", ")", ";", "String", "ownerClassName", "=", "msgElmt", ".", "getAttributeValue", "(", "\"", "ownerClass", "\"", ")", ";", "if", "(", "ownerClassName", "!=", "null", ")", "{", "Class", "<", "?", ">", "ownerClass", "=", "Class", ".", "forName", "(", "ownerClassName", ")", ";", "try", "{", "Field", "field", "=", "ownerClass", ".", "getDeclaredField", "(", "newType", ")", ";", "newType", "=", "(", "String", ")", "field", ".", "get", "(", "newType", ")", ";", "}", "catch", "(", "NoSuchFieldException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Unable to read the value of the field ", "\"", "+", "ownerClass", ".", "getName", "(", ")", "+", "\"", ".", "\"", "+", "newType", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "try", "{", "SingleQueueAgent", ".", "setMsgType", "(", "moduleClass", ",", "msgElmt", ".", "getAttributeValue", "(", "\"", "name", "\"", ")", ",", "newType", ")", ";", "}", "catch", "(", "NoSuchFieldException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Unable to find the field ", "\"", "+", "moduleClass", ".", "getName", "(", ")", "+", "\"", ".", "\"", "+", "msgElmt", ".", "getAttributeValue", "(", "\"", "name", "\"", ")", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}" ]
An abstract convenient class for solving DCOP instances @author Thomas Leaute @param <V> type used for variable values @param <U> type used for utility values @param <S> type used for the solution
[ "An", "abstract", "convenient", "class", "for", "solving", "DCOP", "instances", "@author", "Thomas", "Leaute", "@param", "<V", ">", "type", "used", "for", "variable", "values", "@param", "<U", ">", "type", "used", "for", "utility", "values", "@param", "<S", ">", "type", "used", "for", "the", "solution" ]
[ "// Parse the input arguments", "// *1000 to get it in ms", "// Instantiate the solver", "// Write a first \"timeout\" line to the output file that will be overwritten after the algorithm terminates (if it does)", "// Solve and record the stats", "// 0 = no timeout; 1 = timeout", "// First write statistics about the problem instance", "// Write the statistics about the solution found", "// 0 if the algorithm terminated, 1 if it timed out", "// the name of the problem instance, assumed unique", "// Write statistics about the problem instance, added by the problem generator to the XCSP file", "// Continue with the statistics about the solution", "// Write the name of this problem instance (assuming it is unique)", "// Write statistics about the problem instance", "// 0 = no timeout; 1 = timeout", "// Continue with statistics about the solution", "// NCCCs", "// runtime", "// nbrMessages", "// total msg size", "// max msg size", "// treewidth", "// reported util", "// true util", "// Look up the new value for the message type", "// the attribute \"value\" actually refers to a field in a class", "// Set the message type to its new value" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
334913a2f76e5482b0a0b47b4e5c387470c8be27
alexandrelombard/sarl
main/coreplugins/io.sarl.lang.ui/src-gen/io/sarl/lang/ui/contentassist/AbstractSARLProposalProvider.java
[ "Apache-2.0" ]
Java
AbstractSARLProposalProvider
/** * Represents a generated, default implementation of superclass {@link XtendProposalProvider}. * Methods are dynamically dispatched on the first parameter, i.e., you can override them * with a more concrete subtype. */
Represents a generated, default implementation of superclass XtendProposalProvider. Methods are dynamically dispatched on the first parameter, i.e., you can override them with a more concrete subtype.
[ "Represents", "a", "generated", "default", "implementation", "of", "superclass", "XtendProposalProvider", ".", "Methods", "are", "dynamically", "dispatched", "on", "the", "first", "parameter", "i", ".", "e", ".", "you", "can", "override", "them", "with", "a", "more", "concrete", "subtype", "." ]
public abstract class AbstractSARLProposalProvider extends XtendProposalProvider { public void completeSarlScript_Package(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeSarlScript_ImportSection(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeSarlScript_XtendTypes(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeEventMember_Annotations(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeEventMember_Modifiers(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { if (assignment.getTerminal() instanceof RuleCall) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } if (assignment.getTerminal() instanceof Keyword) { // subclasses may override } } public void completeEventMember_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeEventMember_Type(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeEventMember_InitialValue(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeEventMember_TypeParameters(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeEventMember_Parameters(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeEventMember_Exceptions(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeEventMember_Expression(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_Annotations(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_Modifiers(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_TypeParameters(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_Parameters(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_ReturnType(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_Exceptions(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_FiredEvents(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCapacityMember_Expression(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Annotations(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Guard(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Expression(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Capacities(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Modifiers(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { if (assignment.getTerminal() instanceof RuleCall) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } if (assignment.getTerminal() instanceof Keyword) { // subclasses may override } } public void completeAOPMember_Type(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_InitialValue(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_TypeParameters(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Parameters(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Exceptions(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_ReturnType(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_FiredEvents(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Extends(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Implements(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAOPMember_Members(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeMember_FiredEvents(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeParameter_DefaultValue(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAssertExpression_Condition(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAssertExpression_Message(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAssumeExpression_IsStatic(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void completeAssumeExpression_Condition(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeAssumeExpression_Message(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeSarlCastedExpression_Feature(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { lookupCrossReference(((CrossReference)assignment.getTerminal()), context, acceptor); } public void completeXVariableDeclaration_Extension(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void completeSarlXLoopFormalParameter_Extension(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void completeSarlXLoopFormalParameter_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeSarlXLoopFormalParameter_ParameterType(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeXExponentExpression_Feature(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { lookupCrossReference(((CrossReference)assignment.getTerminal()), context, acceptor); } public void completeXExponentExpression_RightOperand(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void complete_SarlScript(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_EventMember(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_CapacityMember(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_AOPMember(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_BreakExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_ContinueExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_AssertExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_AssumeExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_SarlCastedExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_SarlXLoopFormalParameter(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_XExponentExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OpExponent(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } }
[ "public", "abstract", "class", "AbstractSARLProposalProvider", "extends", "XtendProposalProvider", "{", "public", "void", "completeSarlScript_Package", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeSarlScript_ImportSection", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeSarlScript_XtendTypes", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeEventMember_Annotations", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeEventMember_Modifiers", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "if", "(", "assignment", ".", "getTerminal", "(", ")", "instanceof", "RuleCall", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "if", "(", "assignment", ".", "getTerminal", "(", ")", "instanceof", "Keyword", ")", "{", "}", "}", "public", "void", "completeEventMember_Name", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeEventMember_Type", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeEventMember_InitialValue", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeEventMember_TypeParameters", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeEventMember_Parameters", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeEventMember_Exceptions", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeEventMember_Expression", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_Annotations", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_Modifiers", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_TypeParameters", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_Name", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_Parameters", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_ReturnType", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_Exceptions", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_FiredEvents", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeCapacityMember_Expression", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Annotations", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Name", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Guard", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Expression", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Capacities", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Modifiers", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "if", "(", "assignment", ".", "getTerminal", "(", ")", "instanceof", "RuleCall", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "if", "(", "assignment", ".", "getTerminal", "(", ")", "instanceof", "Keyword", ")", "{", "}", "}", "public", "void", "completeAOPMember_Type", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_InitialValue", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_TypeParameters", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Parameters", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Exceptions", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_ReturnType", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_FiredEvents", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Extends", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Implements", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAOPMember_Members", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeMember_FiredEvents", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeParameter_DefaultValue", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAssertExpression_Condition", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAssertExpression_Message", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAssumeExpression_IsStatic", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "completeAssumeExpression_Condition", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeAssumeExpression_Message", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeSarlCastedExpression_Feature", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "lookupCrossReference", "(", "(", "(", "CrossReference", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeXVariableDeclaration_Extension", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "completeSarlXLoopFormalParameter_Extension", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "completeSarlXLoopFormalParameter_Name", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeSarlXLoopFormalParameter_ParameterType", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeXExponentExpression_Feature", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "lookupCrossReference", "(", "(", "(", "CrossReference", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "completeXExponentExpression_RightOperand", "(", "EObject", "model", ",", "Assignment", "assignment", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "completeRuleCall", "(", "(", "(", "RuleCall", ")", "assignment", ".", "getTerminal", "(", ")", ")", ",", "context", ",", "acceptor", ")", ";", "}", "public", "void", "complete_SarlScript", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_EventMember", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_CapacityMember", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_AOPMember", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_BreakExpression", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_ContinueExpression", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_AssertExpression", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_AssumeExpression", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_SarlCastedExpression", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_SarlXLoopFormalParameter", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_XExponentExpression", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "public", "void", "complete_OpExponent", "(", "EObject", "model", ",", "RuleCall", "ruleCall", ",", "ContentAssistContext", "context", ",", "ICompletionProposalAcceptor", "acceptor", ")", "{", "}", "}" ]
Represents a generated, default implementation of superclass {@link XtendProposalProvider}.
[ "Represents", "a", "generated", "default", "implementation", "of", "superclass", "{", "@link", "XtendProposalProvider", "}", "." ]
[ "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override", "// subclasses may override" ]
[ { "param": "XtendProposalProvider", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "XtendProposalProvider", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
334a88cc3d73eccfbeb0b942e3e87ea5a7aea549
spbooth/SAFE-WEBAPP
src/test/java/uk/ac/ed/epcc/webapp/servlet/RemoteAuthServletTest.java
[ "Apache-2.0" ]
Java
RemoteAuthServletTest
/** * @author spb * @param <A> * */
@author spb @param
[ "@author", "spb", "@param" ]
public class RemoteAuthServletTest<A extends AppUser> extends ServletTest { /** * */ public RemoteAuthServletTest() { // TODO Auto-generated constructor stub } @Override public void setUp() throws Exception { // TODO Auto-generated method stub super.setUp(); servlet=new RemoteAuthServlet(); MockServletConfig config = new MockServletConfig(serv_ctx, "RemoteServlet"); servlet.init(config); req.servlet_path="RemoteServlet"; } @Test public void testRegister() throws ConsistencyError, Exception{ MockTansport.clear(); takeBaseline(); AppUserFactory<A> fac = ctx.getService(SessionService.class).getLoginFactory(); A user = fac.makeBDO(); PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class); user.setEmail("fred@example.com"); composite.setPassword(user,"FredIsDead"); user.commit(); ctx.getService(SessionService.class).setCurrentPerson(user); req.remote_user="fred"; doPost(); checkMessage("remote_auth_set"); checkDiff("/cleanup.xsl", "remote_set.xml"); } @Test @ConfigFixtures("multi_remote.properties") public void testRegisterMulti() throws ConsistencyError, Exception{ MockTansport.clear(); takeBaseline(); AppUserFactory<A> fac = ctx.getService(SessionService.class).getLoginFactory(); A user = fac.makeBDO(); PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class); user.setEmail("fred@example.com"); composite.setPassword(user,"FredIsDead"); user.commit(); ctx.getService(SessionService.class).setCurrentPerson(user); req.remote_user="fred"; doPost(); checkMessage("remote_auth_set"); checkDiff("/cleanup.xsl", "remote_set2.xml"); } @Test public void testSignupRegister() throws ConsistencyError, Exception{ MockTansport.clear(); takeBaseline(); SessionService sess = ctx.getService(SessionService.class); AppUserFactory<A> fac = sess.getLoginFactory(); A user = fac.makeBDO(); PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class); user.setEmail("fred@example.com"); composite.setPassword(user,"FredIsDead"); user.commit(); // Calling registerNewuser should allow a user to bind // an existing is and login RemoteAuthServlet.registerNewUser(ctx, user); assertFalse(sess.haveCurrentUser()); req.remote_user="fred"; doPost(); checkMessage("remote_auth_set"); assertTrue(sess.isCurrentPerson(user)); checkDiff("/cleanup.xsl", "remote_set.xml"); } @Test @ConfigFixtures("multi_remote.properties") public void testSignupRegisterMulti() throws ConsistencyError, Exception{ MockTansport.clear(); takeBaseline(); SessionService sess = ctx.getService(SessionService.class); AppUserFactory<A> fac = sess.getLoginFactory(); A user = fac.makeBDO(); PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class); user.setEmail("fred@example.com"); composite.setPassword(user,"FredIsDead"); user.commit(); // Calling registerNewuser should allow a user to bind // an existing is and login RemoteAuthServlet.registerNewUser(ctx, user); assertFalse(sess.haveCurrentUser()); req.remote_user="fred"; doPost(); checkMessage("remote_auth_set"); assertTrue(sess.isCurrentPerson(user)); checkDiff("/cleanup.xsl", "remote_set2.xml"); } @Test @DataBaseFixtures("remote_set.xml") public void testReRegister() throws ConsistencyError, Exception{ MockTansport.clear(); takeBaseline(); AppUserFactory<A> fac = ctx.getService(SessionService.class).getLoginFactory(); A user = fac.makeBDO(); PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class); user.setEmail("fred2@example.com"); composite.setPassword(user,"FredIsDead"); user.commit(); ctx.getService(SessionService.class).setCurrentPerson(user); req.remote_user="fred"; doPost(); checkMessage("remote_auth_set"); checkDiff("/cleanup.xsl", "remote_reset.xml"); A old_user = fac.findByEmail("fred@example.com"); assertNull(old_user.getRealmName(WebNameFinder.WEB_NAME)); } @Test @DataBaseFixtures("remote_set2.xml") @ConfigFixtures("multi_remote.properties") public void testReRegisterMulti() throws ConsistencyError, Exception{ MockTansport.clear(); takeBaseline(); AppUserFactory<A> fac = ctx.getService(SessionService.class).getLoginFactory(); A user = fac.makeBDO(); PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class); user.setEmail("fred2@example.com"); composite.setPassword(user,"FredIsDead"); user.commit(); ctx.getService(SessionService.class).setCurrentPerson(user); req.remote_user="fred"; doPost(); checkMessage("remote_auth_set"); checkDiff("/cleanup.xsl", "remote_reset2.xml"); A old_user = fac.findByEmail("fred@example.com"); assertNull(old_user.getRealmName(WebNameFinder.WEB_NAME)); } @Test @DataBaseFixtures("remote_set.xml") public void testLogin() throws ConsistencyError, Exception{ req.remote_user="fred"; doPost(); checkRedirect("/main.jsp"); assertEquals("fred@example.com",ctx.getService(SessionService.class).getCurrentPerson().getEmail()); } @Test @DataBaseFixtures("remote_set2.xml") @ConfigFixtures("multi_remote.properties") public void testLoginMulti() throws ConsistencyError, Exception{ req.remote_user="fred"; doPost(); checkRedirect("/main.jsp"); assertEquals("fred@example.com",ctx.getService(SessionService.class).getCurrentPerson().getEmail()); } }
[ "public", "class", "RemoteAuthServletTest", "<", "A", "extends", "AppUser", ">", "extends", "ServletTest", "{", "/**\r\n\t * \r\n\t */", "public", "RemoteAuthServletTest", "(", ")", "{", "}", "@", "Override", "public", "void", "setUp", "(", ")", "throws", "Exception", "{", "super", ".", "setUp", "(", ")", ";", "servlet", "=", "new", "RemoteAuthServlet", "(", ")", ";", "MockServletConfig", "config", "=", "new", "MockServletConfig", "(", "serv_ctx", ",", "\"", "RemoteServlet", "\"", ")", ";", "servlet", ".", "init", "(", "config", ")", ";", "req", ".", "servlet_path", "=", "\"", "RemoteServlet", "\"", ";", "}", "@", "Test", "public", "void", "testRegister", "(", ")", "throws", "ConsistencyError", ",", "Exception", "{", "MockTansport", ".", "clear", "(", ")", ";", "takeBaseline", "(", ")", ";", "AppUserFactory", "<", "A", ">", "fac", "=", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "getLoginFactory", "(", ")", ";", "A", "user", "=", "fac", ".", "makeBDO", "(", ")", ";", "PasswordAuthComposite", "<", "A", ">", "composite", "=", "fac", ".", "getComposite", "(", "PasswordAuthComposite", ".", "class", ")", ";", "user", ".", "setEmail", "(", "\"", "fred@example.com", "\"", ")", ";", "composite", ".", "setPassword", "(", "user", ",", "\"", "FredIsDead", "\"", ")", ";", "user", ".", "commit", "(", ")", ";", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "setCurrentPerson", "(", "user", ")", ";", "req", ".", "remote_user", "=", "\"", "fred", "\"", ";", "doPost", "(", ")", ";", "checkMessage", "(", "\"", "remote_auth_set", "\"", ")", ";", "checkDiff", "(", "\"", "/cleanup.xsl", "\"", ",", "\"", "remote_set.xml", "\"", ")", ";", "}", "@", "Test", "@", "ConfigFixtures", "(", "\"", "multi_remote.properties", "\"", ")", "public", "void", "testRegisterMulti", "(", ")", "throws", "ConsistencyError", ",", "Exception", "{", "MockTansport", ".", "clear", "(", ")", ";", "takeBaseline", "(", ")", ";", "AppUserFactory", "<", "A", ">", "fac", "=", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "getLoginFactory", "(", ")", ";", "A", "user", "=", "fac", ".", "makeBDO", "(", ")", ";", "PasswordAuthComposite", "<", "A", ">", "composite", "=", "fac", ".", "getComposite", "(", "PasswordAuthComposite", ".", "class", ")", ";", "user", ".", "setEmail", "(", "\"", "fred@example.com", "\"", ")", ";", "composite", ".", "setPassword", "(", "user", ",", "\"", "FredIsDead", "\"", ")", ";", "user", ".", "commit", "(", ")", ";", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "setCurrentPerson", "(", "user", ")", ";", "req", ".", "remote_user", "=", "\"", "fred", "\"", ";", "doPost", "(", ")", ";", "checkMessage", "(", "\"", "remote_auth_set", "\"", ")", ";", "checkDiff", "(", "\"", "/cleanup.xsl", "\"", ",", "\"", "remote_set2.xml", "\"", ")", ";", "}", "@", "Test", "public", "void", "testSignupRegister", "(", ")", "throws", "ConsistencyError", ",", "Exception", "{", "MockTansport", ".", "clear", "(", ")", ";", "takeBaseline", "(", ")", ";", "SessionService", "sess", "=", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ";", "AppUserFactory", "<", "A", ">", "fac", "=", "sess", ".", "getLoginFactory", "(", ")", ";", "A", "user", "=", "fac", ".", "makeBDO", "(", ")", ";", "PasswordAuthComposite", "<", "A", ">", "composite", "=", "fac", ".", "getComposite", "(", "PasswordAuthComposite", ".", "class", ")", ";", "user", ".", "setEmail", "(", "\"", "fred@example.com", "\"", ")", ";", "composite", ".", "setPassword", "(", "user", ",", "\"", "FredIsDead", "\"", ")", ";", "user", ".", "commit", "(", ")", ";", "RemoteAuthServlet", ".", "registerNewUser", "(", "ctx", ",", "user", ")", ";", "assertFalse", "(", "sess", ".", "haveCurrentUser", "(", ")", ")", ";", "req", ".", "remote_user", "=", "\"", "fred", "\"", ";", "doPost", "(", ")", ";", "checkMessage", "(", "\"", "remote_auth_set", "\"", ")", ";", "assertTrue", "(", "sess", ".", "isCurrentPerson", "(", "user", ")", ")", ";", "checkDiff", "(", "\"", "/cleanup.xsl", "\"", ",", "\"", "remote_set.xml", "\"", ")", ";", "}", "@", "Test", "@", "ConfigFixtures", "(", "\"", "multi_remote.properties", "\"", ")", "public", "void", "testSignupRegisterMulti", "(", ")", "throws", "ConsistencyError", ",", "Exception", "{", "MockTansport", ".", "clear", "(", ")", ";", "takeBaseline", "(", ")", ";", "SessionService", "sess", "=", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ";", "AppUserFactory", "<", "A", ">", "fac", "=", "sess", ".", "getLoginFactory", "(", ")", ";", "A", "user", "=", "fac", ".", "makeBDO", "(", ")", ";", "PasswordAuthComposite", "<", "A", ">", "composite", "=", "fac", ".", "getComposite", "(", "PasswordAuthComposite", ".", "class", ")", ";", "user", ".", "setEmail", "(", "\"", "fred@example.com", "\"", ")", ";", "composite", ".", "setPassword", "(", "user", ",", "\"", "FredIsDead", "\"", ")", ";", "user", ".", "commit", "(", ")", ";", "RemoteAuthServlet", ".", "registerNewUser", "(", "ctx", ",", "user", ")", ";", "assertFalse", "(", "sess", ".", "haveCurrentUser", "(", ")", ")", ";", "req", ".", "remote_user", "=", "\"", "fred", "\"", ";", "doPost", "(", ")", ";", "checkMessage", "(", "\"", "remote_auth_set", "\"", ")", ";", "assertTrue", "(", "sess", ".", "isCurrentPerson", "(", "user", ")", ")", ";", "checkDiff", "(", "\"", "/cleanup.xsl", "\"", ",", "\"", "remote_set2.xml", "\"", ")", ";", "}", "@", "Test", "@", "DataBaseFixtures", "(", "\"", "remote_set.xml", "\"", ")", "public", "void", "testReRegister", "(", ")", "throws", "ConsistencyError", ",", "Exception", "{", "MockTansport", ".", "clear", "(", ")", ";", "takeBaseline", "(", ")", ";", "AppUserFactory", "<", "A", ">", "fac", "=", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "getLoginFactory", "(", ")", ";", "A", "user", "=", "fac", ".", "makeBDO", "(", ")", ";", "PasswordAuthComposite", "<", "A", ">", "composite", "=", "fac", ".", "getComposite", "(", "PasswordAuthComposite", ".", "class", ")", ";", "user", ".", "setEmail", "(", "\"", "fred2@example.com", "\"", ")", ";", "composite", ".", "setPassword", "(", "user", ",", "\"", "FredIsDead", "\"", ")", ";", "user", ".", "commit", "(", ")", ";", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "setCurrentPerson", "(", "user", ")", ";", "req", ".", "remote_user", "=", "\"", "fred", "\"", ";", "doPost", "(", ")", ";", "checkMessage", "(", "\"", "remote_auth_set", "\"", ")", ";", "checkDiff", "(", "\"", "/cleanup.xsl", "\"", ",", "\"", "remote_reset.xml", "\"", ")", ";", "A", "old_user", "=", "fac", ".", "findByEmail", "(", "\"", "fred@example.com", "\"", ")", ";", "assertNull", "(", "old_user", ".", "getRealmName", "(", "WebNameFinder", ".", "WEB_NAME", ")", ")", ";", "}", "@", "Test", "@", "DataBaseFixtures", "(", "\"", "remote_set2.xml", "\"", ")", "@", "ConfigFixtures", "(", "\"", "multi_remote.properties", "\"", ")", "public", "void", "testReRegisterMulti", "(", ")", "throws", "ConsistencyError", ",", "Exception", "{", "MockTansport", ".", "clear", "(", ")", ";", "takeBaseline", "(", ")", ";", "AppUserFactory", "<", "A", ">", "fac", "=", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "getLoginFactory", "(", ")", ";", "A", "user", "=", "fac", ".", "makeBDO", "(", ")", ";", "PasswordAuthComposite", "<", "A", ">", "composite", "=", "fac", ".", "getComposite", "(", "PasswordAuthComposite", ".", "class", ")", ";", "user", ".", "setEmail", "(", "\"", "fred2@example.com", "\"", ")", ";", "composite", ".", "setPassword", "(", "user", ",", "\"", "FredIsDead", "\"", ")", ";", "user", ".", "commit", "(", ")", ";", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "setCurrentPerson", "(", "user", ")", ";", "req", ".", "remote_user", "=", "\"", "fred", "\"", ";", "doPost", "(", ")", ";", "checkMessage", "(", "\"", "remote_auth_set", "\"", ")", ";", "checkDiff", "(", "\"", "/cleanup.xsl", "\"", ",", "\"", "remote_reset2.xml", "\"", ")", ";", "A", "old_user", "=", "fac", ".", "findByEmail", "(", "\"", "fred@example.com", "\"", ")", ";", "assertNull", "(", "old_user", ".", "getRealmName", "(", "WebNameFinder", ".", "WEB_NAME", ")", ")", ";", "}", "@", "Test", "@", "DataBaseFixtures", "(", "\"", "remote_set.xml", "\"", ")", "public", "void", "testLogin", "(", ")", "throws", "ConsistencyError", ",", "Exception", "{", "req", ".", "remote_user", "=", "\"", "fred", "\"", ";", "doPost", "(", ")", ";", "checkRedirect", "(", "\"", "/main.jsp", "\"", ")", ";", "assertEquals", "(", "\"", "fred@example.com", "\"", ",", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "getCurrentPerson", "(", ")", ".", "getEmail", "(", ")", ")", ";", "}", "@", "Test", "@", "DataBaseFixtures", "(", "\"", "remote_set2.xml", "\"", ")", "@", "ConfigFixtures", "(", "\"", "multi_remote.properties", "\"", ")", "public", "void", "testLoginMulti", "(", ")", "throws", "ConsistencyError", ",", "Exception", "{", "req", ".", "remote_user", "=", "\"", "fred", "\"", ";", "doPost", "(", ")", ";", "checkRedirect", "(", "\"", "/main.jsp", "\"", ")", ";", "assertEquals", "(", "\"", "fred@example.com", "\"", ",", "ctx", ".", "getService", "(", "SessionService", ".", "class", ")", ".", "getCurrentPerson", "(", ")", ".", "getEmail", "(", ")", ")", ";", "}", "}" ]
@author spb @param <A>
[ "@author", "spb", "@param", "<A", ">" ]
[ "// TODO Auto-generated constructor stub\r", "// TODO Auto-generated method stub\r", "// Calling registerNewuser should allow a user to bind\r", "// an existing is and login\r", "// Calling registerNewuser should allow a user to bind\r", "// an existing is and login\r" ]
[ { "param": "ServletTest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ServletTest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
334b17656a41f1e2a4551c971a4e86e1f3f5e953
monowar/DataKit
datakit/src/main/java/org/md2k/datakit/PrefsFragmentSettingsDatabase.java
[ "BSD-2-Clause" ]
Java
PrefsFragmentSettingsDatabase
/** * Preferences fragment for database settings */
Preferences fragment for database settings
[ "Preferences", "fragment", "for", "database", "settings" ]
public class PrefsFragmentSettingsDatabase extends PreferenceFragment { /** Constant used for logging. <p>Uses <code>class.getSimpleName()</code>.</p> */ private static final String TAG = PrefsFragmentSettingsDatabase.class.getSimpleName(); /** Configuration object. */ Configuration configuration; /** * Creates the database settings screen. * * @param savedInstanceState Previous state of this activity, if it existed. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); configuration = ConfigurationManager.read(getActivity()); Log.d(TAG, "configuration=" + configuration); getPreferenceManager().getSharedPreferences().edit().clear().apply(); getPreferenceManager().getSharedPreferences().edit().putString("key_storage", configuration.database.location).apply(); addPreferencesFromResource(R.xml.pref_settings_database); setBackButton(); setSaveButton(); if (getActivity().getIntent().getBooleanExtra("delete", false)) clearDatabase(); } /** * Sets up preferences when the activity is resumed. */ @Override public void onResume() { setupPreferences(); super.onResume(); } /** * Creates a <code>View</code>. * * @param inflater Android LayoutInflater * @param container Android ViewGroup * @param savedInstanceState Previous state of this activity, if it existed. * @return The <code>View</code> that was created. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = super.onCreateView(inflater, container, savedInstanceState); ListView lv = (ListView) v.findViewById(android.R.id.list); lv.setPadding(0, 0, 0, 0); return v; } /** * Creates a back button so the user can close this activity. */ private void setBackButton() { final Button button = (Button) getActivity().findViewById(R.id.button_1); button.setText("Close"); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getActivity().finish(); } }); } /** * Creates a save button so the user can save the current configuration. */ private void setSaveButton() { final Button button = (Button) getActivity().findViewById(R.id.button_2); button.setText("Save"); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences(); configuration.database.location = sharedPreferences.getString("key_storage", configuration.database.location); ConfigurationManager.write(configuration); Toast.makeText(getActivity(), "Saved...", Toast.LENGTH_LONG).show(); setupPreferences(); } }); } /** * Wrapper method for calling setup methods for database preferences. * <p> * <ul> * <li><code>setupStorage()</code></li> * <li><code>setupDatabaseFile()</code></li> * <li><code>setupDatabaseClear()</code></li> * <li><code>setupSDCardSpace()</code></li> * <li><code>setupDatabaseSize()</code></li> * </ul> * </p> */ void setupPreferences() { setupStorage(); setupDatabaseFile(); setupDatabaseClear(); setupSDCardSpace(); setupDatabaseSize(); } /** * Sets up the storage location preferences. */ void setupStorage() { ListPreference preference = (ListPreference) findPreference("key_storage"); String storage = getPreferenceManager().getSharedPreferences().getString("key_storage", configuration.database.location); preference.setValue(storage); Log.d(TAG, "shared=" + storage + " config=" + configuration.database.location); preference.setSummary(findString(getResources().getStringArray(R.array.sdcard_values), getResources().getStringArray(R.array.sdcard_text), storage)); preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { /** * Changes the storage location. * * @param preference Preference to change. * @param newValue New value of the preference. * @return Always returns false. */ @Override public boolean onPreferenceChange(Preference preference, Object newValue) { getPreferenceManager().getSharedPreferences().edit().putString("key_storage", newValue.toString()).apply(); setupPreferences(); return false; } }); } /** * Finds the given string inside of a string array. * * @param values String array created from <code>sdcard_values</code>. * @param strings String array created from <code>sdcard_text</code>. * @param value String to find. * @return The string that matches the value string. */ private String findString(String[] values, String[] strings, String value) { for (int i = 0; i < values.length; i++) if (values[i].equals(value)) return strings[i]; return ("(not selected)"); } /** * Sets up the SD card space preferences. */ void setupSDCardSpace() { Preference preference = findPreference("key_sdcard_size"); String location = getPreferenceManager().getSharedPreferences().getString("key_storage", configuration.database.location); preference.setSummary(FileManager.getLocationType(getActivity(), location) + " [" + FileManager.getSDCardSizeString(getActivity(), location) + "]"); } /** * Sets up the size of the database file. */ void setupDatabaseSize() { Preference preference = findPreference("key_file_size"); String location = getPreferenceManager().getSharedPreferences().getString("key_storage", configuration.database.location); long fileSize = FileManager.getFileSize(getActivity(), location, Constants.DATABASE_FILENAME); preference.setSummary(FileManager.formatSize(fileSize)); } /** * Sets up the database location preferences. */ void setupDatabaseFile() { Preference preference = findPreference("key_directory"); String location = getPreferenceManager().getSharedPreferences().getString("key_storage", configuration.database.location); String filename = FileManager.getDirectory(getActivity(), location) + Constants.DATABASE_FILENAME; preference.setSummary(filename); } /** * Sets up the "Clear database" perference option. */ void setupDatabaseClear() { Preference preference = findPreference("key_delete"); preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { /** * Clears the database if clicked. * * @param preference Preference clicked. * @return Always returns true. */ @Override public boolean onPreferenceClick(Preference preference) { clearDatabase(); return true; } }); } /** * Sends a local broadcast with the given action string. * * @param str Action to broadcast. */ void sendLocalBroadcast(String str) { Intent intent = new Intent("datakit"); intent.putExtra("action", str); LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent); } /** * Prompts the user for whether to delete the archive or not. */ void clearDatabase() { Dialog.simple(getActivity(), "Clear Database", "Clear Database? \n\n" + "Data can't be recovered after deletion\n\n" + "Some apps may have problems after this operation. If it is, please restart those apps", "Yes", "Cancel", new DialogCallback() { /** * Calls <code>DatabaseDeleteAsyncTask()</code> or <code>getActivity().finish()</code> * accordingly. * * @param value Value of the selected dialog button. */ @Override public void onSelected(String value) { if (value.equals("Yes")) { sendLocalBroadcast("stop"); new DatabaseDeleteAsyncTask().execute(); } else { if (getActivity().getIntent().getBooleanExtra("delete", false)) getActivity().finish(); } } }).show(); } /** * Nested class for asynchronously deleting the database data. */ class DatabaseDeleteAsyncTask extends AsyncTask<String, String, String> { /** Dialog for showing the deletion progress. */ private ProgressDialog dialog; /** * Constructor * <p> * Creates a new <code>ProgressDialog</code>. * </p> */ DatabaseDeleteAsyncTask() { dialog = new ProgressDialog(getActivity()); } /** * Shows Progress Bar Dialog and then call doInBackground method */ @Override protected void onPreExecute() { super.onPreExecute(); dialog.setMessage("Deleting database. Please wait..."); dialog.show(); } /** * Deletes the database directories in a background thread. * * @param strings Needed to properly override the method. * @return Null. */ @Override protected String doInBackground(String... strings) { try { String location = ConfigurationManager.read(getActivity()).database.location; String filename = FileManager.getDirectory(getActivity(), location) + Constants.DATABASE_FILENAME; FileManager.deleteFile(filename); } catch (Exception ignored) {} return null; } /** * Sends a local "start" broadcast and dismisses the progress dialog and either finishes * the activity or calls <code>setPreferences()</code>. * * @param file_url Needed to properly override method. */ @Override protected void onPostExecute(String file_url) { sendLocalBroadcast("start"); setupPreferences(); if (dialog.isShowing()) { dialog.dismiss(); } Toast.makeText(getActivity(), "Database is Deleted", Toast.LENGTH_LONG).show(); if (getActivity().getIntent().getBooleanExtra("delete", false)) getActivity().finish(); } } }
[ "public", "class", "PrefsFragmentSettingsDatabase", "extends", "PreferenceFragment", "{", "/** Constant used for logging. <p>Uses <code>class.getSimpleName()</code>.</p> */", "private", "static", "final", "String", "TAG", "=", "PrefsFragmentSettingsDatabase", ".", "class", ".", "getSimpleName", "(", ")", ";", "/** Configuration object. */", "Configuration", "configuration", ";", "/**\n * Creates the database settings screen.\n *\n * @param savedInstanceState Previous state of this activity, if it existed.\n */", "@", "Override", "public", "void", "onCreate", "(", "Bundle", "savedInstanceState", ")", "{", "super", ".", "onCreate", "(", "savedInstanceState", ")", ";", "configuration", "=", "ConfigurationManager", ".", "read", "(", "getActivity", "(", ")", ")", ";", "Log", ".", "d", "(", "TAG", ",", "\"", "configuration=", "\"", "+", "configuration", ")", ";", "getPreferenceManager", "(", ")", ".", "getSharedPreferences", "(", ")", ".", "edit", "(", ")", ".", "clear", "(", ")", ".", "apply", "(", ")", ";", "getPreferenceManager", "(", ")", ".", "getSharedPreferences", "(", ")", ".", "edit", "(", ")", ".", "putString", "(", "\"", "key_storage", "\"", ",", "configuration", ".", "database", ".", "location", ")", ".", "apply", "(", ")", ";", "addPreferencesFromResource", "(", "R", ".", "xml", ".", "pref_settings_database", ")", ";", "setBackButton", "(", ")", ";", "setSaveButton", "(", ")", ";", "if", "(", "getActivity", "(", ")", ".", "getIntent", "(", ")", ".", "getBooleanExtra", "(", "\"", "delete", "\"", ",", "false", ")", ")", "clearDatabase", "(", ")", ";", "}", "/**\n * Sets up preferences when the activity is resumed.\n */", "@", "Override", "public", "void", "onResume", "(", ")", "{", "setupPreferences", "(", ")", ";", "super", ".", "onResume", "(", ")", ";", "}", "/**\n * Creates a <code>View</code>.\n *\n * @param inflater Android LayoutInflater\n * @param container Android ViewGroup\n * @param savedInstanceState Previous state of this activity, if it existed.\n * @return The <code>View</code> that was created.\n */", "@", "Override", "public", "View", "onCreateView", "(", "LayoutInflater", "inflater", ",", "ViewGroup", "container", ",", "Bundle", "savedInstanceState", ")", "{", "View", "v", "=", "super", ".", "onCreateView", "(", "inflater", ",", "container", ",", "savedInstanceState", ")", ";", "ListView", "lv", "=", "(", "ListView", ")", "v", ".", "findViewById", "(", "android", ".", "R", ".", "id", ".", "list", ")", ";", "lv", ".", "setPadding", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "return", "v", ";", "}", "/**\n * Creates a back button so the user can close this activity.\n */", "private", "void", "setBackButton", "(", ")", "{", "final", "Button", "button", "=", "(", "Button", ")", "getActivity", "(", ")", ".", "findViewById", "(", "R", ".", "id", ".", "button_1", ")", ";", "button", ".", "setText", "(", "\"", "Close", "\"", ")", ";", "button", ".", "setOnClickListener", "(", "new", "View", ".", "OnClickListener", "(", ")", "{", "public", "void", "onClick", "(", "View", "v", ")", "{", "getActivity", "(", ")", ".", "finish", "(", ")", ";", "}", "}", ")", ";", "}", "/**\n * Creates a save button so the user can save the current configuration.\n */", "private", "void", "setSaveButton", "(", ")", "{", "final", "Button", "button", "=", "(", "Button", ")", "getActivity", "(", ")", ".", "findViewById", "(", "R", ".", "id", ".", "button_2", ")", ";", "button", ".", "setText", "(", "\"", "Save", "\"", ")", ";", "button", ".", "setOnClickListener", "(", "new", "View", ".", "OnClickListener", "(", ")", "{", "public", "void", "onClick", "(", "View", "v", ")", "{", "SharedPreferences", "sharedPreferences", "=", "getPreferenceManager", "(", ")", ".", "getSharedPreferences", "(", ")", ";", "configuration", ".", "database", ".", "location", "=", "sharedPreferences", ".", "getString", "(", "\"", "key_storage", "\"", ",", "configuration", ".", "database", ".", "location", ")", ";", "ConfigurationManager", ".", "write", "(", "configuration", ")", ";", "Toast", ".", "makeText", "(", "getActivity", "(", ")", ",", "\"", "Saved...", "\"", ",", "Toast", ".", "LENGTH_LONG", ")", ".", "show", "(", ")", ";", "setupPreferences", "(", ")", ";", "}", "}", ")", ";", "}", "/**\n * Wrapper method for calling setup methods for database preferences.\n * <p>\n * <ul>\n * <li><code>setupStorage()</code></li>\n * <li><code>setupDatabaseFile()</code></li>\n * <li><code>setupDatabaseClear()</code></li>\n * <li><code>setupSDCardSpace()</code></li>\n * <li><code>setupDatabaseSize()</code></li>\n * </ul>\n * </p>\n */", "void", "setupPreferences", "(", ")", "{", "setupStorage", "(", ")", ";", "setupDatabaseFile", "(", ")", ";", "setupDatabaseClear", "(", ")", ";", "setupSDCardSpace", "(", ")", ";", "setupDatabaseSize", "(", ")", ";", "}", "/**\n * Sets up the storage location preferences.\n */", "void", "setupStorage", "(", ")", "{", "ListPreference", "preference", "=", "(", "ListPreference", ")", "findPreference", "(", "\"", "key_storage", "\"", ")", ";", "String", "storage", "=", "getPreferenceManager", "(", ")", ".", "getSharedPreferences", "(", ")", ".", "getString", "(", "\"", "key_storage", "\"", ",", "configuration", ".", "database", ".", "location", ")", ";", "preference", ".", "setValue", "(", "storage", ")", ";", "Log", ".", "d", "(", "TAG", ",", "\"", "shared=", "\"", "+", "storage", "+", "\"", " config=", "\"", "+", "configuration", ".", "database", ".", "location", ")", ";", "preference", ".", "setSummary", "(", "findString", "(", "getResources", "(", ")", ".", "getStringArray", "(", "R", ".", "array", ".", "sdcard_values", ")", ",", "getResources", "(", ")", ".", "getStringArray", "(", "R", ".", "array", ".", "sdcard_text", ")", ",", "storage", ")", ")", ";", "preference", ".", "setOnPreferenceChangeListener", "(", "new", "Preference", ".", "OnPreferenceChangeListener", "(", ")", "{", "/**\n * Changes the storage location.\n *\n * @param preference Preference to change.\n * @param newValue New value of the preference.\n * @return Always returns false.\n */", "@", "Override", "public", "boolean", "onPreferenceChange", "(", "Preference", "preference", ",", "Object", "newValue", ")", "{", "getPreferenceManager", "(", ")", ".", "getSharedPreferences", "(", ")", ".", "edit", "(", ")", ".", "putString", "(", "\"", "key_storage", "\"", ",", "newValue", ".", "toString", "(", ")", ")", ".", "apply", "(", ")", ";", "setupPreferences", "(", ")", ";", "return", "false", ";", "}", "}", ")", ";", "}", "/**\n * Finds the given string inside of a string array.\n *\n * @param values String array created from <code>sdcard_values</code>.\n * @param strings String array created from <code>sdcard_text</code>.\n * @param value String to find.\n * @return The string that matches the value string.\n */", "private", "String", "findString", "(", "String", "[", "]", "values", ",", "String", "[", "]", "strings", ",", "String", "value", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "if", "(", "values", "[", "i", "]", ".", "equals", "(", "value", ")", ")", "return", "strings", "[", "i", "]", ";", "return", "(", "\"", "(not selected)", "\"", ")", ";", "}", "/**\n * Sets up the SD card space preferences.\n */", "void", "setupSDCardSpace", "(", ")", "{", "Preference", "preference", "=", "findPreference", "(", "\"", "key_sdcard_size", "\"", ")", ";", "String", "location", "=", "getPreferenceManager", "(", ")", ".", "getSharedPreferences", "(", ")", ".", "getString", "(", "\"", "key_storage", "\"", ",", "configuration", ".", "database", ".", "location", ")", ";", "preference", ".", "setSummary", "(", "FileManager", ".", "getLocationType", "(", "getActivity", "(", ")", ",", "location", ")", "+", "\"", " [", "\"", "+", "FileManager", ".", "getSDCardSizeString", "(", "getActivity", "(", ")", ",", "location", ")", "+", "\"", "]", "\"", ")", ";", "}", "/**\n * Sets up the size of the database file.\n */", "void", "setupDatabaseSize", "(", ")", "{", "Preference", "preference", "=", "findPreference", "(", "\"", "key_file_size", "\"", ")", ";", "String", "location", "=", "getPreferenceManager", "(", ")", ".", "getSharedPreferences", "(", ")", ".", "getString", "(", "\"", "key_storage", "\"", ",", "configuration", ".", "database", ".", "location", ")", ";", "long", "fileSize", "=", "FileManager", ".", "getFileSize", "(", "getActivity", "(", ")", ",", "location", ",", "Constants", ".", "DATABASE_FILENAME", ")", ";", "preference", ".", "setSummary", "(", "FileManager", ".", "formatSize", "(", "fileSize", ")", ")", ";", "}", "/**\n * Sets up the database location preferences.\n */", "void", "setupDatabaseFile", "(", ")", "{", "Preference", "preference", "=", "findPreference", "(", "\"", "key_directory", "\"", ")", ";", "String", "location", "=", "getPreferenceManager", "(", ")", ".", "getSharedPreferences", "(", ")", ".", "getString", "(", "\"", "key_storage", "\"", ",", "configuration", ".", "database", ".", "location", ")", ";", "String", "filename", "=", "FileManager", ".", "getDirectory", "(", "getActivity", "(", ")", ",", "location", ")", "+", "Constants", ".", "DATABASE_FILENAME", ";", "preference", ".", "setSummary", "(", "filename", ")", ";", "}", "/**\n * Sets up the \"Clear database\" perference option.\n */", "void", "setupDatabaseClear", "(", ")", "{", "Preference", "preference", "=", "findPreference", "(", "\"", "key_delete", "\"", ")", ";", "preference", ".", "setOnPreferenceClickListener", "(", "new", "Preference", ".", "OnPreferenceClickListener", "(", ")", "{", "/**\n * Clears the database if clicked.\n *\n * @param preference Preference clicked.\n * @return Always returns true.\n */", "@", "Override", "public", "boolean", "onPreferenceClick", "(", "Preference", "preference", ")", "{", "clearDatabase", "(", ")", ";", "return", "true", ";", "}", "}", ")", ";", "}", "/**\n * Sends a local broadcast with the given action string.\n *\n * @param str Action to broadcast.\n */", "void", "sendLocalBroadcast", "(", "String", "str", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "\"", "datakit", "\"", ")", ";", "intent", ".", "putExtra", "(", "\"", "action", "\"", ",", "str", ")", ";", "LocalBroadcastManager", ".", "getInstance", "(", "getActivity", "(", ")", ")", ".", "sendBroadcast", "(", "intent", ")", ";", "}", "/**\n * Prompts the user for whether to delete the archive or not.\n */", "void", "clearDatabase", "(", ")", "{", "Dialog", ".", "simple", "(", "getActivity", "(", ")", ",", "\"", "Clear Database", "\"", ",", "\"", "Clear Database? ", "\\n", "\\n", "\"", "+", "\"", "Data can't be recovered after deletion", "\\n", "\\n", "\"", "+", "\"", "Some apps may have problems after this operation. If it is, please restart those apps", "\"", ",", "\"", "Yes", "\"", ",", "\"", "Cancel", "\"", ",", "new", "DialogCallback", "(", ")", "{", "/**\n * Calls <code>DatabaseDeleteAsyncTask()</code> or <code>getActivity().finish()</code>\n * accordingly.\n *\n * @param value Value of the selected dialog button.\n */", "@", "Override", "public", "void", "onSelected", "(", "String", "value", ")", "{", "if", "(", "value", ".", "equals", "(", "\"", "Yes", "\"", ")", ")", "{", "sendLocalBroadcast", "(", "\"", "stop", "\"", ")", ";", "new", "DatabaseDeleteAsyncTask", "(", ")", ".", "execute", "(", ")", ";", "}", "else", "{", "if", "(", "getActivity", "(", ")", ".", "getIntent", "(", ")", ".", "getBooleanExtra", "(", "\"", "delete", "\"", ",", "false", ")", ")", "getActivity", "(", ")", ".", "finish", "(", ")", ";", "}", "}", "}", ")", ".", "show", "(", ")", ";", "}", "/**\n * Nested class for asynchronously deleting the database data.\n */", "class", "DatabaseDeleteAsyncTask", "extends", "AsyncTask", "<", "String", ",", "String", ",", "String", ">", "{", "/** Dialog for showing the deletion progress. */", "private", "ProgressDialog", "dialog", ";", "/**\n * Constructor\n * <p>\n * Creates a new <code>ProgressDialog</code>.\n * </p>\n */", "DatabaseDeleteAsyncTask", "(", ")", "{", "dialog", "=", "new", "ProgressDialog", "(", "getActivity", "(", ")", ")", ";", "}", "/**\n * Shows Progress Bar Dialog and then call doInBackground method\n */", "@", "Override", "protected", "void", "onPreExecute", "(", ")", "{", "super", ".", "onPreExecute", "(", ")", ";", "dialog", ".", "setMessage", "(", "\"", "Deleting database. Please wait...", "\"", ")", ";", "dialog", ".", "show", "(", ")", ";", "}", "/**\n * Deletes the database directories in a background thread.\n *\n * @param strings Needed to properly override the method.\n * @return Null.\n */", "@", "Override", "protected", "String", "doInBackground", "(", "String", "...", "strings", ")", "{", "try", "{", "String", "location", "=", "ConfigurationManager", ".", "read", "(", "getActivity", "(", ")", ")", ".", "database", ".", "location", ";", "String", "filename", "=", "FileManager", ".", "getDirectory", "(", "getActivity", "(", ")", ",", "location", ")", "+", "Constants", ".", "DATABASE_FILENAME", ";", "FileManager", ".", "deleteFile", "(", "filename", ")", ";", "}", "catch", "(", "Exception", "ignored", ")", "{", "}", "return", "null", ";", "}", "/**\n * Sends a local \"start\" broadcast and dismisses the progress dialog and either finishes\n * the activity or calls <code>setPreferences()</code>.\n *\n * @param file_url Needed to properly override method.\n */", "@", "Override", "protected", "void", "onPostExecute", "(", "String", "file_url", ")", "{", "sendLocalBroadcast", "(", "\"", "start", "\"", ")", ";", "setupPreferences", "(", ")", ";", "if", "(", "dialog", ".", "isShowing", "(", ")", ")", "{", "dialog", ".", "dismiss", "(", ")", ";", "}", "Toast", ".", "makeText", "(", "getActivity", "(", ")", ",", "\"", "Database is Deleted", "\"", ",", "Toast", ".", "LENGTH_LONG", ")", ".", "show", "(", ")", ";", "if", "(", "getActivity", "(", ")", ".", "getIntent", "(", ")", ".", "getBooleanExtra", "(", "\"", "delete", "\"", ",", "false", ")", ")", "getActivity", "(", ")", ".", "finish", "(", ")", ";", "}", "}", "}" ]
Preferences fragment for database settings
[ "Preferences", "fragment", "for", "database", "settings" ]
[]
[ { "param": "PreferenceFragment", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PreferenceFragment", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
334b17656a41f1e2a4551c971a4e86e1f3f5e953
monowar/DataKit
datakit/src/main/java/org/md2k/datakit/PrefsFragmentSettingsDatabase.java
[ "BSD-2-Clause" ]
Java
DatabaseDeleteAsyncTask
/** * Nested class for asynchronously deleting the database data. */
Nested class for asynchronously deleting the database data.
[ "Nested", "class", "for", "asynchronously", "deleting", "the", "database", "data", "." ]
class DatabaseDeleteAsyncTask extends AsyncTask<String, String, String> { /** Dialog for showing the deletion progress. */ private ProgressDialog dialog; /** * Constructor * <p> * Creates a new <code>ProgressDialog</code>. * </p> */ DatabaseDeleteAsyncTask() { dialog = new ProgressDialog(getActivity()); } /** * Shows Progress Bar Dialog and then call doInBackground method */ @Override protected void onPreExecute() { super.onPreExecute(); dialog.setMessage("Deleting database. Please wait..."); dialog.show(); } /** * Deletes the database directories in a background thread. * * @param strings Needed to properly override the method. * @return Null. */ @Override protected String doInBackground(String... strings) { try { String location = ConfigurationManager.read(getActivity()).database.location; String filename = FileManager.getDirectory(getActivity(), location) + Constants.DATABASE_FILENAME; FileManager.deleteFile(filename); } catch (Exception ignored) {} return null; } /** * Sends a local "start" broadcast and dismisses the progress dialog and either finishes * the activity or calls <code>setPreferences()</code>. * * @param file_url Needed to properly override method. */ @Override protected void onPostExecute(String file_url) { sendLocalBroadcast("start"); setupPreferences(); if (dialog.isShowing()) { dialog.dismiss(); } Toast.makeText(getActivity(), "Database is Deleted", Toast.LENGTH_LONG).show(); if (getActivity().getIntent().getBooleanExtra("delete", false)) getActivity().finish(); } }
[ "class", "DatabaseDeleteAsyncTask", "extends", "AsyncTask", "<", "String", ",", "String", ",", "String", ">", "{", "/** Dialog for showing the deletion progress. */", "private", "ProgressDialog", "dialog", ";", "/**\n * Constructor\n * <p>\n * Creates a new <code>ProgressDialog</code>.\n * </p>\n */", "DatabaseDeleteAsyncTask", "(", ")", "{", "dialog", "=", "new", "ProgressDialog", "(", "getActivity", "(", ")", ")", ";", "}", "/**\n * Shows Progress Bar Dialog and then call doInBackground method\n */", "@", "Override", "protected", "void", "onPreExecute", "(", ")", "{", "super", ".", "onPreExecute", "(", ")", ";", "dialog", ".", "setMessage", "(", "\"", "Deleting database. Please wait...", "\"", ")", ";", "dialog", ".", "show", "(", ")", ";", "}", "/**\n * Deletes the database directories in a background thread.\n *\n * @param strings Needed to properly override the method.\n * @return Null.\n */", "@", "Override", "protected", "String", "doInBackground", "(", "String", "...", "strings", ")", "{", "try", "{", "String", "location", "=", "ConfigurationManager", ".", "read", "(", "getActivity", "(", ")", ")", ".", "database", ".", "location", ";", "String", "filename", "=", "FileManager", ".", "getDirectory", "(", "getActivity", "(", ")", ",", "location", ")", "+", "Constants", ".", "DATABASE_FILENAME", ";", "FileManager", ".", "deleteFile", "(", "filename", ")", ";", "}", "catch", "(", "Exception", "ignored", ")", "{", "}", "return", "null", ";", "}", "/**\n * Sends a local \"start\" broadcast and dismisses the progress dialog and either finishes\n * the activity or calls <code>setPreferences()</code>.\n *\n * @param file_url Needed to properly override method.\n */", "@", "Override", "protected", "void", "onPostExecute", "(", "String", "file_url", ")", "{", "sendLocalBroadcast", "(", "\"", "start", "\"", ")", ";", "setupPreferences", "(", ")", ";", "if", "(", "dialog", ".", "isShowing", "(", ")", ")", "{", "dialog", ".", "dismiss", "(", ")", ";", "}", "Toast", ".", "makeText", "(", "getActivity", "(", ")", ",", "\"", "Database is Deleted", "\"", ",", "Toast", ".", "LENGTH_LONG", ")", ".", "show", "(", ")", ";", "if", "(", "getActivity", "(", ")", ".", "getIntent", "(", ")", ".", "getBooleanExtra", "(", "\"", "delete", "\"", ",", "false", ")", ")", "getActivity", "(", ")", ".", "finish", "(", ")", ";", "}", "}" ]
Nested class for asynchronously deleting the database data.
[ "Nested", "class", "for", "asynchronously", "deleting", "the", "database", "data", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
3352bbcdf35891480a075219d4b4ac5661ba1106
networkdowntime/search
src/main/java/net/networkdowntime/search/trie/Trie.java
[ "MIT" ]
Java
Trie
/** * Base class for implementing a trie or a partial trie. The trie can either a Suffix Trie or an Inverted Suffix Trie depending on the implementation of the abstract methods. * * This software is licensed under the MIT license Copyright (c) 2015 Ryan Wiles * * 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. * * @author rwiles * */
Base class for implementing a trie or a partial trie. The trie can either a Suffix Trie or an Inverted Suffix Trie depending on the implementation of the abstract methods. This software is licensed under the MIT license Copyright (c) 2015 Ryan Wiles 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. @author rwiles
[ "Base", "class", "for", "implementing", "a", "trie", "or", "a", "partial", "trie", ".", "The", "trie", "can", "either", "a", "Suffix", "Trie", "or", "an", "Inverted", "Suffix", "Trie", "depending", "on", "the", "implementation", "of", "the", "abstract", "methods", ".", "This", "software", "is", "licensed", "under", "the", "MIT", "license", "Copyright", "(", "c", ")", "2015", "Ryan", "Wiles", "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", ".", "@author", "rwiles" ]
public abstract class Trie { private static final Logger LOGGER = LogManager.getLogger(Trie.class.getName()); protected boolean createFullTrie = true; protected TrieNode rootNode = new TrieNode(); // tracks the maximium height of the tree private int height; /** * Default constructor generates a full suffix trie */ public Trie() { } /** * Allows the creator to create either a full of non-full trie * * @param createFullTrie */ public Trie(boolean createFullTrie) { this.createFullTrie = createFullTrie; } /** * Gets either the beginning or ending character from the word. Beginning character for a Suffix, ending for an Inverted Suffix * * @param word * @return */ protected abstract char getChar(String word); /** * Gets the character from the opposite end of the word than getChar() * * @param word * @return */ protected abstract char getOppositeChar(String word); /** * Removes a character from a end of the string and returns the substring. Remove the beginning character for a Suffix, ending for an Inverted Suffix * * @param word * @return */ protected abstract String getSubstring(String word); protected abstract String getSubstring(String word, int index); /** * Concatenates the character and the wordPart string and returns the new cost string. wordPart + c for Suffix, c + wordPart for Inverted Suffix * * @param c * @param wordPart * @param cost How much to increment the returned cost by * @return */ protected abstract CostString addCharToWordPart(char c, CostString wordPart, int cost); /** * Inserts the character into the wordPart string at the specified index and returns the new cost string. wordPart + c for Suffix, c + wordPart for Inverted Suffix * * @param c * @param wordPart * @param cost How much to increment the returned cost by * @return */ protected abstract CostString addCharToWordPart(char c, int index, CostString wordPart, int cost); /** * Inserts the character into the wordPart string at the specified index and returns the new cost string. wordPart + c for Suffix, c + wordPart for Inverted Suffix * * @param c * @param wordPart * @param cost How much to increment the returned cost by * @return */ protected abstract CostString deleteCharFromWordPart(int index, CostString wordPart, int cost); /** * Transposes the character at the specified index with the following character and returns the new cost string. * * @param c * @param wordPart * @param cost How much to increment the returned cost by * @return */ protected abstract CostString transposeCharsInWordPart(int startIndex, CostString wordPart, int cost); /** * Concatenates the character and the wordPart string and returns the new cost string. wordPart + c for Suffix, c + wordPart for Inverted Suffix * * @param c * @param wordPart * @param cost How much to increment the returned cost by * @return */ // protected abstract CostString addCharToWordPartBackwards(char c, CostString wordPart, int cost); /** * Gets a char[] in the correct order for node traversal to find completions. left to right for Suffix, reverse order for Inverted Suffix * * @param word * @return */ protected abstract char[] getCharArr(String word); /** * Adds a word to the trie * * @param word */ public int add(String word) { int cost = addInternal(rootNode, word, true, 0); if (word.length() > height) { height = word.length(); } return cost; } /** * Private internal method to recursively add the wordPart to the trie structure * * @param wordPart Word part to be added to the trie */ private int addInternal(TrieNode node, String wordPart, boolean isFullWord, int cost) { cost += 1; // LOGGER.debugprintln("\t\t" + this.getClass().getSimpleName() + // ": adding wordPart: " + wordPart + ", currentCost: " + cost); int length = wordPart.length(); node.children = (node.children != null) ? node.children : new TCharObjectHashMap<TrieNode>(1, 0.9f); char c = getChar(wordPart); TrieNode child = node.children.get(c); if (child == null) { child = new TrieNode(c); node.children.put(c, child); } if (length == 1) { // This is the end of the string and not on the root // node, add a child marker to denote end of suffix child.isEnd = true; child.isFullWordEnd = child.isFullWordEnd || isFullWord; } else { String subString = getSubstring(wordPart); cost += addInternal(child, subString, isFullWord, cost); if (createFullTrie && node.isRootNode()) { // full tree and root node cost += addInternal(node, subString, false, cost); } } return cost; } /** * Remove a word from the trie. Much more expensive than adding a word because the entire trie has to be walked to ensure nodes needed to ensure the integrity of the trie are not pruned. * * @param wordToRemove */ public void remove(String wordToRemove) { Set<String> wordsToPreserve = new HashSet<String>(); if (createFullTrie) { // have to account for all words that share a // character with wordToRemove getFullWordsForRemoval(rootNode, wordToRemove, wordsToPreserve, new CostString("", 0)); wordsToPreserve.remove(wordToRemove); } removeInternal(rootNode, wordToRemove, true, wordsToPreserve); } /** * Private internal method to recursively remove the wordPart from the trie structure * * @param node * @param wordPart * @param isFullWord * @param wordsToPreserve */ private void removeInternal(TrieNode node, String wordPart, boolean isFullWord, Set<String> wordsToPreserve) { int length = wordPart.length(); char c = getChar(wordPart); TrieNode child = node.children.get(c); boolean isRootNode = node.isRootNode(); boolean isPartOfWordToPreserve = false; for (String wordToPreserve : wordsToPreserve) { isPartOfWordToPreserve = isPartOfWordToPreserve || child.c == getOppositeChar(wordToPreserve); } if (length == 1) { child.isFullWordEnd = child.isFullWordEnd && !isFullWord; if (!isPartOfWordToPreserve || !createFullTrie) { child.isEnd = false; } if (!child.isEnd && !child.isFullWordEnd && child.children == null) { node.children.remove(c); } } else { String subString = getSubstring(wordPart); removeInternal(child, subString, isFullWord, wordsToPreserve); if (createFullTrie && isRootNode) { // full tree and root node removeInternal(node, subString, false, wordsToPreserve); } if (child.children.isEmpty() && !child.isEnd) { node.children.remove(child.c); } } } /** * Gets the completions from the trie for the given word part up to the limit. Walks the trie until it finds the last node for the word part and then calls getCompletionsInternal() to find the * completions. * * @param wordPart The word part to find completions for. * @param editDistanceMax Max edit distance for the requested completions * @param subStringOnly Assume that there are no typos in the wordPart (i.e. exact pattern match), use edit distance to only find word completions * @return A list of the completed words. */ public Set<CostString> getCompletions(CostString wordPart, int editDistanceMax, boolean subStringOnly) { LOGGER.debug(getClass().getSimpleName() + "(wordPart=" + wordPart.str + ";" + wordPart.cost + ", editDistanceMax=" + editDistanceMax + ", subStringOnly=" + subStringOnly + "):"); logs.add(getClass().getSimpleName() + "(wordPart=" + wordPart.str + ";" + wordPart.cost + ", editDistanceMax=" + editDistanceMax + ", subStringOnly=" + subStringOnly + "):"); CostStringSet<CostString> completions = new CostStringSet<CostString>(); CostStringSet<CostString> failures = new CostStringSet<CostString>(); getRootCompletions(completions, failures, wordPart, editDistanceMax, subStringOnly, 0); return completions; } private void getRootCompletions(CostStringSet<CostString> completions, CostStringSet<CostString> failures, CostString wordPart, int editDistanceMax, boolean subStringOnly, int tabs) { LOGGER.debug(getTabs(tabs) + "getRootCompletions(): '" + wordPart + "' - " + wordPart.cost + ", failures.size(): " + failures.size()); // try the exact wordPart first to handle no misspellings in the wordPart, but allow all completions CostString failure = failures.get(wordPart); if (failure == null || wordPart.cost < failure.cost) { getCompletionsWalkTree(completions, failures, rootNode, wordPart, 0, editDistanceMax, subStringOnly, tabs + 1); } else { LOGGER.debug(getTabs(tabs) + "\tFailure found for " + wordPart + " - " + wordPart.cost + ", skipping"); } if (!subStringOnly && wordPart.cost < editDistanceMax) { for (int i = 0; i < wordPart.length(); i++) { // find allowable deletions at current index CostString deletionMisspelling = deleteCharFromWordPart(i, wordPart, 1); LOGGER.debug(getTabs(tabs) + "\tdeleted char at index: " + i + "; new wordPart: '" + deletionMisspelling + "' - " + deletionMisspelling.cost); getRootCompletions(completions, failures, deletionMisspelling, editDistanceMax, subStringOnly, tabs + 1); } } } private boolean isValidPath(CostString wordPart, CostStringSet<CostString> completions, CostStringSet<CostString> failures, int tabs) { CostString failure = failures.get(wordPart); if (failure != null && failure.cost <= wordPart.cost) { LOGGER.debug(getTabs(tabs) + "isValidPath(): aborting search path due to previous failure at equal or lesser cost"); return false; } CostString completion = completions.get(wordPart); if (completion != null && completion.cost < wordPart.cost) { LOGGER.debug(getTabs(tabs) + "isValidPath(): aborting search path due to previous completion at equal or lesser cost"); return false; } return true; } private void getCompletionsWalkTree(CostStringSet<CostString> completions, CostStringSet<CostString> failures, TrieNode node, CostString wordPart, int startingWordPartIndex, int editDistanceMax, boolean subStringOnly, int tabs) { TrieNode currentNode = node; char[] charArray = getCharArr(wordPart.str); // walks the Trie based on the characters in the wordPart. fails if wordPart is not in Trie. for (int i = startingWordPartIndex; i < charArray.length; i++) { if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(getTabs(tabs) + "getCompletionsWalkTree(): index: " + i + "; char '" + charArray[i] + "'; " + wordPart + " - " + wordPart.cost + "; node char '" + currentNode.c + "'; children ["); if (currentNode.children != null) { for (TrieNode n : currentNode.children.valueCollection()) { sb.append(n.c + ", "); } } sb.append("]"); LOGGER.debug(sb.toString()); } if (!subStringOnly && currentNode != null && wordPart.cost < editDistanceMax) { // find allowable deletions at current index CostString deletionMisspelling = deleteCharFromWordPart(i, wordPart, 1); LOGGER.debug(getTabs(tabs) + "\tdeleted char at index: " + i + "; new wordPart: '" + deletionMisspelling + "' - " + deletionMisspelling.cost); if (isValidPath(deletionMisspelling, completions, failures, tabs + 1)) { getCompletionsWalkTree(completions, failures, currentNode, deletionMisspelling, i, editDistanceMax, subStringOnly, tabs + 1); } if (i + 1 < charArray.length) { // find allowable transpositions at current index CostString transposeMisspelling = transposeCharsInWordPart(i, wordPart, 1); LOGGER.debug(getTabs(tabs) + "\ttransposed characters at indexes: " + i + "," + (i + 1) + "; new wordPart: '" + transposeMisspelling + "'"); if (isValidPath(transposeMisspelling, completions, failures, tabs + 1)) { getCompletionsWalkTree(completions, failures, currentNode, transposeMisspelling, i, editDistanceMax, subStringOnly, tabs + 1); } } // find allowable insertion at current index if (currentNode.children != null) { for (TrieNode n : currentNode.children.valueCollection()) { if (i > 0) { CostString insertionMisspelling = addCharToWordPart(n.c, i, wordPart, 1); LOGGER.debug(getTabs(tabs) + "\tinserted '" + n.c + "' at index: " + (i + 1) + "; new wordPart: '" + insertionMisspelling + "'"); if (isValidPath(insertionMisspelling, completions, failures, tabs + 1)) { getCompletionsWalkTree(completions, failures, currentNode, insertionMisspelling, i, editDistanceMax, subStringOnly, tabs + 1); } } CostString replacementMisspelling = addCharToWordPart(n.c, i, deletionMisspelling, 0); LOGGER.debug(getTabs(tabs) + "\treplaced '" + n.c + "' at index: " + (i + 1) + "; new wordPart: " + replacementMisspelling + " - " + replacementMisspelling.cost); if (isValidPath(replacementMisspelling, completions, failures, tabs + 1)) { getCompletionsWalkTree(completions, failures, currentNode, replacementMisspelling, i, editDistanceMax, subStringOnly, tabs + 1); } } } } char c = charArray[i]; if (currentNode != null && currentNode.children != null) { currentNode = currentNode.children.get(c); } else { currentNode = null; } if (currentNode == null) { // no match in the part of the string processed so far // failures.add(wordPart); // The below can be replaced with the line above, but leaving it in for clearity in alg. analysis LOGGER.debug(getTabs(tabs) + "\tFailure for " + wordPart + " - " + wordPart.cost + " in getCompletionsExactWordPartMatch()"); CostString failure = failures.get(wordPart); if (failure != null && wordPart.cost < failure.cost) { // lower failure cost LOGGER.debug(getTabs(tabs) + "\tAdded failure for " + wordPart + " - " + wordPart.cost + " in getCompletionsExactWordPartMatch()"); logs.add(getTabs(tabs) + "\tAdded failure for " + wordPart + " - " + wordPart.cost + " in getCompletionsExactWordPartMatch()"); failures.add(wordPart); } return; // then return } } getCompletionsTailInsertions(completions, failures, currentNode, wordPart, editDistanceMax, subStringOnly, tabs + 1); } /** * Private internal method to walk the trie and find the completions beyond the wordPart, this is called from the last matching node of the suffix. Pre-condition, that the trie has been walked to * the end of the wordPart. * * @param node The current node * @param completions The list of completed words * @param wordPart The word being build up from walking the trie * @param size Tracks the number of found completions * @param limit Max number of results to return * @return the current number of completions */ private void getCompletionsTailInsertions(CostStringSet<CostString> completions, CostStringSet<CostString> failures, TrieNode node, CostString wordPart, int editDistanceMax, boolean subStringOnly, int tabs) { LOGGER.debug(getTabs(tabs) + "getCompletionsTailInsertions():"); if (node != null) { if (node.isEnd) { addCompletion(completions, wordPart, tabs); } if (node.children != null) { if (wordPart.cost < editDistanceMax) { for (Object obj : node.children.values()) { TrieNode child = (TrieNode) obj; getCompletionsTailInsertions(completions, failures, child, addCharToWordPart(child.c, wordPart, 1), editDistanceMax, subStringOnly, tabs); } } else { LOGGER.debug(getTabs(tabs) + "Stopped looking completions of '" + wordPart + "': wordPart.cost of " + wordPart.cost + " >= editDistanceMax of " + editDistanceMax); } } } } public static List<String> logs = new ArrayList<String>(); /** * Only adds the wordPart if it's not in completions or this wordPart has a lower cost than an existing completion for the same string * * @param completions The list of completed words * @param wordPart A completed word part, i.e. pattern match up to a end node */ private void addCompletion(CostStringSet<CostString> completions, CostString wordPart, int tabs) { // completions.add(wordPart); // The below can be replaced with the line above, but leaving it in for clearity in alg. analysis CostString existing = completions.get(wordPart); StringBuilder sb = new StringBuilder((getTabs(tabs) + "addCompletion(): " + wordPart + " - " + wordPart.cost)); if (existing == null) { completions.add(wordPart); sb.append(" added, hashcode = " + wordPart.hashCode() + " no previous existing"); } else if (wordPart.cost < existing.cost) { completions.add(wordPart); sb.append(" added, hashcode = " + wordPart.hashCode() + " lesser cost than existing: " + existing.cost); } else { sb.append(" already there with equal or lesser cost " + existing.cost + ", hashcode = " + wordPart.hashCode()); } logs.add(sb.toString()); LOGGER.debug(sb.toString()); } /** * Special method needed to support removing words from a non-partial (full) trie. For a given full word to remove, finds all of the words that could be impacted and need to be preserved. * * @param node The current node * @param wordToRemove A full word that is part of the trie to be removed * @param completions A list of the complete words that need to be preserved * @param wordBeingBuilt The word being build up from walking the trie */ private void getFullWordsForRemoval(TrieNode node, String wordToRemove, Set<String> completions, CostString wordBeingBuilt) { if (node.isFullWordEnd && node.isEnd && wordBeingBuilt.str.contains(wordToRemove)) { completions.add(wordBeingBuilt.str); } if (node.children != null) { if (node.isRootNode() && wordBeingBuilt.str.length() > 0) { // root node TrieNode child = node.children.get(getChar(wordBeingBuilt.str)); if (child != null) { getFullWordsForRemoval(child, wordToRemove, completions, wordBeingBuilt); } } else { for (Object obj : node.children.values()) { TrieNode child = (TrieNode) obj; getFullWordsForRemoval(child, wordToRemove, completions, addCharToWordPart(child.c, wordBeingBuilt, 0)); } } } } /** * Checks if the parameter is a known full word in the trie. * * @param wordCharArr The word to check if it is a known full word in the trie in getCharArr() ordering * @return true if the word is a known full word otherwise false */ public boolean containsWord(char[] wordCharArr, boolean fullWordMatch) { TrieNode currentNode = rootNode; for (char c : wordCharArr) { if (currentNode != null && currentNode.children != null) { currentNode = currentNode.children.get(c); } else { currentNode = null; } if (currentNode == null) { // no match return false; } } return !fullWordMatch || currentNode.isFullWordEnd; } /** * Gets the specified number of tabs as a string. * * @param tabSpaces * @return */ private String getTabs(int tabSpaces) { String tabs = ""; for (int i = 0; i < tabSpaces; i++) { tabs = tabs + "\t"; } return tabs; } /** * Prints the trie structure for inspection. */ public void print() { LOGGER.info(this.getClass().getSimpleName() + ":"); List<String> trace = getTrace(); for (String s : trace) { LOGGER.info(s); } } /** * Gets the trie structure as a list of strings. Used in the print() method and for unit testing. * * @return */ public List<String> getTrace() { return getTrace(rootNode, 0); } /** * Internal method to walk the trie and build up a readable string representation. * * @param node The current node * @param tabSpaces The number of tab spaces to track indentation * @return The trie structure as a list of strings */ private List<String> getTrace(TrieNode node, int tabSpaces) { List<String> trace = new ArrayList<String>(); String tabs = getTabs(tabSpaces); if (node.isRootNode()) { boolean isFirst = true; int childrenSize = (node.children == null) ? 0 : node.children.size(); StringBuilder buff = new StringBuilder(tabs + "Root Node: " + childrenSize + " children ["); if (node.children != null) { for (Object obj : node.children.values()) { buff.append(addCommaIfNeeded(isFirst)); buff.append(((TrieNode) obj).c); isFirst = false; } } buff.append("]"); trace.add(buff.toString()); } else { StringBuilder buff = new StringBuilder(tabs + "Child Node: " + node.c + ": " + ((node.children == null) ? "0" : node.children.size()) + " children ["); boolean isFirst = true; if (node.children != null) { for (Object obj : node.children.values()) { buff.append(addCommaIfNeeded(isFirst)); buff.append(((TrieNode) obj).c); isFirst = false; } } if (node.isEnd) { buff.append(addCommaIfNeeded(isFirst)); buff.append(Character.MAX_VALUE); isFirst = false; } if (node.isFullWordEnd) { buff.append(addCommaIfNeeded(isFirst)); buff.append("FWE"); isFirst = false; } buff.append("]"); trace.add(buff.toString()); } if (node.children != null) { for (Object obj : node.children.values()) { TrieNode childNode = (TrieNode) obj; trace.addAll(getTrace(childNode, tabSpaces + 1)); } } return trace; } private String addCommaIfNeeded(boolean isFirst) { return (isFirst) ? "" : ", "; } }
[ "public", "abstract", "class", "Trie", "{", "private", "static", "final", "Logger", "LOGGER", "=", "LogManager", ".", "getLogger", "(", "Trie", ".", "class", ".", "getName", "(", ")", ")", ";", "protected", "boolean", "createFullTrie", "=", "true", ";", "protected", "TrieNode", "rootNode", "=", "new", "TrieNode", "(", ")", ";", "private", "int", "height", ";", "/**\n\t * Default constructor generates a full suffix trie\n\t */", "public", "Trie", "(", ")", "{", "}", "/**\n\t * Allows the creator to create either a full of non-full trie\n\t * \n\t * @param createFullTrie\n\t */", "public", "Trie", "(", "boolean", "createFullTrie", ")", "{", "this", ".", "createFullTrie", "=", "createFullTrie", ";", "}", "/**\n\t * Gets either the beginning or ending character from the word. Beginning character for a Suffix, ending for an Inverted Suffix\n\t * \n\t * @param word\n\t * @return\n\t */", "protected", "abstract", "char", "getChar", "(", "String", "word", ")", ";", "/**\n\t * Gets the character from the opposite end of the word than getChar()\n\t * \n\t * @param word\n\t * @return\n\t */", "protected", "abstract", "char", "getOppositeChar", "(", "String", "word", ")", ";", "/**\n\t * Removes a character from a end of the string and returns the substring. Remove the beginning character for a Suffix, ending for an Inverted Suffix\n\t * \n\t * @param word\n\t * @return\n\t */", "protected", "abstract", "String", "getSubstring", "(", "String", "word", ")", ";", "protected", "abstract", "String", "getSubstring", "(", "String", "word", ",", "int", "index", ")", ";", "/**\n\t * Concatenates the character and the wordPart string and returns the new cost string. wordPart + c for Suffix, c + wordPart for Inverted Suffix\n\t * \n\t * @param c\n\t * @param wordPart\n\t * @param cost How much to increment the returned cost by\n\t * @return\n\t */", "protected", "abstract", "CostString", "addCharToWordPart", "(", "char", "c", ",", "CostString", "wordPart", ",", "int", "cost", ")", ";", "/**\n\t * Inserts the character into the wordPart string at the specified index and returns the new cost string. wordPart + c for Suffix, c + wordPart for Inverted Suffix\n\t * \n\t * @param c\n\t * @param wordPart\n\t * @param cost How much to increment the returned cost by\n\t * @return\n\t */", "protected", "abstract", "CostString", "addCharToWordPart", "(", "char", "c", ",", "int", "index", ",", "CostString", "wordPart", ",", "int", "cost", ")", ";", "/**\n\t * Inserts the character into the wordPart string at the specified index and returns the new cost string. wordPart + c for Suffix, c + wordPart for Inverted Suffix\n\t * \n\t * @param c\n\t * @param wordPart\n\t * @param cost How much to increment the returned cost by\n\t * @return\n\t */", "protected", "abstract", "CostString", "deleteCharFromWordPart", "(", "int", "index", ",", "CostString", "wordPart", ",", "int", "cost", ")", ";", "/**\n\t * Transposes the character at the specified index with the following character and returns the new cost string.\n\t * \n\t * @param c\n\t * @param wordPart\n\t * @param cost How much to increment the returned cost by\n\t * @return\n\t */", "protected", "abstract", "CostString", "transposeCharsInWordPart", "(", "int", "startIndex", ",", "CostString", "wordPart", ",", "int", "cost", ")", ";", "/**\n\t * Concatenates the character and the wordPart string and returns the new cost string. wordPart + c for Suffix, c + wordPart for Inverted Suffix\n\t * \n\t * @param c\n\t * @param wordPart\n\t * @param cost How much to increment the returned cost by\n\t * @return\n\t */", "/**\n\t * Gets a char[] in the correct order for node traversal to find completions. left to right for Suffix, reverse order for Inverted Suffix\n\t * \n\t * @param word\n\t * @return\n\t */", "protected", "abstract", "char", "[", "]", "getCharArr", "(", "String", "word", ")", ";", "/**\n\t * Adds a word to the trie\n\t * \n\t * @param word\n\t */", "public", "int", "add", "(", "String", "word", ")", "{", "int", "cost", "=", "addInternal", "(", "rootNode", ",", "word", ",", "true", ",", "0", ")", ";", "if", "(", "word", ".", "length", "(", ")", ">", "height", ")", "{", "height", "=", "word", ".", "length", "(", ")", ";", "}", "return", "cost", ";", "}", "/**\n\t * Private internal method to recursively add the wordPart to the trie structure\n\t * \n\t * @param wordPart Word part to be added to the trie\n\t */", "private", "int", "addInternal", "(", "TrieNode", "node", ",", "String", "wordPart", ",", "boolean", "isFullWord", ",", "int", "cost", ")", "{", "cost", "+=", "1", ";", "int", "length", "=", "wordPart", ".", "length", "(", ")", ";", "node", ".", "children", "=", "(", "node", ".", "children", "!=", "null", ")", "?", "node", ".", "children", ":", "new", "TCharObjectHashMap", "<", "TrieNode", ">", "(", "1", ",", "0.9f", ")", ";", "char", "c", "=", "getChar", "(", "wordPart", ")", ";", "TrieNode", "child", "=", "node", ".", "children", ".", "get", "(", "c", ")", ";", "if", "(", "child", "==", "null", ")", "{", "child", "=", "new", "TrieNode", "(", "c", ")", ";", "node", ".", "children", ".", "put", "(", "c", ",", "child", ")", ";", "}", "if", "(", "length", "==", "1", ")", "{", "child", ".", "isEnd", "=", "true", ";", "child", ".", "isFullWordEnd", "=", "child", ".", "isFullWordEnd", "||", "isFullWord", ";", "}", "else", "{", "String", "subString", "=", "getSubstring", "(", "wordPart", ")", ";", "cost", "+=", "addInternal", "(", "child", ",", "subString", ",", "isFullWord", ",", "cost", ")", ";", "if", "(", "createFullTrie", "&&", "node", ".", "isRootNode", "(", ")", ")", "{", "cost", "+=", "addInternal", "(", "node", ",", "subString", ",", "false", ",", "cost", ")", ";", "}", "}", "return", "cost", ";", "}", "/**\n\t * Remove a word from the trie. Much more expensive than adding a word because the entire trie has to be walked to ensure nodes needed to ensure the integrity of the trie are not pruned.\n\t * \n\t * @param wordToRemove\n\t */", "public", "void", "remove", "(", "String", "wordToRemove", ")", "{", "Set", "<", "String", ">", "wordsToPreserve", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "if", "(", "createFullTrie", ")", "{", "getFullWordsForRemoval", "(", "rootNode", ",", "wordToRemove", ",", "wordsToPreserve", ",", "new", "CostString", "(", "\"", "\"", ",", "0", ")", ")", ";", "wordsToPreserve", ".", "remove", "(", "wordToRemove", ")", ";", "}", "removeInternal", "(", "rootNode", ",", "wordToRemove", ",", "true", ",", "wordsToPreserve", ")", ";", "}", "/**\n\t * Private internal method to recursively remove the wordPart from the trie structure\n\t * \n\t * @param node\n\t * @param wordPart\n\t * @param isFullWord\n\t * @param wordsToPreserve\n\t */", "private", "void", "removeInternal", "(", "TrieNode", "node", ",", "String", "wordPart", ",", "boolean", "isFullWord", ",", "Set", "<", "String", ">", "wordsToPreserve", ")", "{", "int", "length", "=", "wordPart", ".", "length", "(", ")", ";", "char", "c", "=", "getChar", "(", "wordPart", ")", ";", "TrieNode", "child", "=", "node", ".", "children", ".", "get", "(", "c", ")", ";", "boolean", "isRootNode", "=", "node", ".", "isRootNode", "(", ")", ";", "boolean", "isPartOfWordToPreserve", "=", "false", ";", "for", "(", "String", "wordToPreserve", ":", "wordsToPreserve", ")", "{", "isPartOfWordToPreserve", "=", "isPartOfWordToPreserve", "||", "child", ".", "c", "==", "getOppositeChar", "(", "wordToPreserve", ")", ";", "}", "if", "(", "length", "==", "1", ")", "{", "child", ".", "isFullWordEnd", "=", "child", ".", "isFullWordEnd", "&&", "!", "isFullWord", ";", "if", "(", "!", "isPartOfWordToPreserve", "||", "!", "createFullTrie", ")", "{", "child", ".", "isEnd", "=", "false", ";", "}", "if", "(", "!", "child", ".", "isEnd", "&&", "!", "child", ".", "isFullWordEnd", "&&", "child", ".", "children", "==", "null", ")", "{", "node", ".", "children", ".", "remove", "(", "c", ")", ";", "}", "}", "else", "{", "String", "subString", "=", "getSubstring", "(", "wordPart", ")", ";", "removeInternal", "(", "child", ",", "subString", ",", "isFullWord", ",", "wordsToPreserve", ")", ";", "if", "(", "createFullTrie", "&&", "isRootNode", ")", "{", "removeInternal", "(", "node", ",", "subString", ",", "false", ",", "wordsToPreserve", ")", ";", "}", "if", "(", "child", ".", "children", ".", "isEmpty", "(", ")", "&&", "!", "child", ".", "isEnd", ")", "{", "node", ".", "children", ".", "remove", "(", "child", ".", "c", ")", ";", "}", "}", "}", "/**\n\t * Gets the completions from the trie for the given word part up to the limit. Walks the trie until it finds the last node for the word part and then calls getCompletionsInternal() to find the\n\t * completions.\n\t * \n\t * @param wordPart The word part to find completions for.\n\t * @param editDistanceMax Max edit distance for the requested completions\n\t * @param subStringOnly Assume that there are no typos in the wordPart (i.e. exact pattern match), use edit distance to only find word completions\n\t * @return A list of the completed words.\n\t */", "public", "Set", "<", "CostString", ">", "getCompletions", "(", "CostString", "wordPart", ",", "int", "editDistanceMax", ",", "boolean", "subStringOnly", ")", "{", "LOGGER", ".", "debug", "(", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\"", "(wordPart=", "\"", "+", "wordPart", ".", "str", "+", "\"", ";", "\"", "+", "wordPart", ".", "cost", "+", "\"", ", editDistanceMax=", "\"", "+", "editDistanceMax", "+", "\"", ", subStringOnly=", "\"", "+", "subStringOnly", "+", "\"", "):", "\"", ")", ";", "logs", ".", "add", "(", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\"", "(wordPart=", "\"", "+", "wordPart", ".", "str", "+", "\"", ";", "\"", "+", "wordPart", ".", "cost", "+", "\"", ", editDistanceMax=", "\"", "+", "editDistanceMax", "+", "\"", ", subStringOnly=", "\"", "+", "subStringOnly", "+", "\"", "):", "\"", ")", ";", "CostStringSet", "<", "CostString", ">", "completions", "=", "new", "CostStringSet", "<", "CostString", ">", "(", ")", ";", "CostStringSet", "<", "CostString", ">", "failures", "=", "new", "CostStringSet", "<", "CostString", ">", "(", ")", ";", "getRootCompletions", "(", "completions", ",", "failures", ",", "wordPart", ",", "editDistanceMax", ",", "subStringOnly", ",", "0", ")", ";", "return", "completions", ";", "}", "private", "void", "getRootCompletions", "(", "CostStringSet", "<", "CostString", ">", "completions", ",", "CostStringSet", "<", "CostString", ">", "failures", ",", "CostString", "wordPart", ",", "int", "editDistanceMax", ",", "boolean", "subStringOnly", ",", "int", "tabs", ")", "{", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "getRootCompletions(): '", "\"", "+", "wordPart", "+", "\"", "' - ", "\"", "+", "wordPart", ".", "cost", "+", "\"", ", failures.size(): ", "\"", "+", "failures", ".", "size", "(", ")", ")", ";", "CostString", "failure", "=", "failures", ".", "get", "(", "wordPart", ")", ";", "if", "(", "failure", "==", "null", "||", "wordPart", ".", "cost", "<", "failure", ".", "cost", ")", "{", "getCompletionsWalkTree", "(", "completions", ",", "failures", ",", "rootNode", ",", "wordPart", ",", "0", ",", "editDistanceMax", ",", "subStringOnly", ",", "tabs", "+", "1", ")", ";", "}", "else", "{", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "Failure found for ", "\"", "+", "wordPart", "+", "\"", " - ", "\"", "+", "wordPart", ".", "cost", "+", "\"", ", skipping", "\"", ")", ";", "}", "if", "(", "!", "subStringOnly", "&&", "wordPart", ".", "cost", "<", "editDistanceMax", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "wordPart", ".", "length", "(", ")", ";", "i", "++", ")", "{", "CostString", "deletionMisspelling", "=", "deleteCharFromWordPart", "(", "i", ",", "wordPart", ",", "1", ")", ";", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "deleted char at index: ", "\"", "+", "i", "+", "\"", "; new wordPart: '", "\"", "+", "deletionMisspelling", "+", "\"", "' - ", "\"", "+", "deletionMisspelling", ".", "cost", ")", ";", "getRootCompletions", "(", "completions", ",", "failures", ",", "deletionMisspelling", ",", "editDistanceMax", ",", "subStringOnly", ",", "tabs", "+", "1", ")", ";", "}", "}", "}", "private", "boolean", "isValidPath", "(", "CostString", "wordPart", ",", "CostStringSet", "<", "CostString", ">", "completions", ",", "CostStringSet", "<", "CostString", ">", "failures", ",", "int", "tabs", ")", "{", "CostString", "failure", "=", "failures", ".", "get", "(", "wordPart", ")", ";", "if", "(", "failure", "!=", "null", "&&", "failure", ".", "cost", "<=", "wordPart", ".", "cost", ")", "{", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "isValidPath(): aborting search path due to previous failure at equal or lesser cost", "\"", ")", ";", "return", "false", ";", "}", "CostString", "completion", "=", "completions", ".", "get", "(", "wordPart", ")", ";", "if", "(", "completion", "!=", "null", "&&", "completion", ".", "cost", "<", "wordPart", ".", "cost", ")", "{", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "isValidPath(): aborting search path due to previous completion at equal or lesser cost", "\"", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}", "private", "void", "getCompletionsWalkTree", "(", "CostStringSet", "<", "CostString", ">", "completions", ",", "CostStringSet", "<", "CostString", ">", "failures", ",", "TrieNode", "node", ",", "CostString", "wordPart", ",", "int", "startingWordPartIndex", ",", "int", "editDistanceMax", ",", "boolean", "subStringOnly", ",", "int", "tabs", ")", "{", "TrieNode", "currentNode", "=", "node", ";", "char", "[", "]", "charArray", "=", "getCharArr", "(", "wordPart", ".", "str", ")", ";", "for", "(", "int", "i", "=", "startingWordPartIndex", ";", "i", "<", "charArray", ".", "length", ";", "i", "++", ")", "{", "if", "(", "LOGGER", ".", "isDebugEnabled", "(", ")", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "getTabs", "(", "tabs", ")", "+", "\"", "getCompletionsWalkTree(): index: ", "\"", "+", "i", "+", "\"", "; char '", "\"", "+", "charArray", "[", "i", "]", "+", "\"", "'; ", "\"", "+", "wordPart", "+", "\"", " - ", "\"", "+", "wordPart", ".", "cost", "+", "\"", "; node char '", "\"", "+", "currentNode", ".", "c", "+", "\"", "'; children [", "\"", ")", ";", "if", "(", "currentNode", ".", "children", "!=", "null", ")", "{", "for", "(", "TrieNode", "n", ":", "currentNode", ".", "children", ".", "valueCollection", "(", ")", ")", "{", "sb", ".", "append", "(", "n", ".", "c", "+", "\"", ", ", "\"", ")", ";", "}", "}", "sb", ".", "append", "(", "\"", "]", "\"", ")", ";", "LOGGER", ".", "debug", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "if", "(", "!", "subStringOnly", "&&", "currentNode", "!=", "null", "&&", "wordPart", ".", "cost", "<", "editDistanceMax", ")", "{", "CostString", "deletionMisspelling", "=", "deleteCharFromWordPart", "(", "i", ",", "wordPart", ",", "1", ")", ";", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "deleted char at index: ", "\"", "+", "i", "+", "\"", "; new wordPart: '", "\"", "+", "deletionMisspelling", "+", "\"", "' - ", "\"", "+", "deletionMisspelling", ".", "cost", ")", ";", "if", "(", "isValidPath", "(", "deletionMisspelling", ",", "completions", ",", "failures", ",", "tabs", "+", "1", ")", ")", "{", "getCompletionsWalkTree", "(", "completions", ",", "failures", ",", "currentNode", ",", "deletionMisspelling", ",", "i", ",", "editDistanceMax", ",", "subStringOnly", ",", "tabs", "+", "1", ")", ";", "}", "if", "(", "i", "+", "1", "<", "charArray", ".", "length", ")", "{", "CostString", "transposeMisspelling", "=", "transposeCharsInWordPart", "(", "i", ",", "wordPart", ",", "1", ")", ";", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "transposed characters at indexes: ", "\"", "+", "i", "+", "\"", ",", "\"", "+", "(", "i", "+", "1", ")", "+", "\"", "; new wordPart: '", "\"", "+", "transposeMisspelling", "+", "\"", "'", "\"", ")", ";", "if", "(", "isValidPath", "(", "transposeMisspelling", ",", "completions", ",", "failures", ",", "tabs", "+", "1", ")", ")", "{", "getCompletionsWalkTree", "(", "completions", ",", "failures", ",", "currentNode", ",", "transposeMisspelling", ",", "i", ",", "editDistanceMax", ",", "subStringOnly", ",", "tabs", "+", "1", ")", ";", "}", "}", "if", "(", "currentNode", ".", "children", "!=", "null", ")", "{", "for", "(", "TrieNode", "n", ":", "currentNode", ".", "children", ".", "valueCollection", "(", ")", ")", "{", "if", "(", "i", ">", "0", ")", "{", "CostString", "insertionMisspelling", "=", "addCharToWordPart", "(", "n", ".", "c", ",", "i", ",", "wordPart", ",", "1", ")", ";", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "inserted '", "\"", "+", "n", ".", "c", "+", "\"", "' at index: ", "\"", "+", "(", "i", "+", "1", ")", "+", "\"", "; new wordPart: '", "\"", "+", "insertionMisspelling", "+", "\"", "'", "\"", ")", ";", "if", "(", "isValidPath", "(", "insertionMisspelling", ",", "completions", ",", "failures", ",", "tabs", "+", "1", ")", ")", "{", "getCompletionsWalkTree", "(", "completions", ",", "failures", ",", "currentNode", ",", "insertionMisspelling", ",", "i", ",", "editDistanceMax", ",", "subStringOnly", ",", "tabs", "+", "1", ")", ";", "}", "}", "CostString", "replacementMisspelling", "=", "addCharToWordPart", "(", "n", ".", "c", ",", "i", ",", "deletionMisspelling", ",", "0", ")", ";", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "replaced '", "\"", "+", "n", ".", "c", "+", "\"", "' at index: ", "\"", "+", "(", "i", "+", "1", ")", "+", "\"", "; new wordPart: ", "\"", "+", "replacementMisspelling", "+", "\"", " - ", "\"", "+", "replacementMisspelling", ".", "cost", ")", ";", "if", "(", "isValidPath", "(", "replacementMisspelling", ",", "completions", ",", "failures", ",", "tabs", "+", "1", ")", ")", "{", "getCompletionsWalkTree", "(", "completions", ",", "failures", ",", "currentNode", ",", "replacementMisspelling", ",", "i", ",", "editDistanceMax", ",", "subStringOnly", ",", "tabs", "+", "1", ")", ";", "}", "}", "}", "}", "char", "c", "=", "charArray", "[", "i", "]", ";", "if", "(", "currentNode", "!=", "null", "&&", "currentNode", ".", "children", "!=", "null", ")", "{", "currentNode", "=", "currentNode", ".", "children", ".", "get", "(", "c", ")", ";", "}", "else", "{", "currentNode", "=", "null", ";", "}", "if", "(", "currentNode", "==", "null", ")", "{", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "Failure for ", "\"", "+", "wordPart", "+", "\"", " - ", "\"", "+", "wordPart", ".", "cost", "+", "\"", " in getCompletionsExactWordPartMatch()", "\"", ")", ";", "CostString", "failure", "=", "failures", ".", "get", "(", "wordPart", ")", ";", "if", "(", "failure", "!=", "null", "&&", "wordPart", ".", "cost", "<", "failure", ".", "cost", ")", "{", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "Added failure for ", "\"", "+", "wordPart", "+", "\"", " - ", "\"", "+", "wordPart", ".", "cost", "+", "\"", " in getCompletionsExactWordPartMatch()", "\"", ")", ";", "logs", ".", "add", "(", "getTabs", "(", "tabs", ")", "+", "\"", "\\t", "Added failure for ", "\"", "+", "wordPart", "+", "\"", " - ", "\"", "+", "wordPart", ".", "cost", "+", "\"", " in getCompletionsExactWordPartMatch()", "\"", ")", ";", "failures", ".", "add", "(", "wordPart", ")", ";", "}", "return", ";", "}", "}", "getCompletionsTailInsertions", "(", "completions", ",", "failures", ",", "currentNode", ",", "wordPart", ",", "editDistanceMax", ",", "subStringOnly", ",", "tabs", "+", "1", ")", ";", "}", "/**\n\t * Private internal method to walk the trie and find the completions beyond the wordPart, this is called from the last matching node of the suffix. Pre-condition, that the trie has been walked to\n\t * the end of the wordPart.\n\t * \n\t * @param node The current node\n\t * @param completions The list of completed words\n\t * @param wordPart The word being build up from walking the trie\n\t * @param size Tracks the number of found completions\n\t * @param limit Max number of results to return\n\t * @return the current number of completions\n\t */", "private", "void", "getCompletionsTailInsertions", "(", "CostStringSet", "<", "CostString", ">", "completions", ",", "CostStringSet", "<", "CostString", ">", "failures", ",", "TrieNode", "node", ",", "CostString", "wordPart", ",", "int", "editDistanceMax", ",", "boolean", "subStringOnly", ",", "int", "tabs", ")", "{", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "getCompletionsTailInsertions():", "\"", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "if", "(", "node", ".", "isEnd", ")", "{", "addCompletion", "(", "completions", ",", "wordPart", ",", "tabs", ")", ";", "}", "if", "(", "node", ".", "children", "!=", "null", ")", "{", "if", "(", "wordPart", ".", "cost", "<", "editDistanceMax", ")", "{", "for", "(", "Object", "obj", ":", "node", ".", "children", ".", "values", "(", ")", ")", "{", "TrieNode", "child", "=", "(", "TrieNode", ")", "obj", ";", "getCompletionsTailInsertions", "(", "completions", ",", "failures", ",", "child", ",", "addCharToWordPart", "(", "child", ".", "c", ",", "wordPart", ",", "1", ")", ",", "editDistanceMax", ",", "subStringOnly", ",", "tabs", ")", ";", "}", "}", "else", "{", "LOGGER", ".", "debug", "(", "getTabs", "(", "tabs", ")", "+", "\"", "Stopped looking completions of '", "\"", "+", "wordPart", "+", "\"", "': wordPart.cost of ", "\"", "+", "wordPart", ".", "cost", "+", "\"", " >= editDistanceMax of ", "\"", "+", "editDistanceMax", ")", ";", "}", "}", "}", "}", "public", "static", "List", "<", "String", ">", "logs", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "/**\n\t * Only adds the wordPart if it's not in completions or this wordPart has a lower cost than an existing completion for the same string\n\t * \n\t * @param completions The list of completed words\n\t * @param wordPart A completed word part, i.e. pattern match up to a end node\n\t */", "private", "void", "addCompletion", "(", "CostStringSet", "<", "CostString", ">", "completions", ",", "CostString", "wordPart", ",", "int", "tabs", ")", "{", "CostString", "existing", "=", "completions", ".", "get", "(", "wordPart", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "(", "getTabs", "(", "tabs", ")", "+", "\"", "addCompletion(): ", "\"", "+", "wordPart", "+", "\"", " - ", "\"", "+", "wordPart", ".", "cost", ")", ")", ";", "if", "(", "existing", "==", "null", ")", "{", "completions", ".", "add", "(", "wordPart", ")", ";", "sb", ".", "append", "(", "\"", " added, hashcode = ", "\"", "+", "wordPart", ".", "hashCode", "(", ")", "+", "\"", " no previous existing", "\"", ")", ";", "}", "else", "if", "(", "wordPart", ".", "cost", "<", "existing", ".", "cost", ")", "{", "completions", ".", "add", "(", "wordPart", ")", ";", "sb", ".", "append", "(", "\"", " added, hashcode = ", "\"", "+", "wordPart", ".", "hashCode", "(", ")", "+", "\"", " lesser cost than existing: ", "\"", "+", "existing", ".", "cost", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", " already there with equal or lesser cost ", "\"", "+", "existing", ".", "cost", "+", "\"", ", hashcode = ", "\"", "+", "wordPart", ".", "hashCode", "(", ")", ")", ";", "}", "logs", ".", "add", "(", "sb", ".", "toString", "(", ")", ")", ";", "LOGGER", ".", "debug", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "/**\n\t * Special method needed to support removing words from a non-partial (full) trie. For a given full word to remove, finds all of the words that could be impacted and need to be preserved.\n\t * \n\t * @param node The current node\n\t * @param wordToRemove A full word that is part of the trie to be removed\n\t * @param completions A list of the complete words that need to be preserved\n\t * @param wordBeingBuilt The word being build up from walking the trie\n\t */", "private", "void", "getFullWordsForRemoval", "(", "TrieNode", "node", ",", "String", "wordToRemove", ",", "Set", "<", "String", ">", "completions", ",", "CostString", "wordBeingBuilt", ")", "{", "if", "(", "node", ".", "isFullWordEnd", "&&", "node", ".", "isEnd", "&&", "wordBeingBuilt", ".", "str", ".", "contains", "(", "wordToRemove", ")", ")", "{", "completions", ".", "add", "(", "wordBeingBuilt", ".", "str", ")", ";", "}", "if", "(", "node", ".", "children", "!=", "null", ")", "{", "if", "(", "node", ".", "isRootNode", "(", ")", "&&", "wordBeingBuilt", ".", "str", ".", "length", "(", ")", ">", "0", ")", "{", "TrieNode", "child", "=", "node", ".", "children", ".", "get", "(", "getChar", "(", "wordBeingBuilt", ".", "str", ")", ")", ";", "if", "(", "child", "!=", "null", ")", "{", "getFullWordsForRemoval", "(", "child", ",", "wordToRemove", ",", "completions", ",", "wordBeingBuilt", ")", ";", "}", "}", "else", "{", "for", "(", "Object", "obj", ":", "node", ".", "children", ".", "values", "(", ")", ")", "{", "TrieNode", "child", "=", "(", "TrieNode", ")", "obj", ";", "getFullWordsForRemoval", "(", "child", ",", "wordToRemove", ",", "completions", ",", "addCharToWordPart", "(", "child", ".", "c", ",", "wordBeingBuilt", ",", "0", ")", ")", ";", "}", "}", "}", "}", "/**\n\t * Checks if the parameter is a known full word in the trie.\n\t * \n\t * @param wordCharArr The word to check if it is a known full word in the trie in getCharArr() ordering\n\t * @return true if the word is a known full word otherwise false\n\t */", "public", "boolean", "containsWord", "(", "char", "[", "]", "wordCharArr", ",", "boolean", "fullWordMatch", ")", "{", "TrieNode", "currentNode", "=", "rootNode", ";", "for", "(", "char", "c", ":", "wordCharArr", ")", "{", "if", "(", "currentNode", "!=", "null", "&&", "currentNode", ".", "children", "!=", "null", ")", "{", "currentNode", "=", "currentNode", ".", "children", ".", "get", "(", "c", ")", ";", "}", "else", "{", "currentNode", "=", "null", ";", "}", "if", "(", "currentNode", "==", "null", ")", "{", "return", "false", ";", "}", "}", "return", "!", "fullWordMatch", "||", "currentNode", ".", "isFullWordEnd", ";", "}", "/**\n\t * Gets the specified number of tabs as a string.\n\t * \n\t * @param tabSpaces\n\t * @return\n\t */", "private", "String", "getTabs", "(", "int", "tabSpaces", ")", "{", "String", "tabs", "=", "\"", "\"", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tabSpaces", ";", "i", "++", ")", "{", "tabs", "=", "tabs", "+", "\"", "\\t", "\"", ";", "}", "return", "tabs", ";", "}", "/**\n\t * Prints the trie structure for inspection.\n\t */", "public", "void", "print", "(", ")", "{", "LOGGER", ".", "info", "(", "this", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\"", ":", "\"", ")", ";", "List", "<", "String", ">", "trace", "=", "getTrace", "(", ")", ";", "for", "(", "String", "s", ":", "trace", ")", "{", "LOGGER", ".", "info", "(", "s", ")", ";", "}", "}", "/**\n\t * Gets the trie structure as a list of strings. Used in the print() method and for unit testing.\n\t * \n\t * @return\n\t */", "public", "List", "<", "String", ">", "getTrace", "(", ")", "{", "return", "getTrace", "(", "rootNode", ",", "0", ")", ";", "}", "/**\n\t * Internal method to walk the trie and build up a readable string representation.\n\t * \n\t * @param node The current node\n\t * @param tabSpaces The number of tab spaces to track indentation\n\t * @return The trie structure as a list of strings\n\t */", "private", "List", "<", "String", ">", "getTrace", "(", "TrieNode", "node", ",", "int", "tabSpaces", ")", "{", "List", "<", "String", ">", "trace", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "String", "tabs", "=", "getTabs", "(", "tabSpaces", ")", ";", "if", "(", "node", ".", "isRootNode", "(", ")", ")", "{", "boolean", "isFirst", "=", "true", ";", "int", "childrenSize", "=", "(", "node", ".", "children", "==", "null", ")", "?", "0", ":", "node", ".", "children", ".", "size", "(", ")", ";", "StringBuilder", "buff", "=", "new", "StringBuilder", "(", "tabs", "+", "\"", "Root Node: ", "\"", "+", "childrenSize", "+", "\"", " children [", "\"", ")", ";", "if", "(", "node", ".", "children", "!=", "null", ")", "{", "for", "(", "Object", "obj", ":", "node", ".", "children", ".", "values", "(", ")", ")", "{", "buff", ".", "append", "(", "addCommaIfNeeded", "(", "isFirst", ")", ")", ";", "buff", ".", "append", "(", "(", "(", "TrieNode", ")", "obj", ")", ".", "c", ")", ";", "isFirst", "=", "false", ";", "}", "}", "buff", ".", "append", "(", "\"", "]", "\"", ")", ";", "trace", ".", "add", "(", "buff", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "StringBuilder", "buff", "=", "new", "StringBuilder", "(", "tabs", "+", "\"", "Child Node: ", "\"", "+", "node", ".", "c", "+", "\"", ": ", "\"", "+", "(", "(", "node", ".", "children", "==", "null", ")", "?", "\"", "0", "\"", ":", "node", ".", "children", ".", "size", "(", ")", ")", "+", "\"", " children [", "\"", ")", ";", "boolean", "isFirst", "=", "true", ";", "if", "(", "node", ".", "children", "!=", "null", ")", "{", "for", "(", "Object", "obj", ":", "node", ".", "children", ".", "values", "(", ")", ")", "{", "buff", ".", "append", "(", "addCommaIfNeeded", "(", "isFirst", ")", ")", ";", "buff", ".", "append", "(", "(", "(", "TrieNode", ")", "obj", ")", ".", "c", ")", ";", "isFirst", "=", "false", ";", "}", "}", "if", "(", "node", ".", "isEnd", ")", "{", "buff", ".", "append", "(", "addCommaIfNeeded", "(", "isFirst", ")", ")", ";", "buff", ".", "append", "(", "Character", ".", "MAX_VALUE", ")", ";", "isFirst", "=", "false", ";", "}", "if", "(", "node", ".", "isFullWordEnd", ")", "{", "buff", ".", "append", "(", "addCommaIfNeeded", "(", "isFirst", ")", ")", ";", "buff", ".", "append", "(", "\"", "FWE", "\"", ")", ";", "isFirst", "=", "false", ";", "}", "buff", ".", "append", "(", "\"", "]", "\"", ")", ";", "trace", ".", "add", "(", "buff", ".", "toString", "(", ")", ")", ";", "}", "if", "(", "node", ".", "children", "!=", "null", ")", "{", "for", "(", "Object", "obj", ":", "node", ".", "children", ".", "values", "(", ")", ")", "{", "TrieNode", "childNode", "=", "(", "TrieNode", ")", "obj", ";", "trace", ".", "addAll", "(", "getTrace", "(", "childNode", ",", "tabSpaces", "+", "1", ")", ")", ";", "}", "}", "return", "trace", ";", "}", "private", "String", "addCommaIfNeeded", "(", "boolean", "isFirst", ")", "{", "return", "(", "isFirst", ")", "?", "\"", "\"", ":", "\"", ", ", "\"", ";", "}", "}" ]
Base class for implementing a trie or a partial trie.
[ "Base", "class", "for", "implementing", "a", "trie", "or", "a", "partial", "trie", "." ]
[ "// tracks the maximium height of the tree", "//\tprotected abstract CostString addCharToWordPartBackwards(char c, CostString wordPart, int cost);", "// LOGGER.debugprintln(\"\\t\\t\" + this.getClass().getSimpleName() +", "// \": adding wordPart: \" + wordPart + \", currentCost: \" + cost);", "// This is the end of the string and not on the root", "// node, add a child marker to denote end of suffix", "// full tree and root node", "// have to account for all words that share a", "// character with wordToRemove", "// full tree and root node", "// try the exact wordPart first to handle no misspellings in the wordPart, but allow all completions", "// find allowable deletions at current index", "// walks the Trie based on the characters in the wordPart. fails if wordPart is not in Trie.", "// find allowable deletions at current index", "// find allowable transpositions at current index", "// find allowable insertion at current index", "// no match in the part of the string processed so far", "// \t\t\t\t\tfailures.add(wordPart);", "// The below can be replaced with the line above, but leaving it in for clearity in alg. analysis", "// lower failure cost", "// then return", "//\t\tcompletions.add(wordPart);", "// The below can be replaced with the line above, but leaving it in for clearity in alg. analysis", "// root node", "// no match" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
3357b9436c37647977eda4603459943acf672d5f
TheOverLordKotan/cxf-basic-example
src/main/java/org/adarchitecture/ws/user/common/basic/ObjectFactory.java
[ "Apache-2.0" ]
Java
ObjectFactory
/** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.adarchitecture.user.common.basic package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */
This object contains factory methods for each Java content interface and Java element interface generated in the org.adarchitecture.user.common.basic package. An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. The Java representation of XML content can consist of schema derived interfaces and classes representing the binding of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in this class.
[ "This", "object", "contains", "factory", "methods", "for", "each", "Java", "content", "interface", "and", "Java", "element", "interface", "generated", "in", "the", "org", ".", "adarchitecture", ".", "user", ".", "common", ".", "basic", "package", ".", "An", "ObjectFactory", "allows", "you", "to", "programatically", "construct", "new", "instances", "of", "the", "Java", "representation", "for", "XML", "content", ".", "The", "Java", "representation", "of", "XML", "content", "can", "consist", "of", "schema", "derived", "interfaces", "and", "classes", "representing", "the", "binding", "of", "schema", "type", "definitions", "element", "declarations", "and", "model", "groups", ".", "Factory", "methods", "for", "each", "of", "these", "are", "provided", "in", "this", "class", "." ]
@XmlRegistry public class ObjectFactory { private final static QName _TipoDocumento_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "tipoDocumento"); private final static QName _NumeroIdentificacion_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "numeroIdentificacion"); private final static QName _PrimerApellido_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "primerApellido"); private final static QName _SegundoApellido_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "segundoApellido"); private final static QName _PrimerNombre_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "primerNombre"); private final static QName _SegundoNombre_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "segundoNombre"); private final static QName _TipoPersona_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "tipoPersona"); private final static QName _FechaCreacion_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "fechaCreacion"); private final static QName _CodRespuesta_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "codRespuesta"); private final static QName _CodRespuestaEquivalente_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "codRespuestaEquivalente"); private final static QName _MsgRespuesta_QNAME = new QName("org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "msgRespuesta"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.adarchitecture.user.common.basic * */ public ObjectFactory() { } /** * Create an instance of {@link TipoDocumentoType } * */ public TipoDocumentoType createTipoDocumentoType() { return new TipoDocumentoType(); } /** * Create an instance of {@link NumeroDocumentoType } * */ public NumeroDocumentoType createNumeroDocumentoType() { return new NumeroDocumentoType(); } /** * Create an instance of {@link PrimerApellidoType } * */ public PrimerApellidoType createPrimerApellidoType() { return new PrimerApellidoType(); } /** * Create an instance of {@link SegundoApellidoType } * */ public SegundoApellidoType createSegundoApellidoType() { return new SegundoApellidoType(); } /** * Create an instance of {@link PrimerNombreType } * */ public PrimerNombreType createPrimerNombreType() { return new PrimerNombreType(); } /** * Create an instance of {@link SegundoNombreType } * */ public SegundoNombreType createSegundoNombreType() { return new SegundoNombreType(); } /** * Create an instance of {@link TipoPersonaType } * */ public TipoPersonaType createTipoPersonaType() { return new TipoPersonaType(); } /** * Create an instance of {@link CreateDateType } * */ public CreateDateType createCreateDateType() { return new CreateDateType(); } /** * Create an instance of {@link CodRespuestaType } * */ public CodRespuestaType createCodRespuestaType() { return new CodRespuestaType(); } /** * Create an instance of {@link MsjRespuestaType } * */ public MsjRespuestaType createMsjRespuestaType() { return new MsjRespuestaType(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link TipoDocumentoType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "tipoDocumento") public JAXBElement<TipoDocumentoType> createTipoDocumento(TipoDocumentoType value) { return new JAXBElement<TipoDocumentoType>(_TipoDocumento_QNAME, TipoDocumentoType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link NumeroDocumentoType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "numeroIdentificacion") public JAXBElement<NumeroDocumentoType> createNumeroIdentificacion(NumeroDocumentoType value) { return new JAXBElement<NumeroDocumentoType>(_NumeroIdentificacion_QNAME, NumeroDocumentoType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link PrimerApellidoType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "primerApellido") public JAXBElement<PrimerApellidoType> createPrimerApellido(PrimerApellidoType value) { return new JAXBElement<PrimerApellidoType>(_PrimerApellido_QNAME, PrimerApellidoType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SegundoApellidoType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "segundoApellido") public JAXBElement<SegundoApellidoType> createSegundoApellido(SegundoApellidoType value) { return new JAXBElement<SegundoApellidoType>(_SegundoApellido_QNAME, SegundoApellidoType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link PrimerNombreType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "primerNombre") public JAXBElement<PrimerNombreType> createPrimerNombre(PrimerNombreType value) { return new JAXBElement<PrimerNombreType>(_PrimerNombre_QNAME, PrimerNombreType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SegundoNombreType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "segundoNombre") public JAXBElement<SegundoNombreType> createSegundoNombre(SegundoNombreType value) { return new JAXBElement<SegundoNombreType>(_SegundoNombre_QNAME, SegundoNombreType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link TipoPersonaType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "tipoPersona") public JAXBElement<TipoPersonaType> createTipoPersona(TipoPersonaType value) { return new JAXBElement<TipoPersonaType>(_TipoPersona_QNAME, TipoPersonaType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateDateType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "fechaCreacion") public JAXBElement<CreateDateType> createFechaCreacion(CreateDateType value) { return new JAXBElement<CreateDateType>(_FechaCreacion_QNAME, CreateDateType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CodRespuestaType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "codRespuesta") public JAXBElement<CodRespuestaType> createCodRespuesta(CodRespuestaType value) { return new JAXBElement<CodRespuestaType>(_CodRespuesta_QNAME, CodRespuestaType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CodRespuestaType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "codRespuestaEquivalente") public JAXBElement<CodRespuestaType> createCodRespuestaEquivalente(CodRespuestaType value) { return new JAXBElement<CodRespuestaType>(_CodRespuestaEquivalente_QNAME, CodRespuestaType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link MsjRespuestaType }{@code >}} * */ @XmlElementDecl(namespace = "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", name = "msgRespuesta") public JAXBElement<MsjRespuestaType> createMsgRespuesta(MsjRespuestaType value) { return new JAXBElement<MsjRespuestaType>(_MsgRespuesta_QNAME, MsjRespuestaType.class, null, value); } }
[ "@", "XmlRegistry", "public", "class", "ObjectFactory", "{", "private", "final", "static", "QName", "_TipoDocumento_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "tipoDocumento", "\"", ")", ";", "private", "final", "static", "QName", "_NumeroIdentificacion_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "numeroIdentificacion", "\"", ")", ";", "private", "final", "static", "QName", "_PrimerApellido_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "primerApellido", "\"", ")", ";", "private", "final", "static", "QName", "_SegundoApellido_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "segundoApellido", "\"", ")", ";", "private", "final", "static", "QName", "_PrimerNombre_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "primerNombre", "\"", ")", ";", "private", "final", "static", "QName", "_SegundoNombre_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "segundoNombre", "\"", ")", ";", "private", "final", "static", "QName", "_TipoPersona_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "tipoPersona", "\"", ")", ";", "private", "final", "static", "QName", "_FechaCreacion_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "fechaCreacion", "\"", ")", ";", "private", "final", "static", "QName", "_CodRespuesta_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "codRespuesta", "\"", ")", ";", "private", "final", "static", "QName", "_CodRespuestaEquivalente_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "codRespuestaEquivalente", "\"", ")", ";", "private", "final", "static", "QName", "_MsgRespuesta_QNAME", "=", "new", "QName", "(", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "\"", "msgRespuesta", "\"", ")", ";", "/**\n * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.adarchitecture.user.common.basic\n * \n */", "public", "ObjectFactory", "(", ")", "{", "}", "/**\n * Create an instance of {@link TipoDocumentoType }\n * \n */", "public", "TipoDocumentoType", "createTipoDocumentoType", "(", ")", "{", "return", "new", "TipoDocumentoType", "(", ")", ";", "}", "/**\n * Create an instance of {@link NumeroDocumentoType }\n * \n */", "public", "NumeroDocumentoType", "createNumeroDocumentoType", "(", ")", "{", "return", "new", "NumeroDocumentoType", "(", ")", ";", "}", "/**\n * Create an instance of {@link PrimerApellidoType }\n * \n */", "public", "PrimerApellidoType", "createPrimerApellidoType", "(", ")", "{", "return", "new", "PrimerApellidoType", "(", ")", ";", "}", "/**\n * Create an instance of {@link SegundoApellidoType }\n * \n */", "public", "SegundoApellidoType", "createSegundoApellidoType", "(", ")", "{", "return", "new", "SegundoApellidoType", "(", ")", ";", "}", "/**\n * Create an instance of {@link PrimerNombreType }\n * \n */", "public", "PrimerNombreType", "createPrimerNombreType", "(", ")", "{", "return", "new", "PrimerNombreType", "(", ")", ";", "}", "/**\n * Create an instance of {@link SegundoNombreType }\n * \n */", "public", "SegundoNombreType", "createSegundoNombreType", "(", ")", "{", "return", "new", "SegundoNombreType", "(", ")", ";", "}", "/**\n * Create an instance of {@link TipoPersonaType }\n * \n */", "public", "TipoPersonaType", "createTipoPersonaType", "(", ")", "{", "return", "new", "TipoPersonaType", "(", ")", ";", "}", "/**\n * Create an instance of {@link CreateDateType }\n * \n */", "public", "CreateDateType", "createCreateDateType", "(", ")", "{", "return", "new", "CreateDateType", "(", ")", ";", "}", "/**\n * Create an instance of {@link CodRespuestaType }\n * \n */", "public", "CodRespuestaType", "createCodRespuestaType", "(", ")", "{", "return", "new", "CodRespuestaType", "(", ")", ";", "}", "/**\n * Create an instance of {@link MsjRespuestaType }\n * \n */", "public", "MsjRespuestaType", "createMsjRespuestaType", "(", ")", "{", "return", "new", "MsjRespuestaType", "(", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link TipoDocumentoType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "tipoDocumento", "\"", ")", "public", "JAXBElement", "<", "TipoDocumentoType", ">", "createTipoDocumento", "(", "TipoDocumentoType", "value", ")", "{", "return", "new", "JAXBElement", "<", "TipoDocumentoType", ">", "(", "_TipoDocumento_QNAME", ",", "TipoDocumentoType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link NumeroDocumentoType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "numeroIdentificacion", "\"", ")", "public", "JAXBElement", "<", "NumeroDocumentoType", ">", "createNumeroIdentificacion", "(", "NumeroDocumentoType", "value", ")", "{", "return", "new", "JAXBElement", "<", "NumeroDocumentoType", ">", "(", "_NumeroIdentificacion_QNAME", ",", "NumeroDocumentoType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link PrimerApellidoType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "primerApellido", "\"", ")", "public", "JAXBElement", "<", "PrimerApellidoType", ">", "createPrimerApellido", "(", "PrimerApellidoType", "value", ")", "{", "return", "new", "JAXBElement", "<", "PrimerApellidoType", ">", "(", "_PrimerApellido_QNAME", ",", "PrimerApellidoType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link SegundoApellidoType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "segundoApellido", "\"", ")", "public", "JAXBElement", "<", "SegundoApellidoType", ">", "createSegundoApellido", "(", "SegundoApellidoType", "value", ")", "{", "return", "new", "JAXBElement", "<", "SegundoApellidoType", ">", "(", "_SegundoApellido_QNAME", ",", "SegundoApellidoType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link PrimerNombreType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "primerNombre", "\"", ")", "public", "JAXBElement", "<", "PrimerNombreType", ">", "createPrimerNombre", "(", "PrimerNombreType", "value", ")", "{", "return", "new", "JAXBElement", "<", "PrimerNombreType", ">", "(", "_PrimerNombre_QNAME", ",", "PrimerNombreType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link SegundoNombreType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "segundoNombre", "\"", ")", "public", "JAXBElement", "<", "SegundoNombreType", ">", "createSegundoNombre", "(", "SegundoNombreType", "value", ")", "{", "return", "new", "JAXBElement", "<", "SegundoNombreType", ">", "(", "_SegundoNombre_QNAME", ",", "SegundoNombreType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link TipoPersonaType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "tipoPersona", "\"", ")", "public", "JAXBElement", "<", "TipoPersonaType", ">", "createTipoPersona", "(", "TipoPersonaType", "value", ")", "{", "return", "new", "JAXBElement", "<", "TipoPersonaType", ">", "(", "_TipoPersona_QNAME", ",", "TipoPersonaType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link CreateDateType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "fechaCreacion", "\"", ")", "public", "JAXBElement", "<", "CreateDateType", ">", "createFechaCreacion", "(", "CreateDateType", "value", ")", "{", "return", "new", "JAXBElement", "<", "CreateDateType", ">", "(", "_FechaCreacion_QNAME", ",", "CreateDateType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link CodRespuestaType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "codRespuesta", "\"", ")", "public", "JAXBElement", "<", "CodRespuestaType", ">", "createCodRespuesta", "(", "CodRespuestaType", "value", ")", "{", "return", "new", "JAXBElement", "<", "CodRespuestaType", ">", "(", "_CodRespuesta_QNAME", ",", "CodRespuestaType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link CodRespuestaType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "codRespuestaEquivalente", "\"", ")", "public", "JAXBElement", "<", "CodRespuestaType", ">", "createCodRespuestaEquivalente", "(", "CodRespuestaType", "value", ")", "{", "return", "new", "JAXBElement", "<", "CodRespuestaType", ">", "(", "_CodRespuestaEquivalente_QNAME", ",", "CodRespuestaType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "/**\n * Create an instance of {@link JAXBElement }{@code <}{@link MsjRespuestaType }{@code >}}\n * \n */", "@", "XmlElementDecl", "(", "namespace", "=", "\"", "org:adarchitecture:salesforce:user:xsd:CommonBasicComponents-2", "\"", ",", "name", "=", "\"", "msgRespuesta", "\"", ")", "public", "JAXBElement", "<", "MsjRespuestaType", ">", "createMsgRespuesta", "(", "MsjRespuestaType", "value", ")", "{", "return", "new", "JAXBElement", "<", "MsjRespuestaType", ">", "(", "_MsgRespuesta_QNAME", ",", "MsjRespuestaType", ".", "class", ",", "null", ",", "value", ")", ";", "}", "}" ]
This object contains factory methods for each Java content interface and Java element interface generated in the org.adarchitecture.user.common.basic package.
[ "This", "object", "contains", "factory", "methods", "for", "each", "Java", "content", "interface", "and", "Java", "element", "interface", "generated", "in", "the", "org", ".", "adarchitecture", ".", "user", ".", "common", ".", "basic", "package", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33597304d2f444477d1a9aba9d77a6c14559a186
Zhaoyy/LuaJTest
src/main/java/org/luaj/vm2/LuaError.java
[ "Apache-2.0" ]
Java
LuaError
/** * RuntimeException that is thrown and caught in response to a lua error. <p> {@link LuaError} is * used wherever a lua call to {@code error()} would be used within a script. <p> Since it is an * unchecked exception inheriting from {@link RuntimeException}, Java method signatures do * notdeclare this exception, althoug it can be thrown on almost any luaj Java operation. This is * analagous to the fact that any lua script can throw a lua error at any time. <p> The LuaError may * be constructed with a message object, in which case the message is the string representation of * that object. getMessageObject will get the object supplied at construct time, or a LuaString * containing the message of an object was not supplied. */
RuntimeException that is thrown and caught in response to a lua error. LuaError is used wherever a lua call to error() would be used within a script. Since it is an unchecked exception inheriting from RuntimeException, Java method signatures do notdeclare this exception, althoug it can be thrown on almost any luaj Java operation. This is analagous to the fact that any lua script can throw a lua error at any time. The LuaError may be constructed with a message object, in which case the message is the string representation of that object. getMessageObject will get the object supplied at construct time, or a LuaString containing the message of an object was not supplied.
[ "RuntimeException", "that", "is", "thrown", "and", "caught", "in", "response", "to", "a", "lua", "error", ".", "LuaError", "is", "used", "wherever", "a", "lua", "call", "to", "error", "()", "would", "be", "used", "within", "a", "script", ".", "Since", "it", "is", "an", "unchecked", "exception", "inheriting", "from", "RuntimeException", "Java", "method", "signatures", "do", "notdeclare", "this", "exception", "althoug", "it", "can", "be", "thrown", "on", "almost", "any", "luaj", "Java", "operation", ".", "This", "is", "analagous", "to", "the", "fact", "that", "any", "lua", "script", "can", "throw", "a", "lua", "error", "at", "any", "time", ".", "The", "LuaError", "may", "be", "constructed", "with", "a", "message", "object", "in", "which", "case", "the", "message", "is", "the", "string", "representation", "of", "that", "object", ".", "getMessageObject", "will", "get", "the", "object", "supplied", "at", "construct", "time", "or", "a", "LuaString", "containing", "the", "message", "of", "an", "object", "was", "not", "supplied", "." ]
public class LuaError extends RuntimeException { private static final long serialVersionUID = 1L; protected int level; protected String fileline; protected String traceback; protected Throwable cause; private LuaValue object; /** * Construct LuaError when a program exception occurs. <p> All errors generated from lua code * should throw LuaError(String) instead. * * @param cause the Throwable that caused the error, if known. */ public LuaError(Throwable cause) { super("vm error: " + cause); this.cause = cause; this.level = 1; } /** * Construct a LuaError with a specific message. * * @param message message to supply */ public LuaError(String message) { super(message); this.level = 1; } /** * Construct a LuaError with a message, and level to draw line number information from. * * @param message message to supply * @param level where to supply line info from in call stack */ public LuaError(String message, int level) { super(message); this.level = level; } /** * Construct a LuaError with a LuaValue as the message object, and level to draw line number * information from. * * @param message_object message string or object to supply */ public LuaError(LuaValue message_object) { super(message_object.tojstring()); this.object = message_object; this.level = 1; } /** * Get the string message if it was supplied, or a string representation of the message object if * that was supplied. */ public String getMessage() { if (traceback != null) { return traceback; } String m = super.getMessage(); if (m == null) { return null; } if (fileline != null) { return fileline + " " + m; } return m; } /** * Get the LuaValue that was provided in the constructor, or a LuaString containing the message if * it was a string error argument. * * @return LuaValue which was used in the constructor, or a LuaString containing the message. */ public LuaValue getMessageObject() { if (object != null) return object; String m = getMessage(); return m != null ? LuaValue.valueOf(m) : null; } /** * Get the cause, if any. */ public Throwable getCause() { return cause; } }
[ "public", "class", "LuaError", "extends", "RuntimeException", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "protected", "int", "level", ";", "protected", "String", "fileline", ";", "protected", "String", "traceback", ";", "protected", "Throwable", "cause", ";", "private", "LuaValue", "object", ";", "/**\n * Construct LuaError when a program exception occurs. <p> All errors generated from lua code\n * should throw LuaError(String) instead.\n *\n * @param cause the Throwable that caused the error, if known.\n */", "public", "LuaError", "(", "Throwable", "cause", ")", "{", "super", "(", "\"", "vm error: ", "\"", "+", "cause", ")", ";", "this", ".", "cause", "=", "cause", ";", "this", ".", "level", "=", "1", ";", "}", "/**\n * Construct a LuaError with a specific message.\n *\n * @param message message to supply\n */", "public", "LuaError", "(", "String", "message", ")", "{", "super", "(", "message", ")", ";", "this", ".", "level", "=", "1", ";", "}", "/**\n * Construct a LuaError with a message, and level to draw line number information from.\n *\n * @param message message to supply\n * @param level where to supply line info from in call stack\n */", "public", "LuaError", "(", "String", "message", ",", "int", "level", ")", "{", "super", "(", "message", ")", ";", "this", ".", "level", "=", "level", ";", "}", "/**\n * Construct a LuaError with a LuaValue as the message object, and level to draw line number\n * information from.\n *\n * @param message_object message string or object to supply\n */", "public", "LuaError", "(", "LuaValue", "message_object", ")", "{", "super", "(", "message_object", ".", "tojstring", "(", ")", ")", ";", "this", ".", "object", "=", "message_object", ";", "this", ".", "level", "=", "1", ";", "}", "/**\n * Get the string message if it was supplied, or a string representation of the message object if\n * that was supplied.\n */", "public", "String", "getMessage", "(", ")", "{", "if", "(", "traceback", "!=", "null", ")", "{", "return", "traceback", ";", "}", "String", "m", "=", "super", ".", "getMessage", "(", ")", ";", "if", "(", "m", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "fileline", "!=", "null", ")", "{", "return", "fileline", "+", "\"", " ", "\"", "+", "m", ";", "}", "return", "m", ";", "}", "/**\n * Get the LuaValue that was provided in the constructor, or a LuaString containing the message if\n * it was a string error argument.\n *\n * @return LuaValue which was used in the constructor, or a LuaString containing the message.\n */", "public", "LuaValue", "getMessageObject", "(", ")", "{", "if", "(", "object", "!=", "null", ")", "return", "object", ";", "String", "m", "=", "getMessage", "(", ")", ";", "return", "m", "!=", "null", "?", "LuaValue", ".", "valueOf", "(", "m", ")", ":", "null", ";", "}", "/**\n * Get the cause, if any.\n */", "public", "Throwable", "getCause", "(", ")", "{", "return", "cause", ";", "}", "}" ]
RuntimeException that is thrown and caught in response to a lua error.
[ "RuntimeException", "that", "is", "thrown", "and", "caught", "in", "response", "to", "a", "lua", "error", "." ]
[]
[ { "param": "RuntimeException", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "RuntimeException", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
335ac60be4632bb6b4a6ac6e36b55852a6db888f
ignaciotcrespo/frutilla
java/src/main/java/org/frutilla/FrutillaParser.java
[ "MIT" ]
Java
FrutillaParser
/** * Parses the Frutilla JUnit sentences. */
Parses the Frutilla JUnit sentences.
[ "Parses", "the", "Frutilla", "JUnit", "sentences", "." ]
class FrutillaParser { private static final String AND = " AND"; private static final String BUT = " BUT"; private static AbstractSentence sRoot; /** * Describes the scenario of the use case. * * @param text the sentence describing the scenario * @return a Scenario object to conitnue adding sentences */ static Scenario scenario(String text) { reset(); final Scenario scenario = new Scenario(text); sRoot = scenario; return scenario; } /** * Describes the entry point of the use case. * * @param text the sentence describing the entry point * @return a Given object to continue adding sentences */ static Given given(String text) { reset(); final Given given = new Given(text); sRoot = given; return given; } static boolean has(String sentence) { return sRoot != null && sRoot.has(sentence); } static void reset() { if (sRoot != null) { sRoot.reset(); sRoot = null; } } static boolean isEmpty() { return sRoot == null || sRoot.isEmpty(); } static String popSentence() { if (sRoot != null) { return sRoot.popSentence(); } return ""; } static String scenario(Frutilla annotation) { String value = ""; if (annotation != null) { final Scenario scenario = new Scenario(annotation.Scenario()); scenario.given(annotation.Given()) .when(annotation.When()) .then(annotation.Then()); value = scenario.popSentence(); } return value; } //---------------------------------------------------------------------------------------------- static abstract class AbstractSentence { private String mSentence; private final List<AbstractSentence> mChildren = new LinkedList<>(); private final String mHeader; private AbstractSentence(String sentence, String header) { if (sentence != null && sentence.trim().toLowerCase(Locale.ENGLISH).startsWith(header.trim().toLowerCase(Locale.ENGLISH) + " ")) { mSentence = sentence.trim().substring((header.trim().toLowerCase(Locale.ENGLISH) + " ").length()); } else { mSentence = sentence; } mHeader = header; } AbstractSentence(String[] sentences, String header) { this(sentences == null || sentences.length == 0 ? "" : sentences[0], header); if (sentences != null) { AbstractSentence child = this; for (int i = 1; i < sentences.length; i++) { final String sentence = sentences[i]; if (sentence != null && sentence.trim().toLowerCase(Locale.ENGLISH).startsWith("and ")) { child = child.and(sentence); } else if (sentence != null && sentence.trim().toLowerCase(Locale.ENGLISH).startsWith("but ")) { child = child.but(sentence); } else { child = child.and(sentence); } } } } boolean has(String sentence) { boolean has = mSentence.equals(sentence); if (!has) { for (AbstractSentence child : mChildren) { has = child.has(sentence); if (has) { break; } } } return has; } void reset() { mSentence = null; for (AbstractSentence child : mChildren) { child.reset(); } mChildren.clear(); } /** * Adds another sentence to the current group, starting with AND. * * @param sentence the sentence in plain text * @return the current group of sentences */ public abstract AbstractSentence and(String sentence); boolean isEmpty() { return mSentence == null && mChildren.isEmpty(); } AbstractSentence addChild(AbstractSentence child) { mChildren.add(child); return child; } String popSentence() { StringBuilder sentence = new StringBuilder(); if (mSentence != null && mSentence.trim().length() > 0) { sentence.append(header()); sentence.append(" "); sentence.append(mSentence); } for (AbstractSentence child : mChildren) { final String text = child.popSentence(); if (!text.trim().isEmpty()) { if (sentence.length() > 0) { sentence.append("\n"); } sentence.append(text); } } reset(); return sentence.toString(); } String header() { return mHeader; } /** * Adds another sentence to the current group, starting with BUT. * * @param sentence the sentence in plain text * @return the current group of sentences */ public abstract AbstractSentence but(String sentence); } //---------------------------------------------------------------------------------------------- /** * Group of sentences describing the scenario of the use case, using plain text. */ public static class Scenario extends AbstractSentence { private Scenario(String sentence) { super(sentence, "SCENARIO"); } private Scenario(String[] sentences) { super(sentences, "SCENARIO"); } private Scenario(String sentence, String header) { super(sentence, header); } /** * Starts describing the action executed in the use case. * * @param sentence the sentence in plain text * @return the current group of sentences */ public Given given(String sentence) { Given given = new Given(sentence); addChild(given); return given; } Given given(String[] sentences) { Given given = new Given(sentences); addChild(given); return given; } @Override public Scenario and(String sentence) { return (Scenario) addChild(new Scenario(sentence, AND)); } @Override public Scenario but(String sentence) { return (Scenario) addChild(new Scenario(sentence, BUT)); } } /** * Group of sentences describing the entry point of the use case, using plain text. */ public static class Given extends AbstractSentence { private Given(String sentence) { super(sentence, "GIVEN"); } private Given(String[] sentences) { super(sentences, "GIVEN"); } private Given(String sentence, String header) { super(sentence, header); } /** * Starts describing the action executed in the use case. * * @param sentence the sentence in plain text * @return the current group of sentences */ public When when(String sentence) { When when = new When(sentence); addChild(when); return when; } When when(String[] sentences) { When when = new When(sentences); addChild(when); return when; } @Override public Given and(String sentence) { return (Given) addChild(new Given(sentence, AND)); } @Override public Given but(String sentence) { return (Given) addChild(new Given(sentence, BUT)); } } //---------------------------------------------------------------------------------------------- /** * A group of sentences describing the action to execute in the use case, using plain text. */ public static class When extends AbstractSentence { private When(String sentence) { super(sentence, "WHEN"); } private When(String[] sentences) { super(sentences, "WHEN"); } private When(String sentence, String header) { super(sentence, header); } /** * Starts describing in plain text the expected behavior after executing the use case. * * @param sentence the sentence in plain text * @return the current group of sentences */ public Then then(String sentence) { return (Then) addChild(new Then(sentence)); } Then then(String[] sentences) { return (Then) addChild(new Then(sentences)); } @Override public When and(String sentence) { return (When) addChild(new When(sentence, AND)); } @Override public When but(String sentence) { return (When) addChild(new When(sentence, BUT)); } } //---------------------------------------------------------------------------------------------- /** * Describes in plain text the expected behavior after executing the use case. */ public static class Then extends AbstractSentence { private Then(String sentence) { super(sentence, "THEN"); } private Then(String[] sentences) { super(sentences, "THEN"); } private Then(String sentence, String header) { super(sentence, header); } @Override public Then and(String sentence) { return (Then) addChild(new Then(sentence, AND)); } @Override public Then but(String sentence) { return (Then) addChild(new Then(sentence, BUT)); } } }
[ "class", "FrutillaParser", "{", "private", "static", "final", "String", "AND", "=", "\"", " AND", "\"", ";", "private", "static", "final", "String", "BUT", "=", "\"", " BUT", "\"", ";", "private", "static", "AbstractSentence", "sRoot", ";", "/**\n * Describes the scenario of the use case.\n *\n * @param text the sentence describing the scenario\n * @return a Scenario object to conitnue adding sentences\n */", "static", "Scenario", "scenario", "(", "String", "text", ")", "{", "reset", "(", ")", ";", "final", "Scenario", "scenario", "=", "new", "Scenario", "(", "text", ")", ";", "sRoot", "=", "scenario", ";", "return", "scenario", ";", "}", "/**\n * Describes the entry point of the use case.\n *\n * @param text the sentence describing the entry point\n * @return a Given object to continue adding sentences\n */", "static", "Given", "given", "(", "String", "text", ")", "{", "reset", "(", ")", ";", "final", "Given", "given", "=", "new", "Given", "(", "text", ")", ";", "sRoot", "=", "given", ";", "return", "given", ";", "}", "static", "boolean", "has", "(", "String", "sentence", ")", "{", "return", "sRoot", "!=", "null", "&&", "sRoot", ".", "has", "(", "sentence", ")", ";", "}", "static", "void", "reset", "(", ")", "{", "if", "(", "sRoot", "!=", "null", ")", "{", "sRoot", ".", "reset", "(", ")", ";", "sRoot", "=", "null", ";", "}", "}", "static", "boolean", "isEmpty", "(", ")", "{", "return", "sRoot", "==", "null", "||", "sRoot", ".", "isEmpty", "(", ")", ";", "}", "static", "String", "popSentence", "(", ")", "{", "if", "(", "sRoot", "!=", "null", ")", "{", "return", "sRoot", ".", "popSentence", "(", ")", ";", "}", "return", "\"", "\"", ";", "}", "static", "String", "scenario", "(", "Frutilla", "annotation", ")", "{", "String", "value", "=", "\"", "\"", ";", "if", "(", "annotation", "!=", "null", ")", "{", "final", "Scenario", "scenario", "=", "new", "Scenario", "(", "annotation", ".", "Scenario", "(", ")", ")", ";", "scenario", ".", "given", "(", "annotation", ".", "Given", "(", ")", ")", ".", "when", "(", "annotation", ".", "When", "(", ")", ")", ".", "then", "(", "annotation", ".", "Then", "(", ")", ")", ";", "value", "=", "scenario", ".", "popSentence", "(", ")", ";", "}", "return", "value", ";", "}", "static", "abstract", "class", "AbstractSentence", "{", "private", "String", "mSentence", ";", "private", "final", "List", "<", "AbstractSentence", ">", "mChildren", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "private", "final", "String", "mHeader", ";", "private", "AbstractSentence", "(", "String", "sentence", ",", "String", "header", ")", "{", "if", "(", "sentence", "!=", "null", "&&", "sentence", ".", "trim", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", ".", "startsWith", "(", "header", ".", "trim", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", "+", "\"", " ", "\"", ")", ")", "{", "mSentence", "=", "sentence", ".", "trim", "(", ")", ".", "substring", "(", "(", "header", ".", "trim", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", "+", "\"", " ", "\"", ")", ".", "length", "(", ")", ")", ";", "}", "else", "{", "mSentence", "=", "sentence", ";", "}", "mHeader", "=", "header", ";", "}", "AbstractSentence", "(", "String", "[", "]", "sentences", ",", "String", "header", ")", "{", "this", "(", "sentences", "==", "null", "||", "sentences", ".", "length", "==", "0", "?", "\"", "\"", ":", "sentences", "[", "0", "]", ",", "header", ")", ";", "if", "(", "sentences", "!=", "null", ")", "{", "AbstractSentence", "child", "=", "this", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "sentences", ".", "length", ";", "i", "++", ")", "{", "final", "String", "sentence", "=", "sentences", "[", "i", "]", ";", "if", "(", "sentence", "!=", "null", "&&", "sentence", ".", "trim", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", ".", "startsWith", "(", "\"", "and ", "\"", ")", ")", "{", "child", "=", "child", ".", "and", "(", "sentence", ")", ";", "}", "else", "if", "(", "sentence", "!=", "null", "&&", "sentence", ".", "trim", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", ".", "startsWith", "(", "\"", "but ", "\"", ")", ")", "{", "child", "=", "child", ".", "but", "(", "sentence", ")", ";", "}", "else", "{", "child", "=", "child", ".", "and", "(", "sentence", ")", ";", "}", "}", "}", "}", "boolean", "has", "(", "String", "sentence", ")", "{", "boolean", "has", "=", "mSentence", ".", "equals", "(", "sentence", ")", ";", "if", "(", "!", "has", ")", "{", "for", "(", "AbstractSentence", "child", ":", "mChildren", ")", "{", "has", "=", "child", ".", "has", "(", "sentence", ")", ";", "if", "(", "has", ")", "{", "break", ";", "}", "}", "}", "return", "has", ";", "}", "void", "reset", "(", ")", "{", "mSentence", "=", "null", ";", "for", "(", "AbstractSentence", "child", ":", "mChildren", ")", "{", "child", ".", "reset", "(", ")", ";", "}", "mChildren", ".", "clear", "(", ")", ";", "}", "/**\n * Adds another sentence to the current group, starting with AND.\n *\n * @param sentence the sentence in plain text\n * @return the current group of sentences\n */", "public", "abstract", "AbstractSentence", "and", "(", "String", "sentence", ")", ";", "boolean", "isEmpty", "(", ")", "{", "return", "mSentence", "==", "null", "&&", "mChildren", ".", "isEmpty", "(", ")", ";", "}", "AbstractSentence", "addChild", "(", "AbstractSentence", "child", ")", "{", "mChildren", ".", "add", "(", "child", ")", ";", "return", "child", ";", "}", "String", "popSentence", "(", ")", "{", "StringBuilder", "sentence", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "mSentence", "!=", "null", "&&", "mSentence", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "sentence", ".", "append", "(", "header", "(", ")", ")", ";", "sentence", ".", "append", "(", "\"", " ", "\"", ")", ";", "sentence", ".", "append", "(", "mSentence", ")", ";", "}", "for", "(", "AbstractSentence", "child", ":", "mChildren", ")", "{", "final", "String", "text", "=", "child", ".", "popSentence", "(", ")", ";", "if", "(", "!", "text", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "sentence", ".", "length", "(", ")", ">", "0", ")", "{", "sentence", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "}", "sentence", ".", "append", "(", "text", ")", ";", "}", "}", "reset", "(", ")", ";", "return", "sentence", ".", "toString", "(", ")", ";", "}", "String", "header", "(", ")", "{", "return", "mHeader", ";", "}", "/**\n * Adds another sentence to the current group, starting with BUT.\n *\n * @param sentence the sentence in plain text\n * @return the current group of sentences\n */", "public", "abstract", "AbstractSentence", "but", "(", "String", "sentence", ")", ";", "}", "/**\n * Group of sentences describing the scenario of the use case, using plain text.\n */", "public", "static", "class", "Scenario", "extends", "AbstractSentence", "{", "private", "Scenario", "(", "String", "sentence", ")", "{", "super", "(", "sentence", ",", "\"", "SCENARIO", "\"", ")", ";", "}", "private", "Scenario", "(", "String", "[", "]", "sentences", ")", "{", "super", "(", "sentences", ",", "\"", "SCENARIO", "\"", ")", ";", "}", "private", "Scenario", "(", "String", "sentence", ",", "String", "header", ")", "{", "super", "(", "sentence", ",", "header", ")", ";", "}", "/**\n * Starts describing the action executed in the use case.\n *\n * @param sentence the sentence in plain text\n * @return the current group of sentences\n */", "public", "Given", "given", "(", "String", "sentence", ")", "{", "Given", "given", "=", "new", "Given", "(", "sentence", ")", ";", "addChild", "(", "given", ")", ";", "return", "given", ";", "}", "Given", "given", "(", "String", "[", "]", "sentences", ")", "{", "Given", "given", "=", "new", "Given", "(", "sentences", ")", ";", "addChild", "(", "given", ")", ";", "return", "given", ";", "}", "@", "Override", "public", "Scenario", "and", "(", "String", "sentence", ")", "{", "return", "(", "Scenario", ")", "addChild", "(", "new", "Scenario", "(", "sentence", ",", "AND", ")", ")", ";", "}", "@", "Override", "public", "Scenario", "but", "(", "String", "sentence", ")", "{", "return", "(", "Scenario", ")", "addChild", "(", "new", "Scenario", "(", "sentence", ",", "BUT", ")", ")", ";", "}", "}", "/**\n * Group of sentences describing the entry point of the use case, using plain text.\n */", "public", "static", "class", "Given", "extends", "AbstractSentence", "{", "private", "Given", "(", "String", "sentence", ")", "{", "super", "(", "sentence", ",", "\"", "GIVEN", "\"", ")", ";", "}", "private", "Given", "(", "String", "[", "]", "sentences", ")", "{", "super", "(", "sentences", ",", "\"", "GIVEN", "\"", ")", ";", "}", "private", "Given", "(", "String", "sentence", ",", "String", "header", ")", "{", "super", "(", "sentence", ",", "header", ")", ";", "}", "/**\n * Starts describing the action executed in the use case.\n *\n * @param sentence the sentence in plain text\n * @return the current group of sentences\n */", "public", "When", "when", "(", "String", "sentence", ")", "{", "When", "when", "=", "new", "When", "(", "sentence", ")", ";", "addChild", "(", "when", ")", ";", "return", "when", ";", "}", "When", "when", "(", "String", "[", "]", "sentences", ")", "{", "When", "when", "=", "new", "When", "(", "sentences", ")", ";", "addChild", "(", "when", ")", ";", "return", "when", ";", "}", "@", "Override", "public", "Given", "and", "(", "String", "sentence", ")", "{", "return", "(", "Given", ")", "addChild", "(", "new", "Given", "(", "sentence", ",", "AND", ")", ")", ";", "}", "@", "Override", "public", "Given", "but", "(", "String", "sentence", ")", "{", "return", "(", "Given", ")", "addChild", "(", "new", "Given", "(", "sentence", ",", "BUT", ")", ")", ";", "}", "}", "/**\n * A group of sentences describing the action to execute in the use case, using plain text.\n */", "public", "static", "class", "When", "extends", "AbstractSentence", "{", "private", "When", "(", "String", "sentence", ")", "{", "super", "(", "sentence", ",", "\"", "WHEN", "\"", ")", ";", "}", "private", "When", "(", "String", "[", "]", "sentences", ")", "{", "super", "(", "sentences", ",", "\"", "WHEN", "\"", ")", ";", "}", "private", "When", "(", "String", "sentence", ",", "String", "header", ")", "{", "super", "(", "sentence", ",", "header", ")", ";", "}", "/**\n * Starts describing in plain text the expected behavior after executing the use case.\n *\n * @param sentence the sentence in plain text\n * @return the current group of sentences\n */", "public", "Then", "then", "(", "String", "sentence", ")", "{", "return", "(", "Then", ")", "addChild", "(", "new", "Then", "(", "sentence", ")", ")", ";", "}", "Then", "then", "(", "String", "[", "]", "sentences", ")", "{", "return", "(", "Then", ")", "addChild", "(", "new", "Then", "(", "sentences", ")", ")", ";", "}", "@", "Override", "public", "When", "and", "(", "String", "sentence", ")", "{", "return", "(", "When", ")", "addChild", "(", "new", "When", "(", "sentence", ",", "AND", ")", ")", ";", "}", "@", "Override", "public", "When", "but", "(", "String", "sentence", ")", "{", "return", "(", "When", ")", "addChild", "(", "new", "When", "(", "sentence", ",", "BUT", ")", ")", ";", "}", "}", "/**\n * Describes in plain text the expected behavior after executing the use case.\n */", "public", "static", "class", "Then", "extends", "AbstractSentence", "{", "private", "Then", "(", "String", "sentence", ")", "{", "super", "(", "sentence", ",", "\"", "THEN", "\"", ")", ";", "}", "private", "Then", "(", "String", "[", "]", "sentences", ")", "{", "super", "(", "sentences", ",", "\"", "THEN", "\"", ")", ";", "}", "private", "Then", "(", "String", "sentence", ",", "String", "header", ")", "{", "super", "(", "sentence", ",", "header", ")", ";", "}", "@", "Override", "public", "Then", "and", "(", "String", "sentence", ")", "{", "return", "(", "Then", ")", "addChild", "(", "new", "Then", "(", "sentence", ",", "AND", ")", ")", ";", "}", "@", "Override", "public", "Then", "but", "(", "String", "sentence", ")", "{", "return", "(", "Then", ")", "addChild", "(", "new", "Then", "(", "sentence", ",", "BUT", ")", ")", ";", "}", "}", "}" ]
Parses the Frutilla JUnit sentences.
[ "Parses", "the", "Frutilla", "JUnit", "sentences", "." ]
[ "//----------------------------------------------------------------------------------------------", "//----------------------------------------------------------------------------------------------", "//----------------------------------------------------------------------------------------------", "//----------------------------------------------------------------------------------------------" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
335ac60be4632bb6b4a6ac6e36b55852a6db888f
ignaciotcrespo/frutilla
java/src/main/java/org/frutilla/FrutillaParser.java
[ "MIT" ]
Java
Scenario
/** * Group of sentences describing the scenario of the use case, using plain text. */
Group of sentences describing the scenario of the use case, using plain text.
[ "Group", "of", "sentences", "describing", "the", "scenario", "of", "the", "use", "case", "using", "plain", "text", "." ]
public static class Scenario extends AbstractSentence { private Scenario(String sentence) { super(sentence, "SCENARIO"); } private Scenario(String[] sentences) { super(sentences, "SCENARIO"); } private Scenario(String sentence, String header) { super(sentence, header); } /** * Starts describing the action executed in the use case. * * @param sentence the sentence in plain text * @return the current group of sentences */ public Given given(String sentence) { Given given = new Given(sentence); addChild(given); return given; } Given given(String[] sentences) { Given given = new Given(sentences); addChild(given); return given; } @Override public Scenario and(String sentence) { return (Scenario) addChild(new Scenario(sentence, AND)); } @Override public Scenario but(String sentence) { return (Scenario) addChild(new Scenario(sentence, BUT)); } }
[ "public", "static", "class", "Scenario", "extends", "AbstractSentence", "{", "private", "Scenario", "(", "String", "sentence", ")", "{", "super", "(", "sentence", ",", "\"", "SCENARIO", "\"", ")", ";", "}", "private", "Scenario", "(", "String", "[", "]", "sentences", ")", "{", "super", "(", "sentences", ",", "\"", "SCENARIO", "\"", ")", ";", "}", "private", "Scenario", "(", "String", "sentence", ",", "String", "header", ")", "{", "super", "(", "sentence", ",", "header", ")", ";", "}", "/**\n * Starts describing the action executed in the use case.\n *\n * @param sentence the sentence in plain text\n * @return the current group of sentences\n */", "public", "Given", "given", "(", "String", "sentence", ")", "{", "Given", "given", "=", "new", "Given", "(", "sentence", ")", ";", "addChild", "(", "given", ")", ";", "return", "given", ";", "}", "Given", "given", "(", "String", "[", "]", "sentences", ")", "{", "Given", "given", "=", "new", "Given", "(", "sentences", ")", ";", "addChild", "(", "given", ")", ";", "return", "given", ";", "}", "@", "Override", "public", "Scenario", "and", "(", "String", "sentence", ")", "{", "return", "(", "Scenario", ")", "addChild", "(", "new", "Scenario", "(", "sentence", ",", "AND", ")", ")", ";", "}", "@", "Override", "public", "Scenario", "but", "(", "String", "sentence", ")", "{", "return", "(", "Scenario", ")", "addChild", "(", "new", "Scenario", "(", "sentence", ",", "BUT", ")", ")", ";", "}", "}" ]
Group of sentences describing the scenario of the use case, using plain text.
[ "Group", "of", "sentences", "describing", "the", "scenario", "of", "the", "use", "case", "using", "plain", "text", "." ]
[]
[ { "param": "AbstractSentence", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractSentence", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
335ac60be4632bb6b4a6ac6e36b55852a6db888f
ignaciotcrespo/frutilla
java/src/main/java/org/frutilla/FrutillaParser.java
[ "MIT" ]
Java
Given
/** * Group of sentences describing the entry point of the use case, using plain text. */
Group of sentences describing the entry point of the use case, using plain text.
[ "Group", "of", "sentences", "describing", "the", "entry", "point", "of", "the", "use", "case", "using", "plain", "text", "." ]
public static class Given extends AbstractSentence { private Given(String sentence) { super(sentence, "GIVEN"); } private Given(String[] sentences) { super(sentences, "GIVEN"); } private Given(String sentence, String header) { super(sentence, header); } /** * Starts describing the action executed in the use case. * * @param sentence the sentence in plain text * @return the current group of sentences */ public When when(String sentence) { When when = new When(sentence); addChild(when); return when; } When when(String[] sentences) { When when = new When(sentences); addChild(when); return when; } @Override public Given and(String sentence) { return (Given) addChild(new Given(sentence, AND)); } @Override public Given but(String sentence) { return (Given) addChild(new Given(sentence, BUT)); } }
[ "public", "static", "class", "Given", "extends", "AbstractSentence", "{", "private", "Given", "(", "String", "sentence", ")", "{", "super", "(", "sentence", ",", "\"", "GIVEN", "\"", ")", ";", "}", "private", "Given", "(", "String", "[", "]", "sentences", ")", "{", "super", "(", "sentences", ",", "\"", "GIVEN", "\"", ")", ";", "}", "private", "Given", "(", "String", "sentence", ",", "String", "header", ")", "{", "super", "(", "sentence", ",", "header", ")", ";", "}", "/**\n * Starts describing the action executed in the use case.\n *\n * @param sentence the sentence in plain text\n * @return the current group of sentences\n */", "public", "When", "when", "(", "String", "sentence", ")", "{", "When", "when", "=", "new", "When", "(", "sentence", ")", ";", "addChild", "(", "when", ")", ";", "return", "when", ";", "}", "When", "when", "(", "String", "[", "]", "sentences", ")", "{", "When", "when", "=", "new", "When", "(", "sentences", ")", ";", "addChild", "(", "when", ")", ";", "return", "when", ";", "}", "@", "Override", "public", "Given", "and", "(", "String", "sentence", ")", "{", "return", "(", "Given", ")", "addChild", "(", "new", "Given", "(", "sentence", ",", "AND", ")", ")", ";", "}", "@", "Override", "public", "Given", "but", "(", "String", "sentence", ")", "{", "return", "(", "Given", ")", "addChild", "(", "new", "Given", "(", "sentence", ",", "BUT", ")", ")", ";", "}", "}" ]
Group of sentences describing the entry point of the use case, using plain text.
[ "Group", "of", "sentences", "describing", "the", "entry", "point", "of", "the", "use", "case", "using", "plain", "text", "." ]
[]
[ { "param": "AbstractSentence", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractSentence", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
335ac60be4632bb6b4a6ac6e36b55852a6db888f
ignaciotcrespo/frutilla
java/src/main/java/org/frutilla/FrutillaParser.java
[ "MIT" ]
Java
When
/** * A group of sentences describing the action to execute in the use case, using plain text. */
A group of sentences describing the action to execute in the use case, using plain text.
[ "A", "group", "of", "sentences", "describing", "the", "action", "to", "execute", "in", "the", "use", "case", "using", "plain", "text", "." ]
public static class When extends AbstractSentence { private When(String sentence) { super(sentence, "WHEN"); } private When(String[] sentences) { super(sentences, "WHEN"); } private When(String sentence, String header) { super(sentence, header); } /** * Starts describing in plain text the expected behavior after executing the use case. * * @param sentence the sentence in plain text * @return the current group of sentences */ public Then then(String sentence) { return (Then) addChild(new Then(sentence)); } Then then(String[] sentences) { return (Then) addChild(new Then(sentences)); } @Override public When and(String sentence) { return (When) addChild(new When(sentence, AND)); } @Override public When but(String sentence) { return (When) addChild(new When(sentence, BUT)); } }
[ "public", "static", "class", "When", "extends", "AbstractSentence", "{", "private", "When", "(", "String", "sentence", ")", "{", "super", "(", "sentence", ",", "\"", "WHEN", "\"", ")", ";", "}", "private", "When", "(", "String", "[", "]", "sentences", ")", "{", "super", "(", "sentences", ",", "\"", "WHEN", "\"", ")", ";", "}", "private", "When", "(", "String", "sentence", ",", "String", "header", ")", "{", "super", "(", "sentence", ",", "header", ")", ";", "}", "/**\n * Starts describing in plain text the expected behavior after executing the use case.\n *\n * @param sentence the sentence in plain text\n * @return the current group of sentences\n */", "public", "Then", "then", "(", "String", "sentence", ")", "{", "return", "(", "Then", ")", "addChild", "(", "new", "Then", "(", "sentence", ")", ")", ";", "}", "Then", "then", "(", "String", "[", "]", "sentences", ")", "{", "return", "(", "Then", ")", "addChild", "(", "new", "Then", "(", "sentences", ")", ")", ";", "}", "@", "Override", "public", "When", "and", "(", "String", "sentence", ")", "{", "return", "(", "When", ")", "addChild", "(", "new", "When", "(", "sentence", ",", "AND", ")", ")", ";", "}", "@", "Override", "public", "When", "but", "(", "String", "sentence", ")", "{", "return", "(", "When", ")", "addChild", "(", "new", "When", "(", "sentence", ",", "BUT", ")", ")", ";", "}", "}" ]
A group of sentences describing the action to execute in the use case, using plain text.
[ "A", "group", "of", "sentences", "describing", "the", "action", "to", "execute", "in", "the", "use", "case", "using", "plain", "text", "." ]
[]
[ { "param": "AbstractSentence", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractSentence", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
335ac60be4632bb6b4a6ac6e36b55852a6db888f
ignaciotcrespo/frutilla
java/src/main/java/org/frutilla/FrutillaParser.java
[ "MIT" ]
Java
Then
/** * Describes in plain text the expected behavior after executing the use case. */
Describes in plain text the expected behavior after executing the use case.
[ "Describes", "in", "plain", "text", "the", "expected", "behavior", "after", "executing", "the", "use", "case", "." ]
public static class Then extends AbstractSentence { private Then(String sentence) { super(sentence, "THEN"); } private Then(String[] sentences) { super(sentences, "THEN"); } private Then(String sentence, String header) { super(sentence, header); } @Override public Then and(String sentence) { return (Then) addChild(new Then(sentence, AND)); } @Override public Then but(String sentence) { return (Then) addChild(new Then(sentence, BUT)); } }
[ "public", "static", "class", "Then", "extends", "AbstractSentence", "{", "private", "Then", "(", "String", "sentence", ")", "{", "super", "(", "sentence", ",", "\"", "THEN", "\"", ")", ";", "}", "private", "Then", "(", "String", "[", "]", "sentences", ")", "{", "super", "(", "sentences", ",", "\"", "THEN", "\"", ")", ";", "}", "private", "Then", "(", "String", "sentence", ",", "String", "header", ")", "{", "super", "(", "sentence", ",", "header", ")", ";", "}", "@", "Override", "public", "Then", "and", "(", "String", "sentence", ")", "{", "return", "(", "Then", ")", "addChild", "(", "new", "Then", "(", "sentence", ",", "AND", ")", ")", ";", "}", "@", "Override", "public", "Then", "but", "(", "String", "sentence", ")", "{", "return", "(", "Then", ")", "addChild", "(", "new", "Then", "(", "sentence", ",", "BUT", ")", ")", ";", "}", "}" ]
Describes in plain text the expected behavior after executing the use case.
[ "Describes", "in", "plain", "text", "the", "expected", "behavior", "after", "executing", "the", "use", "case", "." ]
[]
[ { "param": "AbstractSentence", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractSentence", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
335b9cadbadacbc5b7ae8557ce562ea60307157a
gdela/socomo
socomo-core/src/main/java/pl/gdela/socomo/SocomoMain.java
[ "MIT" ]
Java
SocomoMain
/** * Main class to execute Socomo analysis. This is rarely used, rather the maven/gradle plugins are used. */
Main class to execute Socomo analysis. This is rarely used, rather the maven/gradle plugins are used.
[ "Main", "class", "to", "execute", "Socomo", "analysis", ".", "This", "is", "rarely", "used", "rather", "the", "maven", "/", "gradle", "plugins", "are", "used", "." ]
@Command( name = "java -jar socomo-standalone.jar", description = "Analyzes source code composition of a java project.", sortOptions = false, mixinStandardHelpOptions = true, versionProvider = SocomoMain.ManifestVersionProvider.class ) @SuppressWarnings("UseOfSystemOutOrSystemErr") class SocomoMain implements Callable<Void> { private static final Logger log = LoggerFactory.getLogger(SocomoMain.class); @Parameters( paramLabel = "INPUT", index = "0", arity = "1", description = "*.jar file or directory with *.class files to be analyzed." ) private File input; @Option( names = { "-o", "--output" }, paramLabel = "DIR", description = "Directory to which socomo.html and socomo.data will be written.", defaultValue = "." ) private File outputDir; @Option( names = { "--output-for-html" }, paramLabel = "DIR", description = "Directory to which socomo.html will be written. Overwrites common '-o' option.", hidden = true ) private File outputHtmlDir; @Option( names = { "--output-for-data" }, paramLabel = "DIR", description = "Directory to which socomo.data will be written. Overwrites common '-o' option.", hidden = true ) private File outputDataDir; @Option( names = { "-l", "--level" }, paramLabel = "PACKAGE", description = "The level (name of a java package) which composition will be analyzed. If not specified, it will be guessed." ) private String level; @Option( names = { "-d", "--display" }, description = "Automatically open created socomo.html file in the browser." ) private boolean display; public static void main(String[] args) { CommandLine.call(new SocomoMain(), args); } @Override public Void call() throws IOException { if (outputHtmlDir == null) outputHtmlDir = outputDir; if (!outputHtmlDir.isDirectory() || !outputHtmlDir.canWrite()) { err.println("Invalid output directory: " + outputHtmlDir); err.println("Please specify an existing, writable directory for html output."); CommandLine.usage(this, err); exit(1); } if (outputDataDir == null) outputDataDir = outputDir; if (!outputDataDir.isDirectory() || !outputDataDir.canWrite()) { err.println("Invalid output directory: " + outputDataDir); err.println("Please specify an existing, writable directory for data output."); CommandLine.usage(this, err); exit(1); } if (!input.canRead()) { err.println("Invalid input file/directory: " + input); err.println("Please specify an existing, readable file or directory for input."); CommandLine.usage(this, err); exit(1); } File outputHtmlFile = new File(outputHtmlDir.getCanonicalFile(), "socomo.html"); File outputDataFile = new File(outputDataDir.getCanonicalFile(), "socomo.data"); SocomoFacade socomo = new SocomoFacade(input.toString().replace('\\', '/')); socomo.analyzeBytecode(input); if (level != null) { socomo.chooseLevel(level); } else { socomo.guessLevel(); } socomo.visualizeInto(outputHtmlFile, outputDataFile); if (display) { socomo.display(); } return null; } static class ManifestVersionProvider implements IVersionProvider { @Override public String[] getVersion() { return new String[] { "Socomo " + SocomoVersion.get() }; } } }
[ "@", "Command", "(", "name", "=", "\"", "java -jar socomo-standalone.jar", "\"", ",", "description", "=", "\"", "Analyzes source code composition of a java project.", "\"", ",", "sortOptions", "=", "false", ",", "mixinStandardHelpOptions", "=", "true", ",", "versionProvider", "=", "SocomoMain", ".", "ManifestVersionProvider", ".", "class", ")", "@", "SuppressWarnings", "(", "\"", "UseOfSystemOutOrSystemErr", "\"", ")", "class", "SocomoMain", "implements", "Callable", "<", "Void", ">", "{", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "SocomoMain", ".", "class", ")", ";", "@", "Parameters", "(", "paramLabel", "=", "\"", "INPUT", "\"", ",", "index", "=", "\"", "0", "\"", ",", "arity", "=", "\"", "1", "\"", ",", "description", "=", "\"", "*.jar file or directory with *.class files to be analyzed.", "\"", ")", "private", "File", "input", ";", "@", "Option", "(", "names", "=", "{", "\"", "-o", "\"", ",", "\"", "--output", "\"", "}", ",", "paramLabel", "=", "\"", "DIR", "\"", ",", "description", "=", "\"", "Directory to which socomo.html and socomo.data will be written.", "\"", ",", "defaultValue", "=", "\"", ".", "\"", ")", "private", "File", "outputDir", ";", "@", "Option", "(", "names", "=", "{", "\"", "--output-for-html", "\"", "}", ",", "paramLabel", "=", "\"", "DIR", "\"", ",", "description", "=", "\"", "Directory to which socomo.html will be written. Overwrites common '-o' option.", "\"", ",", "hidden", "=", "true", ")", "private", "File", "outputHtmlDir", ";", "@", "Option", "(", "names", "=", "{", "\"", "--output-for-data", "\"", "}", ",", "paramLabel", "=", "\"", "DIR", "\"", ",", "description", "=", "\"", "Directory to which socomo.data will be written. Overwrites common '-o' option.", "\"", ",", "hidden", "=", "true", ")", "private", "File", "outputDataDir", ";", "@", "Option", "(", "names", "=", "{", "\"", "-l", "\"", ",", "\"", "--level", "\"", "}", ",", "paramLabel", "=", "\"", "PACKAGE", "\"", ",", "description", "=", "\"", "The level (name of a java package) which composition will be analyzed. If not specified, it will be guessed.", "\"", ")", "private", "String", "level", ";", "@", "Option", "(", "names", "=", "{", "\"", "-d", "\"", ",", "\"", "--display", "\"", "}", ",", "description", "=", "\"", "Automatically open created socomo.html file in the browser.", "\"", ")", "private", "boolean", "display", ";", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "CommandLine", ".", "call", "(", "new", "SocomoMain", "(", ")", ",", "args", ")", ";", "}", "@", "Override", "public", "Void", "call", "(", ")", "throws", "IOException", "{", "if", "(", "outputHtmlDir", "==", "null", ")", "outputHtmlDir", "=", "outputDir", ";", "if", "(", "!", "outputHtmlDir", ".", "isDirectory", "(", ")", "||", "!", "outputHtmlDir", ".", "canWrite", "(", ")", ")", "{", "err", ".", "println", "(", "\"", "Invalid output directory: ", "\"", "+", "outputHtmlDir", ")", ";", "err", ".", "println", "(", "\"", "Please specify an existing, writable directory for html output.", "\"", ")", ";", "CommandLine", ".", "usage", "(", "this", ",", "err", ")", ";", "exit", "(", "1", ")", ";", "}", "if", "(", "outputDataDir", "==", "null", ")", "outputDataDir", "=", "outputDir", ";", "if", "(", "!", "outputDataDir", ".", "isDirectory", "(", ")", "||", "!", "outputDataDir", ".", "canWrite", "(", ")", ")", "{", "err", ".", "println", "(", "\"", "Invalid output directory: ", "\"", "+", "outputDataDir", ")", ";", "err", ".", "println", "(", "\"", "Please specify an existing, writable directory for data output.", "\"", ")", ";", "CommandLine", ".", "usage", "(", "this", ",", "err", ")", ";", "exit", "(", "1", ")", ";", "}", "if", "(", "!", "input", ".", "canRead", "(", ")", ")", "{", "err", ".", "println", "(", "\"", "Invalid input file/directory: ", "\"", "+", "input", ")", ";", "err", ".", "println", "(", "\"", "Please specify an existing, readable file or directory for input.", "\"", ")", ";", "CommandLine", ".", "usage", "(", "this", ",", "err", ")", ";", "exit", "(", "1", ")", ";", "}", "File", "outputHtmlFile", "=", "new", "File", "(", "outputHtmlDir", ".", "getCanonicalFile", "(", ")", ",", "\"", "socomo.html", "\"", ")", ";", "File", "outputDataFile", "=", "new", "File", "(", "outputDataDir", ".", "getCanonicalFile", "(", ")", ",", "\"", "socomo.data", "\"", ")", ";", "SocomoFacade", "socomo", "=", "new", "SocomoFacade", "(", "input", ".", "toString", "(", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", ")", ";", "socomo", ".", "analyzeBytecode", "(", "input", ")", ";", "if", "(", "level", "!=", "null", ")", "{", "socomo", ".", "chooseLevel", "(", "level", ")", ";", "}", "else", "{", "socomo", ".", "guessLevel", "(", ")", ";", "}", "socomo", ".", "visualizeInto", "(", "outputHtmlFile", ",", "outputDataFile", ")", ";", "if", "(", "display", ")", "{", "socomo", ".", "display", "(", ")", ";", "}", "return", "null", ";", "}", "static", "class", "ManifestVersionProvider", "implements", "IVersionProvider", "{", "@", "Override", "public", "String", "[", "]", "getVersion", "(", ")", "{", "return", "new", "String", "[", "]", "{", "\"", "Socomo ", "\"", "+", "SocomoVersion", ".", "get", "(", ")", "}", ";", "}", "}", "}" ]
Main class to execute Socomo analysis.
[ "Main", "class", "to", "execute", "Socomo", "analysis", "." ]
[]
[ { "param": "Callable<Void>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Callable<Void>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
335d59c946897b195a3f3356ff23a1654dc978c0
georgfedermann/compilers
straightline/src/main/java/org/poormanscastle/studies/compilers/utils/grammartools/ast/Binding.java
[ "Apache-2.0" ]
Java
Binding
/** * In a SymbolTable each variable name and formal-parameter name are bound to their types. * <p/> * Each method is bound to its parameters, its result type and its local variables. * <p/> * Each class name is bound to its variable declarations and its method declarations. * <p/> * The Binding type is capable of storing all of this information, probably using subclasses like * MethodBinding, ClassBinding and VariableBinding. * TODO factor this type to a type hierarchy as described above. * <p/> * Created by 02eex612 on 19.02.2016. */
In a SymbolTable each variable name and formal-parameter name are bound to their types. Each method is bound to its parameters, its result type and its local variables. Each class name is bound to its variable declarations and its method declarations. The Binding type is capable of storing all of this information, probably using subclasses like MethodBinding, ClassBinding and VariableBinding. TODO factor this type to a type hierarchy as described above.
[ "In", "a", "SymbolTable", "each", "variable", "name", "and", "formal", "-", "parameter", "name", "are", "bound", "to", "their", "types", ".", "Each", "method", "is", "bound", "to", "its", "parameters", "its", "result", "type", "and", "its", "local", "variables", ".", "Each", "class", "name", "is", "bound", "to", "its", "variable", "declarations", "and", "its", "method", "declarations", ".", "The", "Binding", "type", "is", "capable", "of", "storing", "all", "of", "this", "information", "probably", "using", "subclasses", "like", "MethodBinding", "ClassBinding", "and", "VariableBinding", ".", "TODO", "factor", "this", "type", "to", "a", "type", "hierarchy", "as", "described", "above", "." ]
public class Binding { /** * the symbol's type. Like Int, Double, String, Boolean, CustomType ... */ private final String declaredType; /** * at this stage also store a value here, so that the symbol table can * intermediately also be used as an interpreter table. */ private Object value; public Binding(String declaredType, Object value) { checkArgument(!StringUtils.isBlank(declaredType)); this.declaredType = declaredType; this.value = value; } @Override public String toString() { return StringUtils.join("declaredType: ", declaredType, "; value: ", value); } public Binding(String declaredType) { this(declaredType, null); } public String getDeclaredType() { return declaredType; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } }
[ "public", "class", "Binding", "{", "/**\n * the symbol's type. Like Int, Double, String, Boolean, CustomType ...\n */", "private", "final", "String", "declaredType", ";", "/**\n * at this stage also store a value here, so that the symbol table can\n * intermediately also be used as an interpreter table.\n */", "private", "Object", "value", ";", "public", "Binding", "(", "String", "declaredType", ",", "Object", "value", ")", "{", "checkArgument", "(", "!", "StringUtils", ".", "isBlank", "(", "declaredType", ")", ")", ";", "this", ".", "declaredType", "=", "declaredType", ";", "this", ".", "value", "=", "value", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "StringUtils", ".", "join", "(", "\"", "declaredType: ", "\"", ",", "declaredType", ",", "\"", "; value: ", "\"", ",", "value", ")", ";", "}", "public", "Binding", "(", "String", "declaredType", ")", "{", "this", "(", "declaredType", ",", "null", ")", ";", "}", "public", "String", "getDeclaredType", "(", ")", "{", "return", "declaredType", ";", "}", "public", "Object", "getValue", "(", ")", "{", "return", "value", ";", "}", "public", "void", "setValue", "(", "Object", "value", ")", "{", "this", ".", "value", "=", "value", ";", "}", "}" ]
In a SymbolTable each variable name and formal-parameter name are bound to their types.
[ "In", "a", "SymbolTable", "each", "variable", "name", "and", "formal", "-", "parameter", "name", "are", "bound", "to", "their", "types", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
3360d735e1ca17d63ffc32da71be35f00aa289fb
Hundertmark256/trail-android
trail/src/main/java/com/amalbit/trail/ProjectionHelper.java
[ "MIT" ]
Java
ProjectionHelper
/** * Created by amal.chandran on 04/11/17. */
Created by amal.chandran on 04/11/17.
[ "Created", "by", "amal", ".", "chandran", "on", "04", "/", "11", "/", "17", "." ]
class ProjectionHelper { private float x, y; private android.graphics.Point previousPoint; private boolean isRouteSet; private float previousZoomLevel = -1.0f; private boolean isZooming = false; private LatLng mLineChartCenterLatLng; public Point point; private boolean isShadow; private OverlayPolyline overlayPolyline; public ProjectionHelper(OverlayPolyline overlayPolyline, boolean isShadow) { this.overlayPolyline = overlayPolyline; this.isShadow = isShadow; } public LatLng getCenterLatLng() { return mLineChartCenterLatLng; } public void setCenterLatLng(LatLng lineChartCenterLatLng) { mLineChartCenterLatLng = lineChartCenterLatLng; isRouteSet = true; } void onCameraMove(Projection projection, CameraPosition cameraPosition) { if (previousZoomLevel != cameraPosition.zoom) { isZooming = true; } previousZoomLevel = cameraPosition.zoom; point = projection.toScreenLocation(mLineChartCenterLatLng); if (previousPoint != null) { x = previousPoint.x - point.x; y = previousPoint.y - point.y; } if (isRouteSet) { if (isZooming) { if (isShadow) { overlayPolyline.scaleShadowPathMatrix(cameraPosition.zoom); } else { overlayPolyline.scalePathMatrix(cameraPosition.zoom); } isZooming = false; } if (!isShadow) { overlayPolyline.translatePathMatrix(-x, -y); } else { overlayPolyline.translateShadowPathMatrix(-x, -y); } previousPoint = point; } } }
[ "class", "ProjectionHelper", "{", "private", "float", "x", ",", "y", ";", "private", "android", ".", "graphics", ".", "Point", "previousPoint", ";", "private", "boolean", "isRouteSet", ";", "private", "float", "previousZoomLevel", "=", "-", "1.0f", ";", "private", "boolean", "isZooming", "=", "false", ";", "private", "LatLng", "mLineChartCenterLatLng", ";", "public", "Point", "point", ";", "private", "boolean", "isShadow", ";", "private", "OverlayPolyline", "overlayPolyline", ";", "public", "ProjectionHelper", "(", "OverlayPolyline", "overlayPolyline", ",", "boolean", "isShadow", ")", "{", "this", ".", "overlayPolyline", "=", "overlayPolyline", ";", "this", ".", "isShadow", "=", "isShadow", ";", "}", "public", "LatLng", "getCenterLatLng", "(", ")", "{", "return", "mLineChartCenterLatLng", ";", "}", "public", "void", "setCenterLatLng", "(", "LatLng", "lineChartCenterLatLng", ")", "{", "mLineChartCenterLatLng", "=", "lineChartCenterLatLng", ";", "isRouteSet", "=", "true", ";", "}", "void", "onCameraMove", "(", "Projection", "projection", ",", "CameraPosition", "cameraPosition", ")", "{", "if", "(", "previousZoomLevel", "!=", "cameraPosition", ".", "zoom", ")", "{", "isZooming", "=", "true", ";", "}", "previousZoomLevel", "=", "cameraPosition", ".", "zoom", ";", "point", "=", "projection", ".", "toScreenLocation", "(", "mLineChartCenterLatLng", ")", ";", "if", "(", "previousPoint", "!=", "null", ")", "{", "x", "=", "previousPoint", ".", "x", "-", "point", ".", "x", ";", "y", "=", "previousPoint", ".", "y", "-", "point", ".", "y", ";", "}", "if", "(", "isRouteSet", ")", "{", "if", "(", "isZooming", ")", "{", "if", "(", "isShadow", ")", "{", "overlayPolyline", ".", "scaleShadowPathMatrix", "(", "cameraPosition", ".", "zoom", ")", ";", "}", "else", "{", "overlayPolyline", ".", "scalePathMatrix", "(", "cameraPosition", ".", "zoom", ")", ";", "}", "isZooming", "=", "false", ";", "}", "if", "(", "!", "isShadow", ")", "{", "overlayPolyline", ".", "translatePathMatrix", "(", "-", "x", ",", "-", "y", ")", ";", "}", "else", "{", "overlayPolyline", ".", "translateShadowPathMatrix", "(", "-", "x", ",", "-", "y", ")", ";", "}", "previousPoint", "=", "point", ";", "}", "}", "}" ]
Created by amal.chandran on 04/11/17.
[ "Created", "by", "amal", ".", "chandran", "on", "04", "/", "11", "/", "17", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33623079962d9955e5a566dc5e1edda7a09b3699
chengkun123/ReadMark
app/src/main/java/com/mycompany/readmark/ui/widget/bannerview/BannerScroller.java
[ "Apache-2.0" ]
Java
BannerScroller
/** * Created by Lenovo. */
Created by Lenovo.
[ "Created", "by", "Lenovo", "." ]
public class BannerScroller extends Scroller { //固定时间,切换速率 private int mScrollerDuaration = 1000; public void setScrollerDuaration(int scrollerDuaration) { mScrollerDuaration = scrollerDuaration; } public BannerScroller(Context context) { super(context); } public BannerScroller(Context context, Interpolator interpolator) { super(context, interpolator); } public BannerScroller(Context context, Interpolator interpolator, boolean flywheel) { super(context, interpolator, flywheel); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duaration) { //传入固定duaration super.startScroll(startX, startY, dx, dy, mScrollerDuaration); } }
[ "public", "class", "BannerScroller", "extends", "Scroller", "{", "private", "int", "mScrollerDuaration", "=", "1000", ";", "public", "void", "setScrollerDuaration", "(", "int", "scrollerDuaration", ")", "{", "mScrollerDuaration", "=", "scrollerDuaration", ";", "}", "public", "BannerScroller", "(", "Context", "context", ")", "{", "super", "(", "context", ")", ";", "}", "public", "BannerScroller", "(", "Context", "context", ",", "Interpolator", "interpolator", ")", "{", "super", "(", "context", ",", "interpolator", ")", ";", "}", "public", "BannerScroller", "(", "Context", "context", ",", "Interpolator", "interpolator", ",", "boolean", "flywheel", ")", "{", "super", "(", "context", ",", "interpolator", ",", "flywheel", ")", ";", "}", "@", "Override", "public", "void", "startScroll", "(", "int", "startX", ",", "int", "startY", ",", "int", "dx", ",", "int", "dy", ",", "int", "duaration", ")", "{", "super", ".", "startScroll", "(", "startX", ",", "startY", ",", "dx", ",", "dy", ",", "mScrollerDuaration", ")", ";", "}", "}" ]
Created by Lenovo.
[ "Created", "by", "Lenovo", "." ]
[ "//固定时间,切换速率", "//传入固定duaration" ]
[ { "param": "Scroller", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Scroller", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3363fff427e3bea95178f324ce30b0e66314332f
cdhekne/My_Thesis
Thesis_WebApp/src/com/ml/search/SearchServlet.java
[ "Apache-2.0" ]
Java
SearchServlet
/** * Servlet implementation class SearchServlet */
Servlet implementation class SearchServlet
[ "Servlet", "implementation", "class", "SearchServlet" ]
public class SearchServlet extends HttpServlet { private static final long serialVersionUID = 1L; // private static final String url = "/home/cdhekne/Documents/Thesis/udacity_1.ttl"; private static final String db = "http://localhost:3030/Thesis/query"; private final OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, null); private QueryInfo qi = new QueryInfo(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String keyword; keyword = request.getParameter("keyword"); /*if(keyword.isEmpty()) { // Send back to home page response.sendRedirect("index.jsp"); return; } else {*/ // m.read(url, "RDF/XML"); String queryString = "prefix j.0: <http://mooclink.asu.edu/final_Mooc.owl#>\n" + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "PREFIX schema: <http://schema.org/>\n" + "SELECT ?Course_Name ?Course_RecBackground ?Course_Language ?Course_Provider WHERE {\n" + " ?course j.0:Course_Name ?Course_Name ; j.0:Course_RecBackground ?Course_RecBackground .\n" + "OPTIONAL {?course j.0:Course_Language ?Course_Language .} \n"+ "OPTIONAL {?course j.0:Course_Provider ?Course_Provider .} \n"+ "FILTER (regex(?Course_Name, \"" + keyword + "\", \"i\")).\n" + "}"; Query query = QueryFactory.create(queryString) ; QueryExecution qexec = QueryExecutionFactory.sparqlService(db, query); /*Course courses = new Course(); courses.setCourses(qi.getCourses(qexec)); request.setAttribute("courses", courses); */ // Better: forward request & response with redirect // Browser doesn't know that this is a new request, request // and response parameters are carried over ArrayList<Object> jsonObj= new ArrayList<Object>(); try{ ResultSet responseResultSet = qexec.execSelect(); while( responseResultSet.hasNext()) { HashMap<String, String> j = new HashMap<String, String>(); Gson gson = new Gson(); QuerySolution soln = responseResultSet.nextSolution(); RDFNode Course_Name = soln.get("?Course_Name"); RDFNode Course_RecBackground = soln.get("?Course_RecBackground"); RDFNode language = soln.get("?Course_Language"); RDFNode provider = soln.get("?Course_Provider"); Random randomizer = new Random(); List<String> list = new ArrayList<>(); list.add("Coursera"); list.add("edX"); list.add("Udacity"); list.add("Khan Academy"); list.add("OCW"); j.put("Course_Name", Course_Name.toString()); j.put("Course_RecBackground", Course_RecBackground.toString()); if(language==null) j.put("Course_Language", "-"); else j.put("Course_Language", language.toString()); if(provider==null) j.put("Course_Provider", list.get(randomizer.nextInt(list.size()))); else j.put("Course_Provider", provider.toString()); jsonObj.add(j); } } catch(Exception e){ e.printStackTrace(); } // json = "[" + json+ "]"; String json1 = new Gson().toJson(jsonObj); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().print(json1); /* RequestDispatcher dispatcher = request.getRequestDispatcher("results.jsp"); request.setAttribute("json", json1); dispatcher.forward(request, response);*/ /* // fw.close(); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); String json1 = new Gson().toJson(json); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json1); // response.getWriter().write(new Gson().toJson(json)); System.out.println("Done"); RequestDispatcher dispatcher = request.getRequestDispatcher("results.jsp"); request.setAttribute("json", json); dispatcher.forward(request, response);*/ } //} public String removeLastChar(String s) { if (s == null || s.length() == 0) { return s; } return s.substring(0, s.length()-1); } }
[ "public", "class", "SearchServlet", "extends", "HttpServlet", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "static", "final", "String", "db", "=", "\"", "http://localhost:3030/Thesis/query", "\"", ";", "private", "final", "OntModel", "m", "=", "ModelFactory", ".", "createOntologyModel", "(", "OntModelSpec", ".", "OWL_DL_MEM", ",", "null", ")", ";", "private", "QueryInfo", "qi", "=", "new", "QueryInfo", "(", ")", ";", "protected", "void", "doPost", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "String", "keyword", ";", "keyword", "=", "request", ".", "getParameter", "(", "\"", "keyword", "\"", ")", ";", "/*if(keyword.isEmpty()) {\n\t\t\t// Send back to home page\n\t\t\tresponse.sendRedirect(\"index.jsp\");\n\t\t\treturn;\n\t\t}\n\t\telse {*/", "String", "queryString", "=", "\"", "prefix j.0: <http://mooclink.asu.edu/final_Mooc.owl#>", "\\n", "\"", "+", "\"", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>", "\\n", "\"", "+", "\"", "PREFIX schema: <http://schema.org/>", "\\n", "\"", "+", "\"", "SELECT ?Course_Name ?Course_RecBackground ?Course_Language ?Course_Provider WHERE {", "\\n", "\"", "+", "\"", " ?course j.0:Course_Name ?Course_Name ; j.0:Course_RecBackground ?Course_RecBackground .", "\\n", "\"", "+", "\"", "OPTIONAL {?course j.0:Course_Language ?Course_Language .} ", "\\n", "\"", "+", "\"", "OPTIONAL {?course j.0:Course_Provider ?Course_Provider .} ", "\\n", "\"", "+", "\"", "FILTER (regex(?Course_Name, ", "\\\"", "\"", "+", "keyword", "+", "\"", "\\\"", ", ", "\\\"", "i", "\\\"", ")).", "\\n", "\"", "+", "\"", "}", "\"", ";", "Query", "query", "=", "QueryFactory", ".", "create", "(", "queryString", ")", ";", "QueryExecution", "qexec", "=", "QueryExecutionFactory", ".", "sparqlService", "(", "db", ",", "query", ")", ";", "/*Course courses = new Course();\n\t\t\tcourses.setCourses(qi.getCourses(qexec));\n\t\t\trequest.setAttribute(\"courses\", courses);\n\t\t\t*/", "ArrayList", "<", "Object", ">", "jsonObj", "=", "new", "ArrayList", "<", "Object", ">", "(", ")", ";", "try", "{", "ResultSet", "responseResultSet", "=", "qexec", ".", "execSelect", "(", ")", ";", "while", "(", "responseResultSet", ".", "hasNext", "(", ")", ")", "{", "HashMap", "<", "String", ",", "String", ">", "j", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "Gson", "gson", "=", "new", "Gson", "(", ")", ";", "QuerySolution", "soln", "=", "responseResultSet", ".", "nextSolution", "(", ")", ";", "RDFNode", "Course_Name", "=", "soln", ".", "get", "(", "\"", "?Course_Name", "\"", ")", ";", "RDFNode", "Course_RecBackground", "=", "soln", ".", "get", "(", "\"", "?Course_RecBackground", "\"", ")", ";", "RDFNode", "language", "=", "soln", ".", "get", "(", "\"", "?Course_Language", "\"", ")", ";", "RDFNode", "provider", "=", "soln", ".", "get", "(", "\"", "?Course_Provider", "\"", ")", ";", "Random", "randomizer", "=", "new", "Random", "(", ")", ";", "List", "<", "String", ">", "list", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "list", ".", "add", "(", "\"", "Coursera", "\"", ")", ";", "list", ".", "add", "(", "\"", "edX", "\"", ")", ";", "list", ".", "add", "(", "\"", "Udacity", "\"", ")", ";", "list", ".", "add", "(", "\"", "Khan Academy", "\"", ")", ";", "list", ".", "add", "(", "\"", "OCW", "\"", ")", ";", "j", ".", "put", "(", "\"", "Course_Name", "\"", ",", "Course_Name", ".", "toString", "(", ")", ")", ";", "j", ".", "put", "(", "\"", "Course_RecBackground", "\"", ",", "Course_RecBackground", ".", "toString", "(", ")", ")", ";", "if", "(", "language", "==", "null", ")", "j", ".", "put", "(", "\"", "Course_Language", "\"", ",", "\"", "-", "\"", ")", ";", "else", "j", ".", "put", "(", "\"", "Course_Language", "\"", ",", "language", ".", "toString", "(", ")", ")", ";", "if", "(", "provider", "==", "null", ")", "j", ".", "put", "(", "\"", "Course_Provider", "\"", ",", "list", ".", "get", "(", "randomizer", ".", "nextInt", "(", "list", ".", "size", "(", ")", ")", ")", ")", ";", "else", "j", ".", "put", "(", "\"", "Course_Provider", "\"", ",", "provider", ".", "toString", "(", ")", ")", ";", "jsonObj", ".", "add", "(", "j", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "String", "json1", "=", "new", "Gson", "(", ")", ".", "toJson", "(", "jsonObj", ")", ";", "response", ".", "setContentType", "(", "\"", "application/json", "\"", ")", ";", "response", ".", "setCharacterEncoding", "(", "\"", "UTF-8", "\"", ")", ";", "response", ".", "getWriter", "(", ")", ".", "print", "(", "json1", ")", ";", "/* \n RequestDispatcher dispatcher = request.getRequestDispatcher(\"results.jsp\");\n\t\t\trequest.setAttribute(\"json\", json1);\n\t\t\tdispatcher.forward(request, response);*/", "/* // fw.close();\n response.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n response.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST\");\n response.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type\");\n String json1 = new Gson().toJson(json);\n response.setContentType(\"application/json\");\n response.setCharacterEncoding(\"UTF-8\");\n response.getWriter().write(json1);\n// response.getWriter().write(new Gson().toJson(json)); \n System.out.println(\"Done\");\n\t\t\t\n\t\t\tRequestDispatcher dispatcher = request.getRequestDispatcher(\"results.jsp\");\n\t\t\trequest.setAttribute(\"json\", json);\n\t\t\tdispatcher.forward(request, response);*/", "}", "public", "String", "removeLastChar", "(", "String", "s", ")", "{", "if", "(", "s", "==", "null", "||", "s", ".", "length", "(", ")", "==", "0", ")", "{", "return", "s", ";", "}", "return", "s", ".", "substring", "(", "0", ",", "s", ".", "length", "(", ")", "-", "1", ")", ";", "}", "}" ]
Servlet implementation class SearchServlet
[ "Servlet", "implementation", "class", "SearchServlet" ]
[ "//\tprivate static final String url = \"/home/cdhekne/Documents/Thesis/udacity_1.ttl\";", "//\t\t\tm.read(url, \"RDF/XML\");", "// Better: forward request & response with redirect", "// Browser doesn't know that this is a new request, request", "// and response parameters are carried over", "//\t\t\tjson = \"[\" + json+ \"]\";", "//}" ]
[ { "param": "HttpServlet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HttpServlet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3365ccb3c0cb467702f5e0f036da91c5ea9e4836
Incapture/OG-Platform
projects/OG-LiveData/src/main/java/com/opengamma/livedata/server/RedisLastKnownValueStore.java
[ "Apache-2.0" ]
Java
RedisLastKnownValueStore
/** * A {@link LastKnownValueStore} backed by a Redis server. * In the case where this is not write-through, it primarily just acts * as a local cache which can be asynchronously updated from Redis * to retrieve the current values. * */
A LastKnownValueStore backed by a Redis server. In the case where this is not write-through, it primarily just acts as a local cache which can be asynchronously updated from Redis to retrieve the current values.
[ "A", "LastKnownValueStore", "backed", "by", "a", "Redis", "server", ".", "In", "the", "case", "where", "this", "is", "not", "write", "-", "through", "it", "primarily", "just", "acts", "as", "a", "local", "cache", "which", "can", "be", "asynchronously", "updated", "from", "Redis", "to", "retrieve", "the", "current", "values", "." ]
public class RedisLastKnownValueStore implements LastKnownValueStore { private static final Logger s_logger = LoggerFactory.getLogger(RedisLastKnownValueStore.class); private final FieldHistoryStore _inMemoryStore = new FieldHistoryStore(); private final JedisPool _jedisPool; //private final byte[] _jedisKey; private String _jedisKey; private final boolean _writeThrough; public RedisLastKnownValueStore(JedisPool jedisPool, String jedisKey, boolean writeThrough) { ArgumentChecker.notNull(jedisPool, "Jedis Pool"); ArgumentChecker.notNull(jedisKey, "Jedis key"); _jedisPool = jedisPool; /* try { _jedisKey = jedisKey.getBytes("UTF-8"); } catch (Exception e) { throw new OpenGammaRuntimeException("UTF-8 not a supported charset."); } */ _jedisKey = jedisKey; _writeThrough = writeThrough; updateFromRedis(true); } /** * Gets the jedisKey. * @return the jedisKey */ protected String getJedisKey() { return _jedisKey; } /** * Gets the jedisPool. * @return the jedisPool */ public JedisPool getJedisPool() { return _jedisPool; } /** * Gets the writeThrough. * @return the writeThrough */ public boolean isWriteThrough() { return _writeThrough; } // TODO kirk 2012-07-16 -- Actually implement asynchronous reading from Redis // TODO kirk 2012-07-16 -- Synchronization here is crazy restrictive. // Clearly could be done with a ReadWriteLock. @Override public synchronized void updateFields(FudgeMsg fieldValues) { // TODO kirk 2012-07-16 -- This is really only good enough as a proof of concept. // Ideally you'd want to handle more than just double-as-string ('cos really? That totally lame), // but I just want to get this working. if (isWriteThrough()) { Jedis jedis = getJedisPool().getResource(); try { for (FudgeField field : fieldValues.getAllFields()) { Double doubleValue = null; if (field.getType().getTypeId() == FudgeWireType.DOUBLE_TYPE_ID) { doubleValue = (Double) field.getValue(); } else if (field.getType().getTypeId() == FudgeWireType.STRING_TYPE_ID) { // Try a conversion to double. This can happen if the chunker leaves // a type in raw wire format, and it's a text-based format. try { doubleValue = Double.parseDouble((String) field.getValue()); } catch (Exception e) { // Couldn't be parsed. } } if (doubleValue == null) { s_logger.info("Redis encoding for {} can only handle doubles, can't handle {}", getJedisKey(), field); continue; } // Yep, this is ugly as hell. try { jedis.hset(getJedisKey(), field.getName(), doubleValue.toString()); } catch (JedisDataException jde) { s_logger.warn("Unable to write stuff yo."); } } } catch (Exception e) { s_logger.error("Unable to write fields to Redis : " + _jedisKey, e); } finally { getJedisPool().returnResource(jedis); } } _inMemoryStore.liveDataReceived(fieldValues); } @Override public synchronized FudgeMsg getFields() { return _inMemoryStore.getLastKnownValues(); } @Override public synchronized boolean isEmpty() { return _inMemoryStore.isEmpty(); } /** * * @param failOnError Whether to propagate any exception from a failure to load. * This should be used to control whether this is resilient * in the case of Redis failures. */ public synchronized void updateFromRedis(boolean failOnError) { _inMemoryStore.clear(); Jedis jedis = getJedisPool().getResource(); try { // TODO kirk 2012-07-16 -- Give this a FudgeContext. MutableFudgeMsg fudgeMsg = OpenGammaFudgeContext.getInstance().newMessage(); Map<String, String> allFields = jedis.hgetAll(getJedisKey()); s_logger.debug("Updating {} from Jedis: {}", getJedisKey(), allFields); for (Map.Entry<String, String> fieldEntry : allFields.entrySet()) { fudgeMsg.add(fieldEntry.getKey(), Double.parseDouble(fieldEntry.getValue())); } _inMemoryStore.liveDataReceived(fudgeMsg); } catch (Exception e) { s_logger.error("Unable to update from Redis", e); if (failOnError) { throw new OpenGammaRuntimeException("Unable to load state from underlying Redis instance on " + _jedisKey, e); } } finally { getJedisPool().returnResource(jedis); } } }
[ "public", "class", "RedisLastKnownValueStore", "implements", "LastKnownValueStore", "{", "private", "static", "final", "Logger", "s_logger", "=", "LoggerFactory", ".", "getLogger", "(", "RedisLastKnownValueStore", ".", "class", ")", ";", "private", "final", "FieldHistoryStore", "_inMemoryStore", "=", "new", "FieldHistoryStore", "(", ")", ";", "private", "final", "JedisPool", "_jedisPool", ";", "private", "String", "_jedisKey", ";", "private", "final", "boolean", "_writeThrough", ";", "public", "RedisLastKnownValueStore", "(", "JedisPool", "jedisPool", ",", "String", "jedisKey", ",", "boolean", "writeThrough", ")", "{", "ArgumentChecker", ".", "notNull", "(", "jedisPool", ",", "\"", "Jedis Pool", "\"", ")", ";", "ArgumentChecker", ".", "notNull", "(", "jedisKey", ",", "\"", "Jedis key", "\"", ")", ";", "_jedisPool", "=", "jedisPool", ";", "/*\n try {\n _jedisKey = jedisKey.getBytes(\"UTF-8\");\n } catch (Exception e) {\n throw new OpenGammaRuntimeException(\"UTF-8 not a supported charset.\");\n }\n */", "_jedisKey", "=", "jedisKey", ";", "_writeThrough", "=", "writeThrough", ";", "updateFromRedis", "(", "true", ")", ";", "}", "/**\n * Gets the jedisKey.\n * @return the jedisKey\n */", "protected", "String", "getJedisKey", "(", ")", "{", "return", "_jedisKey", ";", "}", "/**\n * Gets the jedisPool.\n * @return the jedisPool\n */", "public", "JedisPool", "getJedisPool", "(", ")", "{", "return", "_jedisPool", ";", "}", "/**\n * Gets the writeThrough.\n * @return the writeThrough\n */", "public", "boolean", "isWriteThrough", "(", ")", "{", "return", "_writeThrough", ";", "}", "@", "Override", "public", "synchronized", "void", "updateFields", "(", "FudgeMsg", "fieldValues", ")", "{", "if", "(", "isWriteThrough", "(", ")", ")", "{", "Jedis", "jedis", "=", "getJedisPool", "(", ")", ".", "getResource", "(", ")", ";", "try", "{", "for", "(", "FudgeField", "field", ":", "fieldValues", ".", "getAllFields", "(", ")", ")", "{", "Double", "doubleValue", "=", "null", ";", "if", "(", "field", ".", "getType", "(", ")", ".", "getTypeId", "(", ")", "==", "FudgeWireType", ".", "DOUBLE_TYPE_ID", ")", "{", "doubleValue", "=", "(", "Double", ")", "field", ".", "getValue", "(", ")", ";", "}", "else", "if", "(", "field", ".", "getType", "(", ")", ".", "getTypeId", "(", ")", "==", "FudgeWireType", ".", "STRING_TYPE_ID", ")", "{", "try", "{", "doubleValue", "=", "Double", ".", "parseDouble", "(", "(", "String", ")", "field", ".", "getValue", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "if", "(", "doubleValue", "==", "null", ")", "{", "s_logger", ".", "info", "(", "\"", "Redis encoding for {} can only handle doubles, can't handle {}", "\"", ",", "getJedisKey", "(", ")", ",", "field", ")", ";", "continue", ";", "}", "try", "{", "jedis", ".", "hset", "(", "getJedisKey", "(", ")", ",", "field", ".", "getName", "(", ")", ",", "doubleValue", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "JedisDataException", "jde", ")", "{", "s_logger", ".", "warn", "(", "\"", "Unable to write stuff yo.", "\"", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "s_logger", ".", "error", "(", "\"", "Unable to write fields to Redis : ", "\"", "+", "_jedisKey", ",", "e", ")", ";", "}", "finally", "{", "getJedisPool", "(", ")", ".", "returnResource", "(", "jedis", ")", ";", "}", "}", "_inMemoryStore", ".", "liveDataReceived", "(", "fieldValues", ")", ";", "}", "@", "Override", "public", "synchronized", "FudgeMsg", "getFields", "(", ")", "{", "return", "_inMemoryStore", ".", "getLastKnownValues", "(", ")", ";", "}", "@", "Override", "public", "synchronized", "boolean", "isEmpty", "(", ")", "{", "return", "_inMemoryStore", ".", "isEmpty", "(", ")", ";", "}", "/**\n * \n * @param failOnError Whether to propagate any exception from a failure to load.\n * This should be used to control whether this is resilient\n * in the case of Redis failures.\n */", "public", "synchronized", "void", "updateFromRedis", "(", "boolean", "failOnError", ")", "{", "_inMemoryStore", ".", "clear", "(", ")", ";", "Jedis", "jedis", "=", "getJedisPool", "(", ")", ".", "getResource", "(", ")", ";", "try", "{", "MutableFudgeMsg", "fudgeMsg", "=", "OpenGammaFudgeContext", ".", "getInstance", "(", ")", ".", "newMessage", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "allFields", "=", "jedis", ".", "hgetAll", "(", "getJedisKey", "(", ")", ")", ";", "s_logger", ".", "debug", "(", "\"", "Updating {} from Jedis: {}", "\"", ",", "getJedisKey", "(", ")", ",", "allFields", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "fieldEntry", ":", "allFields", ".", "entrySet", "(", ")", ")", "{", "fudgeMsg", ".", "add", "(", "fieldEntry", ".", "getKey", "(", ")", ",", "Double", ".", "parseDouble", "(", "fieldEntry", ".", "getValue", "(", ")", ")", ")", ";", "}", "_inMemoryStore", ".", "liveDataReceived", "(", "fudgeMsg", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "s_logger", ".", "error", "(", "\"", "Unable to update from Redis", "\"", ",", "e", ")", ";", "if", "(", "failOnError", ")", "{", "throw", "new", "OpenGammaRuntimeException", "(", "\"", "Unable to load state from underlying Redis instance on ", "\"", "+", "_jedisKey", ",", "e", ")", ";", "}", "}", "finally", "{", "getJedisPool", "(", ")", ".", "returnResource", "(", "jedis", ")", ";", "}", "}", "}" ]
A {@link LastKnownValueStore} backed by a Redis server.
[ "A", "{", "@link", "LastKnownValueStore", "}", "backed", "by", "a", "Redis", "server", "." ]
[ "//private final byte[] _jedisKey;", "// TODO kirk 2012-07-16 -- Actually implement asynchronous reading from Redis", "// TODO kirk 2012-07-16 -- Synchronization here is crazy restrictive.", "// Clearly could be done with a ReadWriteLock.", "// TODO kirk 2012-07-16 -- This is really only good enough as a proof of concept.", "// Ideally you'd want to handle more than just double-as-string ('cos really? That totally lame),", "// but I just want to get this working.", "// Try a conversion to double. This can happen if the chunker leaves", "// a type in raw wire format, and it's a text-based format.", "// Couldn't be parsed.", "// Yep, this is ugly as hell.", "// TODO kirk 2012-07-16 -- Give this a FudgeContext." ]
[ { "param": "LastKnownValueStore", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "LastKnownValueStore", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3368ac0eec36dfd026005e949f034dae75e14d00
SEALABQualityGroup/SEAA-replication-package
code/easier-logicalSpecification/LogicalSpecification/src/logicalSpecification/actions/UML/impl/UMLMoveActionImpl.java
[ "CC0-1.0" ]
Java
UMLMoveActionImpl
/** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Move Action</b></em>'. * <!-- end-user-doc --> * * @generated */
An implementation of the model object 'Move Action'.
[ "An", "implementation", "of", "the", "model", "object", "'", "Move", "Action", "'", "." ]
public abstract class UMLMoveActionImpl extends MoveActionImpl implements UMLMoveAction { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected UMLMoveActionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return UMLPackage.Literals.UML_MOVE_ACTION; } }
[ "public", "abstract", "class", "UMLMoveActionImpl", "extends", "MoveActionImpl", "implements", "UMLMoveAction", "{", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "protected", "UMLMoveActionImpl", "(", ")", "{", "super", "(", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "@", "Override", "protected", "EClass", "eStaticClass", "(", ")", "{", "return", "UMLPackage", ".", "Literals", ".", "UML_MOVE_ACTION", ";", "}", "}" ]
<!-- begin-user-doc --> An implementation of the model object '<em><b>Move Action</b></em>'.
[ "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "An", "implementation", "of", "the", "model", "object", "'", "<em", ">", "<b", ">", "Move", "Action<", "/", "b", ">", "<", "/", "em", ">", "'", "." ]
[]
[ { "param": "MoveActionImpl", "type": null }, { "param": "UMLMoveAction", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MoveActionImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "UMLMoveAction", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3368adb590371c54ed5598ba1109969f0088ee64
SeanGaoTesing/halo-master
src/main/java/run/halo/app/model/params/StaticContentParam.java
[ "MIT" ]
Java
StaticContentParam
/** * Static content param. * * @author Holldean * @date 2020-05-04 */
Static content param.
[ "Static", "content", "param", "." ]
@Data public class StaticContentParam { private String path; private String content; }
[ "@", "Data", "public", "class", "StaticContentParam", "{", "private", "String", "path", ";", "private", "String", "content", ";", "}" ]
Static content param.
[ "Static", "content", "param", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
336e78acc5a9a172e7ef29375896bfbb9139db43
brippe/ADSync
activedirectory/src/main/java/com/ripware/apps/activedirectory/xml/XMLReader.java
[ "Apache-2.0" ]
Java
XMLReader
/** * Reader for xml messages in the Luminis Broker. This reader handles all messages described in * the <i>Banner Integration for eLearning 8.0 Message Reference Guide</i>. * @author Brad Rippe */
Reader for xml messages in the Luminis Broker. This reader handles all messages described in the Banner Integration for eLearning 8.0 Message Reference Guide. @author Brad Rippe
[ "Reader", "for", "xml", "messages", "in", "the", "Luminis", "Broker", ".", "This", "reader", "handles", "all", "messages", "described", "in", "the", "Banner", "Integration", "for", "eLearning", "8", ".", "0", "Message", "Reference", "Guide", ".", "@author", "Brad", "Rippe" ]
public class XMLReader extends XMLUtils { Logger log = Logger.getLogger(XMLReader.class.getClass()); /** * Reads a Person data message * @param doc the person data message * @return the person information contained in the message */ public Person readPersonXMLMessage(Document doc) { try { Node enterprise = getEnterpriseNodeFromDoc(doc); Person pers = new Person(); Node person = getNode("person", enterprise.getChildNodes()); pers.setRecStatus(getNodeAttr("recstatus", person)); // 3 = delete person = AD disable account NodeList personData = person.getChildNodes(); pers.setEmail(getNodeValue("email", personData)); Node tel = getNode("tel", personData); if(tel != null) { String teleType = getNodeAttr("teltype", tel); if(teleType != null) { if(teleType.equals("1")) { pers.setVoiceTele(getNodeValue(tel)); } else if(teleType.equals("2")) { pers.setFaxTele(getNodeValue(tel)); } else if(teleType.equals("3")) { pers.setMobileTele(getNodeValue(tel)); } else if(teleType.equals("4")) { pers.setPagerTele(getNodeValue(tel)); } } } for(int x = 0; x < personData.getLength(); x++) { Node node = personData.item(x); if(node.getNodeName().equalsIgnoreCase("userid")){ String type = getNodeAttr("useridtype", node); //log.info("Type userid " + getNodeAttr("useridtype", node)); //log.info("userid " + getNodeValue(node)); if(type.equals("Logon ID")){ pers.setLogonID(getNodeValue(node)); pers.setPassword(getNodeAttr("password", node)); pers.setLogonEncryptType(getNodeAttr("pwencryptiontype", node)); // returns "" if none found } else if(type.equals("SCTID")) { pers.setSctID(getNodeValue(node)); pers.setPassword(getNodeAttr("password", node)); pers.setSctEncryptType(getNodeAttr("pwencryptiontype", node)); // returns "" if none found } else if(type.equals("Email ID")) { pers.setEmailID(getNodeValue(node)); } else if (type.equals("UDCIdentifier")) { pers.setUdcIdentifier(getNodeValue(node)); } } } Node name = getNode("name", personData); Node fn = getNode("fn", name.getChildNodes()); pers.setDisplayName(getNodeValue(fn)); Node preferredName = getNode("nickname", name.getChildNodes()); if(preferredName != null) pers.setPreferredName(getNodeValue(preferredName)); Node n = getNode("n", name.getChildNodes()); Node family = getNode("family", n.getChildNodes()); pers.setFamilyName(getNodeValue(family)); Node given = getNode("given", n.getChildNodes()); pers.setGivenName(getNodeValue(given)); Node prefix = getNode("prefix", n.getChildNodes()); if(prefix != null) pers.setPrefix(getNodeValue(prefix)); Node suffix = getNode("suffix", n.getChildNodes()); if(suffix != null) pers.setSuffix(getNodeValue(suffix)); Node partname = getNode("partname", n.getChildNodes()); if(partname != null && getNodeAttr("partnametype", partname) != null && getNodeAttr("partnametype", partname).equals("MiddleName")) { pers.setMiddleName(getNodeValue(partname)); } Node demographics = getNode("demographics", personData); Node gender = getNode("gender", demographics.getChildNodes()); pers.setGender(getNodeValue(gender)); Node adr = getNode("adr", personData); if(adr != null) { Node street = getNode("street", adr.getChildNodes()); pers.setStreet(getNodeValue(street)); Node locality = getNode("locality", adr.getChildNodes()); pers.setCity(getNodeValue(locality)); Node region = getNode("region", adr.getChildNodes()); pers.setState(getNodeValue(region)); Node pcode = getNode("pcode", adr.getChildNodes()); pers.setZipCode(getNodeValue(pcode)); } else { log.debug("No address for " + pers.getDisplayName()); } for(int x = 0; x < personData.getLength(); x++) { Node node = personData.item(x); if(node.getNodeName().equalsIgnoreCase("institutionrole")){ Role role = new Role(); role.setPrimaryrole(getNodeAttr("primaryrole", node)); role.setInstitutionroletype(getNodeAttr("institutionroletype", node)); log.info("Person is a " + role.getInstitutionroletype()); pers.getInstitutionRoles().add(role); } } Node extension = getNode("extension", personData); Node luminisperson = getNode("luminisperson", extension.getChildNodes()); NodeList rols = luminisperson.getChildNodes(); for(int x = 0; x < rols.getLength(); x++) { Node node = rols.item(x); // maybe more than one major if(node.getNodeName().equalsIgnoreCase("academicmajor")) { pers.setMajor(getNodeValue(node)); } else if(node.getNodeName().equalsIgnoreCase("academictitle")) { // faculty member pers.setAcademicTitle(getNodeValue(node)); } else if(node.getNodeName().equalsIgnoreCase("academicdegree")) { // faculty member pers.setAcademicDegree(getNodeValue(node)); } else if(node.getNodeName().equalsIgnoreCase("customrole")) { pers.getLuminisRoles().add(getNodeValue(node)); } } log.info("Processing "+pers.getDisplayName()); return pers; } catch ( Exception e ) { log.error(e); e.printStackTrace(); return null; } } /** * Reads a group message. Group messages are sent for College, Department, * Course, and Term data. * @param doc the group data message * @return a Group based on the type of message where it's for College, Department, Course, * or Term data */ public Group readGroupXMLMessage(Document doc) { try { Node enterprise = getEnterpriseNodeFromDoc(doc); log.info("Group Message"); return parseGroupMessage(enterprise); } catch ( Exception e ) { log.error(e); e.printStackTrace(); return null; } } /** * Reads a cross list section membership message. * @param doc the cross list section membership * @return the cross list section membership message content. */ public CrossListSectionMembership readCrossListUpdateXMLMessage(Document doc) { try { Node enterprise = getEnterpriseNodeFromDoc(doc); log.info("Cross List Section Update Message"); return parseCrossListUpdateMessage(enterprise); // still returns a group } catch ( Exception e ) { log.error(e); e.printStackTrace(); return null; } } /** * Reads a student enrollment message * @param doc the student enrollment message * @return the student enrollment message content. */ public Enroll readEnrollXMLMessage(Document doc) { try { Node enterprise = getEnterpriseNodeFromDoc(doc); log.info("Student Enrollment Message"); return parseStudentEnrollmentMessage(enterprise); } catch ( Exception e ) { log.error(e); e.printStackTrace(); return null; } } /** * Reads a faculty assignment message * @param doc the faculty assignment message * @return the faculty assignment message content */ public Assignment readAssignmentXMLMessage(Document doc) { try { Node enterprise = getEnterpriseNodeFromDoc(doc); log.info("Faculty Assignment Message"); return parseFacultyAssignmentMessage(enterprise); } catch ( Exception e ) { log.error(e); e.printStackTrace(); return null; } } /** * Reads a message to delete a group. Group messages are sent for College, Department, * Course, and Term data. * @param doc the group delete message * @return group information for the group to be deleted */ public Group readDeleteGroupXMLMessage(Document doc) { try { Node enterprise = getEnterpriseNodeFromDoc(doc); // change to message CollegeGroup cg = new CollegeGroup(); Node group = getNode("group", enterprise.getChildNodes()); cg.setRecStatus(getNodeAttr("recstatus", group)); NodeList groupData = group.getChildNodes(); Node sourcedid = getNode("sourcedid", groupData); Node id = getNode("id", sourcedid.getChildNodes()); cg.setGroupID(getNodeValue(id)); Node description = getNode("description", groupData); Node shortDesc = getNode("short", description.getChildNodes()); cg.setShortDescription(getNodeValue(shortDesc)); return cg; } catch ( Exception e ) { log.error(e); e.printStackTrace(); return null; } } /** * Reads a message to delete student enrollment * @param doc the student enrollment deletion message * @return the enrollment information of the student to be deleted */ public Enroll readDeleteEnrollXMLMessage(Document doc) { try { Node enterprise = getEnterpriseNodeFromDoc(doc); // change to message Node membership = getNode("membership", enterprise.getChildNodes()); // adds to cross list sections don't have a group tag NodeList membershipData = membership.getChildNodes(); Node sourcedid = getNode("sourcedid", membershipData); Node id = getNode("id", sourcedid.getChildNodes()); Enroll enroll = new Enroll(); enroll.setCourseId(getNodeValue(id)); log.info("Delete enrollment for Course ID: " + enroll.getCourseId()); for(int x = 0; x < membershipData.getLength(); x++) { Node node = membershipData.item(x); if(node.getNodeName().equalsIgnoreCase("member")){ EnrollMember member = new EnrollMember(); member.setSourceId(getNodeValue(getNode("id", getNode("sourcedid", node.getChildNodes()).getChildNodes()))); member.setIdType(Integer.parseInt(getNodeValue(getNode("idtype", node.getChildNodes())))); member.setStatus(Integer.parseInt(getNodeValue(getNode("status", getNode("role", node.getChildNodes()).getChildNodes())))); Node role = getNode("role", node.getChildNodes()); member.setRecStatus(getNodeAttr("recstatus", role)); log.info("Source Id " + member.getSourceId()); log.info("IdType " + member.getIdType()); log.info("Status " + member.getStatus()); log.info("RecStatus " + member.getRecStatus()); enroll.getMembers().add(member); } } return enroll; } catch ( Exception e ) { log.error(e); e.printStackTrace(); return null; } } /** * Reads a message to delete faculty assignment * @param doc the faculty assignment deletion message * @return the assignment information of the faculty member to be deleted */ public Assignment readDeleteAssignXMLMessage(Document doc) { try { Node enterprise = getEnterpriseNodeFromDoc(doc); // change to message Node membership = getNode("membership", enterprise.getChildNodes()); // adds to cross list sections don't have a group tag NodeList membershipData = membership.getChildNodes(); Node sourcedid = getNode("sourcedid", membershipData); Node id = getNode("id", sourcedid.getChildNodes()); Assignment assign = new Assignment(); assign.setCourseId(getNodeValue(id)); log.info("Delete assignment for Course ID: " + assign.getCourseId()); for(int x = 0; x < membershipData.getLength(); x++) { Node node = membershipData.item(x); if(node.getNodeName().equalsIgnoreCase("member")){ EnrollMember member = new EnrollMember(); member.setSourceId(getNodeValue(getNode("id", getNode("sourcedid", node.getChildNodes()).getChildNodes()))); member.setIdType(Integer.parseInt(getNodeValue(getNode("idtype", node.getChildNodes())))); Node role = getNode("role", node.getChildNodes()); member.setStatus(Integer.parseInt(getNodeValue(getNode("status", role.getChildNodes())))); member.setRecStatus(getNodeAttr("recstatus", role)); log.info("Faculty id " + member.getSourceId()); log.info("IdType " + member.getIdType()); log.info("Status " + member.getStatus()); log.info("RecStatus " + member.getRecStatus()); assign.getMembers().add(member); } } return assign; } catch ( Exception e ) { log.error(e); e.printStackTrace(); return null; } } /** * Determines if the message is a group message * @param doc the message * @return true if a group message, otherwise false */ public boolean isNonGroupMessage(Document doc) { Node enterprise = getEnterpriseNodeFromDoc(doc); NodeList children = enterprise.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() != 1) continue; if(n.getNodeName() == "membership") // this could also be student enrollment; or faculty assignment return true; } return false; } /** * Determines if the message is an enrollment message * @param doc the message * @return true if an enrollment message, otherwise false */ public boolean isStudentEnrollmentMessage(Document doc) { Node enterprise = getEnterpriseNodeFromDoc(doc); NodeList children = enterprise.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() != 1) continue; if(n.getNodeName().equals("membership")) { // this could also be student enrollment; or faculty assignment Node role = getNode("role", getNode("member", n.getChildNodes()).getChildNodes()); //log.info("Role type = " + getNodeAttr("roletype", role)); if(role != null && getNodeAttr("roletype", role).equals("01")) return true; } } return false; } /** * Determines if the message is an student drop message * @param doc the message * @return true if an drop enrollment message, otherwise false */ public boolean isStudentDropMessage(Document doc) { Node enterprise = getEnterpriseNodeFromDoc(doc); NodeList children = enterprise.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() != 1) continue; if(n.getNodeName().equals("membership")) { // this could also be student enrollment; or faculty assignment Node role = getNode("role", getNode("member", n.getChildNodes()).getChildNodes()); String status = getNodeValue(getNode("status", role.getChildNodes())); //log.info("Role type = " + getNodeAttr("roletype", role)); if(role != null && getNodeAttr("roletype", role).equals("01") && (getNodeAttr("recstatus", role).equals("3") || status.equals("0"))) // drop by deletion of enrollment record = 3 // drop by status of the enrollment record being inactive return true; } } return false; } /** * Determines if the message is a faculty assignment message * @param doc the message * @return true if a faculty assignment message, otherwise false */ public boolean isFacultyAssignmentMessage(Document doc) { Node enterprise = getEnterpriseNodeFromDoc(doc); NodeList children = enterprise.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() != 1) continue; if(n.getNodeName().equals("membership")) { // this could also be student enrollment; or faculty assignment Node role = getNode("role", getNode("member", n.getChildNodes()).getChildNodes()); //log.info("Role type = " + getNodeAttr("roletype", role)); if(role != null && getNodeAttr("roletype", role).equals("02")) return true; } } return false; } /** * Determines if the message is a drop faculty assignment message * @param doc the message * @return true if a drop faculty assignment message, otherwise false */ public boolean isFacultyDropMessage(Document doc) { Node enterprise = getEnterpriseNodeFromDoc(doc); NodeList children = enterprise.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() != 1) continue; if(n.getNodeName().equals("membership")) { // this could also be student enrollment; or faculty assignment Node role = getNode("role", getNode("member", n.getChildNodes()).getChildNodes()); //log.info("Role type = " + getNodeAttr("roletype", role)); if(role != null && getNodeAttr("roletype", role).equals("02") && getNodeAttr("recstatus", role).equals("3")) // drop = 3 return true; } } return false; } /** * Determines if the message is a cross list section message * @param doc the message * @return true if a cross list section message, otherwise false */ public boolean isCrossListUpdateMessage(Document doc) { Node enterprise = getEnterpriseNodeFromDoc(doc); NodeList children = enterprise.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() != 1) continue; if(n.getNodeName().equals("membership")) { // this could also be student enrollment; or faculty assignment Node role = getNode("role", getNode("member", n.getChildNodes()).getChildNodes()); //log.info("Role type = " + getNodeAttr("roletype", role)); if(role != null && getNodeAttr("roletype", role) == null) return true; } } return false; } /** * Determines if the message is a delete message for a group * @param doc the message * @return true if a group delete message, otherwise false */ public boolean isGroupDeleteMessage(Document doc) { Node enterprise = getEnterpriseNodeFromDoc(doc); NodeList children = enterprise.getChildNodes(); Node group = getNode("group", children); String recStatus = getNodeAttr("recstatus", group); if(recStatus != null && recStatus.equals("3")) return true; return false; } /** * Creates a Document from an xml message * @param xmlMessage the xml to create the document from * @return the document of the xml * @throws ParserConfigurationException if a configuration error occurred * @throws SAXException if a sax error has occurred * @throws IOException if an i/o error has occurred */ public Document getXMLDocument(String xmlMessage) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlMessage)); //Document doc = docBuilder.parse(new File(fileName)); Document doc = docBuilder.parse(is); doc.getDocumentElement().normalize(); return doc; } /** * Returns the enterprise node from a document. The enterprise element is the root element for all * ldisp 2.0 messages * @param doc the document to get the enterprise element from * @return the enterprise element from an xml document */ private Node getEnterpriseNodeFromDoc(Document doc) { NodeList nodeLst = doc.getElementsByTagName("enterprise"); // 1st child return nodeLst.item(0); } /** * Parses a group message * @param enterprise the root node of the xml message * @return the group content from the message */ private Group parseGroupMessage(Node enterprise) { Node group = getNode("group", enterprise.getChildNodes()); // adds to cross list sections don't have a group tag NodeList groupData = group.getChildNodes(); Node sourcedid = getNode("sourcedid", groupData); Node id = getNode("id", sourcedid.getChildNodes()); Node grouptype = getNode("grouptype", groupData); Node scheme = getNode("scheme", grouptype.getChildNodes()); Node typevalue = getNode("typevalue", grouptype.getChildNodes()); String typeOfGroup = getNodeValue(typevalue); Node description = getNode("description", groupData); Node shortDesc = getNode("short", description.getChildNodes()); Node longDesc = getNode("long", description.getChildNodes()); log.info("Message Type = " + typeOfGroup); Group cg = GroupFactory.instanceOfGroup(typeOfGroup); // returns the proper group cg.setGroupID(getNodeValue(id)); cg.setScheme(getNodeValue(scheme)); cg.setGroupType(getNodeValue(typevalue)); cg.setTypeValueLevel(getNodeAttr("level", typevalue)); cg.setShortDescription(getNodeValue(shortDesc)); if(typeOfGroup.equals("Term")) { Node timeframe = getNode("timeframe", groupData); Node enrollcontrol = getNode("enrollcontrol", groupData); Node begin = getNode("begin", timeframe.getChildNodes()); // there's a restrict attr that if set 0 states that the student can't participate before the beginning date Node end = getNode("end", timeframe.getChildNodes()); // again restrict attr here Node enrollaccept = getNode("enrollaccept", enrollcontrol.getChildNodes()); TermGroup tg = (TermGroup) cg; tg.setBegin(getNodeValue(begin)); tg.setEnd(getNodeValue(end)); try { tg.setEnrollAccept(Integer.parseInt(getNodeValue(enrollaccept))); } catch(NumberFormatException nfe) { tg.setEnrollAccept(0); } } if(typeOfGroup.equals("CourseSection")) { CourseSectionGroup csg = null; try { Node fullDesc = getNode("full", description.getChildNodes()); Node org = getNode("org", groupData); Node orgUnit = getNode("orgunit", org.getChildNodes()); csg = (CourseSectionGroup) cg; csg.setFullDesc(getNodeValue(fullDesc)); csg.setOrg(getNodeValue(orgUnit)); // these tags determine if the message is targeted for the LMS // updates to a section targeted for the LMS require a deletion of the // old section and creation of a new section; these tags may or may not be present Node extension = getNode("extension", groupData); Node luminisgroup = getNode("luminisgroup", extension.getChildNodes()); Node deliverysystem = getNode("deliverysystem", luminisgroup.getChildNodes()); if(deliverysystem != null) csg.setDeliverySystem(getNodeValue(deliverysystem)); Node events = getNode("events", luminisgroup.getChildNodes()); if(events != null) { Node recurringevent = getNode("recurringevent", events.getChildNodes()); csg.setEventDescription(getNodeValue(getNode("eventdescription", recurringevent.getChildNodes()))); csg.setBeginDate(getNodeValue(getNode("begindate", recurringevent.getChildNodes()))); csg.setEndDate(getNodeValue(getNode("enddate", recurringevent.getChildNodes()))); csg.setDaysOfWeek(getNodeValue(getNode("daysofweek", recurringevent.getChildNodes()))); csg.setBeginTime(getNodeValue(getNode("begintime", recurringevent.getChildNodes()))); csg.setEndTime(getNodeValue(getNode("endtime", recurringevent.getChildNodes()))); csg.setLocation(getNodeValue(getNode("location", recurringevent.getChildNodes()))); } } catch(Exception e) { log.info("CourseSection additional LMS tags not present. This is ok!"); // not targeted for the LMS csg.setDeliverySystem(null); } } if(typeOfGroup.equals("Course") || typeOfGroup.equals("CourseSection")) { CourseGroup cg2 = (CourseGroup) cg; for(int x = 0; x < groupData.getLength(); x++) { Node node = groupData.item(x); if(node.getNodeName().equalsIgnoreCase("relationship")){ Relationship relationship = new Relationship(); relationship.setRelation(getNodeAttr("relation", node)); relationship.setRelationshipID(getNodeValue(getNode("id", getNode("sourcedid", node.getChildNodes()).getChildNodes()))); relationship.setLabel(getNodeValue(getNode("label", node.getChildNodes()))); cg2.getRelationships().add(relationship); } } } if(!typeOfGroup.equals("CrossListedSection")) { cg.setLongDescription(getNodeValue(longDesc)); // not long desc in cross list section group } return cg; } /** * Parses a cross list section membership message * @param enterprise the root node of the xml message * @return the cross list section content from the message */ private CrossListSectionMembership parseCrossListUpdateMessage(Node enterprise) { Node membership = getNode("membership", enterprise.getChildNodes()); // adds to cross list sections don't have a group tag NodeList membershipData = membership.getChildNodes(); Node sourcedid = getNode("sourcedid", membershipData); Node id = getNode("id", sourcedid.getChildNodes()); CrossListSectionMembership clsm = new CrossListSectionMembership(); clsm.setId(getNodeValue(id)); for(int x = 0; x < membershipData.getLength(); x++) { Node node = membershipData.item(x); if(node.getNodeName().equalsIgnoreCase("member")){ Member member = new Member(); member.setId(getNodeValue(getNode("id", getNode("sourcedid", node.getChildNodes()).getChildNodes()))); member.setIdType(Integer.parseInt(getNodeValue(getNode("idtype", node.getChildNodes())))); member.setStatus(Integer.parseInt(getNodeValue(getNode("status", getNode("role", node.getChildNodes()).getChildNodes())))); member.setRecStatus(getNodeAttr("recstatus", getNode("role", node.getChildNodes()))); clsm.getMembers().add(member); } } return clsm; } /** * Parses a student enrollment message * @param enterprise the root node of the xml message * @return the student enrollment content from the message */ private Enroll parseStudentEnrollmentMessage(Node enterprise) { Node membership = getNode("membership", enterprise.getChildNodes()); // adds to cross list sections don't have a group tag NodeList membershipData = membership.getChildNodes(); Node sourcedid = getNode("sourcedid", membershipData); Node id = getNode("id", sourcedid.getChildNodes()); Enroll enroll = new Enroll(); enroll.setCourseId(getNodeValue(id)); log.info("Enrollment for Course ID: " + enroll.getCourseId()); for(int x = 0; x < membershipData.getLength(); x++) { Node node = membershipData.item(x); if(node.getNodeName().equalsIgnoreCase("member")){ EnrollMember member = new EnrollMember(); member.setSourceId(getNodeValue(getNode("id", getNode("sourcedid", node.getChildNodes()).getChildNodes()))); member.setIdType(Integer.parseInt(getNodeValue(getNode("idtype", node.getChildNodes())))); Node role = getNode("role", node.getChildNodes()); member.setStatus(Integer.parseInt(getNodeValue(getNode("status", role.getChildNodes())))); //member.setRecStatus(getNodeAttr("recstatus", role)); only used for delete message member.setRoleType(getNodeAttr("roletype", role)); // roletype = 01 ; student enrollment Node timeframe = getNode("timeframe", role.getChildNodes()); Node begin = getNode("begin", timeframe.getChildNodes()); Node end = getNode("end", timeframe.getChildNodes()); member.setBeginEnroll(getNodeValue(begin)); member.setBeginRestricted(Integer.parseInt(getNodeAttr("restrict", end))); member.setEndEnroll(getNodeValue(end)); member.setEndRestricted(Integer.parseInt(getNodeAttr("restrict", end))); NodeList roleChilds = role.getChildNodes(); for(int y = 0; y < roleChilds.getLength(); y++) { Node n = roleChilds.item(y); if(n.getNodeName().equals("intermresult")) { Node midMode = getNode("mode", n.getChildNodes()); if(midMode != null) member.setMidTermGradingMode(getNodeValue(midMode)); } } Node finalresult = getNode("finalresult", role.getChildNodes()); if(finalresult != null) { Node finalMode = getNode("mode", finalresult.getChildNodes()); if(finalMode != null) member.setFinalGradeMode(getNodeValue(finalMode)); } log.info("Event Source ID " + member.getSourceId()); log.info("IdType " + member.getIdType()); log.info("Status " + member.getStatus()); log.info("RecStatus " + member.getRecStatus()); log.info("Role Type " + member.getRoleType()); log.info("Begin Time " + member.getBeginEnroll()); log.info("Begin Restrict " + member.getBeginRestricted()); log.info("End Time " + member.getEndEnroll()); log.info("End Restrict " + member.getEndRestricted()); log.info("Mid Grade Mode " + member.getMidTermGradingMode()); log.info("Final Grade Mode " + member.getFinalGradeMode()); enroll.getMembers().add(member); } } return enroll; } /** * Parses a faculty assignment membership message * @param enterprise the root node of the xml message * @return the faculty assignment content from the message */ private Assignment parseFacultyAssignmentMessage(Node enterprise) { Node membership = getNode("membership", enterprise.getChildNodes()); // adds to cross list sections don't have a group tag NodeList membershipData = membership.getChildNodes(); Node sourcedid = getNode("sourcedid", membershipData); Node id = getNode("id", sourcedid.getChildNodes()); Assignment assign = new Assignment(); assign.setCourseId(getNodeValue(id)); log.info("Assignment for Course ID: " + assign.getCourseId()); for(int x = 0; x < membershipData.getLength(); x++) { Node node = membershipData.item(x); if(node.getNodeName().equalsIgnoreCase("member")){ EnrollMember member = new EnrollMember(); // this is an instructor assignment member.setSourceId(getNodeValue(getNode("id", getNode("sourcedid", node.getChildNodes()).getChildNodes()))); member.setIdType(Integer.parseInt(getNodeValue(getNode("idtype", node.getChildNodes())))); Node role = getNode("role", node.getChildNodes()); member.setStatus(Integer.parseInt(getNodeValue(getNode("status", role.getChildNodes())))); //member.setRecStatus(getNodeAttr("recstatus", role)); only for a delete message member.setRoleType(getNodeAttr("roletype", role)); // roletype = 02; faculty assignment member.setSubRole(getNodeValue(getNode("subrole", role.getChildNodes()))); // Primary or Subordinate log.info("Instructor Source ID " + member.getSourceId()); log.info("IdType " + member.getIdType()); log.info("Status " + member.getStatus()); log.info("RecStatus " + member.getRecStatus()); log.info("Role Type " + member.getRoleType()); log.info("Sub Role " + member.getSubRole()); assign.getMembers().add(member); } } return assign; } }
[ "public", "class", "XMLReader", "extends", "XMLUtils", "{", "Logger", "log", "=", "Logger", ".", "getLogger", "(", "XMLReader", ".", "class", ".", "getClass", "(", ")", ")", ";", "/**\n\t * Reads a Person data message\n\t * @param doc the person data message \n\t * @return the person information contained in the message\n\t */", "public", "Person", "readPersonXMLMessage", "(", "Document", "doc", ")", "{", "try", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "Person", "pers", "=", "new", "Person", "(", ")", ";", "Node", "person", "=", "getNode", "(", "\"", "person", "\"", ",", "enterprise", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setRecStatus", "(", "getNodeAttr", "(", "\"", "recstatus", "\"", ",", "person", ")", ")", ";", "NodeList", "personData", "=", "person", ".", "getChildNodes", "(", ")", ";", "pers", ".", "setEmail", "(", "getNodeValue", "(", "\"", "email", "\"", ",", "personData", ")", ")", ";", "Node", "tel", "=", "getNode", "(", "\"", "tel", "\"", ",", "personData", ")", ";", "if", "(", "tel", "!=", "null", ")", "{", "String", "teleType", "=", "getNodeAttr", "(", "\"", "teltype", "\"", ",", "tel", ")", ";", "if", "(", "teleType", "!=", "null", ")", "{", "if", "(", "teleType", ".", "equals", "(", "\"", "1", "\"", ")", ")", "{", "pers", ".", "setVoiceTele", "(", "getNodeValue", "(", "tel", ")", ")", ";", "}", "else", "if", "(", "teleType", ".", "equals", "(", "\"", "2", "\"", ")", ")", "{", "pers", ".", "setFaxTele", "(", "getNodeValue", "(", "tel", ")", ")", ";", "}", "else", "if", "(", "teleType", ".", "equals", "(", "\"", "3", "\"", ")", ")", "{", "pers", ".", "setMobileTele", "(", "getNodeValue", "(", "tel", ")", ")", ";", "}", "else", "if", "(", "teleType", ".", "equals", "(", "\"", "4", "\"", ")", ")", "{", "pers", ".", "setPagerTele", "(", "getNodeValue", "(", "tel", ")", ")", ";", "}", "}", "}", "for", "(", "int", "x", "=", "0", ";", "x", "<", "personData", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "personData", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "userid", "\"", ")", ")", "{", "String", "type", "=", "getNodeAttr", "(", "\"", "useridtype", "\"", ",", "node", ")", ";", "if", "(", "type", ".", "equals", "(", "\"", "Logon ID", "\"", ")", ")", "{", "pers", ".", "setLogonID", "(", "getNodeValue", "(", "node", ")", ")", ";", "pers", ".", "setPassword", "(", "getNodeAttr", "(", "\"", "password", "\"", ",", "node", ")", ")", ";", "pers", ".", "setLogonEncryptType", "(", "getNodeAttr", "(", "\"", "pwencryptiontype", "\"", ",", "node", ")", ")", ";", "}", "else", "if", "(", "type", ".", "equals", "(", "\"", "SCTID", "\"", ")", ")", "{", "pers", ".", "setSctID", "(", "getNodeValue", "(", "node", ")", ")", ";", "pers", ".", "setPassword", "(", "getNodeAttr", "(", "\"", "password", "\"", ",", "node", ")", ")", ";", "pers", ".", "setSctEncryptType", "(", "getNodeAttr", "(", "\"", "pwencryptiontype", "\"", ",", "node", ")", ")", ";", "}", "else", "if", "(", "type", ".", "equals", "(", "\"", "Email ID", "\"", ")", ")", "{", "pers", ".", "setEmailID", "(", "getNodeValue", "(", "node", ")", ")", ";", "}", "else", "if", "(", "type", ".", "equals", "(", "\"", "UDCIdentifier", "\"", ")", ")", "{", "pers", ".", "setUdcIdentifier", "(", "getNodeValue", "(", "node", ")", ")", ";", "}", "}", "}", "Node", "name", "=", "getNode", "(", "\"", "name", "\"", ",", "personData", ")", ";", "Node", "fn", "=", "getNode", "(", "\"", "fn", "\"", ",", "name", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setDisplayName", "(", "getNodeValue", "(", "fn", ")", ")", ";", "Node", "preferredName", "=", "getNode", "(", "\"", "nickname", "\"", ",", "name", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "preferredName", "!=", "null", ")", "pers", ".", "setPreferredName", "(", "getNodeValue", "(", "preferredName", ")", ")", ";", "Node", "n", "=", "getNode", "(", "\"", "n", "\"", ",", "name", ".", "getChildNodes", "(", ")", ")", ";", "Node", "family", "=", "getNode", "(", "\"", "family", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setFamilyName", "(", "getNodeValue", "(", "family", ")", ")", ";", "Node", "given", "=", "getNode", "(", "\"", "given", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setGivenName", "(", "getNodeValue", "(", "given", ")", ")", ";", "Node", "prefix", "=", "getNode", "(", "\"", "prefix", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "prefix", "!=", "null", ")", "pers", ".", "setPrefix", "(", "getNodeValue", "(", "prefix", ")", ")", ";", "Node", "suffix", "=", "getNode", "(", "\"", "suffix", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "suffix", "!=", "null", ")", "pers", ".", "setSuffix", "(", "getNodeValue", "(", "suffix", ")", ")", ";", "Node", "partname", "=", "getNode", "(", "\"", "partname", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "partname", "!=", "null", "&&", "getNodeAttr", "(", "\"", "partnametype", "\"", ",", "partname", ")", "!=", "null", "&&", "getNodeAttr", "(", "\"", "partnametype", "\"", ",", "partname", ")", ".", "equals", "(", "\"", "MiddleName", "\"", ")", ")", "{", "pers", ".", "setMiddleName", "(", "getNodeValue", "(", "partname", ")", ")", ";", "}", "Node", "demographics", "=", "getNode", "(", "\"", "demographics", "\"", ",", "personData", ")", ";", "Node", "gender", "=", "getNode", "(", "\"", "gender", "\"", ",", "demographics", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setGender", "(", "getNodeValue", "(", "gender", ")", ")", ";", "Node", "adr", "=", "getNode", "(", "\"", "adr", "\"", ",", "personData", ")", ";", "if", "(", "adr", "!=", "null", ")", "{", "Node", "street", "=", "getNode", "(", "\"", "street", "\"", ",", "adr", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setStreet", "(", "getNodeValue", "(", "street", ")", ")", ";", "Node", "locality", "=", "getNode", "(", "\"", "locality", "\"", ",", "adr", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setCity", "(", "getNodeValue", "(", "locality", ")", ")", ";", "Node", "region", "=", "getNode", "(", "\"", "region", "\"", ",", "adr", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setState", "(", "getNodeValue", "(", "region", ")", ")", ";", "Node", "pcode", "=", "getNode", "(", "\"", "pcode", "\"", ",", "adr", ".", "getChildNodes", "(", ")", ")", ";", "pers", ".", "setZipCode", "(", "getNodeValue", "(", "pcode", ")", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "\"", "No address for ", "\"", "+", "pers", ".", "getDisplayName", "(", ")", ")", ";", "}", "for", "(", "int", "x", "=", "0", ";", "x", "<", "personData", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "personData", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "institutionrole", "\"", ")", ")", "{", "Role", "role", "=", "new", "Role", "(", ")", ";", "role", ".", "setPrimaryrole", "(", "getNodeAttr", "(", "\"", "primaryrole", "\"", ",", "node", ")", ")", ";", "role", ".", "setInstitutionroletype", "(", "getNodeAttr", "(", "\"", "institutionroletype", "\"", ",", "node", ")", ")", ";", "log", ".", "info", "(", "\"", "Person is a ", "\"", "+", "role", ".", "getInstitutionroletype", "(", ")", ")", ";", "pers", ".", "getInstitutionRoles", "(", ")", ".", "add", "(", "role", ")", ";", "}", "}", "Node", "extension", "=", "getNode", "(", "\"", "extension", "\"", ",", "personData", ")", ";", "Node", "luminisperson", "=", "getNode", "(", "\"", "luminisperson", "\"", ",", "extension", ".", "getChildNodes", "(", ")", ")", ";", "NodeList", "rols", "=", "luminisperson", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "rols", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "rols", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "academicmajor", "\"", ")", ")", "{", "pers", ".", "setMajor", "(", "getNodeValue", "(", "node", ")", ")", ";", "}", "else", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "academictitle", "\"", ")", ")", "{", "pers", ".", "setAcademicTitle", "(", "getNodeValue", "(", "node", ")", ")", ";", "}", "else", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "academicdegree", "\"", ")", ")", "{", "pers", ".", "setAcademicDegree", "(", "getNodeValue", "(", "node", ")", ")", ";", "}", "else", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "customrole", "\"", ")", ")", "{", "pers", ".", "getLuminisRoles", "(", ")", ".", "add", "(", "getNodeValue", "(", "node", ")", ")", ";", "}", "}", "log", ".", "info", "(", "\"", "Processing ", "\"", "+", "pers", ".", "getDisplayName", "(", ")", ")", ";", "return", "pers", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "/**\n\t * Reads a group message. Group messages are sent for College, Department,\n\t * Course, and Term data. \n\t * @param doc the group data message \n\t * @return a Group based on the type of message where it's for College, Department, Course,\n\t * \t\t\tor Term data\n\t */", "public", "Group", "readGroupXMLMessage", "(", "Document", "doc", ")", "{", "try", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "log", ".", "info", "(", "\"", "Group Message", "\"", ")", ";", "return", "parseGroupMessage", "(", "enterprise", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "/**\n\t * Reads a cross list section membership message. \n\t * @param doc the cross list section membership\n\t * @return the cross list section membership message content.\n\t */", "public", "CrossListSectionMembership", "readCrossListUpdateXMLMessage", "(", "Document", "doc", ")", "{", "try", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "log", ".", "info", "(", "\"", "Cross List Section Update Message", "\"", ")", ";", "return", "parseCrossListUpdateMessage", "(", "enterprise", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "/**\n\t * Reads a student enrollment message\n\t * @param doc the student enrollment message \n\t * @return the student enrollment message content.\n\t */", "public", "Enroll", "readEnrollXMLMessage", "(", "Document", "doc", ")", "{", "try", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "log", ".", "info", "(", "\"", "Student Enrollment Message", "\"", ")", ";", "return", "parseStudentEnrollmentMessage", "(", "enterprise", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "/**\n\t * Reads a faculty assignment message\n\t * @param doc the faculty assignment message\n\t * @return the faculty assignment message content\n\t */", "public", "Assignment", "readAssignmentXMLMessage", "(", "Document", "doc", ")", "{", "try", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "log", ".", "info", "(", "\"", "Faculty Assignment Message", "\"", ")", ";", "return", "parseFacultyAssignmentMessage", "(", "enterprise", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "/**\n\t * Reads a message to delete a group. Group messages are sent for College, Department,\n\t * Course, and Term data. \n\t * @param doc the group delete message\n\t * @return group information for the group to be deleted\n\t */", "public", "Group", "readDeleteGroupXMLMessage", "(", "Document", "doc", ")", "{", "try", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "CollegeGroup", "cg", "=", "new", "CollegeGroup", "(", ")", ";", "Node", "group", "=", "getNode", "(", "\"", "group", "\"", ",", "enterprise", ".", "getChildNodes", "(", ")", ")", ";", "cg", ".", "setRecStatus", "(", "getNodeAttr", "(", "\"", "recstatus", "\"", ",", "group", ")", ")", ";", "NodeList", "groupData", "=", "group", ".", "getChildNodes", "(", ")", ";", "Node", "sourcedid", "=", "getNode", "(", "\"", "sourcedid", "\"", ",", "groupData", ")", ";", "Node", "id", "=", "getNode", "(", "\"", "id", "\"", ",", "sourcedid", ".", "getChildNodes", "(", ")", ")", ";", "cg", ".", "setGroupID", "(", "getNodeValue", "(", "id", ")", ")", ";", "Node", "description", "=", "getNode", "(", "\"", "description", "\"", ",", "groupData", ")", ";", "Node", "shortDesc", "=", "getNode", "(", "\"", "short", "\"", ",", "description", ".", "getChildNodes", "(", ")", ")", ";", "cg", ".", "setShortDescription", "(", "getNodeValue", "(", "shortDesc", ")", ")", ";", "return", "cg", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "/**\n\t * Reads a message to delete student enrollment \n\t * @param doc the student enrollment deletion message\n\t * @return the enrollment information of the student to be deleted\n\t */", "public", "Enroll", "readDeleteEnrollXMLMessage", "(", "Document", "doc", ")", "{", "try", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "Node", "membership", "=", "getNode", "(", "\"", "membership", "\"", ",", "enterprise", ".", "getChildNodes", "(", ")", ")", ";", "NodeList", "membershipData", "=", "membership", ".", "getChildNodes", "(", ")", ";", "Node", "sourcedid", "=", "getNode", "(", "\"", "sourcedid", "\"", ",", "membershipData", ")", ";", "Node", "id", "=", "getNode", "(", "\"", "id", "\"", ",", "sourcedid", ".", "getChildNodes", "(", ")", ")", ";", "Enroll", "enroll", "=", "new", "Enroll", "(", ")", ";", "enroll", ".", "setCourseId", "(", "getNodeValue", "(", "id", ")", ")", ";", "log", ".", "info", "(", "\"", "Delete enrollment for Course ID: ", "\"", "+", "enroll", ".", "getCourseId", "(", ")", ")", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "membershipData", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "membershipData", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "member", "\"", ")", ")", "{", "EnrollMember", "member", "=", "new", "EnrollMember", "(", ")", ";", "member", ".", "setSourceId", "(", "getNodeValue", "(", "getNode", "(", "\"", "id", "\"", ",", "getNode", "(", "\"", "sourcedid", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "member", ".", "setIdType", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "idtype", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "member", ".", "setStatus", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "status", "\"", ",", "getNode", "(", "\"", "role", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ";", "member", ".", "setRecStatus", "(", "getNodeAttr", "(", "\"", "recstatus", "\"", ",", "role", ")", ")", ";", "log", ".", "info", "(", "\"", "Source Id ", "\"", "+", "member", ".", "getSourceId", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "IdType ", "\"", "+", "member", ".", "getIdType", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Status ", "\"", "+", "member", ".", "getStatus", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "RecStatus ", "\"", "+", "member", ".", "getRecStatus", "(", ")", ")", ";", "enroll", ".", "getMembers", "(", ")", ".", "add", "(", "member", ")", ";", "}", "}", "return", "enroll", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "/**\n\t * Reads a message to delete faculty assignment \n\t * @param doc the faculty assignment deletion message\n\t * @return the assignment information of the faculty member to be deleted\n\t */", "public", "Assignment", "readDeleteAssignXMLMessage", "(", "Document", "doc", ")", "{", "try", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "Node", "membership", "=", "getNode", "(", "\"", "membership", "\"", ",", "enterprise", ".", "getChildNodes", "(", ")", ")", ";", "NodeList", "membershipData", "=", "membership", ".", "getChildNodes", "(", ")", ";", "Node", "sourcedid", "=", "getNode", "(", "\"", "sourcedid", "\"", ",", "membershipData", ")", ";", "Node", "id", "=", "getNode", "(", "\"", "id", "\"", ",", "sourcedid", ".", "getChildNodes", "(", ")", ")", ";", "Assignment", "assign", "=", "new", "Assignment", "(", ")", ";", "assign", ".", "setCourseId", "(", "getNodeValue", "(", "id", ")", ")", ";", "log", ".", "info", "(", "\"", "Delete assignment for Course ID: ", "\"", "+", "assign", ".", "getCourseId", "(", ")", ")", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "membershipData", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "membershipData", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "member", "\"", ")", ")", "{", "EnrollMember", "member", "=", "new", "EnrollMember", "(", ")", ";", "member", ".", "setSourceId", "(", "getNodeValue", "(", "getNode", "(", "\"", "id", "\"", ",", "getNode", "(", "\"", "sourcedid", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "member", ".", "setIdType", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "idtype", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ";", "member", ".", "setStatus", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "status", "\"", ",", "role", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "member", ".", "setRecStatus", "(", "getNodeAttr", "(", "\"", "recstatus", "\"", ",", "role", ")", ")", ";", "log", ".", "info", "(", "\"", "Faculty id ", "\"", "+", "member", ".", "getSourceId", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "IdType ", "\"", "+", "member", ".", "getIdType", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Status ", "\"", "+", "member", ".", "getStatus", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "RecStatus ", "\"", "+", "member", ".", "getRecStatus", "(", ")", ")", ";", "assign", ".", "getMembers", "(", ")", ".", "add", "(", "member", ")", ";", "}", "}", "return", "assign", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "/**\n\t * Determines if the message is a group message\n\t * @param doc the message\n\t * @return true if a group message, otherwise false\n\t */", "public", "boolean", "isNonGroupMessage", "(", "Document", "doc", ")", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "NodeList", "children", "=", "enterprise", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "children", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "n", "=", "children", ".", "item", "(", "i", ")", ";", "if", "(", "n", ".", "getNodeType", "(", ")", "!=", "1", ")", "continue", ";", "if", "(", "n", ".", "getNodeName", "(", ")", "==", "\"", "membership", "\"", ")", "return", "true", ";", "}", "return", "false", ";", "}", "/**\n\t * Determines if the message is an enrollment message\n\t * @param doc the message\n\t * @return true if an enrollment message, otherwise false\n\t */", "public", "boolean", "isStudentEnrollmentMessage", "(", "Document", "doc", ")", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "NodeList", "children", "=", "enterprise", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "children", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "n", "=", "children", ".", "item", "(", "i", ")", ";", "if", "(", "n", ".", "getNodeType", "(", ")", "!=", "1", ")", "continue", ";", "if", "(", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "membership", "\"", ")", ")", "{", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "getNode", "(", "\"", "member", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "role", "!=", "null", "&&", "getNodeAttr", "(", "\"", "roletype", "\"", ",", "role", ")", ".", "equals", "(", "\"", "01", "\"", ")", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}", "/**\n\t * Determines if the message is an student drop message\n\t * @param doc the message\n\t * @return true if an drop enrollment message, otherwise false\n\t */", "public", "boolean", "isStudentDropMessage", "(", "Document", "doc", ")", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "NodeList", "children", "=", "enterprise", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "children", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "n", "=", "children", ".", "item", "(", "i", ")", ";", "if", "(", "n", ".", "getNodeType", "(", ")", "!=", "1", ")", "continue", ";", "if", "(", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "membership", "\"", ")", ")", "{", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "getNode", "(", "\"", "member", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ";", "String", "status", "=", "getNodeValue", "(", "getNode", "(", "\"", "status", "\"", ",", "role", ".", "getChildNodes", "(", ")", ")", ")", ";", "if", "(", "role", "!=", "null", "&&", "getNodeAttr", "(", "\"", "roletype", "\"", ",", "role", ")", ".", "equals", "(", "\"", "01", "\"", ")", "&&", "(", "getNodeAttr", "(", "\"", "recstatus", "\"", ",", "role", ")", ".", "equals", "(", "\"", "3", "\"", ")", "||", "status", ".", "equals", "(", "\"", "0", "\"", ")", ")", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}", "/**\n\t * Determines if the message is a faculty assignment message\n\t * @param doc the message\n\t * @return true if a faculty assignment message, otherwise false\n\t */", "public", "boolean", "isFacultyAssignmentMessage", "(", "Document", "doc", ")", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "NodeList", "children", "=", "enterprise", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "children", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "n", "=", "children", ".", "item", "(", "i", ")", ";", "if", "(", "n", ".", "getNodeType", "(", ")", "!=", "1", ")", "continue", ";", "if", "(", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "membership", "\"", ")", ")", "{", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "getNode", "(", "\"", "member", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "role", "!=", "null", "&&", "getNodeAttr", "(", "\"", "roletype", "\"", ",", "role", ")", ".", "equals", "(", "\"", "02", "\"", ")", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}", "/**\n\t * Determines if the message is a drop faculty assignment message\n\t * @param doc the message\n\t * @return true if a drop faculty assignment message, otherwise false\n\t */", "public", "boolean", "isFacultyDropMessage", "(", "Document", "doc", ")", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "NodeList", "children", "=", "enterprise", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "children", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "n", "=", "children", ".", "item", "(", "i", ")", ";", "if", "(", "n", ".", "getNodeType", "(", ")", "!=", "1", ")", "continue", ";", "if", "(", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "membership", "\"", ")", ")", "{", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "getNode", "(", "\"", "member", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "role", "!=", "null", "&&", "getNodeAttr", "(", "\"", "roletype", "\"", ",", "role", ")", ".", "equals", "(", "\"", "02", "\"", ")", "&&", "getNodeAttr", "(", "\"", "recstatus", "\"", ",", "role", ")", ".", "equals", "(", "\"", "3", "\"", ")", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}", "/**\n\t * Determines if the message is a cross list section message\n\t * @param doc the message\n\t * @return true if a cross list section message, otherwise false\n\t */", "public", "boolean", "isCrossListUpdateMessage", "(", "Document", "doc", ")", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "NodeList", "children", "=", "enterprise", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "children", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "n", "=", "children", ".", "item", "(", "i", ")", ";", "if", "(", "n", ".", "getNodeType", "(", ")", "!=", "1", ")", "continue", ";", "if", "(", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "membership", "\"", ")", ")", "{", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "getNode", "(", "\"", "member", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "role", "!=", "null", "&&", "getNodeAttr", "(", "\"", "roletype", "\"", ",", "role", ")", "==", "null", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}", "/**\n\t * Determines if the message is a delete message for a group\n\t * @param doc the message\n\t * @return true if a group delete message, otherwise false\n\t */", "public", "boolean", "isGroupDeleteMessage", "(", "Document", "doc", ")", "{", "Node", "enterprise", "=", "getEnterpriseNodeFromDoc", "(", "doc", ")", ";", "NodeList", "children", "=", "enterprise", ".", "getChildNodes", "(", ")", ";", "Node", "group", "=", "getNode", "(", "\"", "group", "\"", ",", "children", ")", ";", "String", "recStatus", "=", "getNodeAttr", "(", "\"", "recstatus", "\"", ",", "group", ")", ";", "if", "(", "recStatus", "!=", "null", "&&", "recStatus", ".", "equals", "(", "\"", "3", "\"", ")", ")", "return", "true", ";", "return", "false", ";", "}", "/**\n\t * Creates a Document from an xml message\n\t * @param xmlMessage the xml to create the document from\n\t * @return the document of the xml\n\t * @throws ParserConfigurationException if a configuration error occurred\n\t * @throws SAXException if a sax error has occurred\n\t * @throws IOException if an i/o error has occurred\n\t */", "public", "Document", "getXMLDocument", "(", "String", "xmlMessage", ")", "throws", "ParserConfigurationException", ",", "SAXException", ",", "IOException", "{", "DocumentBuilderFactory", "dbf", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "DocumentBuilder", "docBuilder", "=", "dbf", ".", "newDocumentBuilder", "(", ")", ";", "InputSource", "is", "=", "new", "InputSource", "(", ")", ";", "is", ".", "setCharacterStream", "(", "new", "StringReader", "(", "xmlMessage", ")", ")", ";", "Document", "doc", "=", "docBuilder", ".", "parse", "(", "is", ")", ";", "doc", ".", "getDocumentElement", "(", ")", ".", "normalize", "(", ")", ";", "return", "doc", ";", "}", "/**\n\t * Returns the enterprise node from a document. The enterprise element is the root element for all\n\t * ldisp 2.0 messages\n\t * @param doc the document to get the enterprise element from\n\t * @return the enterprise element from an xml document\n\t */", "private", "Node", "getEnterpriseNodeFromDoc", "(", "Document", "doc", ")", "{", "NodeList", "nodeLst", "=", "doc", ".", "getElementsByTagName", "(", "\"", "enterprise", "\"", ")", ";", "return", "nodeLst", ".", "item", "(", "0", ")", ";", "}", "/**\n\t * Parses a group message\n\t * @param enterprise the root node of the xml message\n\t * @return the group content from the message\n\t */", "private", "Group", "parseGroupMessage", "(", "Node", "enterprise", ")", "{", "Node", "group", "=", "getNode", "(", "\"", "group", "\"", ",", "enterprise", ".", "getChildNodes", "(", ")", ")", ";", "NodeList", "groupData", "=", "group", ".", "getChildNodes", "(", ")", ";", "Node", "sourcedid", "=", "getNode", "(", "\"", "sourcedid", "\"", ",", "groupData", ")", ";", "Node", "id", "=", "getNode", "(", "\"", "id", "\"", ",", "sourcedid", ".", "getChildNodes", "(", ")", ")", ";", "Node", "grouptype", "=", "getNode", "(", "\"", "grouptype", "\"", ",", "groupData", ")", ";", "Node", "scheme", "=", "getNode", "(", "\"", "scheme", "\"", ",", "grouptype", ".", "getChildNodes", "(", ")", ")", ";", "Node", "typevalue", "=", "getNode", "(", "\"", "typevalue", "\"", ",", "grouptype", ".", "getChildNodes", "(", ")", ")", ";", "String", "typeOfGroup", "=", "getNodeValue", "(", "typevalue", ")", ";", "Node", "description", "=", "getNode", "(", "\"", "description", "\"", ",", "groupData", ")", ";", "Node", "shortDesc", "=", "getNode", "(", "\"", "short", "\"", ",", "description", ".", "getChildNodes", "(", ")", ")", ";", "Node", "longDesc", "=", "getNode", "(", "\"", "long", "\"", ",", "description", ".", "getChildNodes", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Message Type = ", "\"", "+", "typeOfGroup", ")", ";", "Group", "cg", "=", "GroupFactory", ".", "instanceOfGroup", "(", "typeOfGroup", ")", ";", "cg", ".", "setGroupID", "(", "getNodeValue", "(", "id", ")", ")", ";", "cg", ".", "setScheme", "(", "getNodeValue", "(", "scheme", ")", ")", ";", "cg", ".", "setGroupType", "(", "getNodeValue", "(", "typevalue", ")", ")", ";", "cg", ".", "setTypeValueLevel", "(", "getNodeAttr", "(", "\"", "level", "\"", ",", "typevalue", ")", ")", ";", "cg", ".", "setShortDescription", "(", "getNodeValue", "(", "shortDesc", ")", ")", ";", "if", "(", "typeOfGroup", ".", "equals", "(", "\"", "Term", "\"", ")", ")", "{", "Node", "timeframe", "=", "getNode", "(", "\"", "timeframe", "\"", ",", "groupData", ")", ";", "Node", "enrollcontrol", "=", "getNode", "(", "\"", "enrollcontrol", "\"", ",", "groupData", ")", ";", "Node", "begin", "=", "getNode", "(", "\"", "begin", "\"", ",", "timeframe", ".", "getChildNodes", "(", ")", ")", ";", "Node", "end", "=", "getNode", "(", "\"", "end", "\"", ",", "timeframe", ".", "getChildNodes", "(", ")", ")", ";", "Node", "enrollaccept", "=", "getNode", "(", "\"", "enrollaccept", "\"", ",", "enrollcontrol", ".", "getChildNodes", "(", ")", ")", ";", "TermGroup", "tg", "=", "(", "TermGroup", ")", "cg", ";", "tg", ".", "setBegin", "(", "getNodeValue", "(", "begin", ")", ")", ";", "tg", ".", "setEnd", "(", "getNodeValue", "(", "end", ")", ")", ";", "try", "{", "tg", ".", "setEnrollAccept", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "enrollaccept", ")", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "tg", ".", "setEnrollAccept", "(", "0", ")", ";", "}", "}", "if", "(", "typeOfGroup", ".", "equals", "(", "\"", "CourseSection", "\"", ")", ")", "{", "CourseSectionGroup", "csg", "=", "null", ";", "try", "{", "Node", "fullDesc", "=", "getNode", "(", "\"", "full", "\"", ",", "description", ".", "getChildNodes", "(", ")", ")", ";", "Node", "org", "=", "getNode", "(", "\"", "org", "\"", ",", "groupData", ")", ";", "Node", "orgUnit", "=", "getNode", "(", "\"", "orgunit", "\"", ",", "org", ".", "getChildNodes", "(", ")", ")", ";", "csg", "=", "(", "CourseSectionGroup", ")", "cg", ";", "csg", ".", "setFullDesc", "(", "getNodeValue", "(", "fullDesc", ")", ")", ";", "csg", ".", "setOrg", "(", "getNodeValue", "(", "orgUnit", ")", ")", ";", "Node", "extension", "=", "getNode", "(", "\"", "extension", "\"", ",", "groupData", ")", ";", "Node", "luminisgroup", "=", "getNode", "(", "\"", "luminisgroup", "\"", ",", "extension", ".", "getChildNodes", "(", ")", ")", ";", "Node", "deliverysystem", "=", "getNode", "(", "\"", "deliverysystem", "\"", ",", "luminisgroup", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "deliverysystem", "!=", "null", ")", "csg", ".", "setDeliverySystem", "(", "getNodeValue", "(", "deliverysystem", ")", ")", ";", "Node", "events", "=", "getNode", "(", "\"", "events", "\"", ",", "luminisgroup", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "events", "!=", "null", ")", "{", "Node", "recurringevent", "=", "getNode", "(", "\"", "recurringevent", "\"", ",", "events", ".", "getChildNodes", "(", ")", ")", ";", "csg", ".", "setEventDescription", "(", "getNodeValue", "(", "getNode", "(", "\"", "eventdescription", "\"", ",", "recurringevent", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "csg", ".", "setBeginDate", "(", "getNodeValue", "(", "getNode", "(", "\"", "begindate", "\"", ",", "recurringevent", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "csg", ".", "setEndDate", "(", "getNodeValue", "(", "getNode", "(", "\"", "enddate", "\"", ",", "recurringevent", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "csg", ".", "setDaysOfWeek", "(", "getNodeValue", "(", "getNode", "(", "\"", "daysofweek", "\"", ",", "recurringevent", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "csg", ".", "setBeginTime", "(", "getNodeValue", "(", "getNode", "(", "\"", "begintime", "\"", ",", "recurringevent", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "csg", ".", "setEndTime", "(", "getNodeValue", "(", "getNode", "(", "\"", "endtime", "\"", ",", "recurringevent", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "csg", ".", "setLocation", "(", "getNodeValue", "(", "getNode", "(", "\"", "location", "\"", ",", "recurringevent", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "info", "(", "\"", "CourseSection additional LMS tags not present. This is ok!", "\"", ")", ";", "csg", ".", "setDeliverySystem", "(", "null", ")", ";", "}", "}", "if", "(", "typeOfGroup", ".", "equals", "(", "\"", "Course", "\"", ")", "||", "typeOfGroup", ".", "equals", "(", "\"", "CourseSection", "\"", ")", ")", "{", "CourseGroup", "cg2", "=", "(", "CourseGroup", ")", "cg", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "groupData", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "groupData", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "relationship", "\"", ")", ")", "{", "Relationship", "relationship", "=", "new", "Relationship", "(", ")", ";", "relationship", ".", "setRelation", "(", "getNodeAttr", "(", "\"", "relation", "\"", ",", "node", ")", ")", ";", "relationship", ".", "setRelationshipID", "(", "getNodeValue", "(", "getNode", "(", "\"", "id", "\"", ",", "getNode", "(", "\"", "sourcedid", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "relationship", ".", "setLabel", "(", "getNodeValue", "(", "getNode", "(", "\"", "label", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "cg2", ".", "getRelationships", "(", ")", ".", "add", "(", "relationship", ")", ";", "}", "}", "}", "if", "(", "!", "typeOfGroup", ".", "equals", "(", "\"", "CrossListedSection", "\"", ")", ")", "{", "cg", ".", "setLongDescription", "(", "getNodeValue", "(", "longDesc", ")", ")", ";", "}", "return", "cg", ";", "}", "/**\n\t * Parses a cross list section membership message\n\t * @param enterprise the root node of the xml message\n\t * @return the cross list section content from the message\n\t */", "private", "CrossListSectionMembership", "parseCrossListUpdateMessage", "(", "Node", "enterprise", ")", "{", "Node", "membership", "=", "getNode", "(", "\"", "membership", "\"", ",", "enterprise", ".", "getChildNodes", "(", ")", ")", ";", "NodeList", "membershipData", "=", "membership", ".", "getChildNodes", "(", ")", ";", "Node", "sourcedid", "=", "getNode", "(", "\"", "sourcedid", "\"", ",", "membershipData", ")", ";", "Node", "id", "=", "getNode", "(", "\"", "id", "\"", ",", "sourcedid", ".", "getChildNodes", "(", ")", ")", ";", "CrossListSectionMembership", "clsm", "=", "new", "CrossListSectionMembership", "(", ")", ";", "clsm", ".", "setId", "(", "getNodeValue", "(", "id", ")", ")", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "membershipData", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "membershipData", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "member", "\"", ")", ")", "{", "Member", "member", "=", "new", "Member", "(", ")", ";", "member", ".", "setId", "(", "getNodeValue", "(", "getNode", "(", "\"", "id", "\"", ",", "getNode", "(", "\"", "sourcedid", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "member", ".", "setIdType", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "idtype", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "member", ".", "setStatus", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "status", "\"", ",", "getNode", "(", "\"", "role", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "member", ".", "setRecStatus", "(", "getNodeAttr", "(", "\"", "recstatus", "\"", ",", "getNode", "(", "\"", "role", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "clsm", ".", "getMembers", "(", ")", ".", "add", "(", "member", ")", ";", "}", "}", "return", "clsm", ";", "}", "/**\n\t * Parses a student enrollment message\n\t * @param enterprise the root node of the xml message\n\t * @return the student enrollment content from the message\n\t */", "private", "Enroll", "parseStudentEnrollmentMessage", "(", "Node", "enterprise", ")", "{", "Node", "membership", "=", "getNode", "(", "\"", "membership", "\"", ",", "enterprise", ".", "getChildNodes", "(", ")", ")", ";", "NodeList", "membershipData", "=", "membership", ".", "getChildNodes", "(", ")", ";", "Node", "sourcedid", "=", "getNode", "(", "\"", "sourcedid", "\"", ",", "membershipData", ")", ";", "Node", "id", "=", "getNode", "(", "\"", "id", "\"", ",", "sourcedid", ".", "getChildNodes", "(", ")", ")", ";", "Enroll", "enroll", "=", "new", "Enroll", "(", ")", ";", "enroll", ".", "setCourseId", "(", "getNodeValue", "(", "id", ")", ")", ";", "log", ".", "info", "(", "\"", "Enrollment for Course ID: ", "\"", "+", "enroll", ".", "getCourseId", "(", ")", ")", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "membershipData", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "membershipData", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "member", "\"", ")", ")", "{", "EnrollMember", "member", "=", "new", "EnrollMember", "(", ")", ";", "member", ".", "setSourceId", "(", "getNodeValue", "(", "getNode", "(", "\"", "id", "\"", ",", "getNode", "(", "\"", "sourcedid", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "member", ".", "setIdType", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "idtype", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ";", "member", ".", "setStatus", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "status", "\"", ",", "role", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "member", ".", "setRoleType", "(", "getNodeAttr", "(", "\"", "roletype", "\"", ",", "role", ")", ")", ";", "Node", "timeframe", "=", "getNode", "(", "\"", "timeframe", "\"", ",", "role", ".", "getChildNodes", "(", ")", ")", ";", "Node", "begin", "=", "getNode", "(", "\"", "begin", "\"", ",", "timeframe", ".", "getChildNodes", "(", ")", ")", ";", "Node", "end", "=", "getNode", "(", "\"", "end", "\"", ",", "timeframe", ".", "getChildNodes", "(", ")", ")", ";", "member", ".", "setBeginEnroll", "(", "getNodeValue", "(", "begin", ")", ")", ";", "member", ".", "setBeginRestricted", "(", "Integer", ".", "parseInt", "(", "getNodeAttr", "(", "\"", "restrict", "\"", ",", "end", ")", ")", ")", ";", "member", ".", "setEndEnroll", "(", "getNodeValue", "(", "end", ")", ")", ";", "member", ".", "setEndRestricted", "(", "Integer", ".", "parseInt", "(", "getNodeAttr", "(", "\"", "restrict", "\"", ",", "end", ")", ")", ")", ";", "NodeList", "roleChilds", "=", "role", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "y", "=", "0", ";", "y", "<", "roleChilds", ".", "getLength", "(", ")", ";", "y", "++", ")", "{", "Node", "n", "=", "roleChilds", ".", "item", "(", "y", ")", ";", "if", "(", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "intermresult", "\"", ")", ")", "{", "Node", "midMode", "=", "getNode", "(", "\"", "mode", "\"", ",", "n", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "midMode", "!=", "null", ")", "member", ".", "setMidTermGradingMode", "(", "getNodeValue", "(", "midMode", ")", ")", ";", "}", "}", "Node", "finalresult", "=", "getNode", "(", "\"", "finalresult", "\"", ",", "role", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "finalresult", "!=", "null", ")", "{", "Node", "finalMode", "=", "getNode", "(", "\"", "mode", "\"", ",", "finalresult", ".", "getChildNodes", "(", ")", ")", ";", "if", "(", "finalMode", "!=", "null", ")", "member", ".", "setFinalGradeMode", "(", "getNodeValue", "(", "finalMode", ")", ")", ";", "}", "log", ".", "info", "(", "\"", "Event Source ID ", "\"", "+", "member", ".", "getSourceId", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "IdType ", "\"", "+", "member", ".", "getIdType", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Status ", "\"", "+", "member", ".", "getStatus", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "RecStatus ", "\"", "+", "member", ".", "getRecStatus", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Role Type ", "\"", "+", "member", ".", "getRoleType", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Begin Time ", "\"", "+", "member", ".", "getBeginEnroll", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Begin Restrict ", "\"", "+", "member", ".", "getBeginRestricted", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "End Time ", "\"", "+", "member", ".", "getEndEnroll", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "End Restrict ", "\"", "+", "member", ".", "getEndRestricted", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Mid Grade Mode ", "\"", "+", "member", ".", "getMidTermGradingMode", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Final Grade Mode ", "\"", "+", "member", ".", "getFinalGradeMode", "(", ")", ")", ";", "enroll", ".", "getMembers", "(", ")", ".", "add", "(", "member", ")", ";", "}", "}", "return", "enroll", ";", "}", "/**\n\t * Parses a faculty assignment membership message\n\t * @param enterprise the root node of the xml message\n\t * @return the faculty assignment content from the message\n\t */", "private", "Assignment", "parseFacultyAssignmentMessage", "(", "Node", "enterprise", ")", "{", "Node", "membership", "=", "getNode", "(", "\"", "membership", "\"", ",", "enterprise", ".", "getChildNodes", "(", ")", ")", ";", "NodeList", "membershipData", "=", "membership", ".", "getChildNodes", "(", ")", ";", "Node", "sourcedid", "=", "getNode", "(", "\"", "sourcedid", "\"", ",", "membershipData", ")", ";", "Node", "id", "=", "getNode", "(", "\"", "id", "\"", ",", "sourcedid", ".", "getChildNodes", "(", ")", ")", ";", "Assignment", "assign", "=", "new", "Assignment", "(", ")", ";", "assign", ".", "setCourseId", "(", "getNodeValue", "(", "id", ")", ")", ";", "log", ".", "info", "(", "\"", "Assignment for Course ID: ", "\"", "+", "assign", ".", "getCourseId", "(", ")", ")", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "membershipData", ".", "getLength", "(", ")", ";", "x", "++", ")", "{", "Node", "node", "=", "membershipData", ".", "item", "(", "x", ")", ";", "if", "(", "node", ".", "getNodeName", "(", ")", ".", "equalsIgnoreCase", "(", "\"", "member", "\"", ")", ")", "{", "EnrollMember", "member", "=", "new", "EnrollMember", "(", ")", ";", "member", ".", "setSourceId", "(", "getNodeValue", "(", "getNode", "(", "\"", "id", "\"", ",", "getNode", "(", "\"", "sourcedid", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "member", ".", "setIdType", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "idtype", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "Node", "role", "=", "getNode", "(", "\"", "role", "\"", ",", "node", ".", "getChildNodes", "(", ")", ")", ";", "member", ".", "setStatus", "(", "Integer", ".", "parseInt", "(", "getNodeValue", "(", "getNode", "(", "\"", "status", "\"", ",", "role", ".", "getChildNodes", "(", ")", ")", ")", ")", ")", ";", "member", ".", "setRoleType", "(", "getNodeAttr", "(", "\"", "roletype", "\"", ",", "role", ")", ")", ";", "member", ".", "setSubRole", "(", "getNodeValue", "(", "getNode", "(", "\"", "subrole", "\"", ",", "role", ".", "getChildNodes", "(", ")", ")", ")", ")", ";", "log", ".", "info", "(", "\"", "Instructor Source ID ", "\"", "+", "member", ".", "getSourceId", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "IdType ", "\"", "+", "member", ".", "getIdType", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Status ", "\"", "+", "member", ".", "getStatus", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "RecStatus ", "\"", "+", "member", ".", "getRecStatus", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Role Type ", "\"", "+", "member", ".", "getRoleType", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Sub Role ", "\"", "+", "member", ".", "getSubRole", "(", ")", ")", ";", "assign", ".", "getMembers", "(", ")", ".", "add", "(", "member", ")", ";", "}", "}", "return", "assign", ";", "}", "}" ]
Reader for xml messages in the Luminis Broker.
[ "Reader", "for", "xml", "messages", "in", "the", "Luminis", "Broker", "." ]
[ "// 3 = delete person = AD disable account", "//log.info(\"Type userid \" + getNodeAttr(\"useridtype\", node));", "//log.info(\"userid \" + getNodeValue(node));", "// returns \"\" if none found", "// returns \"\" if none found", "// maybe more than one major", "// faculty member", "// faculty member", "// still returns a group", "// change to message\t ", "// change to message", "// adds to cross list sections don't have a group tag", "// change to message", "// adds to cross list sections don't have a group tag", "// this could also be student enrollment; or faculty assignment", "// this could also be student enrollment; or faculty assignment", "//log.info(\"Role type = \" + getNodeAttr(\"roletype\", role));", "// this could also be student enrollment; or faculty assignment", "//log.info(\"Role type = \" + getNodeAttr(\"roletype\", role));", "// drop by deletion of enrollment record = 3", "// drop by status of the enrollment record being inactive", "// this could also be student enrollment; or faculty assignment", "//log.info(\"Role type = \" + getNodeAttr(\"roletype\", role));", "// this could also be student enrollment; or faculty assignment", "//log.info(\"Role type = \" + getNodeAttr(\"roletype\", role));", "// drop = 3", "// this could also be student enrollment; or faculty assignment", "//log.info(\"Role type = \" + getNodeAttr(\"roletype\", role));", "//Document doc = docBuilder.parse(new File(fileName));", "// 1st child", "// adds to cross list sections don't have a group tag", "// returns the proper group", "// there's a restrict attr that if set 0 states that the student can't participate before the beginning date", "// again restrict attr here", "// these tags determine if the message is targeted for the LMS", "// updates to a section targeted for the LMS require a deletion of the", "// old section and creation of a new section; these tags may or may not be present", "// not targeted for the LMS\t\t\t\t", "// not long desc in cross list section group", "// adds to cross list sections don't have a group tag", "// adds to cross list sections don't have a group tag", "//member.setRecStatus(getNodeAttr(\"recstatus\", role)); only used for delete message", "// roletype = 01 ; student enrollment", "// adds to cross list sections don't have a group tag", "// this is an instructor assignment", "//member.setRecStatus(getNodeAttr(\"recstatus\", role)); only for a delete message\t \t\t", "// roletype = 02; faculty assignment", "// Primary or Subordinate" ]
[ { "param": "XMLUtils", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "XMLUtils", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
337283be8eb27937b105e0ea3145b7658040661a
SoftwareEngineeringToolDemos/type-inference
inference-framework/annotation-tools/annotation-file-utilities/src/annotator/find/GenericArrayLocationCriterion.java
[ "Apache-2.0" ]
Java
GenericArrayLocationCriterion
/** * GenericArrayLocationCriterion represents the criterion specifying the location * of an element in the generic/array hierarchy as specified by the * JSR 308 proposal. */
GenericArrayLocationCriterion represents the criterion specifying the location of an element in the generic/array hierarchy as specified by the JSR 308 proposal.
[ "GenericArrayLocationCriterion", "represents", "the", "criterion", "specifying", "the", "location", "of", "an", "element", "in", "the", "generic", "/", "array", "hierarchy", "as", "specified", "by", "the", "JSR", "308", "proposal", "." ]
public class GenericArrayLocationCriterion implements Criterion { private static final boolean debug = false; // the full location list private final List<Integer> location; // The last element of the location list -- that is, // location.get(location.size() - 1), or null if (location.size() == 0). // // Needs to be visible for TreeFinder, for a hacky access from there. // TODO: make private // Also TODO: locationInParent is not used for any logic in this class, // just abused by TreeFinder. See whether you can clean this up. Integer locationInParent; // represents all but the last element of the location list // TODO: this field is initialized, but never read! // I removed it, see the version control history. // private Criterion parentCriterion; /** * Creates a new GenericArrayLocationCriterion specifying that the element * is an outer type, such as: * <code>@A List<Integer></code> * or * <code>Integer @A []</code> */ public GenericArrayLocationCriterion() { this(new ArrayList<Integer>()); } /** * Creates a new GenericArrayLocationCriterion representing the given * location. * * @param innerTypeLoc the location of the element being represented */ public GenericArrayLocationCriterion(InnerTypeLocation innerTypeLoc) { this(innerTypeLoc.location); } private GenericArrayLocationCriterion(List<Integer> location) { this.location = location; if (location.size() == 0) { this.locationInParent = null; } else { this.locationInParent = location.get(location.size() - 1); } } /** {@inheritDoc} */ @Override public boolean isSatisfiedBy(TreePath path, Tree leaf) { assert path == null || path.getLeaf() == leaf; return isSatisfiedBy(path); } /** {@inheritDoc} */ @Override public boolean isSatisfiedBy(TreePath path) { if (path == null) { if (debug) { System.out.println("GenericArrayLocationCriterion.isSatisfiedBy() with null path gives false."); } return false; } if (debug) { System.out.printf("GenericArrayLocationCriterion.isSatisfiedBy():%n leaf of path: %s%n searched location: %s%n", path.getLeaf(), location); } if (locationInParent == null) { // no inner type location, want to annotate outermost type // e.g., @Readonly List list; // @Readonly List<String> list; // String @Readonly [] array; Tree leaf = path.getLeaf(); Tree parent = path.getParentPath().getLeaf(); boolean result = ((leaf.getKind() == Tree.Kind.NEW_ARRAY) || (leaf.getKind() == Tree.Kind.NEW_CLASS) || ((isGenericOrArray(leaf) // or, it might be a raw type || (leaf.getKind() == Tree.Kind.IDENTIFIER) // IdentifierTree || (leaf.getKind() == Tree.Kind.METHOD) // MethodTree || (leaf.getKind() == Tree.Kind.TYPE_PARAMETER) // TypeParameterTree // I don't know why a GenericArrayLocationCriterion // is being created in this case, but it is. || (leaf.getKind() == Tree.Kind.PRIMITIVE_TYPE) // PrimitiveTypeTree // TODO: do we need wildcards here? // || leaf instanceof WildcardTree ) && ! isGenericOrArray(parent))); if (debug) { System.out.printf("GenericArrayLocationCriterion.isSatisfiedBy: locationInParent==null%n leaf=%s (%s)%n parent=%s (%s)%n => %s (%s %s)%n", leaf, leaf.getClass(), parent, parent.getClass(), result, isGenericOrArray(leaf), ! isGenericOrArray(parent)); } return result; } TreePath pathRemaining = path; List<Integer> locationRemaining = new ArrayList<Integer>(location); while (locationRemaining.size() != 0) { // annotating an inner type Tree leaf = pathRemaining.getLeaf(); if ((leaf.getKind() == Tree.Kind.NEW_ARRAY) && (locationRemaining.size() == 1)) { if (debug) { System.out.println("Found a matching NEW_ARRAY"); } return true; } TreePath parentPath = pathRemaining.getParentPath(); if (parentPath == null) { if (debug) { System.out.println("Parent path is null and therefore false."); } return false; } Tree parent = parentPath.getLeaf(); if (parent.getKind() == Tree.Kind.ANNOTATED_TYPE) { // If the parent is an annotated type, we did not really go up a level. // Therefore, skip up one more level. parentPath = parentPath.getParentPath(); parent = parentPath.getLeaf(); } if (debug) { System.out.printf("locationRemaining: %s, leaf: %s parent: %s %s%n", locationRemaining, Main.treeToString(leaf), Main.treeToString(parent), parent.getClass()); } int loc = locationRemaining.get(locationRemaining.size()-1); if (parent.getKind() == Tree.Kind.PARAMETERIZED_TYPE) { // annotating List<@A Integer> // System.out.printf("parent instanceof ParameterizedTypeTree: %s loc=%d%n", // Main.treeToString(parent), loc); ParameterizedTypeTree ptt = (ParameterizedTypeTree) parent; List<? extends Tree> childTrees = ptt.getTypeArguments(); boolean found = false; if (childTrees.size() > loc ) { Tree childi = childTrees.get(loc); if (childi.getKind() == Tree.Kind.ANNOTATED_TYPE) { childi = ((AnnotatedTypeTree) childi).getUnderlyingType(); } if (childi.equals(leaf)) { locationRemaining.remove(locationRemaining.size()-1); pathRemaining = parentPath; found = true; } } if (!found) { if (debug) { System.out.printf("Generic failed for leaf: %s: nr children: %d loc: %d child: %s%n", leaf, childTrees.size(), loc, ((childTrees.size() > loc) ? childTrees.get(loc) : null)); } return false; } } else if (parent.getKind() == Tree.Kind.EXTENDS_WILDCARD) { // annotating List<? extends @A Integer> // System.out.printf("parent instanceof extends WildcardTree: %s loc=%d%n", // Main.treeToString(parent), loc); WildcardTree wct = (WildcardTree) parent; Tree boundTree = wct.getBound(); if (debug) { System.out.printf("ExtendsWildcard with bound %s gives %s%n", boundTree, boundTree.equals(leaf)); } return boundTree.equals(leaf); } else if (parent.getKind() == Tree.Kind.SUPER_WILDCARD) { // annotating List<? super @A Integer> // System.out.printf("parent instanceof super WildcardTree: %s loc=%d%n", // Main.treeToString(parent), loc); WildcardTree wct = (WildcardTree) parent; Tree boundTree = wct.getBound(); if (debug) { System.out.printf("SuperWildcard with bound %s gives %s%n", boundTree, boundTree.equals(leaf)); } return boundTree.equals(leaf); // } else if (parent.getKind() == Tree.Kind.UNBOUNDED_WILDCARD) { // The parent can never be the unbounded wildcard, as it doesn't have any members. } else if (parent.getKind() == Tree.Kind.ARRAY_TYPE) { // annotating Integer @A [] parentPath = TreeFinder.largestContainingArray(parentPath); parent = parentPath.getLeaf(); // System.out.printf("parent instanceof ArrayTypeTree: %s loc=%d%n", // parent, loc); Tree elt = ((ArrayTypeTree) parent).getType(); for (int i=0; i<loc; i++) { if (! (elt.getKind() == Tree.Kind.ARRAY_TYPE)) { // ArrayTypeTree if (debug) { System.out.printf("Element: %s is not an ArrayTypeTree and therefore false.", elt); } return false; } elt = ((ArrayTypeTree) elt).getType(); } boolean b = elt.equals(leaf); if (debug) { System.out.printf("parent %s instanceof ArrayTypeTree: %b %s %s %d%n", parent, elt.equals(leaf), elt, leaf, loc); System.out.printf("b=%s elt=%s leaf=%s%n", b, elt, leaf); } // TODO: The parent criterion should be exact, not just "in". // Otherwise the criterion [1] matches [5 4 3 2 1]. // This is a disadvantage of working from the inside out instead of the outside in. if (b) { locationRemaining.remove(locationRemaining.size()-1); pathRemaining = parentPath; } else { return false; } } else if (parent.getKind() == Tree.Kind.NEW_ARRAY) { if (debug) { System.out.println("Parent is a NEW_ARRAY and always gives true."); } return true; } else { if (debug) { System.out.printf("unrecognized parent kind = %s%n", parent.getKind()); } return false; } } // no (remaining) inner type location, want to annotate outermost type // e.g., @Readonly List list; // @Readonly List<String> list; Tree parent = pathRemaining.getParentPath().getLeaf(); if (debug) { Tree leaf = pathRemaining.getLeaf(); System.out.printf("No (remaining) inner type location:%n leaf: %s %b%n parent: %s %b%n result: %s%n", Main.treeToString(leaf), isGenericOrArray(leaf), Main.treeToString(parent), isGenericOrArray(parent), ! isGenericOrArray(parent)); } return ! isGenericOrArray(parent); } private boolean isGenericOrArray(Tree t) { return ((t.getKind() == Tree.Kind.PARAMETERIZED_TYPE) || (t.getKind() == Tree.Kind.ARRAY_TYPE) || (t.getKind() == Tree.Kind.ANNOTATED_TYPE && isGenericOrArray(((AnnotatedTypeTree)t).getUnderlyingType())) // Monolithic: one node for entire "new". So, handle specially. // || (t.getKind() == Tree.Kind.NEW_ARRAY) ); } @Override public Kind getKind() { return Criterion.Kind.GENERIC_ARRAY_LOCATION; } @Override public String toString() { return "GenericArrayLocationCriterion at " + ((locationInParent == null) ? "outermost type" : ("( " + location.toString() + " )")); } }
[ "public", "class", "GenericArrayLocationCriterion", "implements", "Criterion", "{", "private", "static", "final", "boolean", "debug", "=", "false", ";", "private", "final", "List", "<", "Integer", ">", "location", ";", "Integer", "locationInParent", ";", "/**\n * Creates a new GenericArrayLocationCriterion specifying that the element\n * is an outer type, such as:\n * <code>@A List<Integer></code>\n * or\n * <code>Integer @A []</code>\n */", "public", "GenericArrayLocationCriterion", "(", ")", "{", "this", "(", "new", "ArrayList", "<", "Integer", ">", "(", ")", ")", ";", "}", "/**\n * Creates a new GenericArrayLocationCriterion representing the given\n * location.\n *\n * @param innerTypeLoc the location of the element being represented\n */", "public", "GenericArrayLocationCriterion", "(", "InnerTypeLocation", "innerTypeLoc", ")", "{", "this", "(", "innerTypeLoc", ".", "location", ")", ";", "}", "private", "GenericArrayLocationCriterion", "(", "List", "<", "Integer", ">", "location", ")", "{", "this", ".", "location", "=", "location", ";", "if", "(", "location", ".", "size", "(", ")", "==", "0", ")", "{", "this", ".", "locationInParent", "=", "null", ";", "}", "else", "{", "this", ".", "locationInParent", "=", "location", ".", "get", "(", "location", ".", "size", "(", ")", "-", "1", ")", ";", "}", "}", "/** {@inheritDoc} */", "@", "Override", "public", "boolean", "isSatisfiedBy", "(", "TreePath", "path", ",", "Tree", "leaf", ")", "{", "assert", "path", "==", "null", "||", "path", ".", "getLeaf", "(", ")", "==", "leaf", ";", "return", "isSatisfiedBy", "(", "path", ")", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "boolean", "isSatisfiedBy", "(", "TreePath", "path", ")", "{", "if", "(", "path", "==", "null", ")", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "GenericArrayLocationCriterion.isSatisfiedBy() with null path gives false.", "\"", ")", ";", "}", "return", "false", ";", "}", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "GenericArrayLocationCriterion.isSatisfiedBy():%n leaf of path: %s%n searched location: %s%n", "\"", ",", "path", ".", "getLeaf", "(", ")", ",", "location", ")", ";", "}", "if", "(", "locationInParent", "==", "null", ")", "{", "Tree", "leaf", "=", "path", ".", "getLeaf", "(", ")", ";", "Tree", "parent", "=", "path", ".", "getParentPath", "(", ")", ".", "getLeaf", "(", ")", ";", "boolean", "result", "=", "(", "(", "leaf", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "NEW_ARRAY", ")", "||", "(", "leaf", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "NEW_CLASS", ")", "||", "(", "(", "isGenericOrArray", "(", "leaf", ")", "||", "(", "leaf", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "IDENTIFIER", ")", "||", "(", "leaf", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "METHOD", ")", "||", "(", "leaf", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "TYPE_PARAMETER", ")", "||", "(", "leaf", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "PRIMITIVE_TYPE", ")", ")", "&&", "!", "isGenericOrArray", "(", "parent", ")", ")", ")", ";", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "GenericArrayLocationCriterion.isSatisfiedBy: locationInParent==null%n leaf=%s (%s)%n parent=%s (%s)%n => %s (%s %s)%n", "\"", ",", "leaf", ",", "leaf", ".", "getClass", "(", ")", ",", "parent", ",", "parent", ".", "getClass", "(", ")", ",", "result", ",", "isGenericOrArray", "(", "leaf", ")", ",", "!", "isGenericOrArray", "(", "parent", ")", ")", ";", "}", "return", "result", ";", "}", "TreePath", "pathRemaining", "=", "path", ";", "List", "<", "Integer", ">", "locationRemaining", "=", "new", "ArrayList", "<", "Integer", ">", "(", "location", ")", ";", "while", "(", "locationRemaining", ".", "size", "(", ")", "!=", "0", ")", "{", "Tree", "leaf", "=", "pathRemaining", ".", "getLeaf", "(", ")", ";", "if", "(", "(", "leaf", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "NEW_ARRAY", ")", "&&", "(", "locationRemaining", ".", "size", "(", ")", "==", "1", ")", ")", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Found a matching NEW_ARRAY", "\"", ")", ";", "}", "return", "true", ";", "}", "TreePath", "parentPath", "=", "pathRemaining", ".", "getParentPath", "(", ")", ";", "if", "(", "parentPath", "==", "null", ")", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Parent path is null and therefore false.", "\"", ")", ";", "}", "return", "false", ";", "}", "Tree", "parent", "=", "parentPath", ".", "getLeaf", "(", ")", ";", "if", "(", "parent", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "ANNOTATED_TYPE", ")", "{", "parentPath", "=", "parentPath", ".", "getParentPath", "(", ")", ";", "parent", "=", "parentPath", ".", "getLeaf", "(", ")", ";", "}", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "locationRemaining: %s, leaf: %s parent: %s %s%n", "\"", ",", "locationRemaining", ",", "Main", ".", "treeToString", "(", "leaf", ")", ",", "Main", ".", "treeToString", "(", "parent", ")", ",", "parent", ".", "getClass", "(", ")", ")", ";", "}", "int", "loc", "=", "locationRemaining", ".", "get", "(", "locationRemaining", ".", "size", "(", ")", "-", "1", ")", ";", "if", "(", "parent", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "PARAMETERIZED_TYPE", ")", "{", "ParameterizedTypeTree", "ptt", "=", "(", "ParameterizedTypeTree", ")", "parent", ";", "List", "<", "?", "extends", "Tree", ">", "childTrees", "=", "ptt", ".", "getTypeArguments", "(", ")", ";", "boolean", "found", "=", "false", ";", "if", "(", "childTrees", ".", "size", "(", ")", ">", "loc", ")", "{", "Tree", "childi", "=", "childTrees", ".", "get", "(", "loc", ")", ";", "if", "(", "childi", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "ANNOTATED_TYPE", ")", "{", "childi", "=", "(", "(", "AnnotatedTypeTree", ")", "childi", ")", ".", "getUnderlyingType", "(", ")", ";", "}", "if", "(", "childi", ".", "equals", "(", "leaf", ")", ")", "{", "locationRemaining", ".", "remove", "(", "locationRemaining", ".", "size", "(", ")", "-", "1", ")", ";", "pathRemaining", "=", "parentPath", ";", "found", "=", "true", ";", "}", "}", "if", "(", "!", "found", ")", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "Generic failed for leaf: %s: nr children: %d loc: %d child: %s%n", "\"", ",", "leaf", ",", "childTrees", ".", "size", "(", ")", ",", "loc", ",", "(", "(", "childTrees", ".", "size", "(", ")", ">", "loc", ")", "?", "childTrees", ".", "get", "(", "loc", ")", ":", "null", ")", ")", ";", "}", "return", "false", ";", "}", "}", "else", "if", "(", "parent", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "EXTENDS_WILDCARD", ")", "{", "WildcardTree", "wct", "=", "(", "WildcardTree", ")", "parent", ";", "Tree", "boundTree", "=", "wct", ".", "getBound", "(", ")", ";", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "ExtendsWildcard with bound %s gives %s%n", "\"", ",", "boundTree", ",", "boundTree", ".", "equals", "(", "leaf", ")", ")", ";", "}", "return", "boundTree", ".", "equals", "(", "leaf", ")", ";", "}", "else", "if", "(", "parent", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "SUPER_WILDCARD", ")", "{", "WildcardTree", "wct", "=", "(", "WildcardTree", ")", "parent", ";", "Tree", "boundTree", "=", "wct", ".", "getBound", "(", ")", ";", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "SuperWildcard with bound %s gives %s%n", "\"", ",", "boundTree", ",", "boundTree", ".", "equals", "(", "leaf", ")", ")", ";", "}", "return", "boundTree", ".", "equals", "(", "leaf", ")", ";", "}", "else", "if", "(", "parent", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "ARRAY_TYPE", ")", "{", "parentPath", "=", "TreeFinder", ".", "largestContainingArray", "(", "parentPath", ")", ";", "parent", "=", "parentPath", ".", "getLeaf", "(", ")", ";", "Tree", "elt", "=", "(", "(", "ArrayTypeTree", ")", "parent", ")", ".", "getType", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "loc", ";", "i", "++", ")", "{", "if", "(", "!", "(", "elt", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "ARRAY_TYPE", ")", ")", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "Element: %s is not an ArrayTypeTree and therefore false.", "\"", ",", "elt", ")", ";", "}", "return", "false", ";", "}", "elt", "=", "(", "(", "ArrayTypeTree", ")", "elt", ")", ".", "getType", "(", ")", ";", "}", "boolean", "b", "=", "elt", ".", "equals", "(", "leaf", ")", ";", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "parent %s instanceof ArrayTypeTree: %b %s %s %d%n", "\"", ",", "parent", ",", "elt", ".", "equals", "(", "leaf", ")", ",", "elt", ",", "leaf", ",", "loc", ")", ";", "System", ".", "out", ".", "printf", "(", "\"", "b=%s elt=%s leaf=%s%n", "\"", ",", "b", ",", "elt", ",", "leaf", ")", ";", "}", "if", "(", "b", ")", "{", "locationRemaining", ".", "remove", "(", "locationRemaining", ".", "size", "(", ")", "-", "1", ")", ";", "pathRemaining", "=", "parentPath", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "if", "(", "parent", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "NEW_ARRAY", ")", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Parent is a NEW_ARRAY and always gives true.", "\"", ")", ";", "}", "return", "true", ";", "}", "else", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "unrecognized parent kind = %s%n", "\"", ",", "parent", ".", "getKind", "(", ")", ")", ";", "}", "return", "false", ";", "}", "}", "Tree", "parent", "=", "pathRemaining", ".", "getParentPath", "(", ")", ".", "getLeaf", "(", ")", ";", "if", "(", "debug", ")", "{", "Tree", "leaf", "=", "pathRemaining", ".", "getLeaf", "(", ")", ";", "System", ".", "out", ".", "printf", "(", "\"", "No (remaining) inner type location:%n leaf: %s %b%n parent: %s %b%n result: %s%n", "\"", ",", "Main", ".", "treeToString", "(", "leaf", ")", ",", "isGenericOrArray", "(", "leaf", ")", ",", "Main", ".", "treeToString", "(", "parent", ")", ",", "isGenericOrArray", "(", "parent", ")", ",", "!", "isGenericOrArray", "(", "parent", ")", ")", ";", "}", "return", "!", "isGenericOrArray", "(", "parent", ")", ";", "}", "private", "boolean", "isGenericOrArray", "(", "Tree", "t", ")", "{", "return", "(", "(", "t", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "PARAMETERIZED_TYPE", ")", "||", "(", "t", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "ARRAY_TYPE", ")", "||", "(", "t", ".", "getKind", "(", ")", "==", "Tree", ".", "Kind", ".", "ANNOTATED_TYPE", "&&", "isGenericOrArray", "(", "(", "(", "AnnotatedTypeTree", ")", "t", ")", ".", "getUnderlyingType", "(", ")", ")", ")", ")", ";", "}", "@", "Override", "public", "Kind", "getKind", "(", ")", "{", "return", "Criterion", ".", "Kind", ".", "GENERIC_ARRAY_LOCATION", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "GenericArrayLocationCriterion at ", "\"", "+", "(", "(", "locationInParent", "==", "null", ")", "?", "\"", "outermost type", "\"", ":", "(", "\"", "( ", "\"", "+", "location", ".", "toString", "(", ")", "+", "\"", " )", "\"", ")", ")", ";", "}", "}" ]
GenericArrayLocationCriterion represents the criterion specifying the location of an element in the generic/array hierarchy as specified by the JSR 308 proposal.
[ "GenericArrayLocationCriterion", "represents", "the", "criterion", "specifying", "the", "location", "of", "an", "element", "in", "the", "generic", "/", "array", "hierarchy", "as", "specified", "by", "the", "JSR", "308", "proposal", "." ]
[ "// the full location list", "// The last element of the location list -- that is,", "// location.get(location.size() - 1), or null if (location.size() == 0).", "// ", "// Needs to be visible for TreeFinder, for a hacky access from there. ", "// TODO: make private", "// Also TODO: locationInParent is not used for any logic in this class,", "// just abused by TreeFinder. See whether you can clean this up.", "// represents all but the last element of the location list", "// TODO: this field is initialized, but never read!", "// I removed it, see the version control history.", "// private Criterion parentCriterion;", "// no inner type location, want to annotate outermost type", "// e.g., @Readonly List list;", "// @Readonly List<String> list;", "// String @Readonly [] array;", "// or, it might be a raw type", "// IdentifierTree", "// MethodTree", "// TypeParameterTree", "// I don't know why a GenericArrayLocationCriterion", "// is being created in this case, but it is.", "// PrimitiveTypeTree", "// TODO: do we need wildcards here?", "// || leaf instanceof WildcardTree", "// annotating an inner type", "// If the parent is an annotated type, we did not really go up a level.", "// Therefore, skip up one more level.", "// annotating List<@A Integer>", "// System.out.printf(\"parent instanceof ParameterizedTypeTree: %s loc=%d%n\",", "// Main.treeToString(parent), loc);", "// annotating List<? extends @A Integer>", "// System.out.printf(\"parent instanceof extends WildcardTree: %s loc=%d%n\",", "// Main.treeToString(parent), loc);", "// annotating List<? super @A Integer>", "// System.out.printf(\"parent instanceof super WildcardTree: %s loc=%d%n\",", "// Main.treeToString(parent), loc);", "// } else if (parent.getKind() == Tree.Kind.UNBOUNDED_WILDCARD) {", "// The parent can never be the unbounded wildcard, as it doesn't have any members.", "// annotating Integer @A []", "// System.out.printf(\"parent instanceof ArrayTypeTree: %s loc=%d%n\",", "// parent, loc);", "// ArrayTypeTree", "// TODO: The parent criterion should be exact, not just \"in\".", "// Otherwise the criterion [1] matches [5 4 3 2 1].", "// This is a disadvantage of working from the inside out instead of the outside in.", "// no (remaining) inner type location, want to annotate outermost type", "// e.g., @Readonly List list;", "// @Readonly List<String> list;", "// Monolithic: one node for entire \"new\". So, handle specially.", "// || (t.getKind() == Tree.Kind.NEW_ARRAY)" ]
[ { "param": "Criterion", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Criterion", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33773d1b753f64d14122f473aac0b061582f7d5c
kitodo/kitodo-contentserver
src/de/unigoettingen/sub/commons/contentlib/imagelib/ErrorImage.java
[ "Apache-2.0" ]
Java
ErrorImage
// TODO: check if this is needed and if so let it implement the Image interface
check if this is needed and if so let it implement the Image interface
[ "check", "if", "this", "is", "needed", "and", "if", "so", "let", "it", "implement", "the", "Image", "interface" ]
public class ErrorImage { private List<WatermarkText> allTexts = new LinkedList<WatermarkText>(); private URL uri; /** * set url for error image * * @param inuri the given url */ public ErrorImage(URL inuri) { uri = inuri; } /** * Add text to Watermark * * @param wt the watermark to add */ public void addWatermarkText(WatermarkText wt) { allTexts.add(wt); } /** * Writes the whole Image as a JPEG Image! * * @param ostream the outputstream to write to * @throws ImageManagerException */ public void renderAsJPG(OutputStream ostream) throws ImageManagerException { // get image ImageManager imagemanager = new ImageManager(uri); ImageInterpreter myInterpreter = imagemanager.getMyInterpreter(); RenderedImage backgroundImage = myInterpreter.getRenderedImage(); Watermark newImage = new Watermark(backgroundImage.getHeight(), backgroundImage.getWidth()); // add BackgroundImage WatermarkImage wi = new WatermarkImage(0, backgroundImage); wi.setX(0); wi.setY(0); newImage.addWatermarkComponent(wi); // add all Text Components newImage.setAllWatermarkComponents(new LinkedList<WatermarkComponent>(allTexts)); // write the new image to output RenderedImage ri = newImage.getRenderedImage(); JpegInterpreter ti = new JpegInterpreter(ri); ti.setXResolution(72f); ti.setYResolution(72f); ti.setColordepth(8); ti.setSamplesperpixel(3); ti.writeToStream(null, ostream); } }
[ "public", "class", "ErrorImage", "{", "private", "List", "<", "WatermarkText", ">", "allTexts", "=", "new", "LinkedList", "<", "WatermarkText", ">", "(", ")", ";", "private", "URL", "uri", ";", "/**\n * set url for error image\n * \n * @param inuri the given url\n */", "public", "ErrorImage", "(", "URL", "inuri", ")", "{", "uri", "=", "inuri", ";", "}", "/**\n * Add text to Watermark\n * \n * @param wt the watermark to add\n */", "public", "void", "addWatermarkText", "(", "WatermarkText", "wt", ")", "{", "allTexts", ".", "add", "(", "wt", ")", ";", "}", "/**\n * Writes the whole Image as a JPEG Image!\n * \n * @param ostream the outputstream to write to\n * @throws ImageManagerException\n */", "public", "void", "renderAsJPG", "(", "OutputStream", "ostream", ")", "throws", "ImageManagerException", "{", "ImageManager", "imagemanager", "=", "new", "ImageManager", "(", "uri", ")", ";", "ImageInterpreter", "myInterpreter", "=", "imagemanager", ".", "getMyInterpreter", "(", ")", ";", "RenderedImage", "backgroundImage", "=", "myInterpreter", ".", "getRenderedImage", "(", ")", ";", "Watermark", "newImage", "=", "new", "Watermark", "(", "backgroundImage", ".", "getHeight", "(", ")", ",", "backgroundImage", ".", "getWidth", "(", ")", ")", ";", "WatermarkImage", "wi", "=", "new", "WatermarkImage", "(", "0", ",", "backgroundImage", ")", ";", "wi", ".", "setX", "(", "0", ")", ";", "wi", ".", "setY", "(", "0", ")", ";", "newImage", ".", "addWatermarkComponent", "(", "wi", ")", ";", "newImage", ".", "setAllWatermarkComponents", "(", "new", "LinkedList", "<", "WatermarkComponent", ">", "(", "allTexts", ")", ")", ";", "RenderedImage", "ri", "=", "newImage", ".", "getRenderedImage", "(", ")", ";", "JpegInterpreter", "ti", "=", "new", "JpegInterpreter", "(", "ri", ")", ";", "ti", ".", "setXResolution", "(", "72f", ")", ";", "ti", ".", "setYResolution", "(", "72f", ")", ";", "ti", ".", "setColordepth", "(", "8", ")", ";", "ti", ".", "setSamplesperpixel", "(", "3", ")", ";", "ti", ".", "writeToStream", "(", "null", ",", "ostream", ")", ";", "}", "}" ]
TODO: check if this is needed and if so let it implement the Image interface
[ "TODO", ":", "check", "if", "this", "is", "needed", "and", "if", "so", "let", "it", "implement", "the", "Image", "interface" ]
[ "// get image", "// add BackgroundImage", "// add all Text Components", "// write the new image to output" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
337851153f7aa826cd635212e5d778667e7dd273
Apelon-VA/ISAAC
lego-view/src/main/java/gov/va/legoEdit/model/ModelUtil.java
[ "Apache-2.0" ]
Java
ModelUtil
/** * * ModelUtil * * @author <a href="mailto:daniel.armbrust.list@gmail.com">Dan Armbrust</a> * Copyright 2013 */
@author Dan Armbrust Copyright 2013
[ "@author", "Dan", "Armbrust", "Copyright", "2013" ]
public class ModelUtil { public static String makeUniqueLegoID(Lego lego) { return makeUniqueLegoID(lego.getLegoUUID(), lego.getStamp().getUuid()); } public static String makeUniqueLegoID(String legoUUID, String stampUUID) { return legoUUID + ":" + stampUUID; } }
[ "public", "class", "ModelUtil", "{", "public", "static", "String", "makeUniqueLegoID", "(", "Lego", "lego", ")", "{", "return", "makeUniqueLegoID", "(", "lego", ".", "getLegoUUID", "(", ")", ",", "lego", ".", "getStamp", "(", ")", ".", "getUuid", "(", ")", ")", ";", "}", "public", "static", "String", "makeUniqueLegoID", "(", "String", "legoUUID", ",", "String", "stampUUID", ")", "{", "return", "legoUUID", "+", "\"", ":", "\"", "+", "stampUUID", ";", "}", "}" ]
ModelUtil
[ "ModelUtil" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
337c8c9d31b849d99af381e06664d6a7d65dd60c
RyanStansifer/Submit-Server
submit/server/AllSubmissionsReport.java
[ "MIT" ]
Java
FileComparator
// File sorts on the path; this sorts on the name
File sorts on the path; this sorts on the name
[ "File", "sorts", "on", "the", "path", ";", "this", "sorts", "on", "the", "name" ]
public static class FileComparator implements Comparator <File> { public int compare (File f1, File f2) { final String name1 = f1.getName(); final String name2 = f2.getName(); final int x = name1.compareTo (name2); if (x==0) { // Files of same name better not compare the same // or they may get lost in the set. return f1.compareTo (f2); } else { return x; } } }
[ "public", "static", "class", "FileComparator", "implements", "Comparator", "<", "File", ">", "{", "public", "int", "compare", "(", "File", "f1", ",", "File", "f2", ")", "{", "final", "String", "name1", "=", "f1", ".", "getName", "(", ")", ";", "final", "String", "name2", "=", "f2", ".", "getName", "(", ")", ";", "final", "int", "x", "=", "name1", ".", "compareTo", "(", "name2", ")", ";", "if", "(", "x", "==", "0", ")", "{", "return", "f1", ".", "compareTo", "(", "f2", ")", ";", "}", "else", "{", "return", "x", ";", "}", "}", "}" ]
File sorts on the path; this sorts on the name
[ "File", "sorts", "on", "the", "path", ";", "this", "sorts", "on", "the", "name" ]
[ "// Files of same name better not compare the same", "// or they may get lost in the set." ]
[ { "param": "Comparator <File>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Comparator <File>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
337dcf7409d5bfcb2161ab3516a1d3e41af87163
rsahlin/graphics-by-opengl
graphics-by-opengl-j2se/src/main/java/com/nucleus/scene/AbstractMeshNode.java
[ "Apache-2.0" ]
Java
AbstractMeshNode
/** * Node that has support for one or more generic Meshes. * This node can be used by implementations as a base for {@link RenderableNode} functionality. * Use this for custom Mesh types that are not loaded assets. * * @param <T> The Mesh typeclass. This is the Mesh class that will be rendered. */
Node that has support for one or more generic Meshes. This node can be used by implementations as a base for RenderableNode functionality. Use this for custom Mesh types that are not loaded assets. @param The Mesh typeclass. This is the Mesh class that will be rendered.
[ "Node", "that", "has", "support", "for", "one", "or", "more", "generic", "Meshes", ".", "This", "node", "can", "be", "used", "by", "implementations", "as", "a", "base", "for", "RenderableNode", "functionality", ".", "Use", "this", "for", "custom", "Mesh", "types", "that", "are", "not", "loaded", "assets", ".", "@param", "The", "Mesh", "typeclass", ".", "This", "is", "the", "Mesh", "class", "that", "will", "be", "rendered", "." ]
public abstract class AbstractMeshNode<T> extends AbstractNode implements RenderableNode<T> { public final static String NULL_PROGRAM_STRING = "Pipeline is null"; @SerializedName(Transform.TRANSFORM) protected Transform transform; @SerializedName(ViewFrustum.VIEWFRUSTUM) protected ViewFrustum viewFrustum; @SerializedName(Material.MATERIAL) protected Material material; @SerializedName(RenderPass.RENDERPASS) private ArrayList<RenderPass> renderPass; /** * Reference to texture, used when importing / exporting. * No runtime meaning */ @SerializedName(TEXTUREREF) protected ExternalReference textureRef; transient protected ArrayList<T> meshes = new ArrayList<T>(); transient protected ArrayList<T> nodeMeshes = new ArrayList<>(); transient protected FrameSampler timeKeeper = FrameSampler.getInstance(); transient protected NodeRenderer<RenderableNode<Mesh>> nodeRenderer = new DefaultNodeRenderer(); /** * Optional projection Matrix for the node, this will affect all child nodes. */ transient float[] projection; /** * The node concatenated model matrix at time of render, this is set when the node is rendered and * {@link #concatModelMatrix(float[])} is called * May be used when calculating bounds/collision on the current frame. * DO NOT WRITE TO THIS! */ transient float[] modelMatrix = Matrix.createMatrix(); transient protected GraphicsShader program; /** * Used by GSON and {@link #createInstance(RootNode)} method - do NOT call directly */ protected AbstractMeshNode() { super(); } /** * Default constructor * * @param root * @param type */ protected AbstractMeshNode(RootNode root, Type<Node> type) { super(root, type); } /** * Sets (copies) the data from the source * Note! This will not copy children or the transient values. * Call {@link #createTransient()} to set transient values * * @param source * @throws ClassCastException If source node is not same class as this. */ protected void set(AbstractMeshNode<T> source) { super.set(source); setRenderPass(source.getRenderPass()); textureRef = source.textureRef; copyTransform(source); copyViewFrustum(source); copyMaterial(source); } @Override public ArrayList<T> getMeshes(ArrayList<T> list) { list.addAll(meshes); return list; } /** * Adds a mesh to be rendered with this node. The mesh is added at the specified index, if specified * NOT THREADSAFE * THIS IS AN INTERNAL METHOD AND SHOULD NOT BE USED! * * @param mesh * @param index The index where this mesh is added or null to add at end of current list */ @Deprecated public void addMesh(T mesh, MeshIndex index) { if (index == null) { meshes.add(mesh); } else { meshes.add(index.index, mesh); } } /** * Removes the mesh from this node, if present. * If many meshes are added this method may have a performance impact. * NOT THREADSAFE * THIS IS AN INTERNAL METHOD AND SHOULD NOT BE USED! * * @param mesh The mesh to remove from this Node. * @return true if the mesh was removed */ @Deprecated public boolean removeMesh(T mesh) { return meshes.remove(mesh); } /** * Returns the number of meshes in this node * * @return */ public int getMeshCount() { return meshes.size(); } @Override public GraphicsShader getProgram() { return program; } @Override public void setProgram(GraphicsShader program) { if (program == null) { throw new IllegalArgumentException(NULL_PROGRAM_STRING); } this.program = program; } @Override public Material getMaterial() { return material; } /** * Returns the external reference of the texture for this node, this is used when importing * * @return */ public ExternalReference getTextureRef() { return textureRef; } /** * Returns the mesh for a specific index * * @param type * @return Mesh for the specified index or null */ public T getMesh(MeshIndex index) { if (index.index < meshes.size()) { return meshes.get(index.index); } return null; } /** * Returns the mesh at the specified index * * @param index * @return The mesh, or null */ public T getMesh(int index) { return meshes.get(index); } @Override public void destroy(NucleusRenderer renderer) { super.destroy(renderer); transform = null; viewFrustum = null; } @Override public void addMesh(T mesh) { if (mesh != null) { meshes.add(mesh); } } /** * Sets texture, material and shapebuilder from the parent node - if not already set in builder. * Sets objectcount and attribute per vertex size. * If parent does not have program the * {@link com.nucleus.geometry.MeshBuilder#createProgram()} * method is called to create a suitable program. * The returned builder shall have needed values to create a mesh. * * @param renderer * @param count Number of objects * @param shapeBuilder * @param builder * @throws IOException * @throws BackendException */ protected MeshBuilder<T> initMeshBuilder(NucleusRenderer renderer, int count, ShapeBuilder<T> shapeBuilder, MeshBuilder<Mesh> builder) throws IOException, BackendException { if (builder.getTexture() == null) { builder.setTexture(getTextureRef()); } if (builder.getMaterial() == null) { builder.setMaterial(getMaterial() != null ? getMaterial() : new Material()); } builder.setObjectCount(count); if (builder.getShapeBuilder() == null) { builder.setShapeBuilder(shapeBuilder); } if (getProgram() == null) { setProgram(builder.createProgram()); } builder.setAttributesPerVertex(getProgram().getPipeline().getAttributeSizes()); return (MeshBuilder<T>) builder; } @Override public com.nucleus.renderer.NodeRenderer<?> getNodeRenderer() { return nodeRenderer; } /** * Copies the transform from the source node, if the transform in the source is null then this nodes transform * is set to null as well. * * @param source The node to copy the transform from. */ public void copyTransform(RenderableNode<T> source) { if (source.getTransform() != null) { copyTransform(source.getTransform()); } else { this.transform = null; } } /** * Fetches the projection matrix for the specified pass, if set. * * @param pass * @return Projection matrix for this node and childnodes, or null if not set */ @Override public float[] getProjection(Pass pass) { switch (pass) { case SHADOW1: return null; default: return projection; } } @Override public ViewFrustum getViewFrustum() { return viewFrustum; } @Override public void setViewFrustum(ViewFrustum source) { viewFrustum = source; setProjection(source.getMatrix()); } /** * Copies the viewfrustum from the source node into this class, if the viewfrustum is null in the source * the viewfrustum is set to null * * @param source The source node * @throws NullPointerException If source is null */ protected void copyViewFrustum(RenderableNode<T> source) { if (source.getViewFrustum() != null) { copyViewFrustum(source.getViewFrustum()); } else { viewFrustum = null; } } /** * Copies the viewfrustum into this class. * * @param source The viewfrustum to copy * @throws NullPointerException If source is null */ public void copyViewFrustum(ViewFrustum source) { if (viewFrustum != null) { viewFrustum.set(source); } else { viewFrustum = new ViewFrustum(source); } } /** * Returns the transform for this node. * * @return */ @Override public Transform getTransform() { return transform; } /** * Copies the material from the source to this node. If the material in the source is null, the material in this * node is set to null * * @param source * @throws NullPointerException If source is null */ protected void copyMaterial(RenderableNode<T> source) { if (source.getMaterial() != null) { copyMaterial(source.getMaterial()); } } /** * Copies the material into this node * * @param source */ protected void copyMaterial(Material source) { if (material != null) { material.copy(source); } else { material = new Material(source); } } /** * Copies the transform from the source to this class. * This will copy all values, creating the transform in this node if needed. * * @param source The source transform to copy. */ public void copyTransform(Transform source) { if (transform == null) { transform = new Transform(source); } else { transform.set(source); } } /** * Returns the resulting model matrix for this node. * It is updated with the concatenated model matrix for the node when it is rendered. * This will contain the sum of the model matrices of this nodes parents. * If object space collision shall be done this matrix can be used to transform the bounds. * * @return The concatenated MVP from last rendered frame, if Node is not rendered the matrix will not be updated. * It will contain the values from the last frame it was processed/rendered */ public float[] getModelMatrix() { return modelMatrix; } /** * Sets the optional projection for this node and child nodes. * If set this matrix will be used instead of the renderers projection matrix. * * @param projection Projection matrix or null */ public void setProjection(float[] projection) { this.projection = projection; } @Override public void setRenderPass(ArrayList<RenderPass> renderPass) { if (renderPass != null) { this.renderPass = new ArrayList<>(); Set<String> ids = new HashSet<>(); for (RenderPass rp : renderPass) { if (rp.getId() != null && ids.contains(rp.getId())) { throw new IllegalArgumentException("Already contains renderpass with id: " + rp.getId()); } ids.add(rp.getId()); this.renderPass.add(rp); } } else { this.renderPass = null; } } @Override public ArrayList<RenderPass> getRenderPass() { return renderPass; } @Override public float[] concatModelMatrix(float[] concatModel) { if (concatModel == null) { return transform != null ? Matrix.copy(transform.updateMatrix(), 0, modelMatrix, 0) : Matrix.setIdentity(modelMatrix, 0); } Matrix.mul4(concatModel, transform != null ? transform.updateMatrix() : Matrix.IDENTITY_MATRIX, modelMatrix); return modelMatrix; } @Override public boolean isInside(float[] position) { if (bounds != null && (state == State.ON || state == State.ACTOR)) { bounds.transform(modelMatrix, 0); return bounds.isPointInside(position, 0); } return false; } @Override public void onCreated() { // Check if bounds should be created explicitly ViewFrustum vf = getViewFrustum(); if (bounds != null && bounds.getBounds() == null) { // Bounds object defined in node but no bound values set. // try to calculate from viewfrustum. if (getProperty(EventHandler.EventType.POINTERINPUT.name(), Constants.FALSE) .equals(Constants.TRUE)) { // Has pointer input so must have bounds vf = vf != null ? vf : getParentsView(); if (vf == null) { throw new IllegalArgumentException( "Node " + getId() + " defines pointer input but does not have bounds and ViewFrustum defined in any parent"); } } if (vf != null) { float[] values = vf.getValues(); initBounds(new Rectangle(values[ViewFrustum.LEFT_INDEX], values[ViewFrustum.TOP_INDEX], vf.getWidth(), vf.getHeight())); } } if (vf != null) { setProjection(vf.getMatrix()); } } @Override public String toString() { return super.toString() + ", " + meshes.size() + " meshes" + (renderPass != null ? ", has renderpass" : ""); } }
[ "public", "abstract", "class", "AbstractMeshNode", "<", "T", ">", "extends", "AbstractNode", "implements", "RenderableNode", "<", "T", ">", "{", "public", "final", "static", "String", "NULL_PROGRAM_STRING", "=", "\"", "Pipeline is null", "\"", ";", "@", "SerializedName", "(", "Transform", ".", "TRANSFORM", ")", "protected", "Transform", "transform", ";", "@", "SerializedName", "(", "ViewFrustum", ".", "VIEWFRUSTUM", ")", "protected", "ViewFrustum", "viewFrustum", ";", "@", "SerializedName", "(", "Material", ".", "MATERIAL", ")", "protected", "Material", "material", ";", "@", "SerializedName", "(", "RenderPass", ".", "RENDERPASS", ")", "private", "ArrayList", "<", "RenderPass", ">", "renderPass", ";", "/**\n * Reference to texture, used when importing / exporting.\n * No runtime meaning\n */", "@", "SerializedName", "(", "TEXTUREREF", ")", "protected", "ExternalReference", "textureRef", ";", "transient", "protected", "ArrayList", "<", "T", ">", "meshes", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "transient", "protected", "ArrayList", "<", "T", ">", "nodeMeshes", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "transient", "protected", "FrameSampler", "timeKeeper", "=", "FrameSampler", ".", "getInstance", "(", ")", ";", "transient", "protected", "NodeRenderer", "<", "RenderableNode", "<", "Mesh", ">", ">", "nodeRenderer", "=", "new", "DefaultNodeRenderer", "(", ")", ";", "/**\n * Optional projection Matrix for the node, this will affect all child nodes.\n */", "transient", "float", "[", "]", "projection", ";", "/**\n * The node concatenated model matrix at time of render, this is set when the node is rendered and\n * {@link #concatModelMatrix(float[])} is called\n * May be used when calculating bounds/collision on the current frame.\n * DO NOT WRITE TO THIS!\n */", "transient", "float", "[", "]", "modelMatrix", "=", "Matrix", ".", "createMatrix", "(", ")", ";", "transient", "protected", "GraphicsShader", "program", ";", "/**\n * Used by GSON and {@link #createInstance(RootNode)} method - do NOT call directly\n */", "protected", "AbstractMeshNode", "(", ")", "{", "super", "(", ")", ";", "}", "/**\n * Default constructor\n * \n * @param root\n * @param type\n */", "protected", "AbstractMeshNode", "(", "RootNode", "root", ",", "Type", "<", "Node", ">", "type", ")", "{", "super", "(", "root", ",", "type", ")", ";", "}", "/**\n * Sets (copies) the data from the source\n * Note! This will not copy children or the transient values.\n * Call {@link #createTransient()} to set transient values\n * \n * @param source\n * @throws ClassCastException If source node is not same class as this.\n */", "protected", "void", "set", "(", "AbstractMeshNode", "<", "T", ">", "source", ")", "{", "super", ".", "set", "(", "source", ")", ";", "setRenderPass", "(", "source", ".", "getRenderPass", "(", ")", ")", ";", "textureRef", "=", "source", ".", "textureRef", ";", "copyTransform", "(", "source", ")", ";", "copyViewFrustum", "(", "source", ")", ";", "copyMaterial", "(", "source", ")", ";", "}", "@", "Override", "public", "ArrayList", "<", "T", ">", "getMeshes", "(", "ArrayList", "<", "T", ">", "list", ")", "{", "list", ".", "addAll", "(", "meshes", ")", ";", "return", "list", ";", "}", "/**\n * Adds a mesh to be rendered with this node. The mesh is added at the specified index, if specified\n * NOT THREADSAFE\n * THIS IS AN INTERNAL METHOD AND SHOULD NOT BE USED!\n * \n * @param mesh\n * @param index The index where this mesh is added or null to add at end of current list\n */", "@", "Deprecated", "public", "void", "addMesh", "(", "T", "mesh", ",", "MeshIndex", "index", ")", "{", "if", "(", "index", "==", "null", ")", "{", "meshes", ".", "add", "(", "mesh", ")", ";", "}", "else", "{", "meshes", ".", "add", "(", "index", ".", "index", ",", "mesh", ")", ";", "}", "}", "/**\n * Removes the mesh from this node, if present.\n * If many meshes are added this method may have a performance impact.\n * NOT THREADSAFE\n * THIS IS AN INTERNAL METHOD AND SHOULD NOT BE USED!\n * \n * @param mesh The mesh to remove from this Node.\n * @return true if the mesh was removed\n */", "@", "Deprecated", "public", "boolean", "removeMesh", "(", "T", "mesh", ")", "{", "return", "meshes", ".", "remove", "(", "mesh", ")", ";", "}", "/**\n * Returns the number of meshes in this node\n * \n * @return\n */", "public", "int", "getMeshCount", "(", ")", "{", "return", "meshes", ".", "size", "(", ")", ";", "}", "@", "Override", "public", "GraphicsShader", "getProgram", "(", ")", "{", "return", "program", ";", "}", "@", "Override", "public", "void", "setProgram", "(", "GraphicsShader", "program", ")", "{", "if", "(", "program", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "NULL_PROGRAM_STRING", ")", ";", "}", "this", ".", "program", "=", "program", ";", "}", "@", "Override", "public", "Material", "getMaterial", "(", ")", "{", "return", "material", ";", "}", "/**\n * Returns the external reference of the texture for this node, this is used when importing\n * \n * @return\n */", "public", "ExternalReference", "getTextureRef", "(", ")", "{", "return", "textureRef", ";", "}", "/**\n * Returns the mesh for a specific index\n * \n * @param type\n * @return Mesh for the specified index or null\n */", "public", "T", "getMesh", "(", "MeshIndex", "index", ")", "{", "if", "(", "index", ".", "index", "<", "meshes", ".", "size", "(", ")", ")", "{", "return", "meshes", ".", "get", "(", "index", ".", "index", ")", ";", "}", "return", "null", ";", "}", "/**\n * Returns the mesh at the specified index\n * \n * @param index\n * @return The mesh, or null\n */", "public", "T", "getMesh", "(", "int", "index", ")", "{", "return", "meshes", ".", "get", "(", "index", ")", ";", "}", "@", "Override", "public", "void", "destroy", "(", "NucleusRenderer", "renderer", ")", "{", "super", ".", "destroy", "(", "renderer", ")", ";", "transform", "=", "null", ";", "viewFrustum", "=", "null", ";", "}", "@", "Override", "public", "void", "addMesh", "(", "T", "mesh", ")", "{", "if", "(", "mesh", "!=", "null", ")", "{", "meshes", ".", "add", "(", "mesh", ")", ";", "}", "}", "/**\n * Sets texture, material and shapebuilder from the parent node - if not already set in builder.\n * Sets objectcount and attribute per vertex size.\n * If parent does not have program the\n * {@link com.nucleus.geometry.MeshBuilder#createProgram()}\n * method is called to create a suitable program.\n * The returned builder shall have needed values to create a mesh.\n * \n * @param renderer\n * @param count Number of objects\n * @param shapeBuilder\n * @param builder\n * @throws IOException\n * @throws BackendException\n */", "protected", "MeshBuilder", "<", "T", ">", "initMeshBuilder", "(", "NucleusRenderer", "renderer", ",", "int", "count", ",", "ShapeBuilder", "<", "T", ">", "shapeBuilder", ",", "MeshBuilder", "<", "Mesh", ">", "builder", ")", "throws", "IOException", ",", "BackendException", "{", "if", "(", "builder", ".", "getTexture", "(", ")", "==", "null", ")", "{", "builder", ".", "setTexture", "(", "getTextureRef", "(", ")", ")", ";", "}", "if", "(", "builder", ".", "getMaterial", "(", ")", "==", "null", ")", "{", "builder", ".", "setMaterial", "(", "getMaterial", "(", ")", "!=", "null", "?", "getMaterial", "(", ")", ":", "new", "Material", "(", ")", ")", ";", "}", "builder", ".", "setObjectCount", "(", "count", ")", ";", "if", "(", "builder", ".", "getShapeBuilder", "(", ")", "==", "null", ")", "{", "builder", ".", "setShapeBuilder", "(", "shapeBuilder", ")", ";", "}", "if", "(", "getProgram", "(", ")", "==", "null", ")", "{", "setProgram", "(", "builder", ".", "createProgram", "(", ")", ")", ";", "}", "builder", ".", "setAttributesPerVertex", "(", "getProgram", "(", ")", ".", "getPipeline", "(", ")", ".", "getAttributeSizes", "(", ")", ")", ";", "return", "(", "MeshBuilder", "<", "T", ">", ")", "builder", ";", "}", "@", "Override", "public", "com", ".", "nucleus", ".", "renderer", ".", "NodeRenderer", "<", "?", ">", "getNodeRenderer", "(", ")", "{", "return", "nodeRenderer", ";", "}", "/**\n * Copies the transform from the source node, if the transform in the source is null then this nodes transform\n * is set to null as well.\n * \n * @param source The node to copy the transform from.\n */", "public", "void", "copyTransform", "(", "RenderableNode", "<", "T", ">", "source", ")", "{", "if", "(", "source", ".", "getTransform", "(", ")", "!=", "null", ")", "{", "copyTransform", "(", "source", ".", "getTransform", "(", ")", ")", ";", "}", "else", "{", "this", ".", "transform", "=", "null", ";", "}", "}", "/**\n * Fetches the projection matrix for the specified pass, if set.\n * \n * @param pass\n * @return Projection matrix for this node and childnodes, or null if not set\n */", "@", "Override", "public", "float", "[", "]", "getProjection", "(", "Pass", "pass", ")", "{", "switch", "(", "pass", ")", "{", "case", "SHADOW1", ":", "return", "null", ";", "default", ":", "return", "projection", ";", "}", "}", "@", "Override", "public", "ViewFrustum", "getViewFrustum", "(", ")", "{", "return", "viewFrustum", ";", "}", "@", "Override", "public", "void", "setViewFrustum", "(", "ViewFrustum", "source", ")", "{", "viewFrustum", "=", "source", ";", "setProjection", "(", "source", ".", "getMatrix", "(", ")", ")", ";", "}", "/**\n * Copies the viewfrustum from the source node into this class, if the viewfrustum is null in the source\n * the viewfrustum is set to null\n * \n * @param source The source node\n * @throws NullPointerException If source is null\n */", "protected", "void", "copyViewFrustum", "(", "RenderableNode", "<", "T", ">", "source", ")", "{", "if", "(", "source", ".", "getViewFrustum", "(", ")", "!=", "null", ")", "{", "copyViewFrustum", "(", "source", ".", "getViewFrustum", "(", ")", ")", ";", "}", "else", "{", "viewFrustum", "=", "null", ";", "}", "}", "/**\n * Copies the viewfrustum into this class.\n * \n * @param source The viewfrustum to copy\n * @throws NullPointerException If source is null\n */", "public", "void", "copyViewFrustum", "(", "ViewFrustum", "source", ")", "{", "if", "(", "viewFrustum", "!=", "null", ")", "{", "viewFrustum", ".", "set", "(", "source", ")", ";", "}", "else", "{", "viewFrustum", "=", "new", "ViewFrustum", "(", "source", ")", ";", "}", "}", "/**\n * Returns the transform for this node.\n * \n * @return\n */", "@", "Override", "public", "Transform", "getTransform", "(", ")", "{", "return", "transform", ";", "}", "/**\n * Copies the material from the source to this node. If the material in the source is null, the material in this\n * node is set to null\n * \n * @param source\n * @throws NullPointerException If source is null\n */", "protected", "void", "copyMaterial", "(", "RenderableNode", "<", "T", ">", "source", ")", "{", "if", "(", "source", ".", "getMaterial", "(", ")", "!=", "null", ")", "{", "copyMaterial", "(", "source", ".", "getMaterial", "(", ")", ")", ";", "}", "}", "/**\n * Copies the material into this node\n * \n * @param source\n */", "protected", "void", "copyMaterial", "(", "Material", "source", ")", "{", "if", "(", "material", "!=", "null", ")", "{", "material", ".", "copy", "(", "source", ")", ";", "}", "else", "{", "material", "=", "new", "Material", "(", "source", ")", ";", "}", "}", "/**\n * Copies the transform from the source to this class.\n * This will copy all values, creating the transform in this node if needed.\n * \n * @param source The source transform to copy.\n */", "public", "void", "copyTransform", "(", "Transform", "source", ")", "{", "if", "(", "transform", "==", "null", ")", "{", "transform", "=", "new", "Transform", "(", "source", ")", ";", "}", "else", "{", "transform", ".", "set", "(", "source", ")", ";", "}", "}", "/**\n * Returns the resulting model matrix for this node.\n * It is updated with the concatenated model matrix for the node when it is rendered.\n * This will contain the sum of the model matrices of this nodes parents.\n * If object space collision shall be done this matrix can be used to transform the bounds.\n * \n * @return The concatenated MVP from last rendered frame, if Node is not rendered the matrix will not be updated.\n * It will contain the values from the last frame it was processed/rendered\n */", "public", "float", "[", "]", "getModelMatrix", "(", ")", "{", "return", "modelMatrix", ";", "}", "/**\n * Sets the optional projection for this node and child nodes.\n * If set this matrix will be used instead of the renderers projection matrix.\n * \n * @param projection Projection matrix or null\n */", "public", "void", "setProjection", "(", "float", "[", "]", "projection", ")", "{", "this", ".", "projection", "=", "projection", ";", "}", "@", "Override", "public", "void", "setRenderPass", "(", "ArrayList", "<", "RenderPass", ">", "renderPass", ")", "{", "if", "(", "renderPass", "!=", "null", ")", "{", "this", ".", "renderPass", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "Set", "<", "String", ">", "ids", "=", "new", "HashSet", "<", ">", "(", ")", ";", "for", "(", "RenderPass", "rp", ":", "renderPass", ")", "{", "if", "(", "rp", ".", "getId", "(", ")", "!=", "null", "&&", "ids", ".", "contains", "(", "rp", ".", "getId", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Already contains renderpass with id: ", "\"", "+", "rp", ".", "getId", "(", ")", ")", ";", "}", "ids", ".", "add", "(", "rp", ".", "getId", "(", ")", ")", ";", "this", ".", "renderPass", ".", "add", "(", "rp", ")", ";", "}", "}", "else", "{", "this", ".", "renderPass", "=", "null", ";", "}", "}", "@", "Override", "public", "ArrayList", "<", "RenderPass", ">", "getRenderPass", "(", ")", "{", "return", "renderPass", ";", "}", "@", "Override", "public", "float", "[", "]", "concatModelMatrix", "(", "float", "[", "]", "concatModel", ")", "{", "if", "(", "concatModel", "==", "null", ")", "{", "return", "transform", "!=", "null", "?", "Matrix", ".", "copy", "(", "transform", ".", "updateMatrix", "(", ")", ",", "0", ",", "modelMatrix", ",", "0", ")", ":", "Matrix", ".", "setIdentity", "(", "modelMatrix", ",", "0", ")", ";", "}", "Matrix", ".", "mul4", "(", "concatModel", ",", "transform", "!=", "null", "?", "transform", ".", "updateMatrix", "(", ")", ":", "Matrix", ".", "IDENTITY_MATRIX", ",", "modelMatrix", ")", ";", "return", "modelMatrix", ";", "}", "@", "Override", "public", "boolean", "isInside", "(", "float", "[", "]", "position", ")", "{", "if", "(", "bounds", "!=", "null", "&&", "(", "state", "==", "State", ".", "ON", "||", "state", "==", "State", ".", "ACTOR", ")", ")", "{", "bounds", ".", "transform", "(", "modelMatrix", ",", "0", ")", ";", "return", "bounds", ".", "isPointInside", "(", "position", ",", "0", ")", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "void", "onCreated", "(", ")", "{", "ViewFrustum", "vf", "=", "getViewFrustum", "(", ")", ";", "if", "(", "bounds", "!=", "null", "&&", "bounds", ".", "getBounds", "(", ")", "==", "null", ")", "{", "if", "(", "getProperty", "(", "EventHandler", ".", "EventType", ".", "POINTERINPUT", ".", "name", "(", ")", ",", "Constants", ".", "FALSE", ")", ".", "equals", "(", "Constants", ".", "TRUE", ")", ")", "{", "vf", "=", "vf", "!=", "null", "?", "vf", ":", "getParentsView", "(", ")", ";", "if", "(", "vf", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Node ", "\"", "+", "getId", "(", ")", "+", "\"", " defines pointer input but does not have bounds and ViewFrustum defined in any parent", "\"", ")", ";", "}", "}", "if", "(", "vf", "!=", "null", ")", "{", "float", "[", "]", "values", "=", "vf", ".", "getValues", "(", ")", ";", "initBounds", "(", "new", "Rectangle", "(", "values", "[", "ViewFrustum", ".", "LEFT_INDEX", "]", ",", "values", "[", "ViewFrustum", ".", "TOP_INDEX", "]", ",", "vf", ".", "getWidth", "(", ")", ",", "vf", ".", "getHeight", "(", ")", ")", ")", ";", "}", "}", "if", "(", "vf", "!=", "null", ")", "{", "setProjection", "(", "vf", ".", "getMatrix", "(", ")", ")", ";", "}", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "super", ".", "toString", "(", ")", "+", "\"", ", ", "\"", "+", "meshes", ".", "size", "(", ")", "+", "\"", " meshes", "\"", "+", "(", "renderPass", "!=", "null", "?", "\"", ", has renderpass", "\"", ":", "\"", "\"", ")", ";", "}", "}" ]
Node that has support for one or more generic Meshes.
[ "Node", "that", "has", "support", "for", "one", "or", "more", "generic", "Meshes", "." ]
[ "// Check if bounds should be created explicitly", "// Bounds object defined in node but no bound values set.", "// try to calculate from viewfrustum.", "// Has pointer input so must have bounds" ]
[ { "param": "AbstractNode", "type": null }, { "param": "RenderableNode<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractNode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "RenderableNode<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
337f6cbdd84fd2be02c89614c4a0a1d89fc62dc7
mousedogpig/solr5.5.4
solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java
[ "Apache-2.0" ]
Java
DistribJoinFromCollectionTest
/** * Tests using fromIndex that points to a collection in SolrCloud mode. */
Tests using fromIndex that points to a collection in SolrCloud mode.
[ "Tests", "using", "fromIndex", "that", "points", "to", "a", "collection", "in", "SolrCloud", "mode", "." ]
public class DistribJoinFromCollectionTest extends AbstractFullDistribZkTestBase { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public DistribJoinFromCollectionTest() { super(); } @Before @Override public void setUp() throws Exception { super.setUp(); System.setProperty("numShards", Integer.toString(sliceCount)); } @Override @After public void tearDown() throws Exception { try { super.tearDown(); } catch (Exception exc) {} resetExceptionIgnores(); } @Test public void test() throws Exception { // create a collection holding data for the "to" side of the JOIN String toColl = "to_2x2"; createCollection(toColl, 2, 2, 2); ensureAllReplicasAreActive(toColl, "shard1", 2, 2, 30); ensureAllReplicasAreActive(toColl, "shard2", 2, 2, 30); // get the set of nodes where replicas for the "to" collection exist Set<String> nodeSet = new HashSet<>(); ClusterState cs = cloudClient.getZkStateReader().getClusterState(); for (Slice slice : cs.getActiveSlices(toColl)) for (Replica replica : slice.getReplicas()) nodeSet.add(replica.getNodeName()); assertTrue(nodeSet.size() > 0); // deploy the "from" collection to all nodes where the "to" collection exists String fromColl = "from_1x2"; createCollection(null, fromColl, 1, nodeSet.size(), 1, null, StringUtils.join(nodeSet,",")); ensureAllReplicasAreActive(fromColl, "shard1", 1, nodeSet.size(), 30); // both to and from collections are up and active, index some docs ... Integer toDocId = indexDoc(toColl, 1001, "a", null, "b"); indexDoc(fromColl, 2001, "a", "c", null); Thread.sleep(1000); // so the commits fire //without score testJoins(toColl, fromColl, toDocId, false); //with score testJoins(toColl, fromColl, toDocId, true); log.info("DistribJoinFromCollectionTest logic complete ... deleting the " + toColl + " and " + fromColl + " collections"); // try to clean up for (String c : new String[]{ toColl, fromColl }) { try { CollectionAdminRequest.Delete req = new CollectionAdminRequest.Delete() .setCollectionName(c); req.process(cloudClient); } catch (Exception e) { // don't fail the test log.warn("Could not delete collection {} after test completed due to: " + e, c); } } log.info("DistribJoinFromCollectionTest succeeded ... shutting down now!"); } private void testJoins(String toColl, String fromColl, Integer toDocId, boolean isScoresTest) throws SolrServerException, IOException { // verify the join with fromIndex works final String[] scoreModes = {"avg","max","min","total"}; String joinQ = "{!join " + anyScoreMode(isScoresTest, scoreModes) + "from=join_s fromIndex=" + fromColl + " to=join_s}match_s:c"; QueryRequest qr = new QueryRequest(params("collection", toColl, "q", joinQ, "fl", "id,get_s,score")); QueryResponse rsp = new QueryResponse(cloudClient.request(qr), cloudClient); SolrDocumentList hits = rsp.getResults(); assertTrue("Expected 1 doc", hits.getNumFound() == 1); SolrDocument doc = hits.get(0); assertEquals(toDocId, doc.getFirstValue("id")); assertEquals("b", doc.getFirstValue("get_s")); assertScore(isScoresTest, doc); //negative test before creating an alias checkAbsentFromIndex(fromColl, toColl, isScoresTest, scoreModes); // create an alias for the fromIndex and then query through the alias String alias = fromColl+"Alias"; CollectionAdminRequest.CreateAlias request = new CollectionAdminRequest.CreateAlias(); request.setAliasName(alias); request.setAliasedCollections(fromColl); request.process(cloudClient); joinQ = "{!join " + anyScoreMode(isScoresTest, scoreModes) + "from=join_s fromIndex=" + alias + " to=join_s}match_s:c"; qr = new QueryRequest(params("collection", toColl, "q", joinQ, "fl", "id,get_s,score")); rsp = new QueryResponse(cloudClient.request(qr), cloudClient); hits = rsp.getResults(); assertTrue("Expected 1 doc", hits.getNumFound() == 1); doc = hits.get(0); assertEquals(toDocId, doc.getFirstValue("id")); assertEquals("b", doc.getFirstValue("get_s")); assertScore(isScoresTest, doc); //negative test after creating an alias checkAbsentFromIndex(fromColl, toColl, isScoresTest, scoreModes); // verify join doesn't work if no match in the "from" index joinQ = "{!join " + (anyScoreMode(isScoresTest, scoreModes)) + "from=join_s fromIndex=" + fromColl + " to=join_s}match_s:d"; qr = new QueryRequest(params("collection", toColl, "q", joinQ, "fl", "id,get_s,score")); rsp = new QueryResponse(cloudClient.request(qr), cloudClient); hits = rsp.getResults(); assertTrue("Expected no hits", hits.getNumFound() == 0); assertScore(isScoresTest, doc); } private void assertScore(boolean isScoresTest, SolrDocument doc) { if (isScoresTest) { assertThat(doc.getFirstValue("score").toString(), not("1.0")); } else { assertEquals("1.0", doc.getFirstValue("score").toString()); } } private String anyScoreMode(boolean isScoresTest, String[] scoreModes) { return isScoresTest ? "score=" + (scoreModes[random().nextInt(scoreModes.length)]) + " " : ""; } private void checkAbsentFromIndex(String fromColl, String toColl, boolean isScoresTest, String[] scoreModes) throws SolrServerException, IOException { final String wrongName = fromColl + "WrongName"; final String joinQ = "{!join " + (anyScoreMode(isScoresTest, scoreModes)) + "from=join_s fromIndex=" + wrongName + " to=join_s}match_s:c"; final QueryRequest qr = new QueryRequest(params("collection", toColl, "q", joinQ, "fl", "id,get_s,score")); try { cloudClient.request(qr); } catch (HttpSolrClient.RemoteSolrException ex) { assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code()); assertTrue(ex.getMessage().contains(wrongName)); } } protected Integer indexDoc(String collection, int id, String joinField, String matchField, String getField) throws Exception { UpdateRequest up = new UpdateRequest(); up.setCommitWithin(50); up.setParam("collection", collection); SolrInputDocument doc = new SolrInputDocument(); Integer docId = new Integer(id); doc.addField("id", docId); doc.addField("join_s", joinField); if (matchField != null) doc.addField("match_s", matchField); if (getField != null) doc.addField("get_s", getField); up.add(doc); cloudClient.request(up); return docId; } }
[ "public", "class", "DistribJoinFromCollectionTest", "extends", "AbstractFullDistribZkTestBase", "{", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "MethodHandles", ".", "lookup", "(", ")", ".", "lookupClass", "(", ")", ")", ";", "public", "DistribJoinFromCollectionTest", "(", ")", "{", "super", "(", ")", ";", "}", "@", "Before", "@", "Override", "public", "void", "setUp", "(", ")", "throws", "Exception", "{", "super", ".", "setUp", "(", ")", ";", "System", ".", "setProperty", "(", "\"", "numShards", "\"", ",", "Integer", ".", "toString", "(", "sliceCount", ")", ")", ";", "}", "@", "Override", "@", "After", "public", "void", "tearDown", "(", ")", "throws", "Exception", "{", "try", "{", "super", ".", "tearDown", "(", ")", ";", "}", "catch", "(", "Exception", "exc", ")", "{", "}", "resetExceptionIgnores", "(", ")", ";", "}", "@", "Test", "public", "void", "test", "(", ")", "throws", "Exception", "{", "String", "toColl", "=", "\"", "to_2x2", "\"", ";", "createCollection", "(", "toColl", ",", "2", ",", "2", ",", "2", ")", ";", "ensureAllReplicasAreActive", "(", "toColl", ",", "\"", "shard1", "\"", ",", "2", ",", "2", ",", "30", ")", ";", "ensureAllReplicasAreActive", "(", "toColl", ",", "\"", "shard2", "\"", ",", "2", ",", "2", ",", "30", ")", ";", "Set", "<", "String", ">", "nodeSet", "=", "new", "HashSet", "<", ">", "(", ")", ";", "ClusterState", "cs", "=", "cloudClient", ".", "getZkStateReader", "(", ")", ".", "getClusterState", "(", ")", ";", "for", "(", "Slice", "slice", ":", "cs", ".", "getActiveSlices", "(", "toColl", ")", ")", "for", "(", "Replica", "replica", ":", "slice", ".", "getReplicas", "(", ")", ")", "nodeSet", ".", "add", "(", "replica", ".", "getNodeName", "(", ")", ")", ";", "assertTrue", "(", "nodeSet", ".", "size", "(", ")", ">", "0", ")", ";", "String", "fromColl", "=", "\"", "from_1x2", "\"", ";", "createCollection", "(", "null", ",", "fromColl", ",", "1", ",", "nodeSet", ".", "size", "(", ")", ",", "1", ",", "null", ",", "StringUtils", ".", "join", "(", "nodeSet", ",", "\"", ",", "\"", ")", ")", ";", "ensureAllReplicasAreActive", "(", "fromColl", ",", "\"", "shard1", "\"", ",", "1", ",", "nodeSet", ".", "size", "(", ")", ",", "30", ")", ";", "Integer", "toDocId", "=", "indexDoc", "(", "toColl", ",", "1001", ",", "\"", "a", "\"", ",", "null", ",", "\"", "b", "\"", ")", ";", "indexDoc", "(", "fromColl", ",", "2001", ",", "\"", "a", "\"", ",", "\"", "c", "\"", ",", "null", ")", ";", "Thread", ".", "sleep", "(", "1000", ")", ";", "testJoins", "(", "toColl", ",", "fromColl", ",", "toDocId", ",", "false", ")", ";", "testJoins", "(", "toColl", ",", "fromColl", ",", "toDocId", ",", "true", ")", ";", "log", ".", "info", "(", "\"", "DistribJoinFromCollectionTest logic complete ... deleting the ", "\"", "+", "toColl", "+", "\"", " and ", "\"", "+", "fromColl", "+", "\"", " collections", "\"", ")", ";", "for", "(", "String", "c", ":", "new", "String", "[", "]", "{", "toColl", ",", "fromColl", "}", ")", "{", "try", "{", "CollectionAdminRequest", ".", "Delete", "req", "=", "new", "CollectionAdminRequest", ".", "Delete", "(", ")", ".", "setCollectionName", "(", "c", ")", ";", "req", ".", "process", "(", "cloudClient", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "warn", "(", "\"", "Could not delete collection {} after test completed due to: ", "\"", "+", "e", ",", "c", ")", ";", "}", "}", "log", ".", "info", "(", "\"", "DistribJoinFromCollectionTest succeeded ... shutting down now!", "\"", ")", ";", "}", "private", "void", "testJoins", "(", "String", "toColl", ",", "String", "fromColl", ",", "Integer", "toDocId", ",", "boolean", "isScoresTest", ")", "throws", "SolrServerException", ",", "IOException", "{", "final", "String", "[", "]", "scoreModes", "=", "{", "\"", "avg", "\"", ",", "\"", "max", "\"", ",", "\"", "min", "\"", ",", "\"", "total", "\"", "}", ";", "String", "joinQ", "=", "\"", "{!join ", "\"", "+", "anyScoreMode", "(", "isScoresTest", ",", "scoreModes", ")", "+", "\"", "from=join_s fromIndex=", "\"", "+", "fromColl", "+", "\"", " to=join_s}match_s:c", "\"", ";", "QueryRequest", "qr", "=", "new", "QueryRequest", "(", "params", "(", "\"", "collection", "\"", ",", "toColl", ",", "\"", "q", "\"", ",", "joinQ", ",", "\"", "fl", "\"", ",", "\"", "id,get_s,score", "\"", ")", ")", ";", "QueryResponse", "rsp", "=", "new", "QueryResponse", "(", "cloudClient", ".", "request", "(", "qr", ")", ",", "cloudClient", ")", ";", "SolrDocumentList", "hits", "=", "rsp", ".", "getResults", "(", ")", ";", "assertTrue", "(", "\"", "Expected 1 doc", "\"", ",", "hits", ".", "getNumFound", "(", ")", "==", "1", ")", ";", "SolrDocument", "doc", "=", "hits", ".", "get", "(", "0", ")", ";", "assertEquals", "(", "toDocId", ",", "doc", ".", "getFirstValue", "(", "\"", "id", "\"", ")", ")", ";", "assertEquals", "(", "\"", "b", "\"", ",", "doc", ".", "getFirstValue", "(", "\"", "get_s", "\"", ")", ")", ";", "assertScore", "(", "isScoresTest", ",", "doc", ")", ";", "checkAbsentFromIndex", "(", "fromColl", ",", "toColl", ",", "isScoresTest", ",", "scoreModes", ")", ";", "String", "alias", "=", "fromColl", "+", "\"", "Alias", "\"", ";", "CollectionAdminRequest", ".", "CreateAlias", "request", "=", "new", "CollectionAdminRequest", ".", "CreateAlias", "(", ")", ";", "request", ".", "setAliasName", "(", "alias", ")", ";", "request", ".", "setAliasedCollections", "(", "fromColl", ")", ";", "request", ".", "process", "(", "cloudClient", ")", ";", "joinQ", "=", "\"", "{!join ", "\"", "+", "anyScoreMode", "(", "isScoresTest", ",", "scoreModes", ")", "+", "\"", "from=join_s fromIndex=", "\"", "+", "alias", "+", "\"", " to=join_s}match_s:c", "\"", ";", "qr", "=", "new", "QueryRequest", "(", "params", "(", "\"", "collection", "\"", ",", "toColl", ",", "\"", "q", "\"", ",", "joinQ", ",", "\"", "fl", "\"", ",", "\"", "id,get_s,score", "\"", ")", ")", ";", "rsp", "=", "new", "QueryResponse", "(", "cloudClient", ".", "request", "(", "qr", ")", ",", "cloudClient", ")", ";", "hits", "=", "rsp", ".", "getResults", "(", ")", ";", "assertTrue", "(", "\"", "Expected 1 doc", "\"", ",", "hits", ".", "getNumFound", "(", ")", "==", "1", ")", ";", "doc", "=", "hits", ".", "get", "(", "0", ")", ";", "assertEquals", "(", "toDocId", ",", "doc", ".", "getFirstValue", "(", "\"", "id", "\"", ")", ")", ";", "assertEquals", "(", "\"", "b", "\"", ",", "doc", ".", "getFirstValue", "(", "\"", "get_s", "\"", ")", ")", ";", "assertScore", "(", "isScoresTest", ",", "doc", ")", ";", "checkAbsentFromIndex", "(", "fromColl", ",", "toColl", ",", "isScoresTest", ",", "scoreModes", ")", ";", "joinQ", "=", "\"", "{!join ", "\"", "+", "(", "anyScoreMode", "(", "isScoresTest", ",", "scoreModes", ")", ")", "+", "\"", "from=join_s fromIndex=", "\"", "+", "fromColl", "+", "\"", " to=join_s}match_s:d", "\"", ";", "qr", "=", "new", "QueryRequest", "(", "params", "(", "\"", "collection", "\"", ",", "toColl", ",", "\"", "q", "\"", ",", "joinQ", ",", "\"", "fl", "\"", ",", "\"", "id,get_s,score", "\"", ")", ")", ";", "rsp", "=", "new", "QueryResponse", "(", "cloudClient", ".", "request", "(", "qr", ")", ",", "cloudClient", ")", ";", "hits", "=", "rsp", ".", "getResults", "(", ")", ";", "assertTrue", "(", "\"", "Expected no hits", "\"", ",", "hits", ".", "getNumFound", "(", ")", "==", "0", ")", ";", "assertScore", "(", "isScoresTest", ",", "doc", ")", ";", "}", "private", "void", "assertScore", "(", "boolean", "isScoresTest", ",", "SolrDocument", "doc", ")", "{", "if", "(", "isScoresTest", ")", "{", "assertThat", "(", "doc", ".", "getFirstValue", "(", "\"", "score", "\"", ")", ".", "toString", "(", ")", ",", "not", "(", "\"", "1.0", "\"", ")", ")", ";", "}", "else", "{", "assertEquals", "(", "\"", "1.0", "\"", ",", "doc", ".", "getFirstValue", "(", "\"", "score", "\"", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "private", "String", "anyScoreMode", "(", "boolean", "isScoresTest", ",", "String", "[", "]", "scoreModes", ")", "{", "return", "isScoresTest", "?", "\"", "score=", "\"", "+", "(", "scoreModes", "[", "random", "(", ")", ".", "nextInt", "(", "scoreModes", ".", "length", ")", "]", ")", "+", "\"", " ", "\"", ":", "\"", "\"", ";", "}", "private", "void", "checkAbsentFromIndex", "(", "String", "fromColl", ",", "String", "toColl", ",", "boolean", "isScoresTest", ",", "String", "[", "]", "scoreModes", ")", "throws", "SolrServerException", ",", "IOException", "{", "final", "String", "wrongName", "=", "fromColl", "+", "\"", "WrongName", "\"", ";", "final", "String", "joinQ", "=", "\"", "{!join ", "\"", "+", "(", "anyScoreMode", "(", "isScoresTest", ",", "scoreModes", ")", ")", "+", "\"", "from=join_s fromIndex=", "\"", "+", "wrongName", "+", "\"", " to=join_s}match_s:c", "\"", ";", "final", "QueryRequest", "qr", "=", "new", "QueryRequest", "(", "params", "(", "\"", "collection", "\"", ",", "toColl", ",", "\"", "q", "\"", ",", "joinQ", ",", "\"", "fl", "\"", ",", "\"", "id,get_s,score", "\"", ")", ")", ";", "try", "{", "cloudClient", ".", "request", "(", "qr", ")", ";", "}", "catch", "(", "HttpSolrClient", ".", "RemoteSolrException", "ex", ")", "{", "assertEquals", "(", "SolrException", ".", "ErrorCode", ".", "BAD_REQUEST", ".", "code", ",", "ex", ".", "code", "(", ")", ")", ";", "assertTrue", "(", "ex", ".", "getMessage", "(", ")", ".", "contains", "(", "wrongName", ")", ")", ";", "}", "}", "protected", "Integer", "indexDoc", "(", "String", "collection", ",", "int", "id", ",", "String", "joinField", ",", "String", "matchField", ",", "String", "getField", ")", "throws", "Exception", "{", "UpdateRequest", "up", "=", "new", "UpdateRequest", "(", ")", ";", "up", ".", "setCommitWithin", "(", "50", ")", ";", "up", ".", "setParam", "(", "\"", "collection", "\"", ",", "collection", ")", ";", "SolrInputDocument", "doc", "=", "new", "SolrInputDocument", "(", ")", ";", "Integer", "docId", "=", "new", "Integer", "(", "id", ")", ";", "doc", ".", "addField", "(", "\"", "id", "\"", ",", "docId", ")", ";", "doc", ".", "addField", "(", "\"", "join_s", "\"", ",", "joinField", ")", ";", "if", "(", "matchField", "!=", "null", ")", "doc", ".", "addField", "(", "\"", "match_s", "\"", ",", "matchField", ")", ";", "if", "(", "getField", "!=", "null", ")", "doc", ".", "addField", "(", "\"", "get_s", "\"", ",", "getField", ")", ";", "up", ".", "add", "(", "doc", ")", ";", "cloudClient", ".", "request", "(", "up", ")", ";", "return", "docId", ";", "}", "}" ]
Tests using fromIndex that points to a collection in SolrCloud mode.
[ "Tests", "using", "fromIndex", "that", "points", "to", "a", "collection", "in", "SolrCloud", "mode", "." ]
[ "// create a collection holding data for the \"to\" side of the JOIN", "// get the set of nodes where replicas for the \"to\" collection exist", "// deploy the \"from\" collection to all nodes where the \"to\" collection exists", "// both to and from collections are up and active, index some docs ...", "// so the commits fire", "//without score", "//with score", "// try to clean up", "// don't fail the test", "// verify the join with fromIndex works", "//negative test before creating an alias", "// create an alias for the fromIndex and then query through the alias", "//negative test after creating an alias", "// verify join doesn't work if no match in the \"from\" index" ]
[ { "param": "AbstractFullDistribZkTestBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractFullDistribZkTestBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
337f872e38de0cd8c8bcf2df281d284b8fbcf155
Eliav2rll2v/suryadev967
src/test/java/coverTest/RGBBody.java
[ "Apache-2.0" ]
Java
RGBBody
/** * @param * @DATA * @Author LiDaPeng * @Description */
@param @DATA @Author LiDaPeng @Description
[ "@param", "@DATA", "@Author", "LiDaPeng", "@Description" ]
public class RGBBody { private double r; private double g; private double b; private double rgb; public double getR() { return r; } public void setR(double r) { this.r = r; } public double getG() { return g; } public void setG(double g) { this.g = g; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getRgb() { return rgb; } public void setRgb(double rgb) { this.rgb = rgb; } }
[ "public", "class", "RGBBody", "{", "private", "double", "r", ";", "private", "double", "g", ";", "private", "double", "b", ";", "private", "double", "rgb", ";", "public", "double", "getR", "(", ")", "{", "return", "r", ";", "}", "public", "void", "setR", "(", "double", "r", ")", "{", "this", ".", "r", "=", "r", ";", "}", "public", "double", "getG", "(", ")", "{", "return", "g", ";", "}", "public", "void", "setG", "(", "double", "g", ")", "{", "this", ".", "g", "=", "g", ";", "}", "public", "double", "getB", "(", ")", "{", "return", "b", ";", "}", "public", "void", "setB", "(", "double", "b", ")", "{", "this", ".", "b", "=", "b", ";", "}", "public", "double", "getRgb", "(", ")", "{", "return", "rgb", ";", "}", "public", "void", "setRgb", "(", "double", "rgb", ")", "{", "this", ".", "rgb", "=", "rgb", ";", "}", "}" ]
@param @DATA @Author LiDaPeng @Description
[ "@param", "@DATA", "@Author", "LiDaPeng", "@Description" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
3380e71ddb5c1af4a4ec13b63fd7a17a3de6c78d
alfionso/finances
backend/src/main/java/es/alfonsomarin/finances/core/security/authentication/internal/InternalWebSecurityConfig.java
[ "Apache-2.0" ]
Java
InternalWebSecurityConfig
/** * Internal web security config * * @author alfonso.marin.lopez */
Internal web security config @author alfonso.marin.lopez
[ "Internal", "web", "security", "config", "@author", "alfonso", ".", "marin", ".", "lopez" ]
@Profile("local") @Configuration @EnableWebSecurity public class InternalWebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_URL = "/login"; private static final String API_URL = "/api/**"; private static final String API_MESSAGES_URL = "/api/config/messages"; private static final String REPORTS_URL = "/report/**"; @Value("${system.admin.user}") private String userName; @Value("${system.admin.password}") private String password; private CsrfCookieFilter csrfCookieFilter; private CsrfTokenRepository csrfTokenRepository; private AuthenticationSuccessHandler authenticationSuccessHandler; private AuthenticationFailureHandler authenticationFailureHandler; private SessionManagementFilter sessionManagementFilter; private LogoutSuccessHandler logoutSuccessHandler; private LogoutHandler cookieClearingLogoutHandler; @Override protected void configure(HttpSecurity http) throws Exception { http .addFilter(authenticationFilter()) .addFilter(sessionManagementFilter) .addFilterAfter(csrfCookieFilter, CsrfFilter.class) .addFilterBefore(new WebSecurityCorsFilter(), ChannelProcessingFilter.class) .headers() .cacheControl().and() .xssProtection().and() .frameOptions().sameOrigin().and() .authorizeRequests() .antMatchers(API_MESSAGES_URL).permitAll() .antMatchers(API_URL).authenticated() .antMatchers(REPORTS_URL).authenticated() .and() .logout() .logoutSuccessHandler(logoutSuccessHandler) .addLogoutHandler(cookieClearingLogoutHandler) .invalidateHttpSession(true) .and() .csrf() .csrfTokenRepository(csrfTokenRepository); } /** * Configure global. * * @param auth the auth * @throws Exception the exception */ @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .passwordEncoder(passwordEncoder()) .withUser(userName).password(password).roles("USER"); } /** * Password encoder b crypt password encoder. * * @return the b crypt password encoder */ @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } private UsernamePasswordAuthenticationFilter authenticationFilter() throws Exception { UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(authenticationManagerBean()); filter.setAuthenticationFailureHandler(authenticationFailureHandler); filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); return filter; } /** * Sets csrf cookie filter. * * @param csrfCookieFilter the csrf cookie filter */ @Autowired public void setCsrfCookieFilter(CsrfCookieFilter csrfCookieFilter) { this.csrfCookieFilter = csrfCookieFilter; } /** * Sets csrf token repository. * * @param csrfTokenRepository the csrf token repository */ @Autowired public void setCsrfTokenRepository(CsrfTokenRepository csrfTokenRepository) { this.csrfTokenRepository = csrfTokenRepository; } /** * Sets authentication success handler. * * @param authenticationSuccessHandler the authentication success handler */ @Autowired public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) { this.authenticationSuccessHandler = authenticationSuccessHandler; } /** * Sets authentication failure handler. * * @param authenticationFailureHandler the authentication failure handler */ @Autowired public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) { this.authenticationFailureHandler = authenticationFailureHandler; } /** * Sets session management filter. * * @param sessionManagementFilter the session management filter */ @Autowired public void setSessionManagementFilter(SessionManagementFilter sessionManagementFilter) { this.sessionManagementFilter = sessionManagementFilter; } /** * Sets logout success handler. * * @param logoutSuccessHandler the logout success handler */ @Autowired public void setLogoutSuccessHandler(LogoutSuccessHandler logoutSuccessHandler) { this.logoutSuccessHandler = logoutSuccessHandler; } /** * Sets cookie clearing logout handler. * * @param cookieClearingLogoutHandler the cookie clearing logout handler */ @Autowired public void setCookieClearingLogoutHandler(LogoutHandler cookieClearingLogoutHandler) { this.cookieClearingLogoutHandler = cookieClearingLogoutHandler; } }
[ "@", "Profile", "(", "\"", "local", "\"", ")", "@", "Configuration", "@", "EnableWebSecurity", "public", "class", "InternalWebSecurityConfig", "extends", "WebSecurityConfigurerAdapter", "{", "private", "static", "final", "String", "LOGIN_URL", "=", "\"", "/login", "\"", ";", "private", "static", "final", "String", "API_URL", "=", "\"", "/api/**", "\"", ";", "private", "static", "final", "String", "API_MESSAGES_URL", "=", "\"", "/api/config/messages", "\"", ";", "private", "static", "final", "String", "REPORTS_URL", "=", "\"", "/report/**", "\"", ";", "@", "Value", "(", "\"", "${system.admin.user}", "\"", ")", "private", "String", "userName", ";", "@", "Value", "(", "\"", "${system.admin.password}", "\"", ")", "private", "String", "password", ";", "private", "CsrfCookieFilter", "csrfCookieFilter", ";", "private", "CsrfTokenRepository", "csrfTokenRepository", ";", "private", "AuthenticationSuccessHandler", "authenticationSuccessHandler", ";", "private", "AuthenticationFailureHandler", "authenticationFailureHandler", ";", "private", "SessionManagementFilter", "sessionManagementFilter", ";", "private", "LogoutSuccessHandler", "logoutSuccessHandler", ";", "private", "LogoutHandler", "cookieClearingLogoutHandler", ";", "@", "Override", "protected", "void", "configure", "(", "HttpSecurity", "http", ")", "throws", "Exception", "{", "http", ".", "addFilter", "(", "authenticationFilter", "(", ")", ")", ".", "addFilter", "(", "sessionManagementFilter", ")", ".", "addFilterAfter", "(", "csrfCookieFilter", ",", "CsrfFilter", ".", "class", ")", ".", "addFilterBefore", "(", "new", "WebSecurityCorsFilter", "(", ")", ",", "ChannelProcessingFilter", ".", "class", ")", ".", "headers", "(", ")", ".", "cacheControl", "(", ")", ".", "and", "(", ")", ".", "xssProtection", "(", ")", ".", "and", "(", ")", ".", "frameOptions", "(", ")", ".", "sameOrigin", "(", ")", ".", "and", "(", ")", ".", "authorizeRequests", "(", ")", ".", "antMatchers", "(", "API_MESSAGES_URL", ")", ".", "permitAll", "(", ")", ".", "antMatchers", "(", "API_URL", ")", ".", "authenticated", "(", ")", ".", "antMatchers", "(", "REPORTS_URL", ")", ".", "authenticated", "(", ")", ".", "and", "(", ")", ".", "logout", "(", ")", ".", "logoutSuccessHandler", "(", "logoutSuccessHandler", ")", ".", "addLogoutHandler", "(", "cookieClearingLogoutHandler", ")", ".", "invalidateHttpSession", "(", "true", ")", ".", "and", "(", ")", ".", "csrf", "(", ")", ".", "csrfTokenRepository", "(", "csrfTokenRepository", ")", ";", "}", "/**\n * Configure global.\n *\n * @param auth the auth\n * @throws Exception the exception\n */", "@", "Autowired", "public", "void", "configureGlobal", "(", "AuthenticationManagerBuilder", "auth", ")", "throws", "Exception", "{", "auth", ".", "inMemoryAuthentication", "(", ")", ".", "passwordEncoder", "(", "passwordEncoder", "(", ")", ")", ".", "withUser", "(", "userName", ")", ".", "password", "(", "password", ")", ".", "roles", "(", "\"", "USER", "\"", ")", ";", "}", "/**\n * Password encoder b crypt password encoder.\n *\n * @return the b crypt password encoder\n */", "@", "Bean", "public", "BCryptPasswordEncoder", "passwordEncoder", "(", ")", "{", "return", "new", "BCryptPasswordEncoder", "(", ")", ";", "}", "private", "UsernamePasswordAuthenticationFilter", "authenticationFilter", "(", ")", "throws", "Exception", "{", "UsernamePasswordAuthenticationFilter", "filter", "=", "new", "UsernamePasswordAuthenticationFilter", "(", ")", ";", "filter", ".", "setAuthenticationManager", "(", "authenticationManagerBean", "(", ")", ")", ";", "filter", ".", "setAuthenticationFailureHandler", "(", "authenticationFailureHandler", ")", ";", "filter", ".", "setAuthenticationSuccessHandler", "(", "authenticationSuccessHandler", ")", ";", "return", "filter", ";", "}", "/**\n * Sets csrf cookie filter.\n *\n * @param csrfCookieFilter the csrf cookie filter\n */", "@", "Autowired", "public", "void", "setCsrfCookieFilter", "(", "CsrfCookieFilter", "csrfCookieFilter", ")", "{", "this", ".", "csrfCookieFilter", "=", "csrfCookieFilter", ";", "}", "/**\n * Sets csrf token repository.\n *\n * @param csrfTokenRepository the csrf token repository\n */", "@", "Autowired", "public", "void", "setCsrfTokenRepository", "(", "CsrfTokenRepository", "csrfTokenRepository", ")", "{", "this", ".", "csrfTokenRepository", "=", "csrfTokenRepository", ";", "}", "/**\n * Sets authentication success handler.\n *\n * @param authenticationSuccessHandler the authentication success handler\n */", "@", "Autowired", "public", "void", "setAuthenticationSuccessHandler", "(", "AuthenticationSuccessHandler", "authenticationSuccessHandler", ")", "{", "this", ".", "authenticationSuccessHandler", "=", "authenticationSuccessHandler", ";", "}", "/**\n * Sets authentication failure handler.\n *\n * @param authenticationFailureHandler the authentication failure handler\n */", "@", "Autowired", "public", "void", "setAuthenticationFailureHandler", "(", "AuthenticationFailureHandler", "authenticationFailureHandler", ")", "{", "this", ".", "authenticationFailureHandler", "=", "authenticationFailureHandler", ";", "}", "/**\n * Sets session management filter.\n *\n * @param sessionManagementFilter the session management filter\n */", "@", "Autowired", "public", "void", "setSessionManagementFilter", "(", "SessionManagementFilter", "sessionManagementFilter", ")", "{", "this", ".", "sessionManagementFilter", "=", "sessionManagementFilter", ";", "}", "/**\n * Sets logout success handler.\n *\n * @param logoutSuccessHandler the logout success handler\n */", "@", "Autowired", "public", "void", "setLogoutSuccessHandler", "(", "LogoutSuccessHandler", "logoutSuccessHandler", ")", "{", "this", ".", "logoutSuccessHandler", "=", "logoutSuccessHandler", ";", "}", "/**\n * Sets cookie clearing logout handler.\n *\n * @param cookieClearingLogoutHandler the cookie clearing logout handler\n */", "@", "Autowired", "public", "void", "setCookieClearingLogoutHandler", "(", "LogoutHandler", "cookieClearingLogoutHandler", ")", "{", "this", ".", "cookieClearingLogoutHandler", "=", "cookieClearingLogoutHandler", ";", "}", "}" ]
Internal web security config @author alfonso.marin.lopez
[ "Internal", "web", "security", "config", "@author", "alfonso", ".", "marin", ".", "lopez" ]
[]
[ { "param": "WebSecurityConfigurerAdapter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "WebSecurityConfigurerAdapter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3385255e75543aa27ecdb85f92bb9c321f3032b6
brickviking/TinkersConstruct
src/main/java/slimeknights/tconstruct/library/tools/stat/ModifierStatsBuilder.java
[ "MIT" ]
Java
ModifierStatsBuilder
/** * Stat builder for modifiers, allows more fine control over just setting the value */
Stat builder for modifiers, allows more fine control over just setting the value
[ "Stat", "builder", "for", "modifiers", "allows", "more", "fine", "control", "over", "just", "setting", "the", "value" ]
@NoArgsConstructor(staticName = "builder") public class ModifierStatsBuilder { /** If true, a change was made */ private boolean dirty = false; /** Map of all stats in the builder */ private final Map<IToolStat<?>,Object> map = new HashMap<>(); /** Map of multipliers set */ private final Map<INumericToolStat<?>,Float> multipliers = new HashMap<>(); /** * Updates the given stat in the builder * @param stat New value * @param consumer Consumer for your builder instance. Will be the same object type as the builder from {@link IToolStat#makeBuilder()} */ @SuppressWarnings("unchecked") public <B> void updateStat(IToolStat<?> stat, Consumer<B> consumer) { consumer.accept((B)map.computeIfAbsent(stat, IToolStat::makeBuilder)); dirty = true; } /** Sets the given stat into the builder from the base NBT, method to help with generics */ private <T> void setStat(StatsNBT.Builder builder, IToolStat<T> stat, StatsNBT base) { if (map.containsKey(stat)) { builder.set(stat, stat.build(map.get(stat), base.get(stat))); } else { builder.set(stat, base.get(stat)); } } /** Multiplies the given multiplier value by the parameter */ public void multiplier(INumericToolStat<?> stat, double value) { multipliers.put(stat, (float)(multipliers.getOrDefault(stat, 1f) * value)); } /** Builds the given stat, method exists to make generic easier */ private <T> void buildStat(StatsNBT.Builder builder, IToolStat<T> stat) { builder.set(stat, stat.build(map.get(stat), stat.getDefaultValue())); } /** * Builds the stats * @param base Base stats * @return Built stats */ public StatsNBT build(StatsNBT base) { if (!dirty) { return base; } StatsNBT.Builder builder = StatsNBT.builder(); // first, iterate all stats in the base set Set<IToolStat<?>> existing = base.getContainedStats(); for (IToolStat<?> stat : existing) { setStat(builder, stat, base); } // next, iterate any stats we have that are not in base for (IToolStat<?> stat : map.keySet()) { if (!existing.contains(stat)) { buildStat(builder, stat); } } return builder.build(); } /** * Builds the stat multiplier object for global stat multipliers * @return Multipliers stats */ public MultiplierNBT buildMultipliers() { MultiplierNBT.Builder builder = MultiplierNBT.builder(); for (Entry<INumericToolStat<?>,Float> entry : multipliers.entrySet()) { builder.set(entry.getKey(), entry.getValue()); } return builder.build(); } }
[ "@", "NoArgsConstructor", "(", "staticName", "=", "\"", "builder", "\"", ")", "public", "class", "ModifierStatsBuilder", "{", "/** If true, a change was made */", "private", "boolean", "dirty", "=", "false", ";", "/** Map of all stats in the builder */", "private", "final", "Map", "<", "IToolStat", "<", "?", ">", ",", "Object", ">", "map", "=", "new", "HashMap", "<", ">", "(", ")", ";", "/** Map of multipliers set */", "private", "final", "Map", "<", "INumericToolStat", "<", "?", ">", ",", "Float", ">", "multipliers", "=", "new", "HashMap", "<", ">", "(", ")", ";", "/**\n * Updates the given stat in the builder\n * @param stat New value\n * @param consumer Consumer for your builder instance. Will be the same object type as the builder from {@link IToolStat#makeBuilder()}\n */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "public", "<", "B", ">", "void", "updateStat", "(", "IToolStat", "<", "?", ">", "stat", ",", "Consumer", "<", "B", ">", "consumer", ")", "{", "consumer", ".", "accept", "(", "(", "B", ")", "map", ".", "computeIfAbsent", "(", "stat", ",", "IToolStat", "::", "makeBuilder", ")", ")", ";", "dirty", "=", "true", ";", "}", "/** Sets the given stat into the builder from the base NBT, method to help with generics */", "private", "<", "T", ">", "void", "setStat", "(", "StatsNBT", ".", "Builder", "builder", ",", "IToolStat", "<", "T", ">", "stat", ",", "StatsNBT", "base", ")", "{", "if", "(", "map", ".", "containsKey", "(", "stat", ")", ")", "{", "builder", ".", "set", "(", "stat", ",", "stat", ".", "build", "(", "map", ".", "get", "(", "stat", ")", ",", "base", ".", "get", "(", "stat", ")", ")", ")", ";", "}", "else", "{", "builder", ".", "set", "(", "stat", ",", "base", ".", "get", "(", "stat", ")", ")", ";", "}", "}", "/** Multiplies the given multiplier value by the parameter */", "public", "void", "multiplier", "(", "INumericToolStat", "<", "?", ">", "stat", ",", "double", "value", ")", "{", "multipliers", ".", "put", "(", "stat", ",", "(", "float", ")", "(", "multipliers", ".", "getOrDefault", "(", "stat", ",", "1f", ")", "*", "value", ")", ")", ";", "}", "/** Builds the given stat, method exists to make generic easier */", "private", "<", "T", ">", "void", "buildStat", "(", "StatsNBT", ".", "Builder", "builder", ",", "IToolStat", "<", "T", ">", "stat", ")", "{", "builder", ".", "set", "(", "stat", ",", "stat", ".", "build", "(", "map", ".", "get", "(", "stat", ")", ",", "stat", ".", "getDefaultValue", "(", ")", ")", ")", ";", "}", "/**\n * Builds the stats\n * @param base Base stats\n * @return Built stats\n */", "public", "StatsNBT", "build", "(", "StatsNBT", "base", ")", "{", "if", "(", "!", "dirty", ")", "{", "return", "base", ";", "}", "StatsNBT", ".", "Builder", "builder", "=", "StatsNBT", ".", "builder", "(", ")", ";", "Set", "<", "IToolStat", "<", "?", ">", ">", "existing", "=", "base", ".", "getContainedStats", "(", ")", ";", "for", "(", "IToolStat", "<", "?", ">", "stat", ":", "existing", ")", "{", "setStat", "(", "builder", ",", "stat", ",", "base", ")", ";", "}", "for", "(", "IToolStat", "<", "?", ">", "stat", ":", "map", ".", "keySet", "(", ")", ")", "{", "if", "(", "!", "existing", ".", "contains", "(", "stat", ")", ")", "{", "buildStat", "(", "builder", ",", "stat", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}", "/**\n * Builds the stat multiplier object for global stat multipliers\n * @return Multipliers stats\n */", "public", "MultiplierNBT", "buildMultipliers", "(", ")", "{", "MultiplierNBT", ".", "Builder", "builder", "=", "MultiplierNBT", ".", "builder", "(", ")", ";", "for", "(", "Entry", "<", "INumericToolStat", "<", "?", ">", ",", "Float", ">", "entry", ":", "multipliers", ".", "entrySet", "(", ")", ")", "{", "builder", ".", "set", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "return", "builder", ".", "build", "(", ")", ";", "}", "}" ]
Stat builder for modifiers, allows more fine control over just setting the value
[ "Stat", "builder", "for", "modifiers", "allows", "more", "fine", "control", "over", "just", "setting", "the", "value" ]
[ "// first, iterate all stats in the base set", "// next, iterate any stats we have that are not in base" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
3385fa57f12d24b58316cee8f2ea86b0ccb73018
rrockenbaugh/incubator-pirk
src/main/java/org/apache/pirk/test/utils/BaseTests.java
[ "Apache-2.0" ]
Java
BaseTests
/** * Class to hold the base functional distributed tests */
Class to hold the base functional distributed tests
[ "Class", "to", "hold", "the", "base", "functional", "distributed", "tests" ]
public class BaseTests { private static final Logger logger = LoggerFactory.getLogger(BaseTests.class); public static final UUID queryIdentifier = UUID.randomUUID(); public static final int dataPartitionBitSize = 8; // Selectors for domain and IP queries, queryIdentifier is the first entry for file generation public static List<String> selectorsDomain = new ArrayList<>( Arrays.asList("s.t.u.net", "d.e.com", "r.r.r.r", "a.b.c.com", "something.else", "x.y.net")); public static List<String> selectorsIP = new ArrayList<>(Arrays.asList("55.55.55.55", "5.6.7.8", "10.20.30.40", "13.14.15.16", "21.22.23.24")); // Encryption variables -- Paillier mechanisms are tested in the Paillier test code, so these are fixed... public static final int hashBitSize = 12; public static final int paillierBitSize = 384; public static final int certainty = 128; public static void testDNSHostnameQuery(ArrayList<JSONObject> dataElements, int numThreads, boolean testFalsePositive) throws Exception { testDNSHostnameQuery(dataElements, null, false, false, numThreads, testFalsePositive, false); } public static void testDNSHostnameQuery(List<JSONObject> dataElements, FileSystem fs, boolean isSpark, boolean isDistributed, int numThreads) throws Exception { testDNSHostnameQuery(dataElements, fs, isSpark, isDistributed, numThreads, false, false); } // Query for the watched hostname occurred; ; watched value type: hostname (String) public static void testDNSHostnameQuery(List<JSONObject> dataElements, FileSystem fs, boolean isSpark, boolean isDistributed, int numThreads, boolean testFalsePositive, boolean isStreaming) throws Exception { logger.info("Running testDNSHostnameQuery(): "); int numExpectedResults = 6; List<QueryResponseJSON> results; if (isDistributed) { results = DistTestSuite.performQuery(Inputs.DNS_HOSTNAME_QUERY, selectorsDomain, fs, isSpark, numThreads, isStreaming); } else { results = StandaloneQuery.performStandaloneQuery(dataElements, Inputs.DNS_HOSTNAME_QUERY, selectorsDomain, numThreads, testFalsePositive); if (!testFalsePositive) { numExpectedResults = 7; // all 7 for non distributed case; if testFalsePositive==true, then 6 } } checkDNSHostnameQueryResults(results, isDistributed, numExpectedResults, testFalsePositive, dataElements); logger.info("Completed testDNSHostnameQuery(): "); } public static void checkDNSHostnameQueryResults(List<QueryResponseJSON> results, boolean isDistributed, int numExpectedResults, boolean testFalsePositive, List<JSONObject> dataElements) { QuerySchema qSchema = QuerySchemaRegistry.get(Inputs.DNS_HOSTNAME_QUERY); logger.info("results:"); printResultList(results); if (isDistributed && SystemConfiguration.isSetTrue("pir.limitHitsPerSelector")) { // 3 elements returned - one for each qname -- a.b.c.com, d.e.com, something.else if (results.size() != 3) { fail("results.size() = " + results.size() + " -- must equal 3"); } // Check that each qname appears once in the result set HashSet<String> correctQnames = new HashSet<>(); correctQnames.add("a.b.c.com"); correctQnames.add("d.e.com"); correctQnames.add("something.else"); HashSet<String> resultQnames = new HashSet<>(); for (QueryResponseJSON qrJSON : results) { resultQnames.add((String) qrJSON.getValue(Inputs.QNAME)); } if (correctQnames.size() != resultQnames.size()) { fail("correctQnames.size() = " + correctQnames.size() + " != resultQnames.size() " + resultQnames.size()); } for (String resultQname : resultQnames) { if (!correctQnames.contains(resultQname)) { fail("correctQnames does not contain resultQname = " + resultQname); } } } else { if (results.size() != numExpectedResults) { fail("results.size() = " + results.size() + " -- must equal " + numExpectedResults); } // Number of original elements at the end of the list that we do not need to consider for hits int removeTailElements = 2; // the last two data elements should not hit if (testFalsePositive) { removeTailElements = 3; } ArrayList<QueryResponseJSON> correctResults = new ArrayList<>(); int i = 0; while (i < (dataElements.size() - removeTailElements)) { JSONObject dataMap = dataElements.get(i); boolean addElement = true; if (isDistributed && dataMap.get(Inputs.RCODE).toString().equals("3")) { addElement = false; } if (addElement) { QueryResponseJSON wlJSON = new QueryResponseJSON(); wlJSON.setMapping(QueryResponseJSON.QUERY_ID, queryIdentifier.toString()); wlJSON.setMapping(QueryResponseJSON.EVENT_TYPE, Inputs.DNS_HOSTNAME_QUERY); wlJSON.setMapping(Inputs.DATE, dataMap.get(Inputs.DATE)); wlJSON.setMapping(Inputs.SRCIP, dataMap.get(Inputs.SRCIP)); wlJSON.setMapping(Inputs.DSTIP, dataMap.get(Inputs.DSTIP)); wlJSON.setMapping(Inputs.QNAME, dataMap.get(Inputs.QNAME)); // this gets re-embedded as the original selector after decryption wlJSON.setMapping(Inputs.QTYPE, parseShortArray(dataMap, Inputs.QTYPE)); wlJSON.setMapping(Inputs.RCODE, dataMap.get(Inputs.RCODE)); wlJSON.setMapping(Inputs.IPS, parseArray(dataMap, Inputs.IPS, true)); wlJSON.setMapping(QueryResponseJSON.SELECTOR, QueryUtils.getSelectorByQueryTypeJSON(qSchema, dataMap)); correctResults.add(wlJSON); } ++i; } logger.info("correctResults: "); printResultList(correctResults); if (results.size() != correctResults.size()) { logger.info("correctResults:"); printResultList(correctResults); fail("results.size() = " + results.size() + " != correctResults.size() = " + correctResults.size()); } for (QueryResponseJSON result : results) { if (!compareResultArray(correctResults, result)) { fail("correctResults does not contain result = " + result.toString()); } } } } public static void testDNSIPQuery(ArrayList<JSONObject> dataElements, int numThreads) throws Exception { testDNSIPQuery(dataElements, null, false, false, numThreads, false); } // The watched IP address was detected in the response to a query; watched value type: IP address (String) public static void testDNSIPQuery(List<JSONObject> dataElements, FileSystem fs, boolean isSpark, boolean isDistributed, int numThreads, boolean isStreaming) throws Exception { logger.info("Running testDNSIPQuery(): "); QuerySchema qSchema = QuerySchemaRegistry.get(Inputs.DNS_IP_QUERY); List<QueryResponseJSON> results; if (isDistributed) { results = DistTestSuite.performQuery(Inputs.DNS_IP_QUERY, selectorsIP, fs, isSpark, numThreads, isStreaming); if (results.size() != 5) { fail("results.size() = " + results.size() + " -- must equal 5"); } } else { results = StandaloneQuery.performStandaloneQuery(dataElements, Inputs.DNS_IP_QUERY, selectorsIP, numThreads, false); if (results.size() != 6) { fail("results.size() = " + results.size() + " -- must equal 6"); } } printResultList(results); ArrayList<QueryResponseJSON> correctResults = new ArrayList<>(); int i = 0; while (i < (dataElements.size() - 3)) // last three data elements not hit - one on stoplist, two don't match selectors { JSONObject dataMap = dataElements.get(i); boolean addElement = true; if (isDistributed && dataMap.get(Inputs.RCODE).toString().equals("3")) { addElement = false; } if (addElement) { QueryResponseJSON wlJSON = new QueryResponseJSON(); wlJSON.setMapping(QueryResponseJSON.QUERY_ID, queryIdentifier); wlJSON.setMapping(QueryResponseJSON.EVENT_TYPE, Inputs.DNS_IP_QUERY); wlJSON.setMapping(Inputs.SRCIP, dataMap.get(Inputs.SRCIP)); wlJSON.setMapping(Inputs.DSTIP, dataMap.get(Inputs.DSTIP)); wlJSON.setMapping(Inputs.IPS, parseArray(dataMap, Inputs.IPS, true)); wlJSON.setMapping(QueryResponseJSON.SELECTOR, QueryUtils.getSelectorByQueryTypeJSON(qSchema, dataMap)); correctResults.add(wlJSON); } ++i; } if (results.size() != correctResults.size()) { logger.info("correctResults:"); printResultList(correctResults); fail("results.size() = " + results.size() + " != correctResults.size() = " + correctResults.size()); } for (QueryResponseJSON result : results) { if (!compareResultArray(correctResults, result)) { fail("correctResults does not contain result = " + result.toString()); } } logger.info("Completed testDNSIPQuery(): "); } public static void testDNSNXDOMAINQuery(ArrayList<JSONObject> dataElements, int numThreads) throws Exception { testDNSNXDOMAINQuery(dataElements, null, false, false, numThreads); } // A query that returned an nxdomain response was made for the watched hostname; watched value type: hostname (String) public static void testDNSNXDOMAINQuery(List<JSONObject> dataElements, FileSystem fs, boolean isSpark, boolean isDistributed, int numThreads) throws Exception { logger.info("Running testDNSNXDOMAINQuery(): "); QuerySchema qSchema = QuerySchemaRegistry.get(Inputs.DNS_NXDOMAIN_QUERY); List<QueryResponseJSON> results; if (isDistributed) { results = DistTestSuite.performQuery(Inputs.DNS_NXDOMAIN_QUERY, selectorsDomain, fs, isSpark, numThreads, false); } else { results = StandaloneQuery.performStandaloneQuery(dataElements, Inputs.DNS_NXDOMAIN_QUERY, selectorsDomain, numThreads, false); } printResultList(results); if (results.size() != 1) { fail("results.size() = " + results.size() + " -- must equal 1"); } ArrayList<QueryResponseJSON> correctResults = new ArrayList<>(); int i = 0; while (i < dataElements.size()) { JSONObject dataMap = dataElements.get(i); if (dataMap.get(Inputs.RCODE).toString().equals("3")) { QueryResponseJSON wlJSON = new QueryResponseJSON(); wlJSON.setMapping(QueryResponseJSON.QUERY_ID, queryIdentifier); wlJSON.setMapping(QueryResponseJSON.EVENT_TYPE, Inputs.DNS_NXDOMAIN_QUERY); wlJSON.setMapping(Inputs.QNAME, dataMap.get(Inputs.QNAME)); // this gets re-embedded as the original selector after decryption wlJSON.setMapping(Inputs.DSTIP, dataMap.get(Inputs.DSTIP)); wlJSON.setMapping(Inputs.SRCIP, dataMap.get(Inputs.SRCIP)); wlJSON.setMapping(QueryResponseJSON.SELECTOR, QueryUtils.getSelectorByQueryTypeJSON(qSchema, dataMap)); correctResults.add(wlJSON); } ++i; } if (results.size() != correctResults.size()) { logger.info("correctResults:"); printResultList(correctResults); fail("results.size() = " + results.size() + " != correctResults.size() = " + correctResults.size()); } for (QueryResponseJSON result : results) { if (!compareResultArray(correctResults, result)) { fail("correctResults does not contain result = " + result.toString()); } } logger.info("Completed testDNSNXDOMAINQuery(): "); } public static void testSRCIPQuery(ArrayList<JSONObject> dataElements, int numThreads) throws Exception { testSRCIPQuery(dataElements, null, false, false, numThreads, false); } // Query for responses from watched srcIPs public static void testSRCIPQuery(List<JSONObject> dataElements, FileSystem fs, boolean isSpark, boolean isDistributed, int numThreads, boolean isStreaming) throws Exception { logger.info("Running testSRCIPQuery(): "); QuerySchema qSchema = QuerySchemaRegistry.get(Inputs.DNS_SRCIP_QUERY); List<QueryResponseJSON> results; int removeTailElements = 0; int numExpectedResults = 1; if (isDistributed) { results = DistTestSuite.performQuery(Inputs.DNS_SRCIP_QUERY, selectorsIP, fs, isSpark, numThreads, isStreaming); removeTailElements = 2; // The last two elements are on the distributed stoplist } else { numExpectedResults = 3; results = StandaloneQuery.performStandaloneQuery(dataElements, Inputs.DNS_SRCIP_QUERY, selectorsIP, numThreads, false); } printResultList(results); if (results.size() != numExpectedResults) { fail("results.size() = " + results.size() + " -- must equal " + numExpectedResults); } ArrayList<QueryResponseJSON> correctResults = new ArrayList<>(); int i = 0; while (i < (dataElements.size() - removeTailElements)) { JSONObject dataMap = dataElements.get(i); boolean addElement = false; if (dataMap.get(Inputs.SRCIP).toString().equals("55.55.55.55") || dataMap.get(Inputs.SRCIP).toString().equals("5.6.7.8")) { addElement = true; } if (addElement) { // Form the correct result QueryResponseJSON object QueryResponseJSON qrJSON = new QueryResponseJSON(); qrJSON.setMapping(QueryResponseJSON.QUERY_ID, queryIdentifier); qrJSON.setMapping(QueryResponseJSON.EVENT_TYPE, Inputs.DNS_SRCIP_QUERY); qrJSON.setMapping(Inputs.QNAME, parseString(dataMap, Inputs.QNAME)); qrJSON.setMapping(Inputs.DSTIP, dataMap.get(Inputs.DSTIP)); qrJSON.setMapping(Inputs.SRCIP, dataMap.get(Inputs.SRCIP)); qrJSON.setMapping(Inputs.IPS, parseArray(dataMap, Inputs.IPS, true)); qrJSON.setMapping(QueryResponseJSON.SELECTOR, QueryUtils.getSelectorByQueryTypeJSON(qSchema, dataMap)); correctResults.add(qrJSON); } ++i; } logger.info("correctResults:"); printResultList(correctResults); if (results.size() != correctResults.size()) { logger.info("correctResults:"); printResultList(correctResults); fail("results.size() = " + results.size() + " != correctResults.size() = " + correctResults.size()); } for (QueryResponseJSON result : results) { if (!compareResultArray(correctResults, result)) { fail("correctResults does not contain result = " + result.toString()); } } logger.info("Completed testSRCIPQuery(): "); } // Query for responses from watched srcIPs public static void testSRCIPQueryNoFilter(List<JSONObject> dataElements, FileSystem fs, boolean isSpark, boolean isDistributed, int numThreads, boolean isStreaming) throws Exception { logger.info("Running testSRCIPQueryNoFilter(): "); QuerySchema qSchema = QuerySchemaRegistry.get(Inputs.DNS_SRCIP_QUERY_NO_FILTER); List<QueryResponseJSON> results; int numExpectedResults = 3; if (isDistributed) { results = DistTestSuite.performQuery(Inputs.DNS_SRCIP_QUERY_NO_FILTER, selectorsIP, fs, isSpark, numThreads, isStreaming); } else { results = StandaloneQuery.performStandaloneQuery(dataElements, Inputs.DNS_SRCIP_QUERY_NO_FILTER, selectorsIP, numThreads, false); } printResultList(results); if (results.size() != numExpectedResults) { fail("results.size() = " + results.size() + " -- must equal " + numExpectedResults); } ArrayList<QueryResponseJSON> correctResults = new ArrayList<>(); int i = 0; while (i < dataElements.size()) { JSONObject dataMap = dataElements.get(i); boolean addElement = false; if (dataMap.get(Inputs.SRCIP).toString().equals("55.55.55.55") || dataMap.get(Inputs.SRCIP).toString().equals("5.6.7.8")) { addElement = true; } if (addElement) { // Form the correct result QueryResponseJSON object QueryResponseJSON qrJSON = new QueryResponseJSON(); qrJSON.setMapping(QueryResponseJSON.QUERY_ID, queryIdentifier); qrJSON.setMapping(QueryResponseJSON.EVENT_TYPE, Inputs.DNS_SRCIP_QUERY_NO_FILTER); qrJSON.setMapping(Inputs.QNAME, parseString(dataMap, Inputs.QNAME)); qrJSON.setMapping(Inputs.DSTIP, dataMap.get(Inputs.DSTIP)); qrJSON.setMapping(Inputs.SRCIP, dataMap.get(Inputs.SRCIP)); qrJSON.setMapping(Inputs.IPS, parseArray(dataMap, Inputs.IPS, true)); qrJSON.setMapping(QueryResponseJSON.SELECTOR, QueryUtils.getSelectorByQueryTypeJSON(qSchema, dataMap)); correctResults.add(qrJSON); } ++i; } logger.info("correctResults:"); printResultList(correctResults); if (results.size() != correctResults.size()) { logger.info("correctResults:"); printResultList(correctResults); fail("results.size() = " + results.size() + " != correctResults.size() = " + correctResults.size()); } for (QueryResponseJSON result : results) { if (!compareResultArray(correctResults, result)) { fail("correctResults does not contain result = " + result.toString()); } } logger.info("Completed testSRCIPQueryNoFilter(): "); } @SuppressWarnings("unchecked") // Method to convert a ArrayList<String> into the correct (padded) returned ArrayList private static ArrayList<String> parseArray(JSONObject dataMap, String fieldName, boolean isIP) { ArrayList<String> retArray = new ArrayList<>(); ArrayList<String> values; if (dataMap.get(fieldName) instanceof ArrayList) { values = (ArrayList<String>) dataMap.get(fieldName); } else { values = StringUtils.jsonArrayStringToArrayList((String) dataMap.get(fieldName)); } int numArrayElementsToReturn = SystemConfiguration.getIntProperty("pir.numReturnArrayElements", 1); for (int i = 0; i < numArrayElementsToReturn; ++i) { if (i < values.size()) { retArray.add(values.get(i)); } else if (isIP) { retArray.add("0.0.0.0"); } else { retArray.add("0"); } } return retArray; } // Method to convert a ArrayList<Short> into the correct (padded) returned ArrayList private static ArrayList<Short> parseShortArray(JSONObject dataMap, String fieldName) { ArrayList<Short> retArray = new ArrayList<>(); ArrayList<Short> values = (ArrayList<Short>) dataMap.get(fieldName); int numArrayElementsToReturn = SystemConfiguration.getIntProperty("pir.numReturnArrayElements", 1); for (int i = 0; i < numArrayElementsToReturn; ++i) { if (i < values.size()) { retArray.add(values.get(i)); } else { retArray.add((short) 0); } } return retArray; } // Method to convert the String field value to the correct returned substring private static String parseString(JSONObject dataMap, String fieldName) { String ret; String element = (String) dataMap.get(fieldName); int numParts = Integer.parseInt(SystemConfiguration.getProperty("pir.stringBits")) / dataPartitionBitSize; int len = numParts; if (element.length() < numParts) { len = element.length(); } ret = new String(element.getBytes(), 0, len); return ret; } // Method to determine whether or not the correctResults contains an object equivalent to // the given result private static boolean compareResultArray(ArrayList<QueryResponseJSON> correctResults, QueryResponseJSON result) { boolean equivalent = false; for (QueryResponseJSON correct : correctResults) { equivalent = compareResults(correct, result); if (equivalent) { break; } } return equivalent; } // Method to test the equivalence of two test results private static boolean compareResults(QueryResponseJSON r1, QueryResponseJSON r2) { boolean equivalent = true; JSONObject jsonR1 = r1.getJSONObject(); JSONObject jsonR2 = r2.getJSONObject(); Set<String> r1KeySet = jsonR1.keySet(); Set<String> r2KeySet = jsonR2.keySet(); if (!r1KeySet.equals(r2KeySet)) { equivalent = false; } if (equivalent) { for (String key : r1KeySet) { if (key.equals(Inputs.QTYPE) || key.equals(Inputs.IPS)) // array types { HashSet<String> set1 = getSetFromList(jsonR1.get(key)); HashSet<String> set2 = getSetFromList(jsonR2.get(key)); if (!set1.equals(set2)) { equivalent = false; } } else { if (!(jsonR1.get(key).toString()).equals(jsonR2.get(key).toString())) { equivalent = false; } } } } return equivalent; } // Method to pull the elements of a list (either an ArrayList or JSONArray) into a HashSet private static HashSet<String> getSetFromList(Object list) { HashSet<String> set = new HashSet<>(); if (list instanceof ArrayList) { for (Object obj : (ArrayList) list) { set.add(obj.toString()); } } else // JSONArray { for (Object obj : (JSONArray) list) { set.add(obj.toString()); } } return set; } private static void printResultList(List<QueryResponseJSON> list) { for (QueryResponseJSON obj : list) { logger.info(obj.toString()); } } }
[ "public", "class", "BaseTests", "{", "private", "static", "final", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "BaseTests", ".", "class", ")", ";", "public", "static", "final", "UUID", "queryIdentifier", "=", "UUID", ".", "randomUUID", "(", ")", ";", "public", "static", "final", "int", "dataPartitionBitSize", "=", "8", ";", "public", "static", "List", "<", "String", ">", "selectorsDomain", "=", "new", "ArrayList", "<", ">", "(", "Arrays", ".", "asList", "(", "\"", "s.t.u.net", "\"", ",", "\"", "d.e.com", "\"", ",", "\"", "r.r.r.r", "\"", ",", "\"", "a.b.c.com", "\"", ",", "\"", "something.else", "\"", ",", "\"", "x.y.net", "\"", ")", ")", ";", "public", "static", "List", "<", "String", ">", "selectorsIP", "=", "new", "ArrayList", "<", ">", "(", "Arrays", ".", "asList", "(", "\"", "55.55.55.55", "\"", ",", "\"", "5.6.7.8", "\"", ",", "\"", "10.20.30.40", "\"", ",", "\"", "13.14.15.16", "\"", ",", "\"", "21.22.23.24", "\"", ")", ")", ";", "public", "static", "final", "int", "hashBitSize", "=", "12", ";", "public", "static", "final", "int", "paillierBitSize", "=", "384", ";", "public", "static", "final", "int", "certainty", "=", "128", ";", "public", "static", "void", "testDNSHostnameQuery", "(", "ArrayList", "<", "JSONObject", ">", "dataElements", ",", "int", "numThreads", ",", "boolean", "testFalsePositive", ")", "throws", "Exception", "{", "testDNSHostnameQuery", "(", "dataElements", ",", "null", ",", "false", ",", "false", ",", "numThreads", ",", "testFalsePositive", ",", "false", ")", ";", "}", "public", "static", "void", "testDNSHostnameQuery", "(", "List", "<", "JSONObject", ">", "dataElements", ",", "FileSystem", "fs", ",", "boolean", "isSpark", ",", "boolean", "isDistributed", ",", "int", "numThreads", ")", "throws", "Exception", "{", "testDNSHostnameQuery", "(", "dataElements", ",", "fs", ",", "isSpark", ",", "isDistributed", ",", "numThreads", ",", "false", ",", "false", ")", ";", "}", "public", "static", "void", "testDNSHostnameQuery", "(", "List", "<", "JSONObject", ">", "dataElements", ",", "FileSystem", "fs", ",", "boolean", "isSpark", ",", "boolean", "isDistributed", ",", "int", "numThreads", ",", "boolean", "testFalsePositive", ",", "boolean", "isStreaming", ")", "throws", "Exception", "{", "logger", ".", "info", "(", "\"", "Running testDNSHostnameQuery(): ", "\"", ")", ";", "int", "numExpectedResults", "=", "6", ";", "List", "<", "QueryResponseJSON", ">", "results", ";", "if", "(", "isDistributed", ")", "{", "results", "=", "DistTestSuite", ".", "performQuery", "(", "Inputs", ".", "DNS_HOSTNAME_QUERY", ",", "selectorsDomain", ",", "fs", ",", "isSpark", ",", "numThreads", ",", "isStreaming", ")", ";", "}", "else", "{", "results", "=", "StandaloneQuery", ".", "performStandaloneQuery", "(", "dataElements", ",", "Inputs", ".", "DNS_HOSTNAME_QUERY", ",", "selectorsDomain", ",", "numThreads", ",", "testFalsePositive", ")", ";", "if", "(", "!", "testFalsePositive", ")", "{", "numExpectedResults", "=", "7", ";", "}", "}", "checkDNSHostnameQueryResults", "(", "results", ",", "isDistributed", ",", "numExpectedResults", ",", "testFalsePositive", ",", "dataElements", ")", ";", "logger", ".", "info", "(", "\"", "Completed testDNSHostnameQuery(): ", "\"", ")", ";", "}", "public", "static", "void", "checkDNSHostnameQueryResults", "(", "List", "<", "QueryResponseJSON", ">", "results", ",", "boolean", "isDistributed", ",", "int", "numExpectedResults", ",", "boolean", "testFalsePositive", ",", "List", "<", "JSONObject", ">", "dataElements", ")", "{", "QuerySchema", "qSchema", "=", "QuerySchemaRegistry", ".", "get", "(", "Inputs", ".", "DNS_HOSTNAME_QUERY", ")", ";", "logger", ".", "info", "(", "\"", "results:", "\"", ")", ";", "printResultList", "(", "results", ")", ";", "if", "(", "isDistributed", "&&", "SystemConfiguration", ".", "isSetTrue", "(", "\"", "pir.limitHitsPerSelector", "\"", ")", ")", "{", "if", "(", "results", ".", "size", "(", ")", "!=", "3", ")", "{", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " -- must equal 3", "\"", ")", ";", "}", "HashSet", "<", "String", ">", "correctQnames", "=", "new", "HashSet", "<", ">", "(", ")", ";", "correctQnames", ".", "add", "(", "\"", "a.b.c.com", "\"", ")", ";", "correctQnames", ".", "add", "(", "\"", "d.e.com", "\"", ")", ";", "correctQnames", ".", "add", "(", "\"", "something.else", "\"", ")", ";", "HashSet", "<", "String", ">", "resultQnames", "=", "new", "HashSet", "<", ">", "(", ")", ";", "for", "(", "QueryResponseJSON", "qrJSON", ":", "results", ")", "{", "resultQnames", ".", "add", "(", "(", "String", ")", "qrJSON", ".", "getValue", "(", "Inputs", ".", "QNAME", ")", ")", ";", "}", "if", "(", "correctQnames", ".", "size", "(", ")", "!=", "resultQnames", ".", "size", "(", ")", ")", "{", "fail", "(", "\"", "correctQnames.size() = ", "\"", "+", "correctQnames", ".", "size", "(", ")", "+", "\"", " != resultQnames.size() ", "\"", "+", "resultQnames", ".", "size", "(", ")", ")", ";", "}", "for", "(", "String", "resultQname", ":", "resultQnames", ")", "{", "if", "(", "!", "correctQnames", ".", "contains", "(", "resultQname", ")", ")", "{", "fail", "(", "\"", "correctQnames does not contain resultQname = ", "\"", "+", "resultQname", ")", ";", "}", "}", "}", "else", "{", "if", "(", "results", ".", "size", "(", ")", "!=", "numExpectedResults", ")", "{", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " -- must equal ", "\"", "+", "numExpectedResults", ")", ";", "}", "int", "removeTailElements", "=", "2", ";", "if", "(", "testFalsePositive", ")", "{", "removeTailElements", "=", "3", ";", "}", "ArrayList", "<", "QueryResponseJSON", ">", "correctResults", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "int", "i", "=", "0", ";", "while", "(", "i", "<", "(", "dataElements", ".", "size", "(", ")", "-", "removeTailElements", ")", ")", "{", "JSONObject", "dataMap", "=", "dataElements", ".", "get", "(", "i", ")", ";", "boolean", "addElement", "=", "true", ";", "if", "(", "isDistributed", "&&", "dataMap", ".", "get", "(", "Inputs", ".", "RCODE", ")", ".", "toString", "(", ")", ".", "equals", "(", "\"", "3", "\"", ")", ")", "{", "addElement", "=", "false", ";", "}", "if", "(", "addElement", ")", "{", "QueryResponseJSON", "wlJSON", "=", "new", "QueryResponseJSON", "(", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "QUERY_ID", ",", "queryIdentifier", ".", "toString", "(", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "EVENT_TYPE", ",", "Inputs", ".", "DNS_HOSTNAME_QUERY", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "DATE", ",", "dataMap", ".", "get", "(", "Inputs", ".", "DATE", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "SRCIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "DSTIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "DSTIP", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "QNAME", ",", "dataMap", ".", "get", "(", "Inputs", ".", "QNAME", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "QTYPE", ",", "parseShortArray", "(", "dataMap", ",", "Inputs", ".", "QTYPE", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "RCODE", ",", "dataMap", ".", "get", "(", "Inputs", ".", "RCODE", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "IPS", ",", "parseArray", "(", "dataMap", ",", "Inputs", ".", "IPS", ",", "true", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "SELECTOR", ",", "QueryUtils", ".", "getSelectorByQueryTypeJSON", "(", "qSchema", ",", "dataMap", ")", ")", ";", "correctResults", ".", "add", "(", "wlJSON", ")", ";", "}", "++", "i", ";", "}", "logger", ".", "info", "(", "\"", "correctResults: ", "\"", ")", ";", "printResultList", "(", "correctResults", ")", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "correctResults", ".", "size", "(", ")", ")", "{", "logger", ".", "info", "(", "\"", "correctResults:", "\"", ")", ";", "printResultList", "(", "correctResults", ")", ";", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " != correctResults.size() = ", "\"", "+", "correctResults", ".", "size", "(", ")", ")", ";", "}", "for", "(", "QueryResponseJSON", "result", ":", "results", ")", "{", "if", "(", "!", "compareResultArray", "(", "correctResults", ",", "result", ")", ")", "{", "fail", "(", "\"", "correctResults does not contain result = ", "\"", "+", "result", ".", "toString", "(", ")", ")", ";", "}", "}", "}", "}", "public", "static", "void", "testDNSIPQuery", "(", "ArrayList", "<", "JSONObject", ">", "dataElements", ",", "int", "numThreads", ")", "throws", "Exception", "{", "testDNSIPQuery", "(", "dataElements", ",", "null", ",", "false", ",", "false", ",", "numThreads", ",", "false", ")", ";", "}", "public", "static", "void", "testDNSIPQuery", "(", "List", "<", "JSONObject", ">", "dataElements", ",", "FileSystem", "fs", ",", "boolean", "isSpark", ",", "boolean", "isDistributed", ",", "int", "numThreads", ",", "boolean", "isStreaming", ")", "throws", "Exception", "{", "logger", ".", "info", "(", "\"", "Running testDNSIPQuery(): ", "\"", ")", ";", "QuerySchema", "qSchema", "=", "QuerySchemaRegistry", ".", "get", "(", "Inputs", ".", "DNS_IP_QUERY", ")", ";", "List", "<", "QueryResponseJSON", ">", "results", ";", "if", "(", "isDistributed", ")", "{", "results", "=", "DistTestSuite", ".", "performQuery", "(", "Inputs", ".", "DNS_IP_QUERY", ",", "selectorsIP", ",", "fs", ",", "isSpark", ",", "numThreads", ",", "isStreaming", ")", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "5", ")", "{", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " -- must equal 5", "\"", ")", ";", "}", "}", "else", "{", "results", "=", "StandaloneQuery", ".", "performStandaloneQuery", "(", "dataElements", ",", "Inputs", ".", "DNS_IP_QUERY", ",", "selectorsIP", ",", "numThreads", ",", "false", ")", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "6", ")", "{", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " -- must equal 6", "\"", ")", ";", "}", "}", "printResultList", "(", "results", ")", ";", "ArrayList", "<", "QueryResponseJSON", ">", "correctResults", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "int", "i", "=", "0", ";", "while", "(", "i", "<", "(", "dataElements", ".", "size", "(", ")", "-", "3", ")", ")", "{", "JSONObject", "dataMap", "=", "dataElements", ".", "get", "(", "i", ")", ";", "boolean", "addElement", "=", "true", ";", "if", "(", "isDistributed", "&&", "dataMap", ".", "get", "(", "Inputs", ".", "RCODE", ")", ".", "toString", "(", ")", ".", "equals", "(", "\"", "3", "\"", ")", ")", "{", "addElement", "=", "false", ";", "}", "if", "(", "addElement", ")", "{", "QueryResponseJSON", "wlJSON", "=", "new", "QueryResponseJSON", "(", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "QUERY_ID", ",", "queryIdentifier", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "EVENT_TYPE", ",", "Inputs", ".", "DNS_IP_QUERY", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "SRCIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "DSTIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "DSTIP", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "IPS", ",", "parseArray", "(", "dataMap", ",", "Inputs", ".", "IPS", ",", "true", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "SELECTOR", ",", "QueryUtils", ".", "getSelectorByQueryTypeJSON", "(", "qSchema", ",", "dataMap", ")", ")", ";", "correctResults", ".", "add", "(", "wlJSON", ")", ";", "}", "++", "i", ";", "}", "if", "(", "results", ".", "size", "(", ")", "!=", "correctResults", ".", "size", "(", ")", ")", "{", "logger", ".", "info", "(", "\"", "correctResults:", "\"", ")", ";", "printResultList", "(", "correctResults", ")", ";", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " != correctResults.size() = ", "\"", "+", "correctResults", ".", "size", "(", ")", ")", ";", "}", "for", "(", "QueryResponseJSON", "result", ":", "results", ")", "{", "if", "(", "!", "compareResultArray", "(", "correctResults", ",", "result", ")", ")", "{", "fail", "(", "\"", "correctResults does not contain result = ", "\"", "+", "result", ".", "toString", "(", ")", ")", ";", "}", "}", "logger", ".", "info", "(", "\"", "Completed testDNSIPQuery(): ", "\"", ")", ";", "}", "public", "static", "void", "testDNSNXDOMAINQuery", "(", "ArrayList", "<", "JSONObject", ">", "dataElements", ",", "int", "numThreads", ")", "throws", "Exception", "{", "testDNSNXDOMAINQuery", "(", "dataElements", ",", "null", ",", "false", ",", "false", ",", "numThreads", ")", ";", "}", "public", "static", "void", "testDNSNXDOMAINQuery", "(", "List", "<", "JSONObject", ">", "dataElements", ",", "FileSystem", "fs", ",", "boolean", "isSpark", ",", "boolean", "isDistributed", ",", "int", "numThreads", ")", "throws", "Exception", "{", "logger", ".", "info", "(", "\"", "Running testDNSNXDOMAINQuery(): ", "\"", ")", ";", "QuerySchema", "qSchema", "=", "QuerySchemaRegistry", ".", "get", "(", "Inputs", ".", "DNS_NXDOMAIN_QUERY", ")", ";", "List", "<", "QueryResponseJSON", ">", "results", ";", "if", "(", "isDistributed", ")", "{", "results", "=", "DistTestSuite", ".", "performQuery", "(", "Inputs", ".", "DNS_NXDOMAIN_QUERY", ",", "selectorsDomain", ",", "fs", ",", "isSpark", ",", "numThreads", ",", "false", ")", ";", "}", "else", "{", "results", "=", "StandaloneQuery", ".", "performStandaloneQuery", "(", "dataElements", ",", "Inputs", ".", "DNS_NXDOMAIN_QUERY", ",", "selectorsDomain", ",", "numThreads", ",", "false", ")", ";", "}", "printResultList", "(", "results", ")", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "1", ")", "{", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " -- must equal 1", "\"", ")", ";", "}", "ArrayList", "<", "QueryResponseJSON", ">", "correctResults", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "int", "i", "=", "0", ";", "while", "(", "i", "<", "dataElements", ".", "size", "(", ")", ")", "{", "JSONObject", "dataMap", "=", "dataElements", ".", "get", "(", "i", ")", ";", "if", "(", "dataMap", ".", "get", "(", "Inputs", ".", "RCODE", ")", ".", "toString", "(", ")", ".", "equals", "(", "\"", "3", "\"", ")", ")", "{", "QueryResponseJSON", "wlJSON", "=", "new", "QueryResponseJSON", "(", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "QUERY_ID", ",", "queryIdentifier", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "EVENT_TYPE", ",", "Inputs", ".", "DNS_NXDOMAIN_QUERY", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "QNAME", ",", "dataMap", ".", "get", "(", "Inputs", ".", "QNAME", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "DSTIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "DSTIP", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "Inputs", ".", "SRCIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ")", ";", "wlJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "SELECTOR", ",", "QueryUtils", ".", "getSelectorByQueryTypeJSON", "(", "qSchema", ",", "dataMap", ")", ")", ";", "correctResults", ".", "add", "(", "wlJSON", ")", ";", "}", "++", "i", ";", "}", "if", "(", "results", ".", "size", "(", ")", "!=", "correctResults", ".", "size", "(", ")", ")", "{", "logger", ".", "info", "(", "\"", "correctResults:", "\"", ")", ";", "printResultList", "(", "correctResults", ")", ";", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " != correctResults.size() = ", "\"", "+", "correctResults", ".", "size", "(", ")", ")", ";", "}", "for", "(", "QueryResponseJSON", "result", ":", "results", ")", "{", "if", "(", "!", "compareResultArray", "(", "correctResults", ",", "result", ")", ")", "{", "fail", "(", "\"", "correctResults does not contain result = ", "\"", "+", "result", ".", "toString", "(", ")", ")", ";", "}", "}", "logger", ".", "info", "(", "\"", "Completed testDNSNXDOMAINQuery(): ", "\"", ")", ";", "}", "public", "static", "void", "testSRCIPQuery", "(", "ArrayList", "<", "JSONObject", ">", "dataElements", ",", "int", "numThreads", ")", "throws", "Exception", "{", "testSRCIPQuery", "(", "dataElements", ",", "null", ",", "false", ",", "false", ",", "numThreads", ",", "false", ")", ";", "}", "public", "static", "void", "testSRCIPQuery", "(", "List", "<", "JSONObject", ">", "dataElements", ",", "FileSystem", "fs", ",", "boolean", "isSpark", ",", "boolean", "isDistributed", ",", "int", "numThreads", ",", "boolean", "isStreaming", ")", "throws", "Exception", "{", "logger", ".", "info", "(", "\"", "Running testSRCIPQuery(): ", "\"", ")", ";", "QuerySchema", "qSchema", "=", "QuerySchemaRegistry", ".", "get", "(", "Inputs", ".", "DNS_SRCIP_QUERY", ")", ";", "List", "<", "QueryResponseJSON", ">", "results", ";", "int", "removeTailElements", "=", "0", ";", "int", "numExpectedResults", "=", "1", ";", "if", "(", "isDistributed", ")", "{", "results", "=", "DistTestSuite", ".", "performQuery", "(", "Inputs", ".", "DNS_SRCIP_QUERY", ",", "selectorsIP", ",", "fs", ",", "isSpark", ",", "numThreads", ",", "isStreaming", ")", ";", "removeTailElements", "=", "2", ";", "}", "else", "{", "numExpectedResults", "=", "3", ";", "results", "=", "StandaloneQuery", ".", "performStandaloneQuery", "(", "dataElements", ",", "Inputs", ".", "DNS_SRCIP_QUERY", ",", "selectorsIP", ",", "numThreads", ",", "false", ")", ";", "}", "printResultList", "(", "results", ")", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "numExpectedResults", ")", "{", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " -- must equal ", "\"", "+", "numExpectedResults", ")", ";", "}", "ArrayList", "<", "QueryResponseJSON", ">", "correctResults", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "int", "i", "=", "0", ";", "while", "(", "i", "<", "(", "dataElements", ".", "size", "(", ")", "-", "removeTailElements", ")", ")", "{", "JSONObject", "dataMap", "=", "dataElements", ".", "get", "(", "i", ")", ";", "boolean", "addElement", "=", "false", ";", "if", "(", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ".", "toString", "(", ")", ".", "equals", "(", "\"", "55.55.55.55", "\"", ")", "||", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ".", "toString", "(", ")", ".", "equals", "(", "\"", "5.6.7.8", "\"", ")", ")", "{", "addElement", "=", "true", ";", "}", "if", "(", "addElement", ")", "{", "QueryResponseJSON", "qrJSON", "=", "new", "QueryResponseJSON", "(", ")", ";", "qrJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "QUERY_ID", ",", "queryIdentifier", ")", ";", "qrJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "EVENT_TYPE", ",", "Inputs", ".", "DNS_SRCIP_QUERY", ")", ";", "qrJSON", ".", "setMapping", "(", "Inputs", ".", "QNAME", ",", "parseString", "(", "dataMap", ",", "Inputs", ".", "QNAME", ")", ")", ";", "qrJSON", ".", "setMapping", "(", "Inputs", ".", "DSTIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "DSTIP", ")", ")", ";", "qrJSON", ".", "setMapping", "(", "Inputs", ".", "SRCIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ")", ";", "qrJSON", ".", "setMapping", "(", "Inputs", ".", "IPS", ",", "parseArray", "(", "dataMap", ",", "Inputs", ".", "IPS", ",", "true", ")", ")", ";", "qrJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "SELECTOR", ",", "QueryUtils", ".", "getSelectorByQueryTypeJSON", "(", "qSchema", ",", "dataMap", ")", ")", ";", "correctResults", ".", "add", "(", "qrJSON", ")", ";", "}", "++", "i", ";", "}", "logger", ".", "info", "(", "\"", "correctResults:", "\"", ")", ";", "printResultList", "(", "correctResults", ")", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "correctResults", ".", "size", "(", ")", ")", "{", "logger", ".", "info", "(", "\"", "correctResults:", "\"", ")", ";", "printResultList", "(", "correctResults", ")", ";", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " != correctResults.size() = ", "\"", "+", "correctResults", ".", "size", "(", ")", ")", ";", "}", "for", "(", "QueryResponseJSON", "result", ":", "results", ")", "{", "if", "(", "!", "compareResultArray", "(", "correctResults", ",", "result", ")", ")", "{", "fail", "(", "\"", "correctResults does not contain result = ", "\"", "+", "result", ".", "toString", "(", ")", ")", ";", "}", "}", "logger", ".", "info", "(", "\"", "Completed testSRCIPQuery(): ", "\"", ")", ";", "}", "public", "static", "void", "testSRCIPQueryNoFilter", "(", "List", "<", "JSONObject", ">", "dataElements", ",", "FileSystem", "fs", ",", "boolean", "isSpark", ",", "boolean", "isDistributed", ",", "int", "numThreads", ",", "boolean", "isStreaming", ")", "throws", "Exception", "{", "logger", ".", "info", "(", "\"", "Running testSRCIPQueryNoFilter(): ", "\"", ")", ";", "QuerySchema", "qSchema", "=", "QuerySchemaRegistry", ".", "get", "(", "Inputs", ".", "DNS_SRCIP_QUERY_NO_FILTER", ")", ";", "List", "<", "QueryResponseJSON", ">", "results", ";", "int", "numExpectedResults", "=", "3", ";", "if", "(", "isDistributed", ")", "{", "results", "=", "DistTestSuite", ".", "performQuery", "(", "Inputs", ".", "DNS_SRCIP_QUERY_NO_FILTER", ",", "selectorsIP", ",", "fs", ",", "isSpark", ",", "numThreads", ",", "isStreaming", ")", ";", "}", "else", "{", "results", "=", "StandaloneQuery", ".", "performStandaloneQuery", "(", "dataElements", ",", "Inputs", ".", "DNS_SRCIP_QUERY_NO_FILTER", ",", "selectorsIP", ",", "numThreads", ",", "false", ")", ";", "}", "printResultList", "(", "results", ")", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "numExpectedResults", ")", "{", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " -- must equal ", "\"", "+", "numExpectedResults", ")", ";", "}", "ArrayList", "<", "QueryResponseJSON", ">", "correctResults", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "int", "i", "=", "0", ";", "while", "(", "i", "<", "dataElements", ".", "size", "(", ")", ")", "{", "JSONObject", "dataMap", "=", "dataElements", ".", "get", "(", "i", ")", ";", "boolean", "addElement", "=", "false", ";", "if", "(", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ".", "toString", "(", ")", ".", "equals", "(", "\"", "55.55.55.55", "\"", ")", "||", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ".", "toString", "(", ")", ".", "equals", "(", "\"", "5.6.7.8", "\"", ")", ")", "{", "addElement", "=", "true", ";", "}", "if", "(", "addElement", ")", "{", "QueryResponseJSON", "qrJSON", "=", "new", "QueryResponseJSON", "(", ")", ";", "qrJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "QUERY_ID", ",", "queryIdentifier", ")", ";", "qrJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "EVENT_TYPE", ",", "Inputs", ".", "DNS_SRCIP_QUERY_NO_FILTER", ")", ";", "qrJSON", ".", "setMapping", "(", "Inputs", ".", "QNAME", ",", "parseString", "(", "dataMap", ",", "Inputs", ".", "QNAME", ")", ")", ";", "qrJSON", ".", "setMapping", "(", "Inputs", ".", "DSTIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "DSTIP", ")", ")", ";", "qrJSON", ".", "setMapping", "(", "Inputs", ".", "SRCIP", ",", "dataMap", ".", "get", "(", "Inputs", ".", "SRCIP", ")", ")", ";", "qrJSON", ".", "setMapping", "(", "Inputs", ".", "IPS", ",", "parseArray", "(", "dataMap", ",", "Inputs", ".", "IPS", ",", "true", ")", ")", ";", "qrJSON", ".", "setMapping", "(", "QueryResponseJSON", ".", "SELECTOR", ",", "QueryUtils", ".", "getSelectorByQueryTypeJSON", "(", "qSchema", ",", "dataMap", ")", ")", ";", "correctResults", ".", "add", "(", "qrJSON", ")", ";", "}", "++", "i", ";", "}", "logger", ".", "info", "(", "\"", "correctResults:", "\"", ")", ";", "printResultList", "(", "correctResults", ")", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "correctResults", ".", "size", "(", ")", ")", "{", "logger", ".", "info", "(", "\"", "correctResults:", "\"", ")", ";", "printResultList", "(", "correctResults", ")", ";", "fail", "(", "\"", "results.size() = ", "\"", "+", "results", ".", "size", "(", ")", "+", "\"", " != correctResults.size() = ", "\"", "+", "correctResults", ".", "size", "(", ")", ")", ";", "}", "for", "(", "QueryResponseJSON", "result", ":", "results", ")", "{", "if", "(", "!", "compareResultArray", "(", "correctResults", ",", "result", ")", ")", "{", "fail", "(", "\"", "correctResults does not contain result = ", "\"", "+", "result", ".", "toString", "(", ")", ")", ";", "}", "}", "logger", ".", "info", "(", "\"", "Completed testSRCIPQueryNoFilter(): ", "\"", ")", ";", "}", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "private", "static", "ArrayList", "<", "String", ">", "parseArray", "(", "JSONObject", "dataMap", ",", "String", "fieldName", ",", "boolean", "isIP", ")", "{", "ArrayList", "<", "String", ">", "retArray", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "ArrayList", "<", "String", ">", "values", ";", "if", "(", "dataMap", ".", "get", "(", "fieldName", ")", "instanceof", "ArrayList", ")", "{", "values", "=", "(", "ArrayList", "<", "String", ">", ")", "dataMap", ".", "get", "(", "fieldName", ")", ";", "}", "else", "{", "values", "=", "StringUtils", ".", "jsonArrayStringToArrayList", "(", "(", "String", ")", "dataMap", ".", "get", "(", "fieldName", ")", ")", ";", "}", "int", "numArrayElementsToReturn", "=", "SystemConfiguration", ".", "getIntProperty", "(", "\"", "pir.numReturnArrayElements", "\"", ",", "1", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numArrayElementsToReturn", ";", "++", "i", ")", "{", "if", "(", "i", "<", "values", ".", "size", "(", ")", ")", "{", "retArray", ".", "add", "(", "values", ".", "get", "(", "i", ")", ")", ";", "}", "else", "if", "(", "isIP", ")", "{", "retArray", ".", "add", "(", "\"", "0.0.0.0", "\"", ")", ";", "}", "else", "{", "retArray", ".", "add", "(", "\"", "0", "\"", ")", ";", "}", "}", "return", "retArray", ";", "}", "private", "static", "ArrayList", "<", "Short", ">", "parseShortArray", "(", "JSONObject", "dataMap", ",", "String", "fieldName", ")", "{", "ArrayList", "<", "Short", ">", "retArray", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "ArrayList", "<", "Short", ">", "values", "=", "(", "ArrayList", "<", "Short", ">", ")", "dataMap", ".", "get", "(", "fieldName", ")", ";", "int", "numArrayElementsToReturn", "=", "SystemConfiguration", ".", "getIntProperty", "(", "\"", "pir.numReturnArrayElements", "\"", ",", "1", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numArrayElementsToReturn", ";", "++", "i", ")", "{", "if", "(", "i", "<", "values", ".", "size", "(", ")", ")", "{", "retArray", ".", "add", "(", "values", ".", "get", "(", "i", ")", ")", ";", "}", "else", "{", "retArray", ".", "add", "(", "(", "short", ")", "0", ")", ";", "}", "}", "return", "retArray", ";", "}", "private", "static", "String", "parseString", "(", "JSONObject", "dataMap", ",", "String", "fieldName", ")", "{", "String", "ret", ";", "String", "element", "=", "(", "String", ")", "dataMap", ".", "get", "(", "fieldName", ")", ";", "int", "numParts", "=", "Integer", ".", "parseInt", "(", "SystemConfiguration", ".", "getProperty", "(", "\"", "pir.stringBits", "\"", ")", ")", "/", "dataPartitionBitSize", ";", "int", "len", "=", "numParts", ";", "if", "(", "element", ".", "length", "(", ")", "<", "numParts", ")", "{", "len", "=", "element", ".", "length", "(", ")", ";", "}", "ret", "=", "new", "String", "(", "element", ".", "getBytes", "(", ")", ",", "0", ",", "len", ")", ";", "return", "ret", ";", "}", "private", "static", "boolean", "compareResultArray", "(", "ArrayList", "<", "QueryResponseJSON", ">", "correctResults", ",", "QueryResponseJSON", "result", ")", "{", "boolean", "equivalent", "=", "false", ";", "for", "(", "QueryResponseJSON", "correct", ":", "correctResults", ")", "{", "equivalent", "=", "compareResults", "(", "correct", ",", "result", ")", ";", "if", "(", "equivalent", ")", "{", "break", ";", "}", "}", "return", "equivalent", ";", "}", "private", "static", "boolean", "compareResults", "(", "QueryResponseJSON", "r1", ",", "QueryResponseJSON", "r2", ")", "{", "boolean", "equivalent", "=", "true", ";", "JSONObject", "jsonR1", "=", "r1", ".", "getJSONObject", "(", ")", ";", "JSONObject", "jsonR2", "=", "r2", ".", "getJSONObject", "(", ")", ";", "Set", "<", "String", ">", "r1KeySet", "=", "jsonR1", ".", "keySet", "(", ")", ";", "Set", "<", "String", ">", "r2KeySet", "=", "jsonR2", ".", "keySet", "(", ")", ";", "if", "(", "!", "r1KeySet", ".", "equals", "(", "r2KeySet", ")", ")", "{", "equivalent", "=", "false", ";", "}", "if", "(", "equivalent", ")", "{", "for", "(", "String", "key", ":", "r1KeySet", ")", "{", "if", "(", "key", ".", "equals", "(", "Inputs", ".", "QTYPE", ")", "||", "key", ".", "equals", "(", "Inputs", ".", "IPS", ")", ")", "{", "HashSet", "<", "String", ">", "set1", "=", "getSetFromList", "(", "jsonR1", ".", "get", "(", "key", ")", ")", ";", "HashSet", "<", "String", ">", "set2", "=", "getSetFromList", "(", "jsonR2", ".", "get", "(", "key", ")", ")", ";", "if", "(", "!", "set1", ".", "equals", "(", "set2", ")", ")", "{", "equivalent", "=", "false", ";", "}", "}", "else", "{", "if", "(", "!", "(", "jsonR1", ".", "get", "(", "key", ")", ".", "toString", "(", ")", ")", ".", "equals", "(", "jsonR2", ".", "get", "(", "key", ")", ".", "toString", "(", ")", ")", ")", "{", "equivalent", "=", "false", ";", "}", "}", "}", "}", "return", "equivalent", ";", "}", "private", "static", "HashSet", "<", "String", ">", "getSetFromList", "(", "Object", "list", ")", "{", "HashSet", "<", "String", ">", "set", "=", "new", "HashSet", "<", ">", "(", ")", ";", "if", "(", "list", "instanceof", "ArrayList", ")", "{", "for", "(", "Object", "obj", ":", "(", "ArrayList", ")", "list", ")", "{", "set", ".", "add", "(", "obj", ".", "toString", "(", ")", ")", ";", "}", "}", "else", "{", "for", "(", "Object", "obj", ":", "(", "JSONArray", ")", "list", ")", "{", "set", ".", "add", "(", "obj", ".", "toString", "(", ")", ")", ";", "}", "}", "return", "set", ";", "}", "private", "static", "void", "printResultList", "(", "List", "<", "QueryResponseJSON", ">", "list", ")", "{", "for", "(", "QueryResponseJSON", "obj", ":", "list", ")", "{", "logger", ".", "info", "(", "obj", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
Class to hold the base functional distributed tests
[ "Class", "to", "hold", "the", "base", "functional", "distributed", "tests" ]
[ "// Selectors for domain and IP queries, queryIdentifier is the first entry for file generation", "// Encryption variables -- Paillier mechanisms are tested in the Paillier test code, so these are fixed...", "// Query for the watched hostname occurred; ; watched value type: hostname (String)", "// all 7 for non distributed case; if testFalsePositive==true, then 6", "// 3 elements returned - one for each qname -- a.b.c.com, d.e.com, something.else", "// Check that each qname appears once in the result set", "// Number of original elements at the end of the list that we do not need to consider for hits", "// the last two data elements should not hit", "// this gets re-embedded as the original selector after decryption", "// The watched IP address was detected in the response to a query; watched value type: IP address (String)", "// last three data elements not hit - one on stoplist, two don't match selectors", "// A query that returned an nxdomain response was made for the watched hostname; watched value type: hostname (String)", "// this gets re-embedded as the original selector after decryption", "// Query for responses from watched srcIPs", "// The last two elements are on the distributed stoplist", "// Form the correct result QueryResponseJSON object", "// Query for responses from watched srcIPs", "// Form the correct result QueryResponseJSON object", "// Method to convert a ArrayList<String> into the correct (padded) returned ArrayList", "// Method to convert a ArrayList<Short> into the correct (padded) returned ArrayList", "// Method to convert the String field value to the correct returned substring", "// Method to determine whether or not the correctResults contains an object equivalent to", "// the given result", "// Method to test the equivalence of two test results", "// array types", "// Method to pull the elements of a list (either an ArrayList or JSONArray) into a HashSet", "// JSONArray" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33869cce51a95dee1a9c05a50741666fe8f5fedb
ryanchung93/big-vooga
src/authoring_actionconditions/ConditionTab.java
[ "MIT" ]
Java
ConditionTab
/** * ConditionTab--contains and manages the conditionHox and conditionVBox classes. The actual tab that the user interacts with for a sprite object * @author Owen Smith * * @param <T>--the kind of row that the conditionVBox stores */
ConditionTab--contains and manages the conditionHox and conditionVBox classes. The actual tab that the user interacts with for a sprite object @author Owen Smith @param --the kind of row that the conditionVBox stores
[ "ConditionTab", "--", "contains", "and", "manages", "the", "conditionHox", "and", "conditionVBox", "classes", ".", "The", "actual", "tab", "that", "the", "user", "interacts", "with", "for", "a", "sprite", "object", "@author", "Owen", "Smith", "@param", "--", "the", "kind", "of", "row", "that", "the", "conditionVBox", "stores" ]
public class ConditionTab<T> extends ActionTab<T> implements ConditionTabI { private static final String DIALOG_TYPE = "ERROR"; private static final String ERROR_SUMMARY = "Invalid selected actions"; public ConditionTab(String title, Supplier<List<AbstractSpriteObject>> supplier) { super(title,supplier); } // public ConditionTab(String title,ConditionVBox<T> actionConditionVBox, ActionConditionHBox topToolBar) { // super(title,actionConditionVBox,topToolBar); // } public void displayRowExceptionMessage(String message) { Alert alert = new Alert(AlertType.ERROR); alert.setTitle(DIALOG_TYPE); alert.setHeaderText(ERROR_SUMMARY); alert.setContentText(message); alert.showAndWait(); } /** * setActionConditionVBox--an implementation of the actionconditionVBox method to return the kind of vBox that should be stored. In this case, it * should be a conditionVBox */ @Override public ActionConditionVBox<T> setActionConditionVBox() { return new ConditionVBox<T>(getSupplier()); } /** * setNewActionOptions--did not end up being used in project */ @Override public void setNewActionOptions(ObservableList<Integer> newActionOptions) { ((ConditionVBox<T>) getActionConditionVBox()).setNewActionOptions(newActionOptions); } /** * addActionOption--calls the conditionVBox to add an action option that the user can choose */ @Override public void addActionOption() { ((ConditionVBox<T>) getActionConditionVBox()).addActionOption(); } /** * removeActionOption--calls the conditionVBox to remove an action as an option. Assumes that that action is currently in the list of actions for * that row */ @Override public void removeActionOption(Integer action) { ((ConditionVBox<T>) getActionConditionVBox()).removeActionOption(action); } /** * addCondition--adds a whole other empty row as a condition with the current full list of action options */ @Override public void addCondition(ObservableList<Integer> currentActions) { ((ConditionVBox<T>) getActionConditionVBox()).addCondition(currentActions); } }
[ "public", "class", "ConditionTab", "<", "T", ">", "extends", "ActionTab", "<", "T", ">", "implements", "ConditionTabI", "{", "private", "static", "final", "String", "DIALOG_TYPE", "=", "\"", "ERROR", "\"", ";", "private", "static", "final", "String", "ERROR_SUMMARY", "=", "\"", "Invalid selected actions", "\"", ";", "public", "ConditionTab", "(", "String", "title", ",", "Supplier", "<", "List", "<", "AbstractSpriteObject", ">", ">", "supplier", ")", "{", "super", "(", "title", ",", "supplier", ")", ";", "}", "public", "void", "displayRowExceptionMessage", "(", "String", "message", ")", "{", "Alert", "alert", "=", "new", "Alert", "(", "AlertType", ".", "ERROR", ")", ";", "alert", ".", "setTitle", "(", "DIALOG_TYPE", ")", ";", "alert", ".", "setHeaderText", "(", "ERROR_SUMMARY", ")", ";", "alert", ".", "setContentText", "(", "message", ")", ";", "alert", ".", "showAndWait", "(", ")", ";", "}", "/**\n\t * setActionConditionVBox--an implementation of the actionconditionVBox method to return the kind of vBox that should be stored. In this case, it \n\t * should be a conditionVBox\n\t */", "@", "Override", "public", "ActionConditionVBox", "<", "T", ">", "setActionConditionVBox", "(", ")", "{", "return", "new", "ConditionVBox", "<", "T", ">", "(", "getSupplier", "(", ")", ")", ";", "}", "/**\n\t * setNewActionOptions--did not end up being used in project\n\t */", "@", "Override", "public", "void", "setNewActionOptions", "(", "ObservableList", "<", "Integer", ">", "newActionOptions", ")", "{", "(", "(", "ConditionVBox", "<", "T", ">", ")", "getActionConditionVBox", "(", ")", ")", ".", "setNewActionOptions", "(", "newActionOptions", ")", ";", "}", "/**\n\t * addActionOption--calls the conditionVBox to add an action option that the user can choose\n\t */", "@", "Override", "public", "void", "addActionOption", "(", ")", "{", "(", "(", "ConditionVBox", "<", "T", ">", ")", "getActionConditionVBox", "(", ")", ")", ".", "addActionOption", "(", ")", ";", "}", "/**\n\t * removeActionOption--calls the conditionVBox to remove an action as an option. Assumes that that action is currently in the list of actions for \n\t * that row\n\t */", "@", "Override", "public", "void", "removeActionOption", "(", "Integer", "action", ")", "{", "(", "(", "ConditionVBox", "<", "T", ">", ")", "getActionConditionVBox", "(", ")", ")", ".", "removeActionOption", "(", "action", ")", ";", "}", "/**\n\t * addCondition--adds a whole other empty row as a condition with the current full list of action options\n\t */", "@", "Override", "public", "void", "addCondition", "(", "ObservableList", "<", "Integer", ">", "currentActions", ")", "{", "(", "(", "ConditionVBox", "<", "T", ">", ")", "getActionConditionVBox", "(", ")", ")", ".", "addCondition", "(", "currentActions", ")", ";", "}", "}" ]
ConditionTab--contains and manages the conditionHox and conditionVBox classes.
[ "ConditionTab", "--", "contains", "and", "manages", "the", "conditionHox", "and", "conditionVBox", "classes", "." ]
[ "//\tpublic ConditionTab(String title,ConditionVBox<T> actionConditionVBox, ActionConditionHBox topToolBar) {", "//\t\tsuper(title,actionConditionVBox,topToolBar);", "//\t}" ]
[ { "param": "ConditionTabI", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ConditionTabI", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3388335d373608a1ba0ff29fce9c3442e5c9682a
ruski550/coms227stuff
hw4_skeleton/src/main/Main.java
[ "MIT" ]
Java
Main
/** * Loads and starts a custom snake game. One can use the "-d" option for debug * mode. * <p> * <p> * For example: * * <pre> * java Main -d Arena.txt * </pre> * <p> * The contents of Arena.txt: * <p> * * <pre> * color.RainbowColorGenerator * graph.SquareMap 15 true * -----------###----------- * --####-------------####-- * --#-------------------#-- * --#--####---#---####--#-- * --#---------#---------#-- * --#---------#---------#-- * ------------#------------ * ---------#######--------- * ------------------------- * ------------S------------ * ------------------------- * ---------#######--------- * ------------#------------ * --#---------#---------#-- * --#---------#---------#-- * --#--####---#---####--#-- * --#-------------------#-- * --####-------------####-- * -----------###----------- * </pre> * * @author Brian Nakayama */
Loads and starts a custom snake game. One can use the "-d" option for debug mode. For example. S @author Brian Nakayama
[ "Loads", "and", "starts", "a", "custom", "snake", "game", ".", "One", "can", "use", "the", "\"", "-", "d", "\"", "option", "for", "debug", "mode", ".", "For", "example", ".", "S", "@author", "Brian", "Nakayama" ]
public class Main { public static void main(String[] args) { GraphMap map; Set<String> argSet = new HashSet<String>(); for (String s : args) { argSet.add(s); } boolean debug = argSet.remove("-d"); if (argSet.size() > 0) { map = new GraphMapFactory(argSet.iterator().next()).createGraphMap(); } else { map = new GraphMapFactory("Default.txt").createGraphMap(); } Runnable r = new Runnable() { public void run() { View gui = new View(map.getPixelWidth(), map.getPixelHeight(), map, debug); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } Clock clock = new Clock(20.0f, gui); clock.init(); } }; SwingUtilities.invokeLater(r); } }
[ "public", "class", "Main", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "GraphMap", "map", ";", "Set", "<", "String", ">", "argSet", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "String", "s", ":", "args", ")", "{", "argSet", ".", "add", "(", "s", ")", ";", "}", "boolean", "debug", "=", "argSet", ".", "remove", "(", "\"", "-d", "\"", ")", ";", "if", "(", "argSet", ".", "size", "(", ")", ">", "0", ")", "{", "map", "=", "new", "GraphMapFactory", "(", "argSet", ".", "iterator", "(", ")", ".", "next", "(", ")", ")", ".", "createGraphMap", "(", ")", ";", "}", "else", "{", "map", "=", "new", "GraphMapFactory", "(", "\"", "Default.txt", "\"", ")", ".", "createGraphMap", "(", ")", ";", "}", "Runnable", "r", "=", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "View", "gui", "=", "new", "View", "(", "map", ".", "getPixelWidth", "(", ")", ",", "map", ".", "getPixelHeight", "(", ")", ",", "map", ",", "debug", ")", ";", "try", "{", "Thread", ".", "sleep", "(", "50", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "Clock", "clock", "=", "new", "Clock", "(", "20.0f", ",", "gui", ")", ";", "clock", ".", "init", "(", ")", ";", "}", "}", ";", "SwingUtilities", ".", "invokeLater", "(", "r", ")", ";", "}", "}" ]
Loads and starts a custom snake game.
[ "Loads", "and", "starts", "a", "custom", "snake", "game", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33971e5f2b6276e97c7991c5f6f9e9f899a732e0
sunxuia/leetcode-solution-java
src/main/java/q1750/Q1704_DetermineIfStringHalvesAreAlike.java
[ "MIT" ]
Java
Q1704_DetermineIfStringHalvesAreAlike
/** * [Easy] 1704. Determine if String Halves Are Alike * https://leetcode.com/problems/determine-if-string-halves-are-alike/ * * You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first * half and b be the second half. * * Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). * Notice that s contains uppercase and lowercase letters. * * Return true if a and b are alike. Otherwise, return false. * * Example 1: * * Input: s = "book" * Output: true * Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. * * Example 2: * * Input: s = "textbook" * Output: false * Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. * Notice that the vowel o is counted twice. * * Example 3: * * Input: s = "MerryChristmas" * Output: false * * Example 4: * * Input: s = "AbCdEfGh" * Output: true * * Constraints: * * 2 <= s.length <= 1000 * s.length is even. * s consists of uppercase and lowercase letters. */
You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Return true if a and b are alike. Otherwise, return false. Example 1. Example 2. Example 3. s = "MerryChristmas" Output: false Example 4. s = "AbCdEfGh" Output: true
[ "You", "are", "given", "a", "string", "s", "of", "even", "length", ".", "Split", "this", "string", "into", "two", "halves", "of", "equal", "lengths", "and", "let", "a", "be", "the", "first", "half", "and", "b", "be", "the", "second", "half", ".", "Return", "true", "if", "a", "and", "b", "are", "alike", ".", "Otherwise", "return", "false", ".", "Example", "1", ".", "Example", "2", ".", "Example", "3", ".", "s", "=", "\"", "MerryChristmas", "\"", "Output", ":", "false", "Example", "4", ".", "s", "=", "\"", "AbCdEfGh", "\"", "Output", ":", "true" ]
@RunWith(LeetCodeRunner.class) public class Q1704_DetermineIfStringHalvesAreAlike { @Answer public boolean halvesAreAlike(String s) { int count = 0; for (int i = 0; i < s.length() / 2; i++) { count += MAP[s.charAt(i)]; } for (int i = s.length() / 2; i < s.length(); i++) { count -= MAP[s.charAt(i)]; } return count == 0; } private static final int[] MAP = new int[127]; static { MAP['a'] = 1; MAP['A'] = 1; MAP['e'] = 1; MAP['E'] = 1; MAP['i'] = 1; MAP['I'] = 1; MAP['o'] = 1; MAP['O'] = 1; MAP['u'] = 1; MAP['U'] = 1; } @TestData public DataExpectation example1 = DataExpectation.create("book").expect(true); @TestData public DataExpectation example2 = DataExpectation.create("textbook").expect(false); @TestData public DataExpectation example3 = DataExpectation.create("MerryChristmas").expect(false); @TestData public DataExpectation example4 = DataExpectation.create("AbCdEfGh").expect(true); }
[ "@", "RunWith", "(", "LeetCodeRunner", ".", "class", ")", "public", "class", "Q1704_DetermineIfStringHalvesAreAlike", "{", "@", "Answer", "public", "boolean", "halvesAreAlike", "(", "String", "s", ")", "{", "int", "count", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", "(", ")", "/", "2", ";", "i", "++", ")", "{", "count", "+=", "MAP", "[", "s", ".", "charAt", "(", "i", ")", "]", ";", "}", "for", "(", "int", "i", "=", "s", ".", "length", "(", ")", "/", "2", ";", "i", "<", "s", ".", "length", "(", ")", ";", "i", "++", ")", "{", "count", "-=", "MAP", "[", "s", ".", "charAt", "(", "i", ")", "]", ";", "}", "return", "count", "==", "0", ";", "}", "private", "static", "final", "int", "[", "]", "MAP", "=", "new", "int", "[", "127", "]", ";", "static", "{", "MAP", "[", "'a'", "]", "=", "1", ";", "MAP", "[", "'A'", "]", "=", "1", ";", "MAP", "[", "'e'", "]", "=", "1", ";", "MAP", "[", "'E'", "]", "=", "1", ";", "MAP", "[", "'i'", "]", "=", "1", ";", "MAP", "[", "'I'", "]", "=", "1", ";", "MAP", "[", "'o'", "]", "=", "1", ";", "MAP", "[", "'O'", "]", "=", "1", ";", "MAP", "[", "'u'", "]", "=", "1", ";", "MAP", "[", "'U'", "]", "=", "1", ";", "}", "@", "TestData", "public", "DataExpectation", "example1", "=", "DataExpectation", ".", "create", "(", "\"", "book", "\"", ")", ".", "expect", "(", "true", ")", ";", "@", "TestData", "public", "DataExpectation", "example2", "=", "DataExpectation", ".", "create", "(", "\"", "textbook", "\"", ")", ".", "expect", "(", "false", ")", ";", "@", "TestData", "public", "DataExpectation", "example3", "=", "DataExpectation", ".", "create", "(", "\"", "MerryChristmas", "\"", ")", ".", "expect", "(", "false", ")", ";", "@", "TestData", "public", "DataExpectation", "example4", "=", "DataExpectation", ".", "create", "(", "\"", "AbCdEfGh", "\"", ")", ".", "expect", "(", "true", ")", ";", "}" ]
[Easy] 1704.
[ "[", "Easy", "]", "1704", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33a1b151360d43d8f5a6230f42141dea0b791cd6
fciubotaru/z-pec
ZimbraSoap/src/java/com/zimbra/soap/json/jackson/ZmBooleanSerializer.java
[ "MIT" ]
Java
ZmBooleanSerializer
/** * For Zimbra SOAP, Historically Booleans have been represented as "0" for false and "1" for true in XML. * This is valid but differs from the default values JAXB marshals to - "true" and "false". * * Some legacy client code cannot accept the values "true" and "false", so the ZmBoolean class has been introduced * whose values will always marshal to either "0" or "1". * * However, for JSON SOAP, the values true and false need to be used. This serializer is responsible for ensuring * that happens. */
For Zimbra SOAP, Historically Booleans have been represented as "0" for false and "1" for true in XML. This is valid but differs from the default values JAXB marshals to - "true" and "false". However, for JSON SOAP, the values true and false need to be used. This serializer is responsible for ensuring that happens.
[ "For", "Zimbra", "SOAP", "Historically", "Booleans", "have", "been", "represented", "as", "\"", "0", "\"", "for", "false", "and", "\"", "1", "\"", "for", "true", "in", "XML", ".", "This", "is", "valid", "but", "differs", "from", "the", "default", "values", "JAXB", "marshals", "to", "-", "\"", "true", "\"", "and", "\"", "false", "\"", ".", "However", "for", "JSON", "SOAP", "the", "values", "true", "and", "false", "need", "to", "be", "used", ".", "This", "serializer", "is", "responsible", "for", "ensuring", "that", "happens", "." ]
public class ZmBooleanSerializer extends JsonSerializer<ZmBoolean> { public ZmBooleanSerializer() { super(); } @Override public void serialize(ZmBoolean value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { if (value == null) { return; } jgen.writeBoolean(ZmBoolean.toBool(value)); } }
[ "public", "class", "ZmBooleanSerializer", "extends", "JsonSerializer", "<", "ZmBoolean", ">", "{", "public", "ZmBooleanSerializer", "(", ")", "{", "super", "(", ")", ";", "}", "@", "Override", "public", "void", "serialize", "(", "ZmBoolean", "value", ",", "JsonGenerator", "jgen", ",", "SerializerProvider", "provider", ")", "throws", "IOException", ",", "JsonProcessingException", "{", "if", "(", "value", "==", "null", ")", "{", "return", ";", "}", "jgen", ".", "writeBoolean", "(", "ZmBoolean", ".", "toBool", "(", "value", ")", ")", ";", "}", "}" ]
For Zimbra SOAP, Historically Booleans have been represented as "0" for false and "1" for true in XML.
[ "For", "Zimbra", "SOAP", "Historically", "Booleans", "have", "been", "represented", "as", "\"", "0", "\"", "for", "false", "and", "\"", "1", "\"", "for", "true", "in", "XML", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33a223d2f8750a34bd6c17c9b2b5f5657167f679
ingorichtsmeier/camunda-spin
core/src/main/java/org/camunda/spin/impl/util/RewindableReader.java
[ "Apache-2.0" ]
Java
RewindableReader
/** * Caches the initial characters that are read from the supplied {@link Reader} and * allows to rewind these. As soon as more than <code>size</code> characters have been read, * rewinding fails. * * @author Thorben Lindhauer */
Caches the initial characters that are read from the supplied Reader and allows to rewind these. As soon as more than size characters have been read, rewinding fails. @author Thorben Lindhauer
[ "Caches", "the", "initial", "characters", "that", "are", "read", "from", "the", "supplied", "Reader", "and", "allows", "to", "rewind", "these", ".", "As", "soon", "as", "more", "than", "size", "characters", "have", "been", "read", "rewinding", "fails", ".", "@author", "Thorben", "Lindhauer" ]
public class RewindableReader extends Reader { private static final SpinCoreLogger LOG = SpinLogger.CORE_LOGGER; protected PushbackReader wrappedReader; protected char[] buffer; protected int pos; protected boolean rewindable; public RewindableReader(Reader input, int size) { this.wrappedReader = new PushbackReader(input, size); this.buffer = new char[size]; this.pos = 0; this.rewindable = true; } public int read(char[] cbuf, int off, int len) throws IOException { int charactersRead = wrappedReader.read(cbuf, off, len); if (charactersRead > 0) { if (rewindable && pos + charactersRead > buffer.length) { rewindable = false; } if (pos < buffer.length) { int freeBufferSpace = buffer.length - pos; int insertableCharacters = Math.min(charactersRead, freeBufferSpace); System.arraycopy(cbuf, off, buffer, pos, insertableCharacters); pos += insertableCharacters; } } return charactersRead; } public int read() throws IOException { int nextCharacter = wrappedReader.read(); if (nextCharacter != -1) { if (pos < buffer.length) { buffer[pos] = (char) nextCharacter; pos++; } else if (rewindable && pos >= buffer.length) { rewindable = false; } } return nextCharacter; } public void close() throws IOException { wrappedReader.close(); } public synchronized void mark(int readlimit) throws IOException { wrappedReader.mark(readlimit); } public boolean markSupported() { return wrappedReader.markSupported(); } public synchronized void reset() throws IOException { wrappedReader.reset(); } public long skip(long n) throws IOException { return wrappedReader.skip(n); } /** * Rewinds the reader such that the initial characters are returned when invoking read(). * * Throws an exception if more than the buffering limit has already been read. * @throws IOException */ public void rewind() throws IOException { if (!rewindable) { throw LOG.unableToRewindReader(); } wrappedReader.unread(buffer, 0, pos); pos = 0; } public int getRewindBufferSize() { return buffer.length; } /** * * @return the number of characters that can still be read and rewound. */ public int getCurrentRewindableCapacity() { return buffer.length - pos; } }
[ "public", "class", "RewindableReader", "extends", "Reader", "{", "private", "static", "final", "SpinCoreLogger", "LOG", "=", "SpinLogger", ".", "CORE_LOGGER", ";", "protected", "PushbackReader", "wrappedReader", ";", "protected", "char", "[", "]", "buffer", ";", "protected", "int", "pos", ";", "protected", "boolean", "rewindable", ";", "public", "RewindableReader", "(", "Reader", "input", ",", "int", "size", ")", "{", "this", ".", "wrappedReader", "=", "new", "PushbackReader", "(", "input", ",", "size", ")", ";", "this", ".", "buffer", "=", "new", "char", "[", "size", "]", ";", "this", ".", "pos", "=", "0", ";", "this", ".", "rewindable", "=", "true", ";", "}", "public", "int", "read", "(", "char", "[", "]", "cbuf", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "int", "charactersRead", "=", "wrappedReader", ".", "read", "(", "cbuf", ",", "off", ",", "len", ")", ";", "if", "(", "charactersRead", ">", "0", ")", "{", "if", "(", "rewindable", "&&", "pos", "+", "charactersRead", ">", "buffer", ".", "length", ")", "{", "rewindable", "=", "false", ";", "}", "if", "(", "pos", "<", "buffer", ".", "length", ")", "{", "int", "freeBufferSpace", "=", "buffer", ".", "length", "-", "pos", ";", "int", "insertableCharacters", "=", "Math", ".", "min", "(", "charactersRead", ",", "freeBufferSpace", ")", ";", "System", ".", "arraycopy", "(", "cbuf", ",", "off", ",", "buffer", ",", "pos", ",", "insertableCharacters", ")", ";", "pos", "+=", "insertableCharacters", ";", "}", "}", "return", "charactersRead", ";", "}", "public", "int", "read", "(", ")", "throws", "IOException", "{", "int", "nextCharacter", "=", "wrappedReader", ".", "read", "(", ")", ";", "if", "(", "nextCharacter", "!=", "-", "1", ")", "{", "if", "(", "pos", "<", "buffer", ".", "length", ")", "{", "buffer", "[", "pos", "]", "=", "(", "char", ")", "nextCharacter", ";", "pos", "++", ";", "}", "else", "if", "(", "rewindable", "&&", "pos", ">=", "buffer", ".", "length", ")", "{", "rewindable", "=", "false", ";", "}", "}", "return", "nextCharacter", ";", "}", "public", "void", "close", "(", ")", "throws", "IOException", "{", "wrappedReader", ".", "close", "(", ")", ";", "}", "public", "synchronized", "void", "mark", "(", "int", "readlimit", ")", "throws", "IOException", "{", "wrappedReader", ".", "mark", "(", "readlimit", ")", ";", "}", "public", "boolean", "markSupported", "(", ")", "{", "return", "wrappedReader", ".", "markSupported", "(", ")", ";", "}", "public", "synchronized", "void", "reset", "(", ")", "throws", "IOException", "{", "wrappedReader", ".", "reset", "(", ")", ";", "}", "public", "long", "skip", "(", "long", "n", ")", "throws", "IOException", "{", "return", "wrappedReader", ".", "skip", "(", "n", ")", ";", "}", "/**\n * Rewinds the reader such that the initial characters are returned when invoking read().\n *\n * Throws an exception if more than the buffering limit has already been read.\n * @throws IOException\n */", "public", "void", "rewind", "(", ")", "throws", "IOException", "{", "if", "(", "!", "rewindable", ")", "{", "throw", "LOG", ".", "unableToRewindReader", "(", ")", ";", "}", "wrappedReader", ".", "unread", "(", "buffer", ",", "0", ",", "pos", ")", ";", "pos", "=", "0", ";", "}", "public", "int", "getRewindBufferSize", "(", ")", "{", "return", "buffer", ".", "length", ";", "}", "/**\n *\n * @return the number of characters that can still be read and rewound.\n */", "public", "int", "getCurrentRewindableCapacity", "(", ")", "{", "return", "buffer", ".", "length", "-", "pos", ";", "}", "}" ]
Caches the initial characters that are read from the supplied {@link Reader} and allows to rewind these.
[ "Caches", "the", "initial", "characters", "that", "are", "read", "from", "the", "supplied", "{", "@link", "Reader", "}", "and", "allows", "to", "rewind", "these", "." ]
[]
[ { "param": "Reader", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Reader", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33aa80e287d3642ceefe0a0e26292df466efae75
rabreu/Accenture-Grupo-JAVAMOS
src/main/java/com/accenture/javamos/controller/exception/ApiExceptionHandler.java
[ "MIT" ]
Java
ApiExceptionHandler
// TODO: handle disabled user
handle disabled user
[ "handle", "disabled", "user" ]
@ControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(Exception.class) public final ResponseEntity<ApiException> handleException( Exception e, WebRequest request ) { HttpHeaders headers = new HttpHeaders(); HttpStatus status; ApiException apiException = new ApiException(); Map<String, Object> errors = new HashMap<>(); String message = null; if (e instanceof MethodArgumentNotValidException) { /** Method Argument Not Valid: @Valid fails */ MethodArgumentNotValidException manve = (MethodArgumentNotValidException) e; status = HttpStatus.BAD_REQUEST; manve .getBindingResult() .getFieldErrors() .stream() .forEach(f -> errors.put(f.getField(), f.getDefaultMessage())); message = "Dado(s) inválido(s)."; } else if (e instanceof EmailAlreadyTakenException) { /** E-mail already exists */ status = HttpStatus.CONFLICT; errors.put("email", "E-mail já cadastrado."); message = "Escolha outro e-mail para registrar uma conta."; } else if (e instanceof DataIntegrityViolationException) { /** Data Integrity Violation */ DataIntegrityViolationException dive = (DataIntegrityViolationException) e; status = HttpStatus.BAD_REQUEST; errors.put("violation", dive.getCause().getCause().getMessage()); message = "O(s) dado(s) inserido(s) viola(m) a integridade da aplicação."; } else if ( e instanceof DisabledException || e instanceof BadCredentialsException || e instanceof UnauthorizedException ) { /** Unauthorized Access */ status = HttpStatus.UNAUTHORIZED; errors.put("credentials", "Credenciais inválidas."); message = "Faça o login."; } else if (e instanceof FlightNotFoundException) { status = HttpStatus.NOT_FOUND; errors.put("flight", ((FlightNotFoundException) e).getMessage()); message = "Verifique o id da passagem"; } else if (e instanceof PagarMeException) { status = HttpStatus.BAD_REQUEST; errors.put("pagarme", e.getMessage()); message = e.getMessage(); } else if (e instanceof PaymentAlreadyCompletedException) { status = HttpStatus.CONFLICT; errors.put("payment", "Pagamento já foi feito para essa passagem"); message = "Você já pagou por essa passagem"; } else { /** Internal Server Error */ status = HttpStatus.INTERNAL_SERVER_ERROR; errors.put( "server", "O servidor não foi capaz de processar a requisição" ); message = "Tente novamente mais tarde. Caso o erro persista, entre em contato com o admin"; } apiException.setMessage(message); apiException.setErrors(errors); return handleExceptionInternal(e, apiException, headers, status, request); } protected ResponseEntity<ApiException> handleExceptionInternal( Exception e, ApiException body, HttpHeaders headers, HttpStatus status, WebRequest request ) { if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) { request.setAttribute( WebUtils.ERROR_EXCEPTION_ATTRIBUTE, e, WebRequest.SCOPE_REQUEST ); } return new ResponseEntity<>(body, headers, status); } }
[ "@", "ControllerAdvice", "public", "class", "ApiExceptionHandler", "{", "@", "ExceptionHandler", "(", "Exception", ".", "class", ")", "public", "final", "ResponseEntity", "<", "ApiException", ">", "handleException", "(", "Exception", "e", ",", "WebRequest", "request", ")", "{", "HttpHeaders", "headers", "=", "new", "HttpHeaders", "(", ")", ";", "HttpStatus", "status", ";", "ApiException", "apiException", "=", "new", "ApiException", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "errors", "=", "new", "HashMap", "<", ">", "(", ")", ";", "String", "message", "=", "null", ";", "if", "(", "e", "instanceof", "MethodArgumentNotValidException", ")", "{", "/** Method Argument Not Valid: @Valid fails */", "MethodArgumentNotValidException", "manve", "=", "(", "MethodArgumentNotValidException", ")", "e", ";", "status", "=", "HttpStatus", ".", "BAD_REQUEST", ";", "manve", ".", "getBindingResult", "(", ")", ".", "getFieldErrors", "(", ")", ".", "stream", "(", ")", ".", "forEach", "(", "f", "->", "errors", ".", "put", "(", "f", ".", "getField", "(", ")", ",", "f", ".", "getDefaultMessage", "(", ")", ")", ")", ";", "message", "=", "\"", "Dado(s) inválido(s).\"", ";", "", "}", "else", "if", "(", "e", "instanceof", "EmailAlreadyTakenException", ")", "{", "/** E-mail already exists */", "status", "=", "HttpStatus", ".", "CONFLICT", ";", "errors", ".", "put", "(", "\"", "email", "\"", ",", "\"", "E-mail já cadastrado.\"", ")", ";", "", "message", "=", "\"", "Escolha outro e-mail para registrar uma conta.", "\"", ";", "}", "else", "if", "(", "e", "instanceof", "DataIntegrityViolationException", ")", "{", "/** Data Integrity Violation */", "DataIntegrityViolationException", "dive", "=", "(", "DataIntegrityViolationException", ")", "e", ";", "status", "=", "HttpStatus", ".", "BAD_REQUEST", ";", "errors", ".", "put", "(", "\"", "violation", "\"", ",", "dive", ".", "getCause", "(", ")", ".", "getCause", "(", ")", ".", "getMessage", "(", ")", ")", ";", "message", "=", "\"", "O(s) dado(s) inserido(s) viola(m) a integridade da aplicação.\";", "", "", "}", "else", "if", "(", "e", "instanceof", "DisabledException", "||", "e", "instanceof", "BadCredentialsException", "||", "e", "instanceof", "UnauthorizedException", ")", "{", "/** Unauthorized Access */", "status", "=", "HttpStatus", ".", "UNAUTHORIZED", ";", "errors", ".", "put", "(", "\"", "credentials", "\"", ",", "\"", "Credenciais inválidas.\"", ")", ";", "", "message", "=", "\"", "Faça o login.\"", ";", "", "}", "else", "if", "(", "e", "instanceof", "FlightNotFoundException", ")", "{", "status", "=", "HttpStatus", ".", "NOT_FOUND", ";", "errors", ".", "put", "(", "\"", "flight", "\"", ",", "(", "(", "FlightNotFoundException", ")", "e", ")", ".", "getMessage", "(", ")", ")", ";", "message", "=", "\"", "Verifique o id da passagem", "\"", ";", "}", "else", "if", "(", "e", "instanceof", "PagarMeException", ")", "{", "status", "=", "HttpStatus", ".", "BAD_REQUEST", ";", "errors", ".", "put", "(", "\"", "pagarme", "\"", ",", "e", ".", "getMessage", "(", ")", ")", ";", "message", "=", "e", ".", "getMessage", "(", ")", ";", "}", "else", "if", "(", "e", "instanceof", "PaymentAlreadyCompletedException", ")", "{", "status", "=", "HttpStatus", ".", "CONFLICT", ";", "errors", ".", "put", "(", "\"", "payment", "\"", ",", "\"", "Pagamento já foi feito para essa passagem\"", ")", ";", "", "message", "=", "\"", "Você já pagou por essa passagem\";", "", "", "}", "else", "{", "/** Internal Server Error */", "status", "=", "HttpStatus", ".", "INTERNAL_SERVER_ERROR", ";", "errors", ".", "put", "(", "\"", "server", "\"", ",", "\"", "O servidor não foi capaz de processar a requisição\"", "", ")", ";", "message", "=", "\"", "Tente novamente mais tarde. Caso o erro persista, entre em contato com o admin", "\"", ";", "}", "apiException", ".", "setMessage", "(", "message", ")", ";", "apiException", ".", "setErrors", "(", "errors", ")", ";", "return", "handleExceptionInternal", "(", "e", ",", "apiException", ",", "headers", ",", "status", ",", "request", ")", ";", "}", "protected", "ResponseEntity", "<", "ApiException", ">", "handleExceptionInternal", "(", "Exception", "e", ",", "ApiException", "body", ",", "HttpHeaders", "headers", ",", "HttpStatus", "status", ",", "WebRequest", "request", ")", "{", "if", "(", "HttpStatus", ".", "INTERNAL_SERVER_ERROR", ".", "equals", "(", "status", ")", ")", "{", "request", ".", "setAttribute", "(", "WebUtils", ".", "ERROR_EXCEPTION_ATTRIBUTE", ",", "e", ",", "WebRequest", ".", "SCOPE_REQUEST", ")", ";", "}", "return", "new", "ResponseEntity", "<", ">", "(", "body", ",", "headers", ",", "status", ")", ";", "}", "}" ]
TODO: handle disabled user
[ "TODO", ":", "handle", "disabled", "user" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33ad86859a740a26423431c5e6b0c8d7e508c1b0
morecar/azure-libraries-for-java
azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/DirectoryObjectInner.java
[ "MIT" ]
Java
DirectoryObjectInner
/** * Represents an Azure Active Directory object. */
Represents an Azure Active Directory object.
[ "Represents", "an", "Azure", "Active", "Directory", "object", "." ]
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType") @JsonTypeName("DirectoryObject") @JsonSubTypes({ @JsonSubTypes.Type(name = "Application", value = ApplicationInner.class), @JsonSubTypes.Type(name = "Group", value = ADGroupInner.class), @JsonSubTypes.Type(name = "ServicePrincipal", value = ServicePrincipalInner.class), @JsonSubTypes.Type(name = "User", value = UserInner.class) }) public class DirectoryObjectInner { /** * Unmatched properties from the message are deserialized this collection. */ @JsonProperty(value = "") private Map<String, Object> additionalProperties; /** * The object ID. */ @JsonProperty(value = "objectId", access = JsonProperty.Access.WRITE_ONLY) private String objectId; /** * The time at which the directory object was deleted. */ @JsonProperty(value = "deletionTimestamp", access = JsonProperty.Access.WRITE_ONLY) private DateTime deletionTimestamp; /** * Get the additionalProperties value. * * @return the additionalProperties value */ public Map<String, Object> additionalProperties() { return this.additionalProperties; } /** * Set the additionalProperties value. * * @param additionalProperties the additionalProperties value to set * @return the DirectoryObjectInner object itself. */ public DirectoryObjectInner withAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; return this; } /** * Get the objectId value. * * @return the objectId value */ public String objectId() { return this.objectId; } /** * Get the deletionTimestamp value. * * @return the deletionTimestamp value */ public DateTime deletionTimestamp() { return this.deletionTimestamp; } }
[ "@", "JsonTypeInfo", "(", "use", "=", "JsonTypeInfo", ".", "Id", ".", "NAME", ",", "include", "=", "JsonTypeInfo", ".", "As", ".", "PROPERTY", ",", "property", "=", "\"", "objectType", "\"", ")", "@", "JsonTypeName", "(", "\"", "DirectoryObject", "\"", ")", "@", "JsonSubTypes", "(", "{", "@", "JsonSubTypes", ".", "Type", "(", "name", "=", "\"", "Application", "\"", ",", "value", "=", "ApplicationInner", ".", "class", ")", ",", "@", "JsonSubTypes", ".", "Type", "(", "name", "=", "\"", "Group", "\"", ",", "value", "=", "ADGroupInner", ".", "class", ")", ",", "@", "JsonSubTypes", ".", "Type", "(", "name", "=", "\"", "ServicePrincipal", "\"", ",", "value", "=", "ServicePrincipalInner", ".", "class", ")", ",", "@", "JsonSubTypes", ".", "Type", "(", "name", "=", "\"", "User", "\"", ",", "value", "=", "UserInner", ".", "class", ")", "}", ")", "public", "class", "DirectoryObjectInner", "{", "/**\n * Unmatched properties from the message are deserialized this collection.\n */", "@", "JsonProperty", "(", "value", "=", "\"", "\"", ")", "private", "Map", "<", "String", ",", "Object", ">", "additionalProperties", ";", "/**\n * The object ID.\n */", "@", "JsonProperty", "(", "value", "=", "\"", "objectId", "\"", ",", "access", "=", "JsonProperty", ".", "Access", ".", "WRITE_ONLY", ")", "private", "String", "objectId", ";", "/**\n * The time at which the directory object was deleted.\n */", "@", "JsonProperty", "(", "value", "=", "\"", "deletionTimestamp", "\"", ",", "access", "=", "JsonProperty", ".", "Access", ".", "WRITE_ONLY", ")", "private", "DateTime", "deletionTimestamp", ";", "/**\n * Get the additionalProperties value.\n *\n * @return the additionalProperties value\n */", "public", "Map", "<", "String", ",", "Object", ">", "additionalProperties", "(", ")", "{", "return", "this", ".", "additionalProperties", ";", "}", "/**\n * Set the additionalProperties value.\n *\n * @param additionalProperties the additionalProperties value to set\n * @return the DirectoryObjectInner object itself.\n */", "public", "DirectoryObjectInner", "withAdditionalProperties", "(", "Map", "<", "String", ",", "Object", ">", "additionalProperties", ")", "{", "this", ".", "additionalProperties", "=", "additionalProperties", ";", "return", "this", ";", "}", "/**\n * Get the objectId value.\n *\n * @return the objectId value\n */", "public", "String", "objectId", "(", ")", "{", "return", "this", ".", "objectId", ";", "}", "/**\n * Get the deletionTimestamp value.\n *\n * @return the deletionTimestamp value\n */", "public", "DateTime", "deletionTimestamp", "(", ")", "{", "return", "this", ".", "deletionTimestamp", ";", "}", "}" ]
Represents an Azure Active Directory object.
[ "Represents", "an", "Azure", "Active", "Directory", "object", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33af855744800ddfb1f33caa00e520df39060c85
jonatas-rezende/estatistica_web
codigos/Estatistica/src/br/com/estatisticaweb/modelo/dao/DadoSimplesDAO.java
[ "Unlicense" ]
Java
DadoSimplesDAO
/** * Objeto de acesso aos dados simples * @author Adallberto */
Objeto de acesso aos dados simples @author Adallberto
[ "Objeto", "de", "acesso", "aos", "dados", "simples", "@author", "Adallberto" ]
public class DadoSimplesDAO extends DAOCRUDBase<DadoSimples> { /** * Método que lista todos os dados simples armazanados no banco de dados * @author Adallberto Lucena Moura * @return lista dos dados simples * @throws Exception possíveis exceções que podem acontecer */ @Override public List listar() throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("select * from dados_simples order by id asc"); ResultSet rs; rs = pstmt.executeQuery(); List lista; lista = new ArrayList(); ProjetoDAO projetoDAO = new ProjetoDAO(); while (rs.next()){ DadoSimples d = new DadoSimples(); d.setId(rs.getInt("id")); d.setValor(rs.getDouble("valor")); d.setProjeto(projetoDAO.selecionar(rs.getInt("projeto"))); lista.add(d); } return lista; } /** * Método responsável pela inserção de dados simples no banco de dados * @author Luciano de Carvalho Borba * @param dto dados simples a ser inserido * @throws Exception possíveis exceções que podem acontecer */ @Override public void inserir(DadoSimples dto) throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt = conexao.prepareStatement("insert into dados_simples (valor, projeto) values(?, ?)", Statement.RETURN_GENERATED_KEYS); pstmt.setDouble(1, dto.getValor()); pstmt.setInt(2, dto.getProjeto().getId()); //Executa a inserção pstmt.executeUpdate(); dto.setId(getId(pstmt)); } /** * Método responsável pela alteração de dados simples no banco de dados * @author Jeferson Rossini Ferreira Lourenço * @param dto dados simples a ser alterado preenchido * @throws Exception possíveis exceções que podem acontecer */ @Override public void alterar(DadoSimples dto) throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("update dados_simples set valor = ?, projeto = ? where id = ?"); pstmt.setDouble(1, dto.getValor()); pstmt.setInt(2, dto.getProjeto().getId()); pstmt.setInt(3, dto.getId()); //executa uma atualização/alteração pstmt.executeUpdate(); } /** * Método responsável por selecionar algum dados simples no banco de dados * @author Macilon Arruda * @param id identificador de dados simples selecionado * @return o dados simples selecionado * @throws Exception - Possíveis exceções que podem acontecer */ @Override public DadoSimples selecionar(int id) throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("select * from dados_simples where id = ?"); pstmt.setInt(1, id); ResultSet rs; rs = pstmt.executeQuery(); ProjetoDAO projetoDAO = new ProjetoDAO(); if(rs.next()) { DadoSimples d = new DadoSimples(); d.setId(rs.getInt("id")); d.setValor(rs.getDouble("valor")); d.setProjeto(projetoDAO.selecionar(rs.getInt("projeto"))); return d; }else{ return null; } } /** * Método que exclui um dado simples * @param id identificador de id de um dado simples * @throws Exception possíveis exceções que podem acontecer * @author Daniel Moreira Cardoso */ @Override public void excluir(int id) throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("delete from dados_simples where id = ?"); pstmt.setInt(1, id); pstmt.executeUpdate(); } }
[ "public", "class", "DadoSimplesDAO", "extends", "DAOCRUDBase", "<", "DadoSimples", ">", "{", "/**\n * Método que lista todos os dados simples armazanados no banco de dados\n * @author Adallberto Lucena Moura\n * @return lista dos dados simples\n * @throws Exception possíveis exceções que podem acontecer\n */", "@", "Override", "public", "List", "listar", "(", ")", "throws", "Exception", "{", "Connection", "conexao", "=", "getConexao", "(", ")", ";", "PreparedStatement", "pstmt", ";", "pstmt", "=", "conexao", ".", "prepareStatement", "(", "\"", "select * from dados_simples order by id asc", "\"", ")", ";", "ResultSet", "rs", ";", "rs", "=", "pstmt", ".", "executeQuery", "(", ")", ";", "List", "lista", ";", "lista", "=", "new", "ArrayList", "(", ")", ";", "ProjetoDAO", "projetoDAO", "=", "new", "ProjetoDAO", "(", ")", ";", "while", "(", "rs", ".", "next", "(", ")", ")", "{", "DadoSimples", "d", "=", "new", "DadoSimples", "(", ")", ";", "d", ".", "setId", "(", "rs", ".", "getInt", "(", "\"", "id", "\"", ")", ")", ";", "d", ".", "setValor", "(", "rs", ".", "getDouble", "(", "\"", "valor", "\"", ")", ")", ";", "d", ".", "setProjeto", "(", "projetoDAO", ".", "selecionar", "(", "rs", ".", "getInt", "(", "\"", "projeto", "\"", ")", ")", ")", ";", "lista", ".", "add", "(", "d", ")", ";", "}", "return", "lista", ";", "}", "/**\n * Método responsável pela inserção de dados simples no banco de dados\n * @author Luciano de Carvalho Borba\n * @param dto dados simples a ser inserido\n * @throws Exception possíveis exceções que podem acontecer\n */", "@", "Override", "public", "void", "inserir", "(", "DadoSimples", "dto", ")", "throws", "Exception", "{", "Connection", "conexao", "=", "getConexao", "(", ")", ";", "PreparedStatement", "pstmt", "=", "conexao", ".", "prepareStatement", "(", "\"", "insert into dados_simples (valor, projeto) values(?, ?)", "\"", ",", "Statement", ".", "RETURN_GENERATED_KEYS", ")", ";", "pstmt", ".", "setDouble", "(", "1", ",", "dto", ".", "getValor", "(", ")", ")", ";", "pstmt", ".", "setInt", "(", "2", ",", "dto", ".", "getProjeto", "(", ")", ".", "getId", "(", ")", ")", ";", "pstmt", ".", "executeUpdate", "(", ")", ";", "dto", ".", "setId", "(", "getId", "(", "pstmt", ")", ")", ";", "}", "/**\n * Método responsável pela alteração de dados simples no banco de dados\n * @author Jeferson Rossini Ferreira Lourenço\n * @param dto dados simples a ser alterado preenchido\n * @throws Exception possíveis exceções que podem acontecer\n */", "@", "Override", "public", "void", "alterar", "(", "DadoSimples", "dto", ")", "throws", "Exception", "{", "Connection", "conexao", "=", "getConexao", "(", ")", ";", "PreparedStatement", "pstmt", ";", "pstmt", "=", "conexao", ".", "prepareStatement", "(", "\"", "update dados_simples set valor = ?, projeto = ? where id = ?", "\"", ")", ";", "pstmt", ".", "setDouble", "(", "1", ",", "dto", ".", "getValor", "(", ")", ")", ";", "pstmt", ".", "setInt", "(", "2", ",", "dto", ".", "getProjeto", "(", ")", ".", "getId", "(", ")", ")", ";", "pstmt", ".", "setInt", "(", "3", ",", "dto", ".", "getId", "(", ")", ")", ";", "pstmt", ".", "executeUpdate", "(", ")", ";", "}", "/**\n * Método responsável por selecionar algum dados simples no banco de dados\n * @author Macilon Arruda\n * @param id identificador de dados simples selecionado\n * @return o dados simples selecionado\n * @throws Exception - Possíveis exceções que podem acontecer\n */", "@", "Override", "public", "DadoSimples", "selecionar", "(", "int", "id", ")", "throws", "Exception", "{", "Connection", "conexao", "=", "getConexao", "(", ")", ";", "PreparedStatement", "pstmt", ";", "pstmt", "=", "conexao", ".", "prepareStatement", "(", "\"", "select * from dados_simples where id = ?", "\"", ")", ";", "pstmt", ".", "setInt", "(", "1", ",", "id", ")", ";", "ResultSet", "rs", ";", "rs", "=", "pstmt", ".", "executeQuery", "(", ")", ";", "ProjetoDAO", "projetoDAO", "=", "new", "ProjetoDAO", "(", ")", ";", "if", "(", "rs", ".", "next", "(", ")", ")", "{", "DadoSimples", "d", "=", "new", "DadoSimples", "(", ")", ";", "d", ".", "setId", "(", "rs", ".", "getInt", "(", "\"", "id", "\"", ")", ")", ";", "d", ".", "setValor", "(", "rs", ".", "getDouble", "(", "\"", "valor", "\"", ")", ")", ";", "d", ".", "setProjeto", "(", "projetoDAO", ".", "selecionar", "(", "rs", ".", "getInt", "(", "\"", "projeto", "\"", ")", ")", ")", ";", "return", "d", ";", "}", "else", "{", "return", "null", ";", "}", "}", "/**\n * Método que exclui um dado simples\n * @param id identificador de id de um dado simples\n * @throws Exception possíveis exceções que podem acontecer\n * @author Daniel Moreira Cardoso\n */", "@", "Override", "public", "void", "excluir", "(", "int", "id", ")", "throws", "Exception", "{", "Connection", "conexao", "=", "getConexao", "(", ")", ";", "PreparedStatement", "pstmt", ";", "pstmt", "=", "conexao", ".", "prepareStatement", "(", "\"", "delete from dados_simples where id = ?", "\"", ")", ";", "pstmt", ".", "setInt", "(", "1", ",", "id", ")", ";", "pstmt", ".", "executeUpdate", "(", ")", ";", "}", "}" ]
Objeto de acesso aos dados simples @author Adallberto
[ "Objeto", "de", "acesso", "aos", "dados", "simples", "@author", "Adallberto" ]
[ "//Executa a inserção", "//executa uma atualização/alteração" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33b5d37a254553170a15ef6b19553ff0fb48a1c8
vitahlin/kennen
javar/jdk8-analysis/src/com/sun/tools/internal/xjc/model/CAdapter.java
[ "MIT" ]
Java
CAdapter
/** * Extended {@link Adapter} for use within XJC. * * @author Kohsuke Kawaguchi */
Extended Adapter for use within XJC. @author Kohsuke Kawaguchi
[ "Extended", "Adapter", "for", "use", "within", "XJC", ".", "@author", "Kohsuke", "Kawaguchi" ]
public final class CAdapter extends Adapter<NType,NClass> { /** * If non-null, the same as {@link #adapterType} but more conveniently typed. */ private JClass adapterClass1; /** * If non-null, the same as {@link #adapterType} but more conveniently typed. */ private Class<? extends XmlAdapter> adapterClass2; /** * When the adapter class is statically known to us. * * @param copy * true to copy the adapter class into the user package, * or otherwise just refer to the class specified via the * adapter parameter. */ public CAdapter(Class<? extends XmlAdapter> adapter, boolean copy) { super(getRef(adapter,copy),NavigatorImpl.theInstance); this.adapterClass1 = null; this.adapterClass2 = adapter; } static NClass getRef( final Class<? extends XmlAdapter> adapter, boolean copy ) { if(copy) { // TODO: this is a hack. the code generation should be defered until // the backend. (right now constant generation happens in the front-end) return new EagerNClass(adapter) { @Override public JClass toType(Outline o, Aspect aspect) { return o.addRuntime(adapter); } public String fullName() { // TODO: implement this method later throw new UnsupportedOperationException(); } }; } else { return NavigatorImpl.theInstance.ref(adapter); } } public CAdapter(JClass adapter) { super( NavigatorImpl.theInstance.ref(adapter), NavigatorImpl.theInstance); this.adapterClass1 = adapter; this.adapterClass2 = null; } public JClass getAdapterClass(Outline o) { if(adapterClass1==null) adapterClass1 = o.getCodeModel().ref(adapterClass2); return adapterType.toType(o, Aspect.EXPOSED); } /** * Returns true if the adapter is for whitespace normalization. * Such an adapter can be ignored when producing a list. */ public boolean isWhitespaceAdapter() { return adapterClass2==CollapsedStringAdapter.class || adapterClass2==NormalizedStringAdapter.class; } /** * Returns the adapter class if the adapter type is statically known to XJC. * <p> * This method is mostly for enabling certain optimized code generation. */ public Class<? extends XmlAdapter> getAdapterIfKnown() { return adapterClass2; } }
[ "public", "final", "class", "CAdapter", "extends", "Adapter", "<", "NType", ",", "NClass", ">", "{", "/**\n * If non-null, the same as {@link #adapterType} but more conveniently typed.\n */", "private", "JClass", "adapterClass1", ";", "/**\n * If non-null, the same as {@link #adapterType} but more conveniently typed.\n */", "private", "Class", "<", "?", "extends", "XmlAdapter", ">", "adapterClass2", ";", "/**\n * When the adapter class is statically known to us.\n *\n * @param copy\n * true to copy the adapter class into the user package,\n * or otherwise just refer to the class specified via the\n * adapter parameter.\n */", "public", "CAdapter", "(", "Class", "<", "?", "extends", "XmlAdapter", ">", "adapter", ",", "boolean", "copy", ")", "{", "super", "(", "getRef", "(", "adapter", ",", "copy", ")", ",", "NavigatorImpl", ".", "theInstance", ")", ";", "this", ".", "adapterClass1", "=", "null", ";", "this", ".", "adapterClass2", "=", "adapter", ";", "}", "static", "NClass", "getRef", "(", "final", "Class", "<", "?", "extends", "XmlAdapter", ">", "adapter", ",", "boolean", "copy", ")", "{", "if", "(", "copy", ")", "{", "return", "new", "EagerNClass", "(", "adapter", ")", "{", "@", "Override", "public", "JClass", "toType", "(", "Outline", "o", ",", "Aspect", "aspect", ")", "{", "return", "o", ".", "addRuntime", "(", "adapter", ")", ";", "}", "public", "String", "fullName", "(", ")", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "}", ";", "}", "else", "{", "return", "NavigatorImpl", ".", "theInstance", ".", "ref", "(", "adapter", ")", ";", "}", "}", "public", "CAdapter", "(", "JClass", "adapter", ")", "{", "super", "(", "NavigatorImpl", ".", "theInstance", ".", "ref", "(", "adapter", ")", ",", "NavigatorImpl", ".", "theInstance", ")", ";", "this", ".", "adapterClass1", "=", "adapter", ";", "this", ".", "adapterClass2", "=", "null", ";", "}", "public", "JClass", "getAdapterClass", "(", "Outline", "o", ")", "{", "if", "(", "adapterClass1", "==", "null", ")", "adapterClass1", "=", "o", ".", "getCodeModel", "(", ")", ".", "ref", "(", "adapterClass2", ")", ";", "return", "adapterType", ".", "toType", "(", "o", ",", "Aspect", ".", "EXPOSED", ")", ";", "}", "/**\n * Returns true if the adapter is for whitespace normalization.\n * Such an adapter can be ignored when producing a list.\n */", "public", "boolean", "isWhitespaceAdapter", "(", ")", "{", "return", "adapterClass2", "==", "CollapsedStringAdapter", ".", "class", "||", "adapterClass2", "==", "NormalizedStringAdapter", ".", "class", ";", "}", "/**\n * Returns the adapter class if the adapter type is statically known to XJC.\n * <p>\n * This method is mostly for enabling certain optimized code generation.\n */", "public", "Class", "<", "?", "extends", "XmlAdapter", ">", "getAdapterIfKnown", "(", ")", "{", "return", "adapterClass2", ";", "}", "}" ]
Extended {@link Adapter} for use within XJC.
[ "Extended", "{", "@link", "Adapter", "}", "for", "use", "within", "XJC", "." ]
[ "// TODO: this is a hack. the code generation should be defered until", "// the backend. (right now constant generation happens in the front-end)", "// TODO: implement this method later" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33bc7fc29f647f354cc3a434dca66dd37fdfcdf8
posborne/mango-movie-manager
src/com/themangoproject/ui/model/navigator/AddSetMutableTreeNode.java
[ "MIT" ]
Java
AddSetMutableTreeNode
/** * Item for throwing up the add set dialog. * * @author Paul Osborne */
Item for throwing up the add set dialog. @author Paul Osborne
[ "Item", "for", "throwing", "up", "the", "add", "set", "dialog", ".", "@author", "Paul", "Osborne" ]
public class AddSetMutableTreeNode extends DefaultMutableTreeNode implements MangoMutableTreeNode { /** Generated UID */ private static final long serialVersionUID = -7776990477125186361L; /** Construct the node */ public AddSetMutableTreeNode() { super("Add New Set"); } /** Throw up the add set dialog */ @Override public void doYourThing(Mango mangoPanel) { SetListDialog sld = new SetListDialog(mangoPanel, true); sld.setLocationRelativeTo(mangoPanel); sld.setSetSelected(); sld.setVisible(true); } /** No popup */ @Override public JPopupMenu getPopupMenu() { return null; } }
[ "public", "class", "AddSetMutableTreeNode", "extends", "DefaultMutableTreeNode", "implements", "MangoMutableTreeNode", "{", "/** Generated UID */", "private", "static", "final", "long", "serialVersionUID", "=", "-", "7776990477125186361L", ";", "/** Construct the node */", "public", "AddSetMutableTreeNode", "(", ")", "{", "super", "(", "\"", "Add New Set", "\"", ")", ";", "}", "/** Throw up the add set dialog */", "@", "Override", "public", "void", "doYourThing", "(", "Mango", "mangoPanel", ")", "{", "SetListDialog", "sld", "=", "new", "SetListDialog", "(", "mangoPanel", ",", "true", ")", ";", "sld", ".", "setLocationRelativeTo", "(", "mangoPanel", ")", ";", "sld", ".", "setSetSelected", "(", ")", ";", "sld", ".", "setVisible", "(", "true", ")", ";", "}", "/** No popup */", "@", "Override", "public", "JPopupMenu", "getPopupMenu", "(", ")", "{", "return", "null", ";", "}", "}" ]
Item for throwing up the add set dialog.
[ "Item", "for", "throwing", "up", "the", "add", "set", "dialog", "." ]
[]
[ { "param": "DefaultMutableTreeNode", "type": null }, { "param": "MangoMutableTreeNode", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DefaultMutableTreeNode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "MangoMutableTreeNode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33c06f0d81828fc0a6fe7fe173b2882ceb4a88d2
dbiir/ParaFlow
paraflow-examples/src/test/java/cn/edu/ruc/iir/paraflow/examples/TestTpchDataSource.java
[ "Apache-2.0" ]
Java
TestTpchDataSource
/** * paraflow * * @author guodong */
paraflow @author guodong
[ "paraflow", "@author", "guodong" ]
public class TestTpchDataSource { @Test public void testTpchDataGeneration() { TpchDataSource dataSource = new TpchDataSource(1, 1, 1, 0, 1_000_000); int counter = 0; while (true) { Message message = dataSource.read(); if (message == null) { break; } counter++; } System.out.println(counter); } }
[ "public", "class", "TestTpchDataSource", "{", "@", "Test", "public", "void", "testTpchDataGeneration", "(", ")", "{", "TpchDataSource", "dataSource", "=", "new", "TpchDataSource", "(", "1", ",", "1", ",", "1", ",", "0", ",", "1_000_000", ")", ";", "int", "counter", "=", "0", ";", "while", "(", "true", ")", "{", "Message", "message", "=", "dataSource", ".", "read", "(", ")", ";", "if", "(", "message", "==", "null", ")", "{", "break", ";", "}", "counter", "++", ";", "}", "System", ".", "out", ".", "println", "(", "counter", ")", ";", "}", "}" ]
paraflow @author guodong
[ "paraflow", "@author", "guodong" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33c2c9b9795d053fe50431a822ed486f0a67b7bc
seco/obliquid-lib
src/main/java/org/obliquid/datatype/strategy/StringStrategy.java
[ "MIT" ]
Java
StringStrategy
/** * Implement basic String DataType behaviour for reuse. (Strategy Pattern). * * @author stivlo * */
Implement basic String DataType behaviour for reuse. (Strategy Pattern). @author stivlo
[ "Implement", "basic", "String", "DataType", "behaviour", "for", "reuse", ".", "(", "Strategy", "Pattern", ")", ".", "@author", "stivlo" ]
public class StringStrategy implements DataType<String> { /** * Universal serial identifier. */ private static final long serialVersionUID = 1L; /** * The data held. */ private String data; @Override public final String formatData(final Locale locale) throws IllegalStateException { return getData(); } @Override public final String getData() throws IllegalStateException { if (data == null) { throw new IllegalStateException("The status is null"); } return data; } @Override public final void setDataFromString(final String theData) throws IllegalArgumentException { setData(theData); } @Override public final void setData(final String theData) throws IllegalArgumentException { if (theData == null) { throw new IllegalArgumentException("The argument can't be null"); } data = theData; } @Override public final boolean isAssigned() { return data != null; } }
[ "public", "class", "StringStrategy", "implements", "DataType", "<", "String", ">", "{", "/**\n * Universal serial identifier.\n */", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\n * The data held.\n */", "private", "String", "data", ";", "@", "Override", "public", "final", "String", "formatData", "(", "final", "Locale", "locale", ")", "throws", "IllegalStateException", "{", "return", "getData", "(", ")", ";", "}", "@", "Override", "public", "final", "String", "getData", "(", ")", "throws", "IllegalStateException", "{", "if", "(", "data", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "The status is null", "\"", ")", ";", "}", "return", "data", ";", "}", "@", "Override", "public", "final", "void", "setDataFromString", "(", "final", "String", "theData", ")", "throws", "IllegalArgumentException", "{", "setData", "(", "theData", ")", ";", "}", "@", "Override", "public", "final", "void", "setData", "(", "final", "String", "theData", ")", "throws", "IllegalArgumentException", "{", "if", "(", "theData", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The argument can't be null", "\"", ")", ";", "}", "data", "=", "theData", ";", "}", "@", "Override", "public", "final", "boolean", "isAssigned", "(", ")", "{", "return", "data", "!=", "null", ";", "}", "}" ]
Implement basic String DataType behaviour for reuse.
[ "Implement", "basic", "String", "DataType", "behaviour", "for", "reuse", "." ]
[]
[ { "param": "DataType<String>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DataType<String>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33c77d6adb082c85dfe177eda8c7e6aa5887396b
Celebrate-future/openimaj
text/nlp/src/test/java/org/openimaj/text/nlp/language/LanguageDetectorTest.java
[ "BSD-3-Clause" ]
Java
LanguageDetectorTest
/** * * Test the language detector * * @author Sina Samangooei (ss@ecs.soton.ac.uk) * */
Test the language detector
[ "Test", "the", "language", "detector" ]
public class LanguageDetectorTest { /** * The temporary output folder */ @Rule public TemporaryFolder folder = new TemporaryFolder(); /** * Load the language model by constructing a new detector. Check the values * are readable. * * @throws IOException */ @Test public void testLanguageModel() throws IOException { final LanguageDetector det = new LanguageDetector(); final String[] englishStrings = new String[] { "This is an english sentence", "The uninstaller it downloads for you is 33.4MB ! For an *un*installer? #wtf" }; assertLanguage(det, englishStrings, Locale.ENGLISH); final String[] germanStrings = new String[] { "in der josefstadt scheint es offenbar sehr knapp zu werden warum dauert die ausz\u00e4hlung im kleinsten bezirk wiens so lange", "bezirk sch\u00f6nbrunner allee \u2013 stauraum vor hetzendorfer stra\u00dfe wird saniert", "das erlebnis im wahllokal im bezirk um im \u00f6sterreich ticker ist heftig" }; assertLanguage(det, germanStrings, Locale.GERMAN); final String[] japaneseStrings = new String[] { "@yuekoo \u304a\u306f\u3088\u30fc\u3002\u5730\u30c7\u30b8\u2025\u306a\u3093\u304b\u3001\u4eca\u306f\u5165\u308b\u2025\u3002\u610f\u5473\u304c\u308f\u304b\u3089\u3093(&gt;_&lt;)", "\u3053\u308C\u306F\u79C1\u304C\u65E5\u672C\u8A9E\u3067\u8A18\u8FF0\u3059\u308B\u6587\u5B57\u5217\u3067\u3059\u3002" }; assertLanguage(det, japaneseStrings, Locale.JAPANESE); final String[] hindiStrings = new String[] { "\u092F\u0939 \u090F\u0915 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917 \u0939\u0948 \u0915\u093F \u092E\u0948\u0902 \u0939\u093F\u0902\u0926\u0940 \u092E\u0947\u0902 \u0932\u093F\u0916\u0928\u093E \u0939\u0948", "\u0924\u0947\u0939\u0930\u093E\u0928. \u0908\u0930\u093E\u0928 \u0915\u0947 \u0930\u093E\u0937\u094D\u091F\u094D\u0930\u092A\u0924\u093F \u092E\u0939\u092E\u0942\u0926 \u0905\u0939\u092E\u0926\u0940\u0928\u0947\u091C\u093E\u0926 \u0928\u0947 \u092C\u0941\u0927\u0935\u093E\u0930 \u0915\u094B \u0930\u093E\u0937\u094D\u091F\u094D\u0930 \u0915\u094B \u0938\u0902\u092C\u094B\u0927\u093F\u0924 \u0915\u0930\u0924\u0947 \u0939\u0941\u090F \u0915\u0939\u093E \u0915\u093F \u0908\u0930\u093E\u0928 \u092C\u092E \u0928\u0939\u0940\u0902 \u092C\u0928\u093E \u0930\u0939\u093E \u0939\u0948\u0964 \u092A\u0930\u092E\u093E\u0923\u0941 \u0915\u093E \u092E\u0924\u0932\u092C \u0938\u093F\u0930\u094D\u092B \u092C\u092E \u0939\u0940 \u0928\u0939\u0940\u0902 \u0939\u094B\u0924\u093E \u0939\u0948\u0964\u0905\u092E\u0947\u0930\u093F\u0915\u093E \u0914\u0930 \u0907\u091C\u0930\u093E\u0907\u0932 \u092A\u0930 \u0924\u0940\u0916\u093E \u092A\u094D\u0930\u0939\u093E\u0930 \u0915\u0930\u0924\u0947 \u0939\u0941\u090F \u0905\u0939\u092E\u0926\u0940\u0928\u0947\u091C\u093E\u0926 \u0928\u0947 \u0915\u0939\u093E \u0915\u093F \u0935\u094B \u0908\u0930\u093E\u0928\u0940 \u0935\u0948\u091C\u094D\u091E\u093E\u0928\u093F\u0915\u094B\u0902 \u0915\u094B \u0907\u0938\u0932\u093F\u090F \u092E\u093E\u0930 \u0930\u0939\u0947 \u0939\u0948\u0902 \u0915\u094D\u092F\u094B\u0902\u0915\u093F \u0935\u094B \u0928\u0939\u0940\u0902 \u091A\u093E\u0939\u0924\u0947 \u0915\u093F \u0915\u094B\u0908 \u0914\u0930 \u092E\u0941\u0932\u094D\u0915 \u0906\u0917\u0947 \u092C\u0922\u093C\u0947\u0964 \u0939\u092E\u093E\u0930\u0947 \u0935\u0948\u091C\u094D\u091E\u093E\u0928\u093F\u0915\u094B\u0902 \u0928\u0947 \u0907\u0938 \u0909\u092A\u0932\u092C\u094D\u0927\u093F \u0915\u094B \u0939\u093E\u0938\u093F\u0932 \u0915\u0930\u0928\u0947 \u092E\u0947\u0902 \u092C\u0939\u0941\u0924 \u092E\u0947\u0939\u0928\u0924 \u0915\u0940 \u0939\u0948\u0964" }; assertLanguage(det, hindiStrings, new Locale("hi")); } /** * Testing the read/write binary code of the language model * * @throws IOException */ @Test public void testLanguageModelReadWrite() throws IOException { final LanguageDetector det = new LanguageDetector(); final File out = folder.newFile("languagemodel.binary"); GZIPOutputStream os = new GZIPOutputStream(new FileOutputStream(out)); IOUtils.writeBinary(os, det.getLanguageModel()); os.flush(); os.close(); final InputStream is = new FileInputStream(out); final LanguageModel readModel = IOUtils.read(new GZIPInputStream(is), LanguageModel.class); final LanguageDetector newdet = new LanguageDetector(readModel); assertTrue(readModel.equals(det.getLanguageModel())); final String[] hindiStrings = new String[] { "\u092F\u0939 \u090F\u0915 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917 \u0939\u0948 \u0915\u093F \u092E\u0948\u0902 \u0939\u093F\u0902\u0926\u0940 \u092E\u0947\u0902 \u0932\u093F\u0916\u0928\u093E \u0939\u0948", "\u0924\u0947\u0939\u0930\u093E\u0928. \u0908\u0930\u093E\u0928 \u0915\u0947 \u0930\u093E\u0937\u094D\u091F\u094D\u0930\u092A\u0924\u093F \u092E\u0939\u092E\u0942\u0926 \u0905\u0939\u092E\u0926\u0940\u0928\u0947\u091C\u093E\u0926 \u0928\u0947 \u092C\u0941\u0927\u0935\u093E\u0930 \u0915\u094B \u0930\u093E\u0937\u094D\u091F\u094D\u0930 \u0915\u094B \u0938\u0902\u092C\u094B\u0927\u093F\u0924 \u0915\u0930\u0924\u0947 \u0939\u0941\u090F \u0915\u0939\u093E \u0915\u093F \u0908\u0930\u093E\u0928 \u092C\u092E \u0928\u0939\u0940\u0902 \u092C\u0928\u093E \u0930\u0939\u093E \u0939\u0948\u0964 \u092A\u0930\u092E\u093E\u0923\u0941 \u0915\u093E \u092E\u0924\u0932\u092C \u0938\u093F\u0930\u094D\u092B \u092C\u092E \u0939\u0940 \u0928\u0939\u0940\u0902 \u0939\u094B\u0924\u093E \u0939\u0948\u0964\u0905\u092E\u0947\u0930\u093F\u0915\u093E \u0914\u0930 \u0907\u091C\u0930\u093E\u0907\u0932 \u092A\u0930 \u0924\u0940\u0916\u093E \u092A\u094D\u0930\u0939\u093E\u0930 \u0915\u0930\u0924\u0947 \u0939\u0941\u090F \u0905\u0939\u092E\u0926\u0940\u0928\u0947\u091C\u093E\u0926 \u0928\u0947 \u0915\u0939\u093E \u0915\u093F \u0935\u094B \u0908\u0930\u093E\u0928\u0940 \u0935\u0948\u091C\u094D\u091E\u093E\u0928\u093F\u0915\u094B\u0902 \u0915\u094B \u0907\u0938\u0932\u093F\u090F \u092E\u093E\u0930 \u0930\u0939\u0947 \u0939\u0948\u0902 \u0915\u094D\u092F\u094B\u0902\u0915\u093F \u0935\u094B \u0928\u0939\u0940\u0902 \u091A\u093E\u0939\u0924\u0947 \u0915\u093F \u0915\u094B\u0908 \u0914\u0930 \u092E\u0941\u0932\u094D\u0915 \u0906\u0917\u0947 \u092C\u0922\u093C\u0947\u0964 \u0939\u092E\u093E\u0930\u0947 \u0935\u0948\u091C\u094D\u091E\u093E\u0928\u093F\u0915\u094B\u0902 \u0928\u0947 \u0907\u0938 \u0909\u092A\u0932\u092C\u094D\u0927\u093F \u0915\u094B \u0939\u093E\u0938\u093F\u0932 \u0915\u0930\u0928\u0947 \u092E\u0947\u0902 \u092C\u0939\u0941\u0924 \u092E\u0947\u0939\u0928\u0924 \u0915\u0940 \u0939\u0948\u0964" }; // assertLanguage(det,hindiStrings,new Locale("hi")); assertLanguage(newdet, hindiStrings, new Locale("hi")); } private void assertLanguage(LanguageDetector det, String[] statements, Locale language) { for (final String statement : statements) { final WeightedLocale estimateLanguage = det.classify(statement); System.out.println(estimateLanguage); Assert.assertEquals(language, estimateLanguage.getLocale()); } } }
[ "public", "class", "LanguageDetectorTest", "{", "/**\n\t * The temporary output folder\n\t */", "@", "Rule", "public", "TemporaryFolder", "folder", "=", "new", "TemporaryFolder", "(", ")", ";", "/**\n\t * Load the language model by constructing a new detector. Check the values\n\t * are readable.\n\t * \n\t * @throws IOException\n\t */", "@", "Test", "public", "void", "testLanguageModel", "(", ")", "throws", "IOException", "{", "final", "LanguageDetector", "det", "=", "new", "LanguageDetector", "(", ")", ";", "final", "String", "[", "]", "englishStrings", "=", "new", "String", "[", "]", "{", "\"", "This is an english sentence", "\"", ",", "\"", "The uninstaller it downloads for you is 33.4MB ! For an *un*installer? #wtf", "\"", "}", ";", "assertLanguage", "(", "det", ",", "englishStrings", ",", "Locale", ".", "ENGLISH", ")", ";", "final", "String", "[", "]", "germanStrings", "=", "new", "String", "[", "]", "{", "\"", "in der josefstadt scheint es offenbar sehr knapp zu werden warum dauert die ausz", "\\u00e4", "hlung im kleinsten bezirk wiens so lange", "\"", ",", "\"", "bezirk sch", "\\u00f6", "nbrunner allee ", "\\u2013", " stauraum vor hetzendorfer stra", "\\u00df", "e wird saniert", "\"", ",", "\"", "das erlebnis im wahllokal im bezirk um im ", "\\u00f6", "sterreich ticker ist heftig", "\"", "}", ";", "assertLanguage", "(", "det", ",", "germanStrings", ",", "Locale", ".", "GERMAN", ")", ";", "final", "String", "[", "]", "japaneseStrings", "=", "new", "String", "[", "]", "{", "\"", "@yuekoo ", "\\u304a", "\\u306f", "\\u3088", "\\u30fc", "\\u3002", "\\u5730", "\\u30c7", "\\u30b8", "\\u2025", "\\u306a", "\\u3093", "\\u304b", "\\u3001", "\\u4eca", "\\u306f", "\\u5165", "\\u308b", "\\u2025", "\\u3002", "\\u610f", "\\u5473", "\\u304c", "\\u308f", "\\u304b", "\\u3089", "\\u3093", "(&gt;_&lt;)", "\"", ",", "\"", "\\u3053", "\\u308C", "\\u306F", "\\u79C1", "\\u304C", "\\u65E5", "\\u672C", "\\u8A9E", "\\u3067", "\\u8A18", "\\u8FF0", "\\u3059", "\\u308B", "\\u6587", "\\u5B57", "\\u5217", "\\u3067", "\\u3059", "\\u3002", "\"", "}", ";", "assertLanguage", "(", "det", ",", "japaneseStrings", ",", "Locale", ".", "JAPANESE", ")", ";", "final", "String", "[", "]", "hindiStrings", "=", "new", "String", "[", "]", "{", "\"", "\\u092F", "\\u0939", " ", "\\u090F", "\\u0915", " ", "\\u0938", "\\u094D", "\\u091F", "\\u094D", "\\u0930", "\\u093F", "\\u0902", "\\u0917", " ", "\\u0939", "\\u0948", " ", "\\u0915", "\\u093F", " ", "\\u092E", "\\u0948", "\\u0902", " ", "\\u0939", "\\u093F", "\\u0902", "\\u0926", "\\u0940", " ", "\\u092E", "\\u0947", "\\u0902", " ", "\\u0932", "\\u093F", "\\u0916", "\\u0928", "\\u093E", " ", "\\u0939", "\\u0948", "\"", ",", "\"", "\\u0924", "\\u0947", "\\u0939", "\\u0930", "\\u093E", "\\u0928", ". ", "\\u0908", "\\u0930", "\\u093E", "\\u0928", " ", "\\u0915", "\\u0947", " ", "\\u0930", "\\u093E", "\\u0937", "\\u094D", "\\u091F", "\\u094D", "\\u0930", "\\u092A", "\\u0924", "\\u093F", " ", "\\u092E", "\\u0939", "\\u092E", "\\u0942", "\\u0926", " ", "\\u0905", "\\u0939", "\\u092E", "\\u0926", "\\u0940", "\\u0928", "\\u0947", "\\u091C", "\\u093E", "\\u0926", " ", "\\u0928", "\\u0947", " ", "\\u092C", "\\u0941", "\\u0927", "\\u0935", "\\u093E", "\\u0930", " ", "\\u0915", "\\u094B", " ", "\\u0930", "\\u093E", "\\u0937", "\\u094D", "\\u091F", "\\u094D", "\\u0930", " ", "\\u0915", "\\u094B", " ", "\\u0938", "\\u0902", "\\u092C", "\\u094B", "\\u0927", "\\u093F", "\\u0924", " ", "\\u0915", "\\u0930", "\\u0924", "\\u0947", " ", "\\u0939", "\\u0941", "\\u090F", " ", "\\u0915", "\\u0939", "\\u093E", " ", "\\u0915", "\\u093F", " ", "\\u0908", "\\u0930", "\\u093E", "\\u0928", " ", "\\u092C", "\\u092E", " ", "\\u0928", "\\u0939", "\\u0940", "\\u0902", " ", "\\u092C", "\\u0928", "\\u093E", " ", "\\u0930", "\\u0939", "\\u093E", " ", "\\u0939", "\\u0948", "\\u0964", " ", "\\u092A", "\\u0930", "\\u092E", "\\u093E", "\\u0923", "\\u0941", " ", "\\u0915", "\\u093E", " ", "\\u092E", "\\u0924", "\\u0932", "\\u092C", " ", "\\u0938", "\\u093F", "\\u0930", "\\u094D", "\\u092B", " ", "\\u092C", "\\u092E", " ", "\\u0939", "\\u0940", " ", "\\u0928", "\\u0939", "\\u0940", "\\u0902", " ", "\\u0939", "\\u094B", "\\u0924", "\\u093E", " ", "\\u0939", "\\u0948", "\\u0964", "\\u0905", "\\u092E", "\\u0947", "\\u0930", "\\u093F", "\\u0915", "\\u093E", " ", "\\u0914", "\\u0930", " ", "\\u0907", "\\u091C", "\\u0930", "\\u093E", "\\u0907", "\\u0932", " ", "\\u092A", "\\u0930", " ", "\\u0924", "\\u0940", "\\u0916", "\\u093E", " ", "\\u092A", "\\u094D", "\\u0930", "\\u0939", "\\u093E", "\\u0930", " ", "\\u0915", "\\u0930", "\\u0924", "\\u0947", " ", "\\u0939", "\\u0941", "\\u090F", " ", "\\u0905", "\\u0939", "\\u092E", "\\u0926", "\\u0940", "\\u0928", "\\u0947", "\\u091C", "\\u093E", "\\u0926", " ", "\\u0928", "\\u0947", " ", "\\u0915", "\\u0939", "\\u093E", " ", "\\u0915", "\\u093F", " ", "\\u0935", "\\u094B", " ", "\\u0908", "\\u0930", "\\u093E", "\\u0928", "\\u0940", " ", "\\u0935", "\\u0948", "\\u091C", "\\u094D", "\\u091E", "\\u093E", "\\u0928", "\\u093F", "\\u0915", "\\u094B", "\\u0902", " ", "\\u0915", "\\u094B", " ", "\\u0907", "\\u0938", "\\u0932", "\\u093F", "\\u090F", " ", "\\u092E", "\\u093E", "\\u0930", " ", "\\u0930", "\\u0939", "\\u0947", " ", "\\u0939", "\\u0948", "\\u0902", " ", "\\u0915", "\\u094D", "\\u092F", "\\u094B", "\\u0902", "\\u0915", "\\u093F", " ", "\\u0935", "\\u094B", " ", "\\u0928", "\\u0939", "\\u0940", "\\u0902", " ", "\\u091A", "\\u093E", "\\u0939", "\\u0924", "\\u0947", " ", "\\u0915", "\\u093F", " ", "\\u0915", "\\u094B", "\\u0908", " ", "\\u0914", "\\u0930", " ", "\\u092E", "\\u0941", "\\u0932", "\\u094D", "\\u0915", " ", "\\u0906", "\\u0917", "\\u0947", " ", "\\u092C", "\\u0922", "\\u093C", "\\u0947", "\\u0964", " ", "\\u0939", "\\u092E", "\\u093E", "\\u0930", "\\u0947", " ", "\\u0935", "\\u0948", "\\u091C", "\\u094D", "\\u091E", "\\u093E", "\\u0928", "\\u093F", "\\u0915", "\\u094B", "\\u0902", " ", "\\u0928", "\\u0947", " ", "\\u0907", "\\u0938", " ", "\\u0909", "\\u092A", "\\u0932", "\\u092C", "\\u094D", "\\u0927", "\\u093F", " ", "\\u0915", "\\u094B", " ", "\\u0939", "\\u093E", "\\u0938", "\\u093F", "\\u0932", " ", "\\u0915", "\\u0930", "\\u0928", "\\u0947", " ", "\\u092E", "\\u0947", "\\u0902", " ", "\\u092C", "\\u0939", "\\u0941", "\\u0924", " ", "\\u092E", "\\u0947", "\\u0939", "\\u0928", "\\u0924", " ", "\\u0915", "\\u0940", " ", "\\u0939", "\\u0948", "\\u0964", "\"", "}", ";", "assertLanguage", "(", "det", ",", "hindiStrings", ",", "new", "Locale", "(", "\"", "hi", "\"", ")", ")", ";", "}", "/**\n\t * Testing the read/write binary code of the language model\n\t * \n\t * @throws IOException\n\t */", "@", "Test", "public", "void", "testLanguageModelReadWrite", "(", ")", "throws", "IOException", "{", "final", "LanguageDetector", "det", "=", "new", "LanguageDetector", "(", ")", ";", "final", "File", "out", "=", "folder", ".", "newFile", "(", "\"", "languagemodel.binary", "\"", ")", ";", "GZIPOutputStream", "os", "=", "new", "GZIPOutputStream", "(", "new", "FileOutputStream", "(", "out", ")", ")", ";", "IOUtils", ".", "writeBinary", "(", "os", ",", "det", ".", "getLanguageModel", "(", ")", ")", ";", "os", ".", "flush", "(", ")", ";", "os", ".", "close", "(", ")", ";", "final", "InputStream", "is", "=", "new", "FileInputStream", "(", "out", ")", ";", "final", "LanguageModel", "readModel", "=", "IOUtils", ".", "read", "(", "new", "GZIPInputStream", "(", "is", ")", ",", "LanguageModel", ".", "class", ")", ";", "final", "LanguageDetector", "newdet", "=", "new", "LanguageDetector", "(", "readModel", ")", ";", "assertTrue", "(", "readModel", ".", "equals", "(", "det", ".", "getLanguageModel", "(", ")", ")", ")", ";", "final", "String", "[", "]", "hindiStrings", "=", "new", "String", "[", "]", "{", "\"", "\\u092F", "\\u0939", " ", "\\u090F", "\\u0915", " ", "\\u0938", "\\u094D", "\\u091F", "\\u094D", "\\u0930", "\\u093F", "\\u0902", "\\u0917", " ", "\\u0939", "\\u0948", " ", "\\u0915", "\\u093F", " ", "\\u092E", "\\u0948", "\\u0902", " ", "\\u0939", "\\u093F", "\\u0902", "\\u0926", "\\u0940", " ", "\\u092E", "\\u0947", "\\u0902", " ", "\\u0932", "\\u093F", "\\u0916", "\\u0928", "\\u093E", " ", "\\u0939", "\\u0948", "\"", ",", "\"", "\\u0924", "\\u0947", "\\u0939", "\\u0930", "\\u093E", "\\u0928", ". ", "\\u0908", "\\u0930", "\\u093E", "\\u0928", " ", "\\u0915", "\\u0947", " ", "\\u0930", "\\u093E", "\\u0937", "\\u094D", "\\u091F", "\\u094D", "\\u0930", "\\u092A", "\\u0924", "\\u093F", " ", "\\u092E", "\\u0939", "\\u092E", "\\u0942", "\\u0926", " ", "\\u0905", "\\u0939", "\\u092E", "\\u0926", "\\u0940", "\\u0928", "\\u0947", "\\u091C", "\\u093E", "\\u0926", " ", "\\u0928", "\\u0947", " ", "\\u092C", "\\u0941", "\\u0927", "\\u0935", "\\u093E", "\\u0930", " ", "\\u0915", "\\u094B", " ", "\\u0930", "\\u093E", "\\u0937", "\\u094D", "\\u091F", "\\u094D", "\\u0930", " ", "\\u0915", "\\u094B", " ", "\\u0938", "\\u0902", "\\u092C", "\\u094B", "\\u0927", "\\u093F", "\\u0924", " ", "\\u0915", "\\u0930", "\\u0924", "\\u0947", " ", "\\u0939", "\\u0941", "\\u090F", " ", "\\u0915", "\\u0939", "\\u093E", " ", "\\u0915", "\\u093F", " ", "\\u0908", "\\u0930", "\\u093E", "\\u0928", " ", "\\u092C", "\\u092E", " ", "\\u0928", "\\u0939", "\\u0940", "\\u0902", " ", "\\u092C", "\\u0928", "\\u093E", " ", "\\u0930", "\\u0939", "\\u093E", " ", "\\u0939", "\\u0948", "\\u0964", " ", "\\u092A", "\\u0930", "\\u092E", "\\u093E", "\\u0923", "\\u0941", " ", "\\u0915", "\\u093E", " ", "\\u092E", "\\u0924", "\\u0932", "\\u092C", " ", "\\u0938", "\\u093F", "\\u0930", "\\u094D", "\\u092B", " ", "\\u092C", "\\u092E", " ", "\\u0939", "\\u0940", " ", "\\u0928", "\\u0939", "\\u0940", "\\u0902", " ", "\\u0939", "\\u094B", "\\u0924", "\\u093E", " ", "\\u0939", "\\u0948", "\\u0964", "\\u0905", "\\u092E", "\\u0947", "\\u0930", "\\u093F", "\\u0915", "\\u093E", " ", "\\u0914", "\\u0930", " ", "\\u0907", "\\u091C", "\\u0930", "\\u093E", "\\u0907", "\\u0932", " ", "\\u092A", "\\u0930", " ", "\\u0924", "\\u0940", "\\u0916", "\\u093E", " ", "\\u092A", "\\u094D", "\\u0930", "\\u0939", "\\u093E", "\\u0930", " ", "\\u0915", "\\u0930", "\\u0924", "\\u0947", " ", "\\u0939", "\\u0941", "\\u090F", " ", "\\u0905", "\\u0939", "\\u092E", "\\u0926", "\\u0940", "\\u0928", "\\u0947", "\\u091C", "\\u093E", "\\u0926", " ", "\\u0928", "\\u0947", " ", "\\u0915", "\\u0939", "\\u093E", " ", "\\u0915", "\\u093F", " ", "\\u0935", "\\u094B", " ", "\\u0908", "\\u0930", "\\u093E", "\\u0928", "\\u0940", " ", "\\u0935", "\\u0948", "\\u091C", "\\u094D", "\\u091E", "\\u093E", "\\u0928", "\\u093F", "\\u0915", "\\u094B", "\\u0902", " ", "\\u0915", "\\u094B", " ", "\\u0907", "\\u0938", "\\u0932", "\\u093F", "\\u090F", " ", "\\u092E", "\\u093E", "\\u0930", " ", "\\u0930", "\\u0939", "\\u0947", " ", "\\u0939", "\\u0948", "\\u0902", " ", "\\u0915", "\\u094D", "\\u092F", "\\u094B", "\\u0902", "\\u0915", "\\u093F", " ", "\\u0935", "\\u094B", " ", "\\u0928", "\\u0939", "\\u0940", "\\u0902", " ", "\\u091A", "\\u093E", "\\u0939", "\\u0924", "\\u0947", " ", "\\u0915", "\\u093F", " ", "\\u0915", "\\u094B", "\\u0908", " ", "\\u0914", "\\u0930", " ", "\\u092E", "\\u0941", "\\u0932", "\\u094D", "\\u0915", " ", "\\u0906", "\\u0917", "\\u0947", " ", "\\u092C", "\\u0922", "\\u093C", "\\u0947", "\\u0964", " ", "\\u0939", "\\u092E", "\\u093E", "\\u0930", "\\u0947", " ", "\\u0935", "\\u0948", "\\u091C", "\\u094D", "\\u091E", "\\u093E", "\\u0928", "\\u093F", "\\u0915", "\\u094B", "\\u0902", " ", "\\u0928", "\\u0947", " ", "\\u0907", "\\u0938", " ", "\\u0909", "\\u092A", "\\u0932", "\\u092C", "\\u094D", "\\u0927", "\\u093F", " ", "\\u0915", "\\u094B", " ", "\\u0939", "\\u093E", "\\u0938", "\\u093F", "\\u0932", " ", "\\u0915", "\\u0930", "\\u0928", "\\u0947", " ", "\\u092E", "\\u0947", "\\u0902", " ", "\\u092C", "\\u0939", "\\u0941", "\\u0924", " ", "\\u092E", "\\u0947", "\\u0939", "\\u0928", "\\u0924", " ", "\\u0915", "\\u0940", " ", "\\u0939", "\\u0948", "\\u0964", "\"", "}", ";", "assertLanguage", "(", "newdet", ",", "hindiStrings", ",", "new", "Locale", "(", "\"", "hi", "\"", ")", ")", ";", "}", "private", "void", "assertLanguage", "(", "LanguageDetector", "det", ",", "String", "[", "]", "statements", ",", "Locale", "language", ")", "{", "for", "(", "final", "String", "statement", ":", "statements", ")", "{", "final", "WeightedLocale", "estimateLanguage", "=", "det", ".", "classify", "(", "statement", ")", ";", "System", ".", "out", ".", "println", "(", "estimateLanguage", ")", ";", "Assert", ".", "assertEquals", "(", "language", ",", "estimateLanguage", ".", "getLocale", "(", ")", ")", ";", "}", "}", "}" ]
Test the language detector
[ "Test", "the", "language", "detector" ]
[ "// assertLanguage(det,hindiStrings,new Locale(\"hi\"));" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33cbc363984314c5dcb3e102b47bc01aaef32019
koendeschacht/smile
demo/src/main/java/smile/demo/plot/SparseMatrixPlotDemo.java
[ "Apache-2.0" ]
Java
SparseMatrixPlotDemo
/** * * @author Haifeng Li */
@author Haifeng Li
[ "@author", "Haifeng", "Li" ]
@SuppressWarnings("serial") public class SparseMatrixPlotDemo extends JPanel { public SparseMatrixPlotDemo() { super(new GridLayout(1,2)); SparseMatrixParser parser = new SparseMatrixParser(); try { SparseMatrix m1 = parser.parse(smile.data.parser.IOUtils.getTestDataFile("matrix/08blocks.txt")); PlotCanvas canvas = SparseMatrixPlot.plot(m1); canvas.setTitle("08blocks"); add(canvas); SparseMatrix m2 = parser.parse(smile.data.parser.IOUtils.getTestDataFile("matrix/mesh2em5.txt")); canvas = SparseMatrixPlot.plot(m2, Palette.jet(256)); canvas.setTitle("mesh2em5"); add(canvas); } catch (Exception ex) { System.err.println(ex); } } @Override public String toString() { return "Sparse Matrix Plot"; } public static void main(String[] args) { JFrame frame = new JFrame("Surface Plot"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.getContentPane().add(new SparseMatrixPlotDemo()); frame.setVisible(true); } }
[ "@", "SuppressWarnings", "(", "\"", "serial", "\"", ")", "public", "class", "SparseMatrixPlotDemo", "extends", "JPanel", "{", "public", "SparseMatrixPlotDemo", "(", ")", "{", "super", "(", "new", "GridLayout", "(", "1", ",", "2", ")", ")", ";", "SparseMatrixParser", "parser", "=", "new", "SparseMatrixParser", "(", ")", ";", "try", "{", "SparseMatrix", "m1", "=", "parser", ".", "parse", "(", "smile", ".", "data", ".", "parser", ".", "IOUtils", ".", "getTestDataFile", "(", "\"", "matrix/08blocks.txt", "\"", ")", ")", ";", "PlotCanvas", "canvas", "=", "SparseMatrixPlot", ".", "plot", "(", "m1", ")", ";", "canvas", ".", "setTitle", "(", "\"", "08blocks", "\"", ")", ";", "add", "(", "canvas", ")", ";", "SparseMatrix", "m2", "=", "parser", ".", "parse", "(", "smile", ".", "data", ".", "parser", ".", "IOUtils", ".", "getTestDataFile", "(", "\"", "matrix/mesh2em5.txt", "\"", ")", ")", ";", "canvas", "=", "SparseMatrixPlot", ".", "plot", "(", "m2", ",", "Palette", ".", "jet", "(", "256", ")", ")", ";", "canvas", ".", "setTitle", "(", "\"", "mesh2em5", "\"", ")", ";", "add", "(", "canvas", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "System", ".", "err", ".", "println", "(", "ex", ")", ";", "}", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "Sparse Matrix Plot", "\"", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "JFrame", "frame", "=", "new", "JFrame", "(", "\"", "Surface Plot", "\"", ")", ";", "frame", ".", "setDefaultCloseOperation", "(", "JFrame", ".", "EXIT_ON_CLOSE", ")", ";", "frame", ".", "setLocationRelativeTo", "(", "null", ")", ";", "frame", ".", "getContentPane", "(", ")", ".", "add", "(", "new", "SparseMatrixPlotDemo", "(", ")", ")", ";", "frame", ".", "setVisible", "(", "true", ")", ";", "}", "}" ]
@author Haifeng Li
[ "@author", "Haifeng", "Li" ]
[]
[ { "param": "JPanel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JPanel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33cc430f2c1687cc9c1054ba1b254c5ebdcb3d7b
Q115/Goalie
app/src/main/java/com/github/q115/goalie_android/ui/login/LoginFragmentPresenter.java
[ "Apache-2.0" ]
Java
LoginFragmentPresenter
/* * Copyright 2017 Qi Li * * 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. */
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "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 LoginFragmentPresenter implements BasePresenter { private final LoginFragmentView mLoginView; public LoginFragmentPresenter(@NonNull LoginFragmentView loginView) { mLoginView = loginView; mLoginView.setPresenter(this); } public void start() { } public void register(Context context, String username) { if (UserHelper.isUsernameValid(username)) { mLoginView.updateProgress(true); final String welcome = context.getString(R.string.welcome); final String usernameTaken = context.getString(R.string.username_taken); RESTRegister rest = new RESTRegister(username, PreferenceHelper.getInstance().getPushID()); rest.setListener(new RESTRegister.Listener() { @Override public void onSuccess() { mLoginView.updateProgress(false); mLoginView.registerComplete(true, welcome); } @Override public void onFailure(String errMsg) { if (errMsg.equals("Already Registered")) errMsg = usernameTaken; mLoginView.updateProgress(false); mLoginView.registerComplete(false, errMsg); } }); rest.execute(); } else mLoginView.registerComplete(false, context.getString(R.string.username_error)); } }
[ "public", "class", "LoginFragmentPresenter", "implements", "BasePresenter", "{", "private", "final", "LoginFragmentView", "mLoginView", ";", "public", "LoginFragmentPresenter", "(", "@", "NonNull", "LoginFragmentView", "loginView", ")", "{", "mLoginView", "=", "loginView", ";", "mLoginView", ".", "setPresenter", "(", "this", ")", ";", "}", "public", "void", "start", "(", ")", "{", "}", "public", "void", "register", "(", "Context", "context", ",", "String", "username", ")", "{", "if", "(", "UserHelper", ".", "isUsernameValid", "(", "username", ")", ")", "{", "mLoginView", ".", "updateProgress", "(", "true", ")", ";", "final", "String", "welcome", "=", "context", ".", "getString", "(", "R", ".", "string", ".", "welcome", ")", ";", "final", "String", "usernameTaken", "=", "context", ".", "getString", "(", "R", ".", "string", ".", "username_taken", ")", ";", "RESTRegister", "rest", "=", "new", "RESTRegister", "(", "username", ",", "PreferenceHelper", ".", "getInstance", "(", ")", ".", "getPushID", "(", ")", ")", ";", "rest", ".", "setListener", "(", "new", "RESTRegister", ".", "Listener", "(", ")", "{", "@", "Override", "public", "void", "onSuccess", "(", ")", "{", "mLoginView", ".", "updateProgress", "(", "false", ")", ";", "mLoginView", ".", "registerComplete", "(", "true", ",", "welcome", ")", ";", "}", "@", "Override", "public", "void", "onFailure", "(", "String", "errMsg", ")", "{", "if", "(", "errMsg", ".", "equals", "(", "\"", "Already Registered", "\"", ")", ")", "errMsg", "=", "usernameTaken", ";", "mLoginView", ".", "updateProgress", "(", "false", ")", ";", "mLoginView", ".", "registerComplete", "(", "false", ",", "errMsg", ")", ";", "}", "}", ")", ";", "rest", ".", "execute", "(", ")", ";", "}", "else", "mLoginView", ".", "registerComplete", "(", "false", ",", "context", ".", "getString", "(", "R", ".", "string", ".", "username_error", ")", ")", ";", "}", "}" ]
Copyright 2017 Qi Li Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
[ "Copyright", "2017", "Qi", "Li", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", "." ]
[]
[ { "param": "BasePresenter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BasePresenter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33d1d416c02134e5a1cd7583e727855e64872ad7
googlemaps/android-on-demand-rides-deliveries-samples
java/driver/src/main/java/com/google/mapsplatform/transportation/sample/driver/VehicleSimulator.java
[ "Apache-2.0" ]
Java
VehicleSimulator
/** * Commands to simulate the vehicle driving along a route. It interacts with the {@link Navigator} * to make the vehicle move along its route to a specified location. */
Commands to simulate the vehicle driving along a route. It interacts with the Navigator to make the vehicle move along its route to a specified location.
[ "Commands", "to", "simulate", "the", "vehicle", "driving", "along", "a", "route", ".", "It", "interacts", "with", "the", "Navigator", "to", "make", "the", "vehicle", "move", "along", "its", "route", "to", "a", "specified", "location", "." ]
class VehicleSimulator { private final Simulator simulator; VehicleSimulator(Simulator simulator) { this.simulator = simulator; } /** Sets the user location to be used for simulation. */ void setLocation(DriverTripConfig.Point location) { if (location != null) { simulator.setUserLocation(new LatLng(location.getLatitude(), location.getLongitude())); } } /** * Starts a simulation to the location defined by {@link #setLocation(DriverTripConfig.Point)} * along a route calculated by the Navigator. */ void start(float speedMultiplier) { simulator.simulateLocationsAlongExistingRoute( new SimulationOptions().speedMultiplier(speedMultiplier)); } /** Pauses a simulation that can later be resumed. */ void pause() { simulator.pause(); } /** Stops the current simulation. */ void unsetLocation() { simulator.unsetUserLocation(); } }
[ "class", "VehicleSimulator", "{", "private", "final", "Simulator", "simulator", ";", "VehicleSimulator", "(", "Simulator", "simulator", ")", "{", "this", ".", "simulator", "=", "simulator", ";", "}", "/** Sets the user location to be used for simulation. */", "void", "setLocation", "(", "DriverTripConfig", ".", "Point", "location", ")", "{", "if", "(", "location", "!=", "null", ")", "{", "simulator", ".", "setUserLocation", "(", "new", "LatLng", "(", "location", ".", "getLatitude", "(", ")", ",", "location", ".", "getLongitude", "(", ")", ")", ")", ";", "}", "}", "/**\n * Starts a simulation to the location defined by {@link #setLocation(DriverTripConfig.Point)}\n * along a route calculated by the Navigator.\n */", "void", "start", "(", "float", "speedMultiplier", ")", "{", "simulator", ".", "simulateLocationsAlongExistingRoute", "(", "new", "SimulationOptions", "(", ")", ".", "speedMultiplier", "(", "speedMultiplier", ")", ")", ";", "}", "/** Pauses a simulation that can later be resumed. */", "void", "pause", "(", ")", "{", "simulator", ".", "pause", "(", ")", ";", "}", "/** Stops the current simulation. */", "void", "unsetLocation", "(", ")", "{", "simulator", ".", "unsetUserLocation", "(", ")", ";", "}", "}" ]
Commands to simulate the vehicle driving along a route.
[ "Commands", "to", "simulate", "the", "vehicle", "driving", "along", "a", "route", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33d4e9ab58abfc39904b90645d3d797c714c1a54
xu6148152/binea_project
FitChart/app/src/main/java/demo/binea/com/fitchart/widget/FitChart.java
[ "MIT" ]
Java
FitChart
/** * Created by xubinggui on 7/7/15. */
Created by xubinggui on 7/7/15.
[ "Created", "by", "xubinggui", "on", "7", "/", "7", "/", "15", "." ]
public class FitChart extends View { private List<FitChartValue> mChartValues; private int mValueStrokeColor = getResources().getColor(R.color.default_chart_value_color); private int mBackStrokeColor = getResources().getColor(R.color.default_back_color); private int mStrokeSize = getResources().getDimensionPixelSize(R.dimen.default_stroke_size); private AnimationMode mAnimationMode = AnimationMode.LINEAR; private final int ANIMATION_MODE_LINEAR = 0; private final int ANIMATION_MODE_OVERDRAW = 1; private Paint mBackStrokePaint; private Paint mValueDesignPaint; private Path mBackPath = new Path(); private RectF mDrawingArea; private final int DEFAULT_VALUE_RADIUS = 0; private final int DEFAULT_MIN_VALUES = 0; private final int DEFAULT_MAX_VALUES = 100; public static final int START_ANGLE = -90; private final int ANIMATION_DURATION = 1000; private final float INITIAL_ANIMATION_PROGRESS = 0.0f; private final float MAXIMUM_SWEEP_ANGLE = 360f; private final int DESIGN_MODE_SWEEP_ANGLE = 216; private float mAnimationProgress = INITIAL_ANIMATION_PROGRESS; private float mMaxSweepAngle = MAXIMUM_SWEEP_ANGLE; private float mMinValue = DEFAULT_MIN_VALUES; private float mMaxValue = DEFAULT_MAX_VALUES; public FitChart(Context context) { this(context, null); } public FitChart(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FitChart(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initializeView(attrs); } private void initializeView(AttributeSet attrs) { mChartValues = new ArrayList<>(); initializeBackground(); readAttributes(attrs); initPaints(); } private void initPaints() { mBackStrokePaint = getPaint(); mBackStrokePaint.setColor(mBackStrokeColor); mBackStrokePaint.setStyle(Paint.Style.STROKE); mBackStrokePaint.setStrokeWidth(mStrokeSize); mValueDesignPaint = getPaint(); mValueDesignPaint.setColor(mValueStrokeColor); mValueDesignPaint.setStyle(Paint.Style.STROKE); mValueDesignPaint.setStrokeCap(Paint.Cap.ROUND); mValueDesignPaint.setStrokeJoin(Paint.Join.ROUND); mValueDesignPaint.setStrokeWidth(mStrokeSize); } private Paint getPaint() { if(!isInEditMode()){ return new Paint(Paint.ANTI_ALIAS_FLAG); } return new Paint(); } private void readAttributes(AttributeSet attrs) { if(null != attrs){ TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.FitChart, 0, 0); mStrokeSize = ta.getDimensionPixelSize(R.styleable.FitChart_strokeSize, mStrokeSize); mValueStrokeColor = ta.getColor(R.styleable.FitChart_valueStrokeColor, mValueStrokeColor); mBackStrokeColor = ta.getColor(R.styleable.FitChart_backStrokeColor, mBackStrokeColor); int animationMode = ta.getInteger(R.styleable.FitChart_animationMode, ANIMATION_MODE_LINEAR); if(animationMode == ANIMATION_MODE_LINEAR){ mAnimationMode = AnimationMode.LINEAR; }else{ mAnimationMode = AnimationMode.OVERDRAW; } ta.recycle(); } } private void initializeBackground() { if(!isInEditMode()){ if(getBackground() == null){ setBackgroundColor(getContext().getResources().getColor(R.color.default_back_color)); } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = Math.max(getMeasuredWidth(), getMeasuredHeight()); setMeasuredDimension(size, size); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); renderBack(canvas); renderValue(canvas); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); calculateDrawableArea(); } private void renderValue(Canvas canvas) { if(!isInEditMode()){ int valueCount = mChartValues.size() - 1; for(int index = valueCount; index >= 0; index--){ renderValue(canvas, mChartValues.get(index)); } }else{ renderValue(canvas, null); } } private void renderValue(Canvas canvas, FitChartValue fitChartValue) { if(!isInEditMode()){ float animationSeek = calculateAnimationSeek(); final Render renderer = RendererFactory.getRenderer(mAnimationMode, fitChartValue, mDrawingArea); final Path path = renderer.buildPath(mAnimationProgress, animationSeek); if(null != path){ canvas.drawPath(path, fitChartValue.getPaint()); } }else{ Path path = new Path(); path.addArc(mDrawingArea, START_ANGLE, DESIGN_MODE_SWEEP_ANGLE); canvas.drawPath(path, mValueDesignPaint); } } private float calculateAnimationSeek() { return mMaxSweepAngle * mAnimationProgress + START_ANGLE; } private void renderBack(Canvas canvas) { final float viewRadius = getViewRadius(); mBackPath.addCircle(mDrawingArea.centerX(), mDrawingArea.centerY(), viewRadius, Path.Direction.CW); canvas.drawPath(mBackPath, mBackStrokePaint); } private float getViewRadius(){ if(mDrawingArea != null){ return mDrawingArea.width() / 2; } return DEFAULT_VALUE_RADIUS; } public void setMinValue(float value){ mMinValue = value; } public void setMaxValue(float value){ mMaxValue = value; } public float getMinValue(){ return mMinValue; } public float getMaxValue(){ return mMaxValue; } public void setValue(float value){ mChartValues.clear(); FitChartValue chartValue = new FitChartValue(value, mValueStrokeColor); chartValue.setPaint(buildPaintForValue()); chartValue.setStartAngle(START_ANGLE); chartValue.setSweepAngle(calculateSweepAngle(value)); mChartValues.add(chartValue); mMaxSweepAngle = chartValue.getSweepAngle(); playAnimation(); } public void setValues(Collection<FitChartValue> values) { mChartValues.clear(); mMaxSweepAngle = 0; float offsetSweepAngle = START_ANGLE; for (FitChartValue chartValue : values) { float sweepAngle = calculateSweepAngle(chartValue.getValue()); chartValue.setPaint(buildPaintForValue()); chartValue.setStartAngle(offsetSweepAngle); chartValue.setSweepAngle(sweepAngle); mChartValues.add(chartValue); offsetSweepAngle += sweepAngle; mMaxSweepAngle += sweepAngle; } playAnimation(); } private void playAnimation() { final ObjectAnimator animator = ObjectAnimator.ofFloat(this, "animationSeek", 0.0f, 1.0f); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setDuration(ANIMATION_DURATION); animatorSet.setInterpolator(new DecelerateInterpolator()); animatorSet.setTarget(this); animatorSet.play(animator); animatorSet.start(); } private float calculateSweepAngle(float value) { float chartValueWindow = Math.max(mMinValue, mMaxValue) - Math.min(mMinValue, mMaxValue); float chartValueScale = (360f / chartValueWindow); return value * chartValueScale; } private Paint buildPaintForValue(){ Paint paint = getPaint(); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(mStrokeSize); paint.setStrokeCap(Paint.Cap.ROUND); return paint; } public void setAnimationMode(AnimationMode mode){ mAnimationMode = mode; } public void setAnimationSeek(float value){ mAnimationProgress = value; invalidate(); } private void calculateDrawableArea(){ float drawPadding = (mStrokeSize / 2); float width = getWidth(); float height = getHeight(); float left = drawPadding; float top = drawPadding; float right = width - drawPadding; float bottom = height - drawPadding; mDrawingArea = new RectF(left, top, right, bottom); } }
[ "public", "class", "FitChart", "extends", "View", "{", "private", "List", "<", "FitChartValue", ">", "mChartValues", ";", "private", "int", "mValueStrokeColor", "=", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "default_chart_value_color", ")", ";", "private", "int", "mBackStrokeColor", "=", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "default_back_color", ")", ";", "private", "int", "mStrokeSize", "=", "getResources", "(", ")", ".", "getDimensionPixelSize", "(", "R", ".", "dimen", ".", "default_stroke_size", ")", ";", "private", "AnimationMode", "mAnimationMode", "=", "AnimationMode", ".", "LINEAR", ";", "private", "final", "int", "ANIMATION_MODE_LINEAR", "=", "0", ";", "private", "final", "int", "ANIMATION_MODE_OVERDRAW", "=", "1", ";", "private", "Paint", "mBackStrokePaint", ";", "private", "Paint", "mValueDesignPaint", ";", "private", "Path", "mBackPath", "=", "new", "Path", "(", ")", ";", "private", "RectF", "mDrawingArea", ";", "private", "final", "int", "DEFAULT_VALUE_RADIUS", "=", "0", ";", "private", "final", "int", "DEFAULT_MIN_VALUES", "=", "0", ";", "private", "final", "int", "DEFAULT_MAX_VALUES", "=", "100", ";", "public", "static", "final", "int", "START_ANGLE", "=", "-", "90", ";", "private", "final", "int", "ANIMATION_DURATION", "=", "1000", ";", "private", "final", "float", "INITIAL_ANIMATION_PROGRESS", "=", "0.0f", ";", "private", "final", "float", "MAXIMUM_SWEEP_ANGLE", "=", "360f", ";", "private", "final", "int", "DESIGN_MODE_SWEEP_ANGLE", "=", "216", ";", "private", "float", "mAnimationProgress", "=", "INITIAL_ANIMATION_PROGRESS", ";", "private", "float", "mMaxSweepAngle", "=", "MAXIMUM_SWEEP_ANGLE", ";", "private", "float", "mMinValue", "=", "DEFAULT_MIN_VALUES", ";", "private", "float", "mMaxValue", "=", "DEFAULT_MAX_VALUES", ";", "public", "FitChart", "(", "Context", "context", ")", "{", "this", "(", "context", ",", "null", ")", ";", "}", "public", "FitChart", "(", "Context", "context", ",", "AttributeSet", "attrs", ")", "{", "this", "(", "context", ",", "attrs", ",", "0", ")", ";", "}", "public", "FitChart", "(", "Context", "context", ",", "AttributeSet", "attrs", ",", "int", "defStyleAttr", ")", "{", "super", "(", "context", ",", "attrs", ",", "defStyleAttr", ")", ";", "initializeView", "(", "attrs", ")", ";", "}", "private", "void", "initializeView", "(", "AttributeSet", "attrs", ")", "{", "mChartValues", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "initializeBackground", "(", ")", ";", "readAttributes", "(", "attrs", ")", ";", "initPaints", "(", ")", ";", "}", "private", "void", "initPaints", "(", ")", "{", "mBackStrokePaint", "=", "getPaint", "(", ")", ";", "mBackStrokePaint", ".", "setColor", "(", "mBackStrokeColor", ")", ";", "mBackStrokePaint", ".", "setStyle", "(", "Paint", ".", "Style", ".", "STROKE", ")", ";", "mBackStrokePaint", ".", "setStrokeWidth", "(", "mStrokeSize", ")", ";", "mValueDesignPaint", "=", "getPaint", "(", ")", ";", "mValueDesignPaint", ".", "setColor", "(", "mValueStrokeColor", ")", ";", "mValueDesignPaint", ".", "setStyle", "(", "Paint", ".", "Style", ".", "STROKE", ")", ";", "mValueDesignPaint", ".", "setStrokeCap", "(", "Paint", ".", "Cap", ".", "ROUND", ")", ";", "mValueDesignPaint", ".", "setStrokeJoin", "(", "Paint", ".", "Join", ".", "ROUND", ")", ";", "mValueDesignPaint", ".", "setStrokeWidth", "(", "mStrokeSize", ")", ";", "}", "private", "Paint", "getPaint", "(", ")", "{", "if", "(", "!", "isInEditMode", "(", ")", ")", "{", "return", "new", "Paint", "(", "Paint", ".", "ANTI_ALIAS_FLAG", ")", ";", "}", "return", "new", "Paint", "(", ")", ";", "}", "private", "void", "readAttributes", "(", "AttributeSet", "attrs", ")", "{", "if", "(", "null", "!=", "attrs", ")", "{", "TypedArray", "ta", "=", "getContext", "(", ")", ".", "getTheme", "(", ")", ".", "obtainStyledAttributes", "(", "attrs", ",", "R", ".", "styleable", ".", "FitChart", ",", "0", ",", "0", ")", ";", "mStrokeSize", "=", "ta", ".", "getDimensionPixelSize", "(", "R", ".", "styleable", ".", "FitChart_strokeSize", ",", "mStrokeSize", ")", ";", "mValueStrokeColor", "=", "ta", ".", "getColor", "(", "R", ".", "styleable", ".", "FitChart_valueStrokeColor", ",", "mValueStrokeColor", ")", ";", "mBackStrokeColor", "=", "ta", ".", "getColor", "(", "R", ".", "styleable", ".", "FitChart_backStrokeColor", ",", "mBackStrokeColor", ")", ";", "int", "animationMode", "=", "ta", ".", "getInteger", "(", "R", ".", "styleable", ".", "FitChart_animationMode", ",", "ANIMATION_MODE_LINEAR", ")", ";", "if", "(", "animationMode", "==", "ANIMATION_MODE_LINEAR", ")", "{", "mAnimationMode", "=", "AnimationMode", ".", "LINEAR", ";", "}", "else", "{", "mAnimationMode", "=", "AnimationMode", ".", "OVERDRAW", ";", "}", "ta", ".", "recycle", "(", ")", ";", "}", "}", "private", "void", "initializeBackground", "(", ")", "{", "if", "(", "!", "isInEditMode", "(", ")", ")", "{", "if", "(", "getBackground", "(", ")", "==", "null", ")", "{", "setBackgroundColor", "(", "getContext", "(", ")", ".", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "default_back_color", ")", ")", ";", "}", "}", "}", "@", "Override", "protected", "void", "onMeasure", "(", "int", "widthMeasureSpec", ",", "int", "heightMeasureSpec", ")", "{", "super", ".", "onMeasure", "(", "widthMeasureSpec", ",", "heightMeasureSpec", ")", ";", "int", "size", "=", "Math", ".", "max", "(", "getMeasuredWidth", "(", ")", ",", "getMeasuredHeight", "(", ")", ")", ";", "setMeasuredDimension", "(", "size", ",", "size", ")", ";", "}", "@", "Override", "protected", "void", "onDraw", "(", "Canvas", "canvas", ")", "{", "super", ".", "onDraw", "(", "canvas", ")", ";", "renderBack", "(", "canvas", ")", ";", "renderValue", "(", "canvas", ")", ";", "}", "@", "Override", "protected", "void", "onSizeChanged", "(", "int", "w", ",", "int", "h", ",", "int", "oldw", ",", "int", "oldh", ")", "{", "super", ".", "onSizeChanged", "(", "w", ",", "h", ",", "oldw", ",", "oldh", ")", ";", "calculateDrawableArea", "(", ")", ";", "}", "private", "void", "renderValue", "(", "Canvas", "canvas", ")", "{", "if", "(", "!", "isInEditMode", "(", ")", ")", "{", "int", "valueCount", "=", "mChartValues", ".", "size", "(", ")", "-", "1", ";", "for", "(", "int", "index", "=", "valueCount", ";", "index", ">=", "0", ";", "index", "--", ")", "{", "renderValue", "(", "canvas", ",", "mChartValues", ".", "get", "(", "index", ")", ")", ";", "}", "}", "else", "{", "renderValue", "(", "canvas", ",", "null", ")", ";", "}", "}", "private", "void", "renderValue", "(", "Canvas", "canvas", ",", "FitChartValue", "fitChartValue", ")", "{", "if", "(", "!", "isInEditMode", "(", ")", ")", "{", "float", "animationSeek", "=", "calculateAnimationSeek", "(", ")", ";", "final", "Render", "renderer", "=", "RendererFactory", ".", "getRenderer", "(", "mAnimationMode", ",", "fitChartValue", ",", "mDrawingArea", ")", ";", "final", "Path", "path", "=", "renderer", ".", "buildPath", "(", "mAnimationProgress", ",", "animationSeek", ")", ";", "if", "(", "null", "!=", "path", ")", "{", "canvas", ".", "drawPath", "(", "path", ",", "fitChartValue", ".", "getPaint", "(", ")", ")", ";", "}", "}", "else", "{", "Path", "path", "=", "new", "Path", "(", ")", ";", "path", ".", "addArc", "(", "mDrawingArea", ",", "START_ANGLE", ",", "DESIGN_MODE_SWEEP_ANGLE", ")", ";", "canvas", ".", "drawPath", "(", "path", ",", "mValueDesignPaint", ")", ";", "}", "}", "private", "float", "calculateAnimationSeek", "(", ")", "{", "return", "mMaxSweepAngle", "*", "mAnimationProgress", "+", "START_ANGLE", ";", "}", "private", "void", "renderBack", "(", "Canvas", "canvas", ")", "{", "final", "float", "viewRadius", "=", "getViewRadius", "(", ")", ";", "mBackPath", ".", "addCircle", "(", "mDrawingArea", ".", "centerX", "(", ")", ",", "mDrawingArea", ".", "centerY", "(", ")", ",", "viewRadius", ",", "Path", ".", "Direction", ".", "CW", ")", ";", "canvas", ".", "drawPath", "(", "mBackPath", ",", "mBackStrokePaint", ")", ";", "}", "private", "float", "getViewRadius", "(", ")", "{", "if", "(", "mDrawingArea", "!=", "null", ")", "{", "return", "mDrawingArea", ".", "width", "(", ")", "/", "2", ";", "}", "return", "DEFAULT_VALUE_RADIUS", ";", "}", "public", "void", "setMinValue", "(", "float", "value", ")", "{", "mMinValue", "=", "value", ";", "}", "public", "void", "setMaxValue", "(", "float", "value", ")", "{", "mMaxValue", "=", "value", ";", "}", "public", "float", "getMinValue", "(", ")", "{", "return", "mMinValue", ";", "}", "public", "float", "getMaxValue", "(", ")", "{", "return", "mMaxValue", ";", "}", "public", "void", "setValue", "(", "float", "value", ")", "{", "mChartValues", ".", "clear", "(", ")", ";", "FitChartValue", "chartValue", "=", "new", "FitChartValue", "(", "value", ",", "mValueStrokeColor", ")", ";", "chartValue", ".", "setPaint", "(", "buildPaintForValue", "(", ")", ")", ";", "chartValue", ".", "setStartAngle", "(", "START_ANGLE", ")", ";", "chartValue", ".", "setSweepAngle", "(", "calculateSweepAngle", "(", "value", ")", ")", ";", "mChartValues", ".", "add", "(", "chartValue", ")", ";", "mMaxSweepAngle", "=", "chartValue", ".", "getSweepAngle", "(", ")", ";", "playAnimation", "(", ")", ";", "}", "public", "void", "setValues", "(", "Collection", "<", "FitChartValue", ">", "values", ")", "{", "mChartValues", ".", "clear", "(", ")", ";", "mMaxSweepAngle", "=", "0", ";", "float", "offsetSweepAngle", "=", "START_ANGLE", ";", "for", "(", "FitChartValue", "chartValue", ":", "values", ")", "{", "float", "sweepAngle", "=", "calculateSweepAngle", "(", "chartValue", ".", "getValue", "(", ")", ")", ";", "chartValue", ".", "setPaint", "(", "buildPaintForValue", "(", ")", ")", ";", "chartValue", ".", "setStartAngle", "(", "offsetSweepAngle", ")", ";", "chartValue", ".", "setSweepAngle", "(", "sweepAngle", ")", ";", "mChartValues", ".", "add", "(", "chartValue", ")", ";", "offsetSweepAngle", "+=", "sweepAngle", ";", "mMaxSweepAngle", "+=", "sweepAngle", ";", "}", "playAnimation", "(", ")", ";", "}", "private", "void", "playAnimation", "(", ")", "{", "final", "ObjectAnimator", "animator", "=", "ObjectAnimator", ".", "ofFloat", "(", "this", ",", "\"", "animationSeek", "\"", ",", "0.0f", ",", "1.0f", ")", ";", "AnimatorSet", "animatorSet", "=", "new", "AnimatorSet", "(", ")", ";", "animatorSet", ".", "setDuration", "(", "ANIMATION_DURATION", ")", ";", "animatorSet", ".", "setInterpolator", "(", "new", "DecelerateInterpolator", "(", ")", ")", ";", "animatorSet", ".", "setTarget", "(", "this", ")", ";", "animatorSet", ".", "play", "(", "animator", ")", ";", "animatorSet", ".", "start", "(", ")", ";", "}", "private", "float", "calculateSweepAngle", "(", "float", "value", ")", "{", "float", "chartValueWindow", "=", "Math", ".", "max", "(", "mMinValue", ",", "mMaxValue", ")", "-", "Math", ".", "min", "(", "mMinValue", ",", "mMaxValue", ")", ";", "float", "chartValueScale", "=", "(", "360f", "/", "chartValueWindow", ")", ";", "return", "value", "*", "chartValueScale", ";", "}", "private", "Paint", "buildPaintForValue", "(", ")", "{", "Paint", "paint", "=", "getPaint", "(", ")", ";", "paint", ".", "setStyle", "(", "Paint", ".", "Style", ".", "STROKE", ")", ";", "paint", ".", "setStrokeWidth", "(", "mStrokeSize", ")", ";", "paint", ".", "setStrokeCap", "(", "Paint", ".", "Cap", ".", "ROUND", ")", ";", "return", "paint", ";", "}", "public", "void", "setAnimationMode", "(", "AnimationMode", "mode", ")", "{", "mAnimationMode", "=", "mode", ";", "}", "public", "void", "setAnimationSeek", "(", "float", "value", ")", "{", "mAnimationProgress", "=", "value", ";", "invalidate", "(", ")", ";", "}", "private", "void", "calculateDrawableArea", "(", ")", "{", "float", "drawPadding", "=", "(", "mStrokeSize", "/", "2", ")", ";", "float", "width", "=", "getWidth", "(", ")", ";", "float", "height", "=", "getHeight", "(", ")", ";", "float", "left", "=", "drawPadding", ";", "float", "top", "=", "drawPadding", ";", "float", "right", "=", "width", "-", "drawPadding", ";", "float", "bottom", "=", "height", "-", "drawPadding", ";", "mDrawingArea", "=", "new", "RectF", "(", "left", ",", "top", ",", "right", ",", "bottom", ")", ";", "}", "}" ]
Created by xubinggui on 7/7/15.
[ "Created", "by", "xubinggui", "on", "7", "/", "7", "/", "15", "." ]
[]
[ { "param": "View", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "View", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33d9cba0c63737b45fae9518d18cd756e25a086f
jharting/undertow
core/src/main/java/io/undertow/websockets/core/protocol/version00/WebSocket00CloseFrameSinkChannel.java
[ "Apache-2.0" ]
Java
WebSocket00CloseFrameSinkChannel
/** * {@link StreamSinkFrameChannel} implementation for writing {@link WebSocketFrameType#CLOSE} * * @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a> */
StreamSinkFrameChannel implementation for writing WebSocketFrameType#CLOSE @author Norman Maurer
[ "StreamSinkFrameChannel", "implementation", "for", "writing", "WebSocketFrameType#CLOSE", "@author", "Norman", "Maurer" ]
class WebSocket00CloseFrameSinkChannel extends StreamSinkFrameChannel { private static final ByteBuffer END = ByteBuffer.allocateDirect(2).put((byte) 0xFF).put((byte) 0x00); WebSocket00CloseFrameSinkChannel(StreamSinkChannel channel, WebSocket00Channel wsChannel) { super(channel, wsChannel, WebSocketFrameType.CLOSE, 0); } @Override protected long write0(ByteBuffer[] srcs, int offset, int length) throws IOException { throw WebSocketMessages.MESSAGES.payloadNotSupportedInCloseFrames(); } @Override protected long transferFrom0(FileChannel src, long position, long count) throws IOException { throw WebSocketMessages.MESSAGES.payloadNotSupportedInCloseFrames(); } @Override protected ByteBuffer createFrameStart() { return Buffers.EMPTY_BYTE_BUFFER; } @Override protected ByteBuffer createFrameEnd() { return END.duplicate(); } }
[ "class", "WebSocket00CloseFrameSinkChannel", "extends", "StreamSinkFrameChannel", "{", "private", "static", "final", "ByteBuffer", "END", "=", "ByteBuffer", ".", "allocateDirect", "(", "2", ")", ".", "put", "(", "(", "byte", ")", "0xFF", ")", ".", "put", "(", "(", "byte", ")", "0x00", ")", ";", "WebSocket00CloseFrameSinkChannel", "(", "StreamSinkChannel", "channel", ",", "WebSocket00Channel", "wsChannel", ")", "{", "super", "(", "channel", ",", "wsChannel", ",", "WebSocketFrameType", ".", "CLOSE", ",", "0", ")", ";", "}", "@", "Override", "protected", "long", "write0", "(", "ByteBuffer", "[", "]", "srcs", ",", "int", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "throw", "WebSocketMessages", ".", "MESSAGES", ".", "payloadNotSupportedInCloseFrames", "(", ")", ";", "}", "@", "Override", "protected", "long", "transferFrom0", "(", "FileChannel", "src", ",", "long", "position", ",", "long", "count", ")", "throws", "IOException", "{", "throw", "WebSocketMessages", ".", "MESSAGES", ".", "payloadNotSupportedInCloseFrames", "(", ")", ";", "}", "@", "Override", "protected", "ByteBuffer", "createFrameStart", "(", ")", "{", "return", "Buffers", ".", "EMPTY_BYTE_BUFFER", ";", "}", "@", "Override", "protected", "ByteBuffer", "createFrameEnd", "(", ")", "{", "return", "END", ".", "duplicate", "(", ")", ";", "}", "}" ]
{@link StreamSinkFrameChannel} implementation for writing {@link WebSocketFrameType#CLOSE} @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a>
[ "{", "@link", "StreamSinkFrameChannel", "}", "implementation", "for", "writing", "{", "@link", "WebSocketFrameType#CLOSE", "}", "@author", "<a", "href", "=", "\"", "mailto", ":", "nmaurer@redhat", ".", "com", "\"", ">", "Norman", "Maurer<", "/", "a", ">" ]
[]
[ { "param": "StreamSinkFrameChannel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "StreamSinkFrameChannel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33e5b8cc249bd00f125b7139ef19ed208ba2f27a
DanIulian/PeerToPeer-Torrent-Client
src/comm_proto/FileDescription.java
[ "MIT" ]
Java
FileDescription
/* * This class is serialized and sent across the network * when a client first publish a file to the central node * It contains information about the file name, the file size, * the size of the first fragment of the file, and lastly the ip * address of the client which publish the file */
This class is serialized and sent across the network when a client first publish a file to the central node It contains information about the file name, the file size, the size of the first fragment of the file, and lastly the ip address of the client which publish the file
[ "This", "class", "is", "serialized", "and", "sent", "across", "the", "network", "when", "a", "client", "first", "publish", "a", "file", "to", "the", "central", "node", "It", "contains", "information", "about", "the", "file", "name", "the", "file", "size", "the", "size", "of", "the", "first", "fragment", "of", "the", "file", "and", "lastly", "the", "ip", "address", "of", "the", "client", "which", "publish", "the", "file" ]
public class FileDescription implements Serializable { public static final long serialVersionUID = 5184014079797152383L; public String clientIPAddress; public String fileName; public int fileSize; public int firstFragmentSize; public FileDescription(String ipAdd, String fileName, int fileSize, int firstFragmentSize){ this.fileName = fileName; this.fileSize = fileSize; this.firstFragmentSize = firstFragmentSize; this.clientIPAddress = ipAdd; } @Override public String toString() { return "FileDescription [clientIPAddress=" + clientIPAddress + ", fileName=" + fileName + ", fileSize=" + fileSize + ", firstFragmentSize=" + firstFragmentSize + "]"; } }
[ "public", "class", "FileDescription", "implements", "Serializable", "{", "public", "static", "final", "long", "serialVersionUID", "=", "5184014079797152383L", ";", "public", "String", "clientIPAddress", ";", "public", "String", "fileName", ";", "public", "int", "fileSize", ";", "public", "int", "firstFragmentSize", ";", "public", "FileDescription", "(", "String", "ipAdd", ",", "String", "fileName", ",", "int", "fileSize", ",", "int", "firstFragmentSize", ")", "{", "this", ".", "fileName", "=", "fileName", ";", "this", ".", "fileSize", "=", "fileSize", ";", "this", ".", "firstFragmentSize", "=", "firstFragmentSize", ";", "this", ".", "clientIPAddress", "=", "ipAdd", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "FileDescription [clientIPAddress=", "\"", "+", "clientIPAddress", "+", "\"", ", fileName=", "\"", "+", "fileName", "+", "\"", ", fileSize=", "\"", "+", "fileSize", "+", "\"", ", firstFragmentSize=", "\"", "+", "firstFragmentSize", "+", "\"", "]", "\"", ";", "}", "}" ]
This class is serialized and sent across the network when a client first publish a file to the central node It contains information about the file name, the file size, the size of the first fragment of the file, and lastly the ip address of the client which publish the file
[ "This", "class", "is", "serialized", "and", "sent", "across", "the", "network", "when", "a", "client", "first", "publish", "a", "file", "to", "the", "central", "node", "It", "contains", "information", "about", "the", "file", "name", "the", "file", "size", "the", "size", "of", "the", "first", "fragment", "of", "the", "file", "and", "lastly", "the", "ip", "address", "of", "the", "client", "which", "publish", "the", "file" ]
[]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33eb8cfe0a078a366b29e90e6a83722bcd44dac0
sigurasg/ghidra
Ghidra/Features/Base/src/main/java/ghidra/plugins/importer/batch/BatchInfo.java
[ "Apache-2.0" ]
Java
BatchInfo
/** * This is the main state of a batch import task, containing the segregated groupings of * applications. * <p> * This class also handles populating the batch groups by recursively descending into files * and the contents of those files. */
This is the main state of a batch import task, containing the segregated groupings of applications. This class also handles populating the batch groups by recursively descending into files and the contents of those files.
[ "This", "is", "the", "main", "state", "of", "a", "batch", "import", "task", "containing", "the", "segregated", "groupings", "of", "applications", ".", "This", "class", "also", "handles", "populating", "the", "batch", "groups", "by", "recursively", "descending", "into", "files", "and", "the", "contents", "of", "those", "files", "." ]
public class BatchInfo { public static final int MAXDEPTH_UNLIMITED = -1; public static final int MAXDEPTH_DEFAULT = 2; private FileSystemService fsService = FileSystemService.getInstance(); /* * These structures need to be synchronized to ensure thread visibility, since they are * written to by a background thread and read from the Swing thread. * * For now, concurrent modification is not an issue, since the client does not read from * these structures while they are being written, as the writes happen during a blocking * operation. */ private Map<BatchSegregatingCriteria, BatchGroup> groupsByCriteria = Collections.synchronizedMap(new HashMap<>()); private Set<FSRL> userAddedFSRLs = Collections.synchronizedSet(new HashSet<>()); private List<UserAddedSourceInfo> userAddedSources = Collections.synchronizedList(new ArrayList<>()); /** * Maximum depth of containers (ie. filesystems) to recurse into when processing * a file added by the user. * <p> * maxDepth of less than or equal to 0 == unlimited. * <p> * maxDepth of 1 == no recursing into containers found in added file, just try it * with a loader. * <p> * Default is {@link #MAXDEPTH_DEFAULT}. */ private int maxDepth; private UserAddedSourceInfo currentUASI; /** * Creates a new BatchInfo object with a default {@link #maxDepth}. */ public BatchInfo() { this(MAXDEPTH_DEFAULT); } /** * Creates a new BatchInfo object using the specified maxDepth. * * @param maxDepth see {@link #maxDepth}. */ public BatchInfo(int maxDepth) { this.maxDepth = maxDepth; } /** * Returns a list of the {@link BatchGroup}s that have been found when processing * the added files. * * @return {@link List} of {@link BatchGroup}s. */ public List<BatchGroup> getGroups() { return new ArrayList<>(groupsByCriteria.values()); } /** * Returns the count of how many importable objects (ie. {@link LoadSpec}s) were found. * * @return count of importable objects. */ public int getTotalCount() { int count = 0; for (BatchGroup batchGroup : groupsByCriteria.values()) { count += batchGroup.getBatchLoadConfig().size(); } return count; } /** * Returns the count of how many files were found while processing the source files. * * @return count of files found while processing source files. */ public int getTotalRawCount() { int count = 0; for (UserAddedSourceInfo uasi : userAddedSources) { count += uasi.getRawFileCount(); } return count; } /** * Returns the count of applications in enabled {@link BatchGroup}s... in other * words, the number of objects that would be imported during this batch. * * @return count of enabled applications. */ public int getEnabledCount() { int count = 0; for (BatchGroup batchGroup : groupsByCriteria.values()) { if (batchGroup.isEnabled()) { count += batchGroup.getBatchLoadConfig().size(); } } return count; } /** * Removes a user-added source file (and all the embedded files inside it) from this * batch. * * @param fsrl {@link FSRL} of the file to remove. */ public void remove(FSRL fsrl) { for (Iterator<Entry<BatchSegregatingCriteria, BatchGroup>> iterator = groupsByCriteria.entrySet().iterator(); iterator.hasNext();) { Entry<BatchSegregatingCriteria, BatchGroup> entry = iterator.next(); BatchGroup bg = entry.getValue(); bg.removeDescendantsOf(fsrl); if (bg.isEmpty()) { iterator.remove(); } } for (Iterator<UserAddedSourceInfo> iterator = userAddedSources.iterator(); iterator.hasNext();) { UserAddedSourceInfo uasi = iterator.next(); if (uasi.getFSRL().equals(fsrl)) { iterator.remove(); } } userAddedFSRLs.remove(fsrl); } /** * Adds a file to this batch as the direct result of a user action. * <p> * If the file is a container for other files, this method will iterate through those * child files and recursively try to add them using this method. * <p> * @param fsrl {@link FSRL} of the file to add. * @param taskMonitor {@link TaskMonitor} to watch and update with progress. * @return boolean true if something in the the file produced something to import. * @throws IOException if io error when reading files. * @throws CancelledException if user cancels. */ public boolean addFile(FSRL fsrl, TaskMonitor taskMonitor) throws IOException, CancelledException { fsrl = fsService.getFullyQualifiedFSRL(fsrl, taskMonitor); if (userAddedFSRLs.contains(fsrl)) { throw new IOException("Batch already contains file " + fsrl); } currentUASI = new UserAddedSourceInfo(fsrl); userAddedSources.add(currentUASI); userAddedFSRLs.add(currentUASI.getFSRL()); int startCount = getTotalCount(); boolean result = doAddFile(fsrl, taskMonitor); int endCount = getTotalCount(); currentUASI.setFileCount(endCount - startCount); return result; } /** * The main worker for adding a file to the batch session. * <p> * The file is probed for high-priority filesystems first, then if no matches, * Ghidra loaders, and then if no matches, all filesystems. * <p> * @param fsrl {@link FSRL} of the file to probe and process * @param taskMonitor {@link TaskMonitor} to watch and update. * @return boolean true if something in the the file produced something to import. * @throws IOException if io error when reading files. * @throws CancelledException if user cancels. */ private boolean doAddFile(FSRL fsrl, TaskMonitor taskMonitor) throws IOException, CancelledException { // use the fsrl param instead of file.getFSRL() as param may have more info (ie. md5) try (RefdFile refdFile = fsService.getRefdFile(fsrl, taskMonitor)) { GFile file = refdFile.file; if (file.isDirectory()) { processFS(file.getFilesystem(), file, taskMonitor); return true; } if (processAsFS(fsrl, taskMonitor)) { return true; } if (processWithLoader(fsrl, taskMonitor)) { return true; } // the file was not of interest, let it be removed from the cache fsService.releaseFileCache(fsrl); return false; } } private boolean shouldTerminateRecurse(FSRL fsrl) { if (maxDepth <= 0) { return false; } int initialLevel = currentUASI.getFSRL().getNestingDepth(); int fsrlLevel = fsrl.getNestingDepth(); return (fsrlLevel - initialLevel) > maxDepth - 1; } /** * Returns true if any of the user source files had containers that were not * recursed into because of the {@link #maxDepth} limit. * * @return true if any of the user source files had containers that were not * recursed into because of the {@link #maxDepth} limit. */ public boolean wasRecurseTerminatedEarly() { for (UserAddedSourceInfo uasi : userAddedSources) { if (uasi.wasRecurseTerminatedEarly()) { return true; } } return false; } /** * Checks the found applications and returns true if only a single binary was found, * even if multiple loaders claim it. * * @return true if single binary and batch is probably not correct importer. */ public boolean isSingleApp() { Set<String> foundLoaders = new HashSet<>(); for (BatchGroup group : groupsByCriteria.values()) { for (BatchLoadConfig batchLoadConfig : group.getBatchLoadConfig()) { String loaderID = batchLoadConfig.getLoadSpecs().iterator().next().getLoader().getName(); if (!foundLoaders.add(loaderID)) { return false; } } } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (BatchGroup similarApps : groupsByCriteria.values()) { sb.append(similarApps.toString()); sb.append("\n"); } return sb.toString(); } private boolean processAsFS(FSRL fsrl, TaskMonitor taskMonitor) throws CancelledException { try (FileSystemRef fsRef = fsService.probeFileForFilesystem(fsrl, taskMonitor, FileSystemProbeConflictResolver.CHOOSEFIRST)) { if (fsRef == null) { return false; } GFileSystem fs = fsRef.getFilesystem(); currentUASI.incContainerCount(); if (shouldTerminateRecurse(fs.getFSRL())) { currentUASI.setRecurseTerminatedEarly(true); return true; } currentUASI.setMaxNestLevel( Math.max(currentUASI.getMaxNestLevel(), fs.getFSRL().getNestingDepth())); processFS(fs, null, taskMonitor); return true; } catch (IOException ioe) { Msg.warn(this, "Error while probing file " + fsrl + " for filesystems: " + ioe.getMessage()); return false; } } /** * Recursively handles files in an already opened GFileSystem. * @param fs {@link GFileSystem} containing the startDir * @param startDir {@link GFile} ref to the directory to process, null if root of the filesystem. * @param taskMonitor {@link TaskMonitor} to watch and update. * @throws CancelledException if user cancels * @throws IOException if io error while reading files. */ private void processFS(GFileSystem fs, GFile startDir, TaskMonitor taskMonitor) throws CancelledException, IOException { // TODO: drop FSUtils.listFileSystem and do recursion here. for (GFile file : FSUtilities.listFileSystem(fs, startDir, null, taskMonitor)) { taskMonitor.checkCanceled(); FSRL fqFSRL; try { fqFSRL = fsService.getFullyQualifiedFSRL(file.getFSRL(), taskMonitor); } catch (IOException e) { Msg.warn(this, "Error getting info for " + file.getFSRL()); continue; } doAddFile(fqFSRL, taskMonitor); currentUASI.incRawFileCount(); } } /** * Tries to open a file using Ghidra {@link Loader}s. * <p> * The {@link BinaryLoader} is unconditionally skipped. * * @param fsrl {@link FSRL} of the file to open * @param monitor {@link TaskMonitor} to use * @return boolean true if successfully processed with a loader, false if no loader claimed * the file. * @throws IOException if io error during processing * @throws CancelledException if user cancels. */ private boolean processWithLoader(FSRL fsrl, TaskMonitor monitor) throws IOException, CancelledException { try (ByteProvider provider = fsService.getByteProvider(fsrl, false, monitor)) { LoaderMap loaderMap = pollLoadersForLoadSpecs(provider, fsrl, monitor); for (Loader loader : loaderMap.keySet()) { Collection<LoadSpec> loadSpecs = loaderMap.get(loader); BatchSegregatingCriteria bsc = new BatchSegregatingCriteria(loader, loadSpecs, provider); BatchGroup batchGroup = groupsByCriteria.get(bsc); if (batchGroup == null) { batchGroup = new BatchGroup(bsc); groupsByCriteria.put(bsc, batchGroup); } batchGroup.add(provider, loadSpecs, fsrl, currentUASI); } return loaderMap.keySet().size() > 0; } catch (IOException ioe) { Msg.warn(this, "Error while probing file " + fsrl + " for loader applications: " + ioe.getMessage()); return false; } } private LoaderMap pollLoadersForLoadSpecs(ByteProvider provider, FSRL fsrl, TaskMonitor monitor) { monitor.setMessage(fsrl.getName()); return LoaderService.getSupportedLoadSpecs(provider, loader -> !(loader instanceof BinaryLoader)); } /** * Returns the {@link List} of files added via {@link #addFile(FSRL, TaskMonitor)}. * * @return {@link List} of files added via {@link #addFile(FSRL, TaskMonitor)}. */ public List<UserAddedSourceInfo> getUserAddedSources() { return userAddedSources; } /** * Maximum depth of containers (ie. filesystems) to recurse into when processing * a file added by the user * * @return the current maximum depth of containers (ie. filesystems) to recurse into when processing * a file added by the user. */ public int getMaxDepth() { return maxDepth; } /** * Sets a new max container recursive depth limit for this batch import * <p> * Doing this requires rescanning all original user-added source files and stopping * at the new max depth. * <p> * @param newMaxDepth new value for the max depth */ public void setMaxDepth(int newMaxDepth) { //@formatter:off new TaskBuilder("Scanning Source Files", monitor -> doSetMaxDepth(newMaxDepth, monitor)) .setStatusTextAlignment(SwingConstants.LEADING) .setHasProgress(false) // indeterminate .launchModal() ; //@formatter:on } /** * Adds the given files to this batch import * * @param filesToAdd the files to add * @return any files that failed to load; exceptions will be logged */ List<FSRL> addFiles(List<FSRL> filesToAdd) { //@formatter:off AddFilesRunnable runnable = new AddFilesRunnable(filesToAdd); new TaskBuilder("Adding Source Files", runnable) .setStatusTextAlignment(SwingConstants.LEADING) .setHasProgress(false) // indeterminate .launchModal() ; //@formatter:on return runnable.getBadFiles(); } private void doSetMaxDepth(int newMaxDepth, TaskMonitor monitor) { if (newMaxDepth == maxDepth) { return; } // TODO: make this smarter and when switching from higher maxDepth to lower, // just remove existing files that are deeper. Recalculating user added source info // number is hard so I'm skipping it now. Msg.trace(this, "Switching maxDepth from " + maxDepth + " to " + newMaxDepth); //@formatter:off List<FSRL> files = userAddedSources .stream() .map(source -> { return source.getFSRL(); }) .collect(Collectors.toList()) ; //@formatter:on groupsByCriteria.clear(); userAddedSources.clear(); userAddedFSRLs.clear(); maxDepth = newMaxDepth; doAddFiles(files, monitor); } private List<FSRL> doAddFiles(List<FSRL> filesToAdd, TaskMonitor monitor) { BatchTaskMonitor batchMonitor = new BatchTaskMonitor(monitor); // start a new CryptoSession to group all password prompting by multiple container // files into a single session, enabling "Cancel All" to really cancel all password // prompts try (CryptoSession cryptoSession = fsService.newCryptoSession()) { List<FSRL> badFiles = new ArrayList<>(); for (FSRL fsrl : filesToAdd) { Msg.trace(this, "Adding " + fsrl); batchMonitor.setPrefix("Processing " + fsrl.getName() + ": "); try { monitor.checkCanceled(); addFile(fsrl, batchMonitor); } catch (CryptoException ce) { FSUtilities.displayException(this, null, "Error Adding File To Batch Import", "Error while adding " + fsrl.getName() + " to batch import", ce); } catch (IOException ioe) { Msg.error(this, "Error while adding " + fsrl.getName() + " to batch import", ioe); badFiles.add(fsrl); } catch (CancelledException e) { Msg.debug(this, "Cancelling Add File task while adding " + fsrl.getName()); // Note: the workflow for this felt odd: press cancel; confirm cancel; press Ok // on dialog showing files not processed. // It seems like the user should not have to see the second dialog // badFiles.addAll(filesToAdd.subList(i, filesToAdd.size())); } } return badFiles; } } //================================================================================================== // Inner Classes //================================================================================================== private class AddFilesRunnable implements MonitoredRunnable { private List<FSRL> files; private List<FSRL> badFiles; AddFilesRunnable(List<FSRL> files) { this.files = files; } @Override public void monitoredRun(TaskMonitor monitor) { badFiles = doAddFiles(files, monitor); } List<FSRL> getBadFiles() { return badFiles; } } /** A task monitor that allows us to control the message content and the progress */ private class BatchTaskMonitor extends WrappingTaskMonitor { private String prefix; BatchTaskMonitor(TaskMonitor delegate) { super(delegate); } void setPrefix(String prefix) { this.prefix = prefix; } @Override public void setMessage(String message) { super.setMessage(prefix + " " + message); } @Override public void initialize(long max) { // we control the max value } @Override public void setProgress(long value) { // we control the progress } } }
[ "public", "class", "BatchInfo", "{", "public", "static", "final", "int", "MAXDEPTH_UNLIMITED", "=", "-", "1", ";", "public", "static", "final", "int", "MAXDEPTH_DEFAULT", "=", "2", ";", "private", "FileSystemService", "fsService", "=", "FileSystemService", ".", "getInstance", "(", ")", ";", "/*\n\t * These structures need to be synchronized to ensure thread visibility, since they are \n\t * written to by a background thread and read from the Swing thread. \n\t * \n\t * For now, concurrent modification is not an issue, since the client does not read from\n\t * these structures while they are being written, as the writes happen during a blocking\n\t * operation.\n\t */", "private", "Map", "<", "BatchSegregatingCriteria", ",", "BatchGroup", ">", "groupsByCriteria", "=", "Collections", ".", "synchronizedMap", "(", "new", "HashMap", "<", ">", "(", ")", ")", ";", "private", "Set", "<", "FSRL", ">", "userAddedFSRLs", "=", "Collections", ".", "synchronizedSet", "(", "new", "HashSet", "<", ">", "(", ")", ")", ";", "private", "List", "<", "UserAddedSourceInfo", ">", "userAddedSources", "=", "Collections", ".", "synchronizedList", "(", "new", "ArrayList", "<", ">", "(", ")", ")", ";", "/**\n\t * Maximum depth of containers (ie. filesystems) to recurse into when processing\n\t * a file added by the user.\n\t * <p>\n\t * maxDepth of less than or equal to 0 == unlimited.\n\t * <p>\n\t * maxDepth of 1 == no recursing into containers found in added file, just try it\n\t * with a loader.\n\t * <p>\n\t * Default is {@link #MAXDEPTH_DEFAULT}.\n\t */", "private", "int", "maxDepth", ";", "private", "UserAddedSourceInfo", "currentUASI", ";", "/**\n\t * Creates a new BatchInfo object with a default {@link #maxDepth}.\n\t */", "public", "BatchInfo", "(", ")", "{", "this", "(", "MAXDEPTH_DEFAULT", ")", ";", "}", "/**\n\t * Creates a new BatchInfo object using the specified maxDepth.\n\t *\n\t * @param maxDepth see {@link #maxDepth}.\n\t */", "public", "BatchInfo", "(", "int", "maxDepth", ")", "{", "this", ".", "maxDepth", "=", "maxDepth", ";", "}", "/**\n\t * Returns a list of the {@link BatchGroup}s that have been found when processing\n\t * the added files.\n\t *\n\t * @return {@link List} of {@link BatchGroup}s.\n\t */", "public", "List", "<", "BatchGroup", ">", "getGroups", "(", ")", "{", "return", "new", "ArrayList", "<", ">", "(", "groupsByCriteria", ".", "values", "(", ")", ")", ";", "}", "/**\n\t * Returns the count of how many importable objects (ie. {@link LoadSpec}s) were found.\n\t *\n\t * @return count of importable objects.\n\t */", "public", "int", "getTotalCount", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "BatchGroup", "batchGroup", ":", "groupsByCriteria", ".", "values", "(", ")", ")", "{", "count", "+=", "batchGroup", ".", "getBatchLoadConfig", "(", ")", ".", "size", "(", ")", ";", "}", "return", "count", ";", "}", "/**\n\t * Returns the count of how many files were found while processing the source files.\n\t *\n\t * @return count of files found while processing source files.\n\t */", "public", "int", "getTotalRawCount", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "UserAddedSourceInfo", "uasi", ":", "userAddedSources", ")", "{", "count", "+=", "uasi", ".", "getRawFileCount", "(", ")", ";", "}", "return", "count", ";", "}", "/**\n\t * Returns the count of applications in enabled {@link BatchGroup}s... in other\n\t * words, the number of objects that would be imported during this batch.\n\t *\n\t * @return count of enabled applications.\n\t */", "public", "int", "getEnabledCount", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "BatchGroup", "batchGroup", ":", "groupsByCriteria", ".", "values", "(", ")", ")", "{", "if", "(", "batchGroup", ".", "isEnabled", "(", ")", ")", "{", "count", "+=", "batchGroup", ".", "getBatchLoadConfig", "(", ")", ".", "size", "(", ")", ";", "}", "}", "return", "count", ";", "}", "/**\n\t * Removes a user-added source file (and all the embedded files inside it) from this\n\t * batch.\n\t *\n\t * @param fsrl {@link FSRL} of the file to remove.\n\t */", "public", "void", "remove", "(", "FSRL", "fsrl", ")", "{", "for", "(", "Iterator", "<", "Entry", "<", "BatchSegregatingCriteria", ",", "BatchGroup", ">", ">", "iterator", "=", "groupsByCriteria", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "iterator", ".", "hasNext", "(", ")", ";", ")", "{", "Entry", "<", "BatchSegregatingCriteria", ",", "BatchGroup", ">", "entry", "=", "iterator", ".", "next", "(", ")", ";", "BatchGroup", "bg", "=", "entry", ".", "getValue", "(", ")", ";", "bg", ".", "removeDescendantsOf", "(", "fsrl", ")", ";", "if", "(", "bg", ".", "isEmpty", "(", ")", ")", "{", "iterator", ".", "remove", "(", ")", ";", "}", "}", "for", "(", "Iterator", "<", "UserAddedSourceInfo", ">", "iterator", "=", "userAddedSources", ".", "iterator", "(", ")", ";", "iterator", ".", "hasNext", "(", ")", ";", ")", "{", "UserAddedSourceInfo", "uasi", "=", "iterator", ".", "next", "(", ")", ";", "if", "(", "uasi", ".", "getFSRL", "(", ")", ".", "equals", "(", "fsrl", ")", ")", "{", "iterator", ".", "remove", "(", ")", ";", "}", "}", "userAddedFSRLs", ".", "remove", "(", "fsrl", ")", ";", "}", "/**\n\t * Adds a file to this batch as the direct result of a user action.\n\t * <p>\n\t * If the file is a container for other files, this method will iterate through those\n\t * child files and recursively try to add them using this method.\n\t * <p>\n\t * @param fsrl {@link FSRL} of the file to add.\n\t * @param taskMonitor {@link TaskMonitor} to watch and update with progress.\n\t * @return boolean true if something in the the file produced something to import.\n\t * @throws IOException if io error when reading files.\n\t * @throws CancelledException if user cancels.\n\t */", "public", "boolean", "addFile", "(", "FSRL", "fsrl", ",", "TaskMonitor", "taskMonitor", ")", "throws", "IOException", ",", "CancelledException", "{", "fsrl", "=", "fsService", ".", "getFullyQualifiedFSRL", "(", "fsrl", ",", "taskMonitor", ")", ";", "if", "(", "userAddedFSRLs", ".", "contains", "(", "fsrl", ")", ")", "{", "throw", "new", "IOException", "(", "\"", "Batch already contains file ", "\"", "+", "fsrl", ")", ";", "}", "currentUASI", "=", "new", "UserAddedSourceInfo", "(", "fsrl", ")", ";", "userAddedSources", ".", "add", "(", "currentUASI", ")", ";", "userAddedFSRLs", ".", "add", "(", "currentUASI", ".", "getFSRL", "(", ")", ")", ";", "int", "startCount", "=", "getTotalCount", "(", ")", ";", "boolean", "result", "=", "doAddFile", "(", "fsrl", ",", "taskMonitor", ")", ";", "int", "endCount", "=", "getTotalCount", "(", ")", ";", "currentUASI", ".", "setFileCount", "(", "endCount", "-", "startCount", ")", ";", "return", "result", ";", "}", "/**\n\t * The main worker for adding a file to the batch session.\n\t * <p>\n\t * The file is probed for high-priority filesystems first, then if no matches,\n\t * Ghidra loaders, and then if no matches, all filesystems.\n\t * <p>\n\t * @param fsrl {@link FSRL} of the file to probe and process\n\t * @param taskMonitor {@link TaskMonitor} to watch and update.\n\t * @return boolean true if something in the the file produced something to import.\n\t * @throws IOException if io error when reading files.\n\t * @throws CancelledException if user cancels.\n\t */", "private", "boolean", "doAddFile", "(", "FSRL", "fsrl", ",", "TaskMonitor", "taskMonitor", ")", "throws", "IOException", ",", "CancelledException", "{", "try", "(", "RefdFile", "refdFile", "=", "fsService", ".", "getRefdFile", "(", "fsrl", ",", "taskMonitor", ")", ")", "{", "GFile", "file", "=", "refdFile", ".", "file", ";", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "processFS", "(", "file", ".", "getFilesystem", "(", ")", ",", "file", ",", "taskMonitor", ")", ";", "return", "true", ";", "}", "if", "(", "processAsFS", "(", "fsrl", ",", "taskMonitor", ")", ")", "{", "return", "true", ";", "}", "if", "(", "processWithLoader", "(", "fsrl", ",", "taskMonitor", ")", ")", "{", "return", "true", ";", "}", "fsService", ".", "releaseFileCache", "(", "fsrl", ")", ";", "return", "false", ";", "}", "}", "private", "boolean", "shouldTerminateRecurse", "(", "FSRL", "fsrl", ")", "{", "if", "(", "maxDepth", "<=", "0", ")", "{", "return", "false", ";", "}", "int", "initialLevel", "=", "currentUASI", ".", "getFSRL", "(", ")", ".", "getNestingDepth", "(", ")", ";", "int", "fsrlLevel", "=", "fsrl", ".", "getNestingDepth", "(", ")", ";", "return", "(", "fsrlLevel", "-", "initialLevel", ")", ">", "maxDepth", "-", "1", ";", "}", "/**\n\t * Returns true if any of the user source files had containers that were not\n\t * recursed into because of the {@link #maxDepth} limit.\n\t *\n\t * @return true if any of the user source files had containers that were not\n\t * recursed into because of the {@link #maxDepth} limit.\n\t */", "public", "boolean", "wasRecurseTerminatedEarly", "(", ")", "{", "for", "(", "UserAddedSourceInfo", "uasi", ":", "userAddedSources", ")", "{", "if", "(", "uasi", ".", "wasRecurseTerminatedEarly", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "/**\n\t * Checks the found applications and returns true if only a single binary was found,\n\t * even if multiple loaders claim it.\n\t * \n\t * @return true if single binary and batch is probably not correct importer.\n\t */", "public", "boolean", "isSingleApp", "(", ")", "{", "Set", "<", "String", ">", "foundLoaders", "=", "new", "HashSet", "<", ">", "(", ")", ";", "for", "(", "BatchGroup", "group", ":", "groupsByCriteria", ".", "values", "(", ")", ")", "{", "for", "(", "BatchLoadConfig", "batchLoadConfig", ":", "group", ".", "getBatchLoadConfig", "(", ")", ")", "{", "String", "loaderID", "=", "batchLoadConfig", ".", "getLoadSpecs", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ".", "getLoader", "(", ")", ".", "getName", "(", ")", ";", "if", "(", "!", "foundLoaders", ".", "add", "(", "loaderID", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "BatchGroup", "similarApps", ":", "groupsByCriteria", ".", "values", "(", ")", ")", "{", "sb", ".", "append", "(", "similarApps", ".", "toString", "(", ")", ")", ";", "sb", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}", "private", "boolean", "processAsFS", "(", "FSRL", "fsrl", ",", "TaskMonitor", "taskMonitor", ")", "throws", "CancelledException", "{", "try", "(", "FileSystemRef", "fsRef", "=", "fsService", ".", "probeFileForFilesystem", "(", "fsrl", ",", "taskMonitor", ",", "FileSystemProbeConflictResolver", ".", "CHOOSEFIRST", ")", ")", "{", "if", "(", "fsRef", "==", "null", ")", "{", "return", "false", ";", "}", "GFileSystem", "fs", "=", "fsRef", ".", "getFilesystem", "(", ")", ";", "currentUASI", ".", "incContainerCount", "(", ")", ";", "if", "(", "shouldTerminateRecurse", "(", "fs", ".", "getFSRL", "(", ")", ")", ")", "{", "currentUASI", ".", "setRecurseTerminatedEarly", "(", "true", ")", ";", "return", "true", ";", "}", "currentUASI", ".", "setMaxNestLevel", "(", "Math", ".", "max", "(", "currentUASI", ".", "getMaxNestLevel", "(", ")", ",", "fs", ".", "getFSRL", "(", ")", ".", "getNestingDepth", "(", ")", ")", ")", ";", "processFS", "(", "fs", ",", "null", ",", "taskMonitor", ")", ";", "return", "true", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "Msg", ".", "warn", "(", "this", ",", "\"", "Error while probing file ", "\"", "+", "fsrl", "+", "\"", " for filesystems: ", "\"", "+", "ioe", ".", "getMessage", "(", ")", ")", ";", "return", "false", ";", "}", "}", "/**\n\t * Recursively handles files in an already opened GFileSystem.\n\t * @param fs {@link GFileSystem} containing the startDir\n\t * @param startDir {@link GFile} ref to the directory to process, null if root of the filesystem.\n\t * @param taskMonitor {@link TaskMonitor} to watch and update.\n\t * @throws CancelledException if user cancels\n\t * @throws IOException if io error while reading files.\n\t */", "private", "void", "processFS", "(", "GFileSystem", "fs", ",", "GFile", "startDir", ",", "TaskMonitor", "taskMonitor", ")", "throws", "CancelledException", ",", "IOException", "{", "for", "(", "GFile", "file", ":", "FSUtilities", ".", "listFileSystem", "(", "fs", ",", "startDir", ",", "null", ",", "taskMonitor", ")", ")", "{", "taskMonitor", ".", "checkCanceled", "(", ")", ";", "FSRL", "fqFSRL", ";", "try", "{", "fqFSRL", "=", "fsService", ".", "getFullyQualifiedFSRL", "(", "file", ".", "getFSRL", "(", ")", ",", "taskMonitor", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "Msg", ".", "warn", "(", "this", ",", "\"", "Error getting info for ", "\"", "+", "file", ".", "getFSRL", "(", ")", ")", ";", "continue", ";", "}", "doAddFile", "(", "fqFSRL", ",", "taskMonitor", ")", ";", "currentUASI", ".", "incRawFileCount", "(", ")", ";", "}", "}", "/**\n\t * Tries to open a file using Ghidra {@link Loader}s.\n\t * <p>\n\t * The {@link BinaryLoader} is unconditionally skipped.\n\t *\n\t * @param fsrl {@link FSRL} of the file to open\n\t * @param monitor {@link TaskMonitor} to use\n\t * @return boolean true if successfully processed with a loader, false if no loader claimed\n\t * the file.\n\t * @throws IOException if io error during processing\n\t * @throws CancelledException if user cancels.\n\t */", "private", "boolean", "processWithLoader", "(", "FSRL", "fsrl", ",", "TaskMonitor", "monitor", ")", "throws", "IOException", ",", "CancelledException", "{", "try", "(", "ByteProvider", "provider", "=", "fsService", ".", "getByteProvider", "(", "fsrl", ",", "false", ",", "monitor", ")", ")", "{", "LoaderMap", "loaderMap", "=", "pollLoadersForLoadSpecs", "(", "provider", ",", "fsrl", ",", "monitor", ")", ";", "for", "(", "Loader", "loader", ":", "loaderMap", ".", "keySet", "(", ")", ")", "{", "Collection", "<", "LoadSpec", ">", "loadSpecs", "=", "loaderMap", ".", "get", "(", "loader", ")", ";", "BatchSegregatingCriteria", "bsc", "=", "new", "BatchSegregatingCriteria", "(", "loader", ",", "loadSpecs", ",", "provider", ")", ";", "BatchGroup", "batchGroup", "=", "groupsByCriteria", ".", "get", "(", "bsc", ")", ";", "if", "(", "batchGroup", "==", "null", ")", "{", "batchGroup", "=", "new", "BatchGroup", "(", "bsc", ")", ";", "groupsByCriteria", ".", "put", "(", "bsc", ",", "batchGroup", ")", ";", "}", "batchGroup", ".", "add", "(", "provider", ",", "loadSpecs", ",", "fsrl", ",", "currentUASI", ")", ";", "}", "return", "loaderMap", ".", "keySet", "(", ")", ".", "size", "(", ")", ">", "0", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "Msg", ".", "warn", "(", "this", ",", "\"", "Error while probing file ", "\"", "+", "fsrl", "+", "\"", " for loader applications: ", "\"", "+", "ioe", ".", "getMessage", "(", ")", ")", ";", "return", "false", ";", "}", "}", "private", "LoaderMap", "pollLoadersForLoadSpecs", "(", "ByteProvider", "provider", ",", "FSRL", "fsrl", ",", "TaskMonitor", "monitor", ")", "{", "monitor", ".", "setMessage", "(", "fsrl", ".", "getName", "(", ")", ")", ";", "return", "LoaderService", ".", "getSupportedLoadSpecs", "(", "provider", ",", "loader", "->", "!", "(", "loader", "instanceof", "BinaryLoader", ")", ")", ";", "}", "/**\n\t * Returns the {@link List} of files added via {@link #addFile(FSRL, TaskMonitor)}.\n\t *\n\t * @return {@link List} of files added via {@link #addFile(FSRL, TaskMonitor)}.\n\t */", "public", "List", "<", "UserAddedSourceInfo", ">", "getUserAddedSources", "(", ")", "{", "return", "userAddedSources", ";", "}", "/**\n\t * Maximum depth of containers (ie. filesystems) to recurse into when processing\n\t * a file added by the user\n\t *\n\t * @return the current maximum depth of containers (ie. filesystems) to recurse into when processing\n\t * a file added by the user.\n\t */", "public", "int", "getMaxDepth", "(", ")", "{", "return", "maxDepth", ";", "}", "/**\n\t * Sets a new max container recursive depth limit for this batch import\n\t * <p>\n\t * Doing this requires rescanning all original user-added source files and stopping\n\t * at the new max depth.\n\t * <p>\n\t * @param newMaxDepth new value for the max depth\n\t */", "public", "void", "setMaxDepth", "(", "int", "newMaxDepth", ")", "{", "new", "TaskBuilder", "(", "\"", "Scanning Source Files", "\"", ",", "monitor", "->", "doSetMaxDepth", "(", "newMaxDepth", ",", "monitor", ")", ")", ".", "setStatusTextAlignment", "(", "SwingConstants", ".", "LEADING", ")", ".", "setHasProgress", "(", "false", ")", ".", "launchModal", "(", ")", ";", "}", "/**\n\t * Adds the given files to this batch import\n\t * \n\t * @param filesToAdd the files to add\n\t * @return any files that failed to load; exceptions will be logged\n\t */", "List", "<", "FSRL", ">", "addFiles", "(", "List", "<", "FSRL", ">", "filesToAdd", ")", "{", "AddFilesRunnable", "runnable", "=", "new", "AddFilesRunnable", "(", "filesToAdd", ")", ";", "new", "TaskBuilder", "(", "\"", "Adding Source Files", "\"", ",", "runnable", ")", ".", "setStatusTextAlignment", "(", "SwingConstants", ".", "LEADING", ")", ".", "setHasProgress", "(", "false", ")", ".", "launchModal", "(", ")", ";", "return", "runnable", ".", "getBadFiles", "(", ")", ";", "}", "private", "void", "doSetMaxDepth", "(", "int", "newMaxDepth", ",", "TaskMonitor", "monitor", ")", "{", "if", "(", "newMaxDepth", "==", "maxDepth", ")", "{", "return", ";", "}", "Msg", ".", "trace", "(", "this", ",", "\"", "Switching maxDepth from ", "\"", "+", "maxDepth", "+", "\"", " to ", "\"", "+", "newMaxDepth", ")", ";", "List", "<", "FSRL", ">", "files", "=", "userAddedSources", ".", "stream", "(", ")", ".", "map", "(", "source", "->", "{", "return", "source", ".", "getFSRL", "(", ")", ";", "}", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "groupsByCriteria", ".", "clear", "(", ")", ";", "userAddedSources", ".", "clear", "(", ")", ";", "userAddedFSRLs", ".", "clear", "(", ")", ";", "maxDepth", "=", "newMaxDepth", ";", "doAddFiles", "(", "files", ",", "monitor", ")", ";", "}", "private", "List", "<", "FSRL", ">", "doAddFiles", "(", "List", "<", "FSRL", ">", "filesToAdd", ",", "TaskMonitor", "monitor", ")", "{", "BatchTaskMonitor", "batchMonitor", "=", "new", "BatchTaskMonitor", "(", "monitor", ")", ";", "try", "(", "CryptoSession", "cryptoSession", "=", "fsService", ".", "newCryptoSession", "(", ")", ")", "{", "List", "<", "FSRL", ">", "badFiles", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "FSRL", "fsrl", ":", "filesToAdd", ")", "{", "Msg", ".", "trace", "(", "this", ",", "\"", "Adding ", "\"", "+", "fsrl", ")", ";", "batchMonitor", ".", "setPrefix", "(", "\"", "Processing ", "\"", "+", "fsrl", ".", "getName", "(", ")", "+", "\"", ": ", "\"", ")", ";", "try", "{", "monitor", ".", "checkCanceled", "(", ")", ";", "addFile", "(", "fsrl", ",", "batchMonitor", ")", ";", "}", "catch", "(", "CryptoException", "ce", ")", "{", "FSUtilities", ".", "displayException", "(", "this", ",", "null", ",", "\"", "Error Adding File To Batch Import", "\"", ",", "\"", "Error while adding ", "\"", "+", "fsrl", ".", "getName", "(", ")", "+", "\"", " to batch import", "\"", ",", "ce", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "Msg", ".", "error", "(", "this", ",", "\"", "Error while adding ", "\"", "+", "fsrl", ".", "getName", "(", ")", "+", "\"", " to batch import", "\"", ",", "ioe", ")", ";", "badFiles", ".", "add", "(", "fsrl", ")", ";", "}", "catch", "(", "CancelledException", "e", ")", "{", "Msg", ".", "debug", "(", "this", ",", "\"", "Cancelling Add File task while adding ", "\"", "+", "fsrl", ".", "getName", "(", ")", ")", ";", "}", "}", "return", "badFiles", ";", "}", "}", "private", "class", "AddFilesRunnable", "implements", "MonitoredRunnable", "{", "private", "List", "<", "FSRL", ">", "files", ";", "private", "List", "<", "FSRL", ">", "badFiles", ";", "AddFilesRunnable", "(", "List", "<", "FSRL", ">", "files", ")", "{", "this", ".", "files", "=", "files", ";", "}", "@", "Override", "public", "void", "monitoredRun", "(", "TaskMonitor", "monitor", ")", "{", "badFiles", "=", "doAddFiles", "(", "files", ",", "monitor", ")", ";", "}", "List", "<", "FSRL", ">", "getBadFiles", "(", ")", "{", "return", "badFiles", ";", "}", "}", "/** A task monitor that allows us to control the message content and the progress */", "private", "class", "BatchTaskMonitor", "extends", "WrappingTaskMonitor", "{", "private", "String", "prefix", ";", "BatchTaskMonitor", "(", "TaskMonitor", "delegate", ")", "{", "super", "(", "delegate", ")", ";", "}", "void", "setPrefix", "(", "String", "prefix", ")", "{", "this", ".", "prefix", "=", "prefix", ";", "}", "@", "Override", "public", "void", "setMessage", "(", "String", "message", ")", "{", "super", ".", "setMessage", "(", "prefix", "+", "\"", " ", "\"", "+", "message", ")", ";", "}", "@", "Override", "public", "void", "initialize", "(", "long", "max", ")", "{", "}", "@", "Override", "public", "void", "setProgress", "(", "long", "value", ")", "{", "}", "}", "}" ]
This is the main state of a batch import task, containing the segregated groupings of applications.
[ "This", "is", "the", "main", "state", "of", "a", "batch", "import", "task", "containing", "the", "segregated", "groupings", "of", "applications", "." ]
[ "// use the fsrl param instead of file.getFSRL() as param may have more info (ie. md5)", "// the file was not of interest, let it be removed from the cache", "// TODO: drop FSUtils.listFileSystem and do recursion here.", "//@formatter:off", "// indeterminate\t\t\t", "//@formatter:on", "//@formatter:off", "// indeterminate", "//@formatter:on", "// TODO: make this smarter and when switching from higher maxDepth to lower,", "// just remove existing files that are deeper. Recalculating user added source info ", "// number is hard so I'm skipping it now.", "//@formatter:off", "//@formatter:on", "// start a new CryptoSession to group all password prompting by multiple container", "// files into a single session, enabling \"Cancel All\" to really cancel all password", "// prompts", "// Note: the workflow for this felt odd: press cancel; confirm cancel; press Ok ", "// on dialog showing files not processed.", "// It seems like the user should not have to see the second dialog", "// badFiles.addAll(filesToAdd.subList(i, filesToAdd.size()));", "//==================================================================================================", "// Inner Classes", "//==================================================================================================\t", "// we control the max value", "// we control the progress" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33eb8cfe0a078a366b29e90e6a83722bcd44dac0
sigurasg/ghidra
Ghidra/Features/Base/src/main/java/ghidra/plugins/importer/batch/BatchInfo.java
[ "Apache-2.0" ]
Java
BatchTaskMonitor
/** A task monitor that allows us to control the message content and the progress */
A task monitor that allows us to control the message content and the progress
[ "A", "task", "monitor", "that", "allows", "us", "to", "control", "the", "message", "content", "and", "the", "progress" ]
private class BatchTaskMonitor extends WrappingTaskMonitor { private String prefix; BatchTaskMonitor(TaskMonitor delegate) { super(delegate); } void setPrefix(String prefix) { this.prefix = prefix; } @Override public void setMessage(String message) { super.setMessage(prefix + " " + message); } @Override public void initialize(long max) { // we control the max value } @Override public void setProgress(long value) { // we control the progress } }
[ "private", "class", "BatchTaskMonitor", "extends", "WrappingTaskMonitor", "{", "private", "String", "prefix", ";", "BatchTaskMonitor", "(", "TaskMonitor", "delegate", ")", "{", "super", "(", "delegate", ")", ";", "}", "void", "setPrefix", "(", "String", "prefix", ")", "{", "this", ".", "prefix", "=", "prefix", ";", "}", "@", "Override", "public", "void", "setMessage", "(", "String", "message", ")", "{", "super", ".", "setMessage", "(", "prefix", "+", "\"", " ", "\"", "+", "message", ")", ";", "}", "@", "Override", "public", "void", "initialize", "(", "long", "max", ")", "{", "}", "@", "Override", "public", "void", "setProgress", "(", "long", "value", ")", "{", "}", "}" ]
A task monitor that allows us to control the message content and the progress
[ "A", "task", "monitor", "that", "allows", "us", "to", "control", "the", "message", "content", "and", "the", "progress" ]
[ "// we control the max value", "// we control the progress" ]
[ { "param": "WrappingTaskMonitor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "WrappingTaskMonitor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33ed44eceec13c0d0e00f5336703904bc493600e
dashorst/wicket-stuff-markup-validator
whattf/src/main/resources/relaxng/datatype/java/classes/org/whattf/datatype/Pattern.java
[ "Apache-2.0" ]
Java
Pattern
/** * This datatype shall accept the strings that are allowed as the value of the Web Forms 2.0 * <a href="http://whatwg.org/specs/web-forms/current-work/#pattern"><code>pattern</code></a> * attribute. * @version $Id$ * @author hsivonen */
This datatype shall accept the strings that are allowed as the value of the Web Forms 2.0 pattern attribute. @version $Id$ @author hsivonen
[ "This", "datatype", "shall", "accept", "the", "strings", "that", "are", "allowed", "as", "the", "value", "of", "the", "Web", "Forms", "2", ".", "0", "pattern", "attribute", ".", "@version", "$Id$", "@author", "hsivonen" ]
public final class Pattern extends AbstractDatatype { /** * The singleton instance. */ public static final Pattern THE_INSTANCE = new Pattern(); /** * Package-private constructor */ private Pattern() { super(); } /** * Checks that the value compiles as an anchored JavaScript regular expression. * @param literal the value * @param context ignored * @throws DatatypeException if the value isn't valid * @see org.relaxng.datatype.Datatype#checkValid(java.lang.String, org.relaxng.datatype.ValidationContext) */ public void checkValid(CharSequence literal) throws DatatypeException { // TODO find out what kind of thread concurrency guarantees are made ContextFactory cf = new ContextFactory(); Context cx = cf.enterContext(); RegExpImpl rei = new RegExpImpl(); String anchoredRegex = "^(?:" + literal + ")$"; try { rei.compileRegExp(cx, anchoredRegex, ""); } catch (EcmaError ee) { throw newDatatypeException(ee.getErrorMessage()); } finally { Context.exit(); } } @Override public String getName() { return "pattern"; } }
[ "public", "final", "class", "Pattern", "extends", "AbstractDatatype", "{", "/**\n * The singleton instance.\n */", "public", "static", "final", "Pattern", "THE_INSTANCE", "=", "new", "Pattern", "(", ")", ";", "/**\n * Package-private constructor\n */", "private", "Pattern", "(", ")", "{", "super", "(", ")", ";", "}", "/**\n * Checks that the value compiles as an anchored JavaScript regular expression.\n * @param literal the value\n * @param context ignored\n * @throws DatatypeException if the value isn't valid\n * @see org.relaxng.datatype.Datatype#checkValid(java.lang.String, org.relaxng.datatype.ValidationContext)\n */", "public", "void", "checkValid", "(", "CharSequence", "literal", ")", "throws", "DatatypeException", "{", "ContextFactory", "cf", "=", "new", "ContextFactory", "(", ")", ";", "Context", "cx", "=", "cf", ".", "enterContext", "(", ")", ";", "RegExpImpl", "rei", "=", "new", "RegExpImpl", "(", ")", ";", "String", "anchoredRegex", "=", "\"", "^(?:", "\"", "+", "literal", "+", "\"", ")$", "\"", ";", "try", "{", "rei", ".", "compileRegExp", "(", "cx", ",", "anchoredRegex", ",", "\"", "\"", ")", ";", "}", "catch", "(", "EcmaError", "ee", ")", "{", "throw", "newDatatypeException", "(", "ee", ".", "getErrorMessage", "(", ")", ")", ";", "}", "finally", "{", "Context", ".", "exit", "(", ")", ";", "}", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "\"", "pattern", "\"", ";", "}", "}" ]
This datatype shall accept the strings that are allowed as the value of the Web Forms 2.0 <a href="http://whatwg.org/specs/web-forms/current-work/#pattern"><code>pattern</code></a> attribute.
[ "This", "datatype", "shall", "accept", "the", "strings", "that", "are", "allowed", "as", "the", "value", "of", "the", "Web", "Forms", "2", ".", "0", "<a", "href", "=", "\"", "http", ":", "//", "whatwg", ".", "org", "/", "specs", "/", "web", "-", "forms", "/", "current", "-", "work", "/", "#pattern", "\"", ">", "<code", ">", "pattern<", "/", "code", ">", "<", "/", "a", ">", "attribute", "." ]
[ "// TODO find out what kind of thread concurrency guarantees are made" ]
[ { "param": "AbstractDatatype", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractDatatype", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33eef13a3a5a5357ae171f30f1fd5bbe9a94496f
azlinr/myplayground
predict4all-core/src/main/java/org/predict4all/nlp/ngram/NGramWordPredictorUtils.java
[ "Apache-2.0" ]
Java
NGramWordPredictorUtils
/** * Utils class useful when predicting words with an ngram dictionaries. * * @author Mathieu THEBAUD */
Utils class useful when predicting words with an ngram dictionaries. @author Mathieu THEBAUD
[ "Utils", "class", "useful", "when", "predicting", "words", "with", "an", "ngram", "dictionaries", ".", "@author", "Mathieu", "THEBAUD" ]
public class NGramWordPredictorUtils { private static final int NGRAM_MAX_LAST_TOKEN_COUNT_FACTOR = 4; /** * Word dictionary associated with ngram dictionaries */ private final WordDictionary wordDictionary; /** * Prediction parameter */ private final PredictionParameter predictionParameter; public NGramWordPredictorUtils(WordDictionary wordDictionary, PredictionParameter predictionParameter) { super(); this.wordDictionary = wordDictionary; this.predictionParameter = predictionParameter; } // PUBLIC API // ======================================================================== /** * Create the prefix for a given raw context (token list) : the context is meant to be used for ngram trie exploring.<br> * The context takes care of using only the last sentence, to detect the current written word, and to retrieve a context of the wanted order.<br> * * @param rawTokensList raw token list (retrieved from parsing a raw text input) * @param wordPrefixFound if a word is started, should contains the started prefix * @param wantedOrder the wanted prefix order * @param addUnknownWordToDictionary if true, when a word in the given token list is unknown, the method {@link WordDictionary#putUserWord(Token)} will be called to retrieve the word id * @return a triple containing the prefix on left : containing the last (wantedOrder-1) words in the given token list.<br> * Resulting prefix will contains {@link Tag#UNKNOWN} if the token list contains unknown word and addUnknownWordToDictionary is false, and will contains {@link Tag#START} if the given token list is not long enough, or if the current * sentence is too short.<br> * The boolean on middle is true if there is only "START" tag in the resulting prefix<br> * The boolean on right is true if we found a unknown word in the prefix (even if it's added to dictionary)<br> */ public Triple<int[], Boolean, Boolean> createPrefixFor(final List<Token> rawTokensList, WordPrefixDetected wordPrefixFound, final int wantedOrder, final boolean addUnknownWordToDictionary) { // If a word is started, we should freeze the end of the token list for each token that compose the word final int lastTokenToFreezeCount = wordPrefixFound != null ? wordPrefixFound.getTokenCount() : 0; // Create a sublist that only keep the minimum token count (optimization) List<Token> tokens = createTokenListForPrediction(rawTokensList, lastTokenToFreezeCount, wantedOrder); // Keep only the last sentence to execute prediction keepOnlyLastSentenceAndLowerCase(tokens, lastTokenToFreezeCount); // Remove all the separator from list, but keep the last tokens if needed removeSeparatorsFromTokenList(tokens, lastTokenToFreezeCount); // Complete with start tag when needed while (tokens.size() - lastTokenToFreezeCount + 1 < wantedOrder) { tokens.add(0, TagToken.create(Tag.START)); } // Create context list : n-1 last words boolean foundUnknown = false; boolean onlyStartTag = true; int[] contextPrefix = new int[wantedOrder - 1]; int tokenIndexStart = tokens.size() - wantedOrder - lastTokenToFreezeCount + 1; for (int tokenIndex = 0; tokenIndex < wantedOrder - 1; tokenIndex++) { // Get token final Token token = tokens.get(tokenIndexStart + tokenIndex); contextPrefix[tokenIndex] = Tag.UNKNOWN.getId(); // Get word from dictionary final int wordId = token.getWordId(wordDictionary); foundUnknown |= wordId == Tag.UNKNOWN.getId(); // If word is unknown and could be used to create a user word (excluding first and last tokens) if (wordId == Tag.UNKNOWN.getId() && tokenIndexStart + tokenIndex > 0 && (wordPrefixFound == null || tokenIndex < wantedOrder - 2) && addUnknownWordToDictionary && wordDictionary.isTokenValidToCreateUserWord(token)) { contextPrefix[tokenIndex] = this.wordDictionary.putUserWord(token); } else { contextPrefix[tokenIndex] = wordId; } onlyStartTag &= wordId == Tag.START.getId(); } return Triple.of(contextPrefix, onlyStartTag, foundUnknown); } // ======================================================================== // PRIVATE //======================================================================== /** * Go through tokens and keep only the last sentence in the given token list (remove every sentence before) * * @param tokens the tokens list * @param lastTokenToFreezeCount the number of last token to keep */ private void keepOnlyLastSentenceAndLowerCase(List<Token> tokens, int lastTokenToFreezeCount) { // Go back to search the last sentence separator (except lastTokenToFreezeCount) int lastSentenceSeparatorIndex = -1; for (int i = tokens.size() - 1 - lastTokenToFreezeCount; i >= 0; i--) { if (tokens.get(i).isSeparator() && tokens.get(i).getSeparator().isSentenceSeparator()) { lastSentenceSeparatorIndex = i; break; } } // Delete all items before last sentence start int i = 0; Iterator<Token> iterator = tokens.iterator(); while (iterator.hasNext()) { iterator.next(); if (i <= lastSentenceSeparatorIndex) { iterator.remove(); } else { break; } i++; } // The first token become lower case (if needed) if (!tokens.isEmpty()) { Token firstToken = tokens.get(0); if (firstToken.isWord() && Predict4AllUtils.isCapitalized(firstToken.getText())) { tokens.set(0, WordToken.create(Predict4AllUtils.lowerCase(firstToken.getText()))); } } } /** * Remove all the separator tokens from the list, but keep the last token count * * @param rawTokensList token list where separator will be removed * @param keepLastCount the number of last token to keep */ private void removeSeparatorsFromTokenList(List<Token> rawTokensList, int keepLastCount) { Iterator<Token> iterator = rawTokensList.iterator(); int stopOnIndex = rawTokensList.size() - keepLastCount; int i = 0; while (iterator.hasNext() && i < stopOnIndex) { if (iterator.next().isSeparator()) { iterator.remove(); } i++; } } /** * Create a list of token from the original raw token list, that will only keep the x last tokens. * * @param rawTokensList the raw token list (source) * @param keepLastCount the token count to keep (plus the initial computed count). * @param ngramMaxOrder the max order in the ngram dictionary * @return a sub list of the given list, that only contains the minimum needed token count (raw token list). */ private ArrayList<Token> createTokenListForPrediction(final List<Token> rawTokensList, int keepLastCount, int ngramMaxOrder) { return new ArrayList<>(rawTokensList.subList( Math.max(0, rawTokensList.size() - keepLastCount - NGRAM_MAX_LAST_TOKEN_COUNT_FACTOR * ngramMaxOrder), rawTokensList.size())); } //======================================================================== }
[ "public", "class", "NGramWordPredictorUtils", "{", "private", "static", "final", "int", "NGRAM_MAX_LAST_TOKEN_COUNT_FACTOR", "=", "4", ";", "/**\n * Word dictionary associated with ngram dictionaries\n */", "private", "final", "WordDictionary", "wordDictionary", ";", "/**\n * Prediction parameter\n */", "private", "final", "PredictionParameter", "predictionParameter", ";", "public", "NGramWordPredictorUtils", "(", "WordDictionary", "wordDictionary", ",", "PredictionParameter", "predictionParameter", ")", "{", "super", "(", ")", ";", "this", ".", "wordDictionary", "=", "wordDictionary", ";", "this", ".", "predictionParameter", "=", "predictionParameter", ";", "}", "/**\n * Create the prefix for a given raw context (token list) : the context is meant to be used for ngram trie exploring.<br>\n * The context takes care of using only the last sentence, to detect the current written word, and to retrieve a context of the wanted order.<br>\n *\n * @param rawTokensList raw token list (retrieved from parsing a raw text input)\n * @param wordPrefixFound if a word is started, should contains the started prefix\n * @param wantedOrder the wanted prefix order\n * @param addUnknownWordToDictionary if true, when a word in the given token list is unknown, the method {@link WordDictionary#putUserWord(Token)} will be called to retrieve the word id\n * @return a triple containing the prefix on left : containing the last (wantedOrder-1) words in the given token list.<br>\n * Resulting prefix will contains {@link Tag#UNKNOWN} if the token list contains unknown word and addUnknownWordToDictionary is false, and will contains {@link Tag#START} if the given token list is not long enough, or if the current\n * sentence is too short.<br>\n * The boolean on middle is true if there is only \"START\" tag in the resulting prefix<br>\n * The boolean on right is true if we found a unknown word in the prefix (even if it's added to dictionary)<br>\n */", "public", "Triple", "<", "int", "[", "]", ",", "Boolean", ",", "Boolean", ">", "createPrefixFor", "(", "final", "List", "<", "Token", ">", "rawTokensList", ",", "WordPrefixDetected", "wordPrefixFound", ",", "final", "int", "wantedOrder", ",", "final", "boolean", "addUnknownWordToDictionary", ")", "{", "final", "int", "lastTokenToFreezeCount", "=", "wordPrefixFound", "!=", "null", "?", "wordPrefixFound", ".", "getTokenCount", "(", ")", ":", "0", ";", "List", "<", "Token", ">", "tokens", "=", "createTokenListForPrediction", "(", "rawTokensList", ",", "lastTokenToFreezeCount", ",", "wantedOrder", ")", ";", "keepOnlyLastSentenceAndLowerCase", "(", "tokens", ",", "lastTokenToFreezeCount", ")", ";", "removeSeparatorsFromTokenList", "(", "tokens", ",", "lastTokenToFreezeCount", ")", ";", "while", "(", "tokens", ".", "size", "(", ")", "-", "lastTokenToFreezeCount", "+", "1", "<", "wantedOrder", ")", "{", "tokens", ".", "add", "(", "0", ",", "TagToken", ".", "create", "(", "Tag", ".", "START", ")", ")", ";", "}", "boolean", "foundUnknown", "=", "false", ";", "boolean", "onlyStartTag", "=", "true", ";", "int", "[", "]", "contextPrefix", "=", "new", "int", "[", "wantedOrder", "-", "1", "]", ";", "int", "tokenIndexStart", "=", "tokens", ".", "size", "(", ")", "-", "wantedOrder", "-", "lastTokenToFreezeCount", "+", "1", ";", "for", "(", "int", "tokenIndex", "=", "0", ";", "tokenIndex", "<", "wantedOrder", "-", "1", ";", "tokenIndex", "++", ")", "{", "final", "Token", "token", "=", "tokens", ".", "get", "(", "tokenIndexStart", "+", "tokenIndex", ")", ";", "contextPrefix", "[", "tokenIndex", "]", "=", "Tag", ".", "UNKNOWN", ".", "getId", "(", ")", ";", "final", "int", "wordId", "=", "token", ".", "getWordId", "(", "wordDictionary", ")", ";", "foundUnknown", "|=", "wordId", "==", "Tag", ".", "UNKNOWN", ".", "getId", "(", ")", ";", "if", "(", "wordId", "==", "Tag", ".", "UNKNOWN", ".", "getId", "(", ")", "&&", "tokenIndexStart", "+", "tokenIndex", ">", "0", "&&", "(", "wordPrefixFound", "==", "null", "||", "tokenIndex", "<", "wantedOrder", "-", "2", ")", "&&", "addUnknownWordToDictionary", "&&", "wordDictionary", ".", "isTokenValidToCreateUserWord", "(", "token", ")", ")", "{", "contextPrefix", "[", "tokenIndex", "]", "=", "this", ".", "wordDictionary", ".", "putUserWord", "(", "token", ")", ";", "}", "else", "{", "contextPrefix", "[", "tokenIndex", "]", "=", "wordId", ";", "}", "onlyStartTag", "&=", "wordId", "==", "Tag", ".", "START", ".", "getId", "(", ")", ";", "}", "return", "Triple", ".", "of", "(", "contextPrefix", ",", "onlyStartTag", ",", "foundUnknown", ")", ";", "}", "/**\n * Go through tokens and keep only the last sentence in the given token list (remove every sentence before)\n *\n * @param tokens the tokens list\n * @param lastTokenToFreezeCount the number of last token to keep\n */", "private", "void", "keepOnlyLastSentenceAndLowerCase", "(", "List", "<", "Token", ">", "tokens", ",", "int", "lastTokenToFreezeCount", ")", "{", "int", "lastSentenceSeparatorIndex", "=", "-", "1", ";", "for", "(", "int", "i", "=", "tokens", ".", "size", "(", ")", "-", "1", "-", "lastTokenToFreezeCount", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "tokens", ".", "get", "(", "i", ")", ".", "isSeparator", "(", ")", "&&", "tokens", ".", "get", "(", "i", ")", ".", "getSeparator", "(", ")", ".", "isSentenceSeparator", "(", ")", ")", "{", "lastSentenceSeparatorIndex", "=", "i", ";", "break", ";", "}", "}", "int", "i", "=", "0", ";", "Iterator", "<", "Token", ">", "iterator", "=", "tokens", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "iterator", ".", "next", "(", ")", ";", "if", "(", "i", "<=", "lastSentenceSeparatorIndex", ")", "{", "iterator", ".", "remove", "(", ")", ";", "}", "else", "{", "break", ";", "}", "i", "++", ";", "}", "if", "(", "!", "tokens", ".", "isEmpty", "(", ")", ")", "{", "Token", "firstToken", "=", "tokens", ".", "get", "(", "0", ")", ";", "if", "(", "firstToken", ".", "isWord", "(", ")", "&&", "Predict4AllUtils", ".", "isCapitalized", "(", "firstToken", ".", "getText", "(", ")", ")", ")", "{", "tokens", ".", "set", "(", "0", ",", "WordToken", ".", "create", "(", "Predict4AllUtils", ".", "lowerCase", "(", "firstToken", ".", "getText", "(", ")", ")", ")", ")", ";", "}", "}", "}", "/**\n * Remove all the separator tokens from the list, but keep the last token count\n *\n * @param rawTokensList token list where separator will be removed\n * @param keepLastCount the number of last token to keep\n */", "private", "void", "removeSeparatorsFromTokenList", "(", "List", "<", "Token", ">", "rawTokensList", ",", "int", "keepLastCount", ")", "{", "Iterator", "<", "Token", ">", "iterator", "=", "rawTokensList", ".", "iterator", "(", ")", ";", "int", "stopOnIndex", "=", "rawTokensList", ".", "size", "(", ")", "-", "keepLastCount", ";", "int", "i", "=", "0", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", "&&", "i", "<", "stopOnIndex", ")", "{", "if", "(", "iterator", ".", "next", "(", ")", ".", "isSeparator", "(", ")", ")", "{", "iterator", ".", "remove", "(", ")", ";", "}", "i", "++", ";", "}", "}", "/**\n * Create a list of token from the original raw token list, that will only keep the x last tokens.\n *\n * @param rawTokensList the raw token list (source)\n * @param keepLastCount the token count to keep (plus the initial computed count).\n * @param ngramMaxOrder the max order in the ngram dictionary\n * @return a sub list of the given list, that only contains the minimum needed token count (raw token list).\n */", "private", "ArrayList", "<", "Token", ">", "createTokenListForPrediction", "(", "final", "List", "<", "Token", ">", "rawTokensList", ",", "int", "keepLastCount", ",", "int", "ngramMaxOrder", ")", "{", "return", "new", "ArrayList", "<", ">", "(", "rawTokensList", ".", "subList", "(", "Math", ".", "max", "(", "0", ",", "rawTokensList", ".", "size", "(", ")", "-", "keepLastCount", "-", "NGRAM_MAX_LAST_TOKEN_COUNT_FACTOR", "*", "ngramMaxOrder", ")", ",", "rawTokensList", ".", "size", "(", ")", ")", ")", ";", "}", "}" ]
Utils class useful when predicting words with an ngram dictionaries.
[ "Utils", "class", "useful", "when", "predicting", "words", "with", "an", "ngram", "dictionaries", "." ]
[ "// PUBLIC API", "// ========================================================================", "// If a word is started, we should freeze the end of the token list for each token that compose the word", "// Create a sublist that only keep the minimum token count (optimization)", "// Keep only the last sentence to execute prediction", "// Remove all the separator from list, but keep the last tokens if needed", "// Complete with start tag when needed", "// Create context list : n-1 last words", "// Get token", "// Get word from dictionary", "// If word is unknown and could be used to create a user word (excluding first and last tokens)", "// ========================================================================", "// PRIVATE", "//========================================================================", "// Go back to search the last sentence separator (except lastTokenToFreezeCount)", "// Delete all items before last sentence start", "// The first token become lower case (if needed)", "//========================================================================" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33f9a661b577f0292c75110a52088f121e23595d
anonymousoopsla21/homeostasis
src/imop/lib/analysis/typeSystem/Type.java
[ "MIT" ]
Java
Type
/** * This is the superclass for all the various * Types supported by IMOP. * * @author aman * */
This is the superclass for all the various Types supported by IMOP. @author aman
[ "This", "is", "the", "superclass", "for", "all", "the", "various", "Types", "supported", "by", "IMOP", ".", "@author", "aman" ]
public abstract class Type { public List<StorageClass> storageClasses; private static Set<Type> deletedTypes = new HashSet<>(); public static void resetStaticFields() { Type.deletedTypes = new HashSet<>(); } /** * This method is overridden at appropriate subclasses * to return true. * * @return */ public boolean isComplete() { return true; } /** * This method is overridden at appropriate subclasses * to return true. * * @return */ public boolean isCharacterType() { return false; } /** * This method is overridden at appropriate subclasses * to return true. * * @return */ public boolean isBasicType() { return false; } /** * This method is overridden at appropriate subclasses * to return true. * * @return */ public boolean isRealType() { return false; } public boolean isScalarType() { if (this instanceof ArithmeticType) { return true; } else if (this instanceof PointerType) { return true; } return false; } /** * Note that unions are not aggregate types. * * @return */ public boolean isAggregateType() { if (this instanceof ArrayType) { return true; } else if (this instanceof StructType) { return true; } return false; } public abstract boolean isKnownConstantSized(); // public boolean isKnownConstantSized() { // if (this.isComplete()) { // if (this instanceof ArrayType && ((ArrayType) this).isVariableLengthed()) { // return false; // } else { // return true; // } // } else { // return false; // } // } public boolean isDerivedDeclaratorType() { if (this instanceof ArrayType || this instanceof FunctionType || this instanceof PointerType) { return true; } else { return false; } } public Type getIntegerPromotedType() { if (this instanceof IntegerType) { IntegerType integerType = (IntegerType) this; if (integerType.getIntegerConversionRank() <= SignedIntType.type().getIntegerConversionRank()) { // TODO: Ensure that later when we know the size of various types, // we should return the more appropriate type of int -- unsigned or signed. // Till then, we send SignedIntType for all. return SignedIntType.type(); } } return this; } /** * Returns the type domain of the types. * Needs to be overridden by the complex types. * * @return */ public TypeDomain getTypeDomain() { return TypeDomain.REAL; } /** * Returns the corresponding real type for the current object. * Should be overridden by complex types. * * @return */ public Type getRealType() { return this; } /** * Returns the corresponding complex type for the current object. * Should be overridden by those real types which have a complex * counterpart. * * @return */ public Type getComplexType() { return this; } public boolean hasConstQualifier() { // TODO: Code here. return false; } protected abstract String preDeclarationString(); // protected String getDeclarationPostString(String tempName, boolean // isFullDeclarator) { // String retString = " " + tempName + " "; // return retString; // } protected abstract String postDeclarationString(); // protected String postDeclarationString(String tempName) { // return this.getDeclarationPostString(tempName, true); // } /** * Returns a declaration for <code>tempName</code> with this type, * such that {@code tempName} can be used to hold a value of any object of * this type. * * @param tempName * @return */ public Declaration getDeclaration(String tempName) { Declaration decl = FrontEnd.parseAlone( this.preDeclarationString() + " " + tempName + " " + this.postDeclarationString() + ";", Declaration.class); return decl; } /** * Returns a declaration for <code>tempName</code> with this type, * without any pointer conversions. Do not use this method if you are * creating temporaries that should be able to hold the value of any object * of this type. * * @param tempName * @return */ public Declaration getExactDeclarationWithoutInit(String tempName) { Declaration decl = FrontEnd.parseAlone(this.preString() + " " + tempName + " " + this.postString() + ";", Declaration.class); return decl; } public abstract boolean isCompatibleWith(Type t); protected abstract String preString(); protected abstract String postString(); protected String preStringForCopy() { return this.preString(); } protected String postStringForCopy() { return this.postString(); } // protected String postDeclarationString(String tempName) { // return this.getDeclarationPostString(tempName, true); // } // protected String postDeclarationString(String tempName) { // return this.getDeclarationPostString(tempName, true); // } /** * Returns a string of an abstract declaration of this type. * * @return */ @Override public final String toString() { return this.preString() + " " + this.postString(); } public final String toString(String idName) { return this.preString() + " " + idName + " " + this.postString(); } public static FunctionType getTypeTree(FunctionDefinition funcDef, Scopeable scope) { // Ensure that all functions with unspecified return type have been // pre-processed to return int. if (!funcDef.getF0().present()) { Misc.exitDueToError("Could not find the return type (int) of : " + funcDef.getInfo().getFunctionName()); } return (FunctionType) Type.getTypeTree((DeclarationSpecifiers) funcDef.getF0().getNode(), funcDef.getF1(), scope); } public static List<Type> getTypeTree(Declaration declaration, Scopeable scope, boolean deleteUserDefinedTypes) { // if (Misc.isTypedef(declaration)) { // return null; // } List<String> ids = declaration.getInfo().getIDNameList(); List<Type> typeList = new ArrayList<>(); for (String name : ids) { Type tempType = getTypeTree(declaration, name, scope, deleteUserDefinedTypes); if (tempType != null) { typeList.add(tempType); } } return typeList; } public static List<Type> getTypeTree(Declaration declaration, Scopeable scope) { // if (Misc.isTypedef(declaration)) { // return null; // } List<String> ids = declaration.getInfo().getIDNameList(); List<Type> typeList = new ArrayList<>(); if (ids.isEmpty()) { getTypeTree(declaration.getF0(), scope); } for (String name : ids) { Type tempType = getTypeTree(declaration, name, scope); if (tempType != null) { typeList.add(tempType); } } return typeList; } public static List<Type> getTypeTree(ParameterTypeList paramTypeList, Scopeable scope) { ParameterList paramList = paramTypeList.getF0(); List<Type> typeList = new ArrayList<>(); typeList.add(getTypeTree(paramList.getF0(), scope)); for (Node nodeSeqNode : paramList.getF1().getNodes()) { NodeSequence nodeSeq = (NodeSequence) nodeSeqNode; typeList.add(getTypeTree((ParameterDeclaration) nodeSeq.getNodes().get(1), scope)); } return typeList; } public static Type getTypeTree(Declaration declaration, String name, Scopeable scope, boolean deleteUserDefinedTypes) { // if (Misc.isTypedef(declaration)) { // return null; // } Declarator declarator = declaration.getInfo().getDeclarator(name); return getTypeTree(declaration.getF0(), declarator, scope, deleteUserDefinedTypes); } public static Type getTypeTree(Declaration declaration, String name, Scopeable scope) { // if (Misc.isTypedef(declaration)) { // return null; // } Declarator declarator = declaration.getInfo().getDeclarator(name); return getTypeTree(declaration.getF0(), declarator, scope); } public static Type getTypeTree(Declaration declaration, String name, Type inType, Scopeable scope) { // if (Misc.isTypedef(declaration)) { // return null; // } Declarator declarator = declaration.getInfo().getDeclarator(name); return getTypeTree(declaration.getF0(), declarator, inType, scope); } public static List<Type> getTypeTree(StructDeclaration structDeclaration, Scopeable scope) { List<String> ids = new ArrayList<>(DeclarationInfo.getIdNameList(structDeclaration)); List<Type> typeList = new ArrayList<>(); for (String name : ids) { typeList.add(getTypeTree(structDeclaration, name, scope)); } return typeList; } public static Type getTypeTree(StructDeclaration structDeclaration, String name, Scopeable scope) { Declarator declarator = DeclarationInfo.getDeclarator(structDeclaration, name); return getTypeTree(structDeclaration.getF0(), declarator, scope); } public static Type getTypeTree(ParameterDeclaration paramDecl, Scopeable scope) { Type paramType = getTypeTree(paramDecl.getF0(), paramDecl.getF1(), scope); if (paramType instanceof ArrayType) { ArrayType arrType = (ArrayType) paramType; paramType = new PointerType(arrType.getElementType()); } // System.out.println(paramDecl + " is a " + paramType + " now."); return paramType; } public static Type getTypeTree(DeclarationSpecifiers declSpec, ParameterAbstraction paramAbs, Scopeable scope) { Type baseType; ArithmeticTypeKeyCollector arithmeticTypeGetter = new ArithmeticTypeKeyCollector(scope); declSpec.accept(arithmeticTypeGetter); baseType = Type.getTypeFromArithmeticKeys(arithmeticTypeGetter.keywords); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope); if (baseType == null) { // Here, the declaration specifiers use a struct, union, enum or typedef. baseType = declSpec.accept(typeTreeGetter, baseType); } // System.out.println("Found a " + baseType + " for " + // declSpec.getInfo().getString()); // TODO: Add qualifiers here. Type typeFromDeclarator = paramAbs.accept(typeTreeGetter, baseType); return typeFromDeclarator; } public static Type getTypeTree(DeclarationSpecifiers declSpec, Scopeable scope, boolean deleteUserSpecifiedTypes) { // if (Misc.isTypedef(declSpec)) { // return null; // } Type baseType; ArithmeticTypeKeyCollector arithmeticTypeGetter = new ArithmeticTypeKeyCollector(scope); declSpec.accept(arithmeticTypeGetter); baseType = Type.getTypeFromArithmeticKeys(arithmeticTypeGetter.keywords); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope, deleteUserSpecifiedTypes); if (baseType == null) { // Here, the declaration specifiers use a struct, union, enum or typedef. baseType = declSpec.accept(typeTreeGetter, baseType); } return baseType; } public static Type getTypeTree(DeclarationSpecifiers declSpec, Scopeable scope) { // if (Misc.isTypedef(declSpec)) { // return null; // } Type baseType; ArithmeticTypeKeyCollector arithmeticTypeGetter = new ArithmeticTypeKeyCollector(scope); declSpec.accept(arithmeticTypeGetter); baseType = Type.getTypeFromArithmeticKeys(arithmeticTypeGetter.keywords); if (baseType == null) { // Here, the declaration specifiers use a struct, union, enum or typedef. TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope); baseType = declSpec.accept(typeTreeGetter, baseType); } return baseType; } public static Type getTypeTree(DeclarationSpecifiers declSpec, Declarator declarator, Scopeable scope, boolean deleteUserDefinedType) { // if (Misc.isTypedef(declSpec)) { // return null; // } Type baseType; ArithmeticTypeKeyCollector arithmeticTypeGetter = new ArithmeticTypeKeyCollector(scope); declSpec.accept(arithmeticTypeGetter); baseType = Type.getTypeFromArithmeticKeys(arithmeticTypeGetter.keywords); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope, deleteUserDefinedType); if (baseType == null) { // Here, the declaration specifiers use a struct, union, enum or typedef. baseType = declSpec.accept(typeTreeGetter, baseType); } // TODO: Add qualifiers here. Type typeFromDeclarator = declarator.accept(typeTreeGetter, baseType); return typeFromDeclarator; } public static Type getTypeTree(DeclarationSpecifiers declSpec, Declarator declarator, Scopeable scope) { // if (Misc.isTypedef(declSpec)) { // return null; // } Type baseType; ArithmeticTypeKeyCollector arithmeticTypeGetter = new ArithmeticTypeKeyCollector(scope); declSpec.accept(arithmeticTypeGetter); baseType = Type.getTypeFromArithmeticKeys(arithmeticTypeGetter.keywords); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope); if (baseType == null) { // Here, the declaration specifiers use a struct, union, enum or typedef. baseType = declSpec.accept(typeTreeGetter, baseType); } // TODO: Add qualifiers here. Type typeFromDeclarator = declarator.accept(typeTreeGetter, baseType); return typeFromDeclarator; } public static Type getTypeTree(SpecifierQualifierList specQualList, Declarator declarator, Scopeable scope) { Type baseType; ArithmeticTypeKeyCollector arithmeticTypeGetter = new ArithmeticTypeKeyCollector(scope); specQualList.accept(arithmeticTypeGetter); baseType = Type.getTypeFromArithmeticKeys(arithmeticTypeGetter.keywords); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope); if (baseType == null) { // Here, the specifier-qualifier list uses a struct, union, enum or typedef. baseType = specQualList.accept(typeTreeGetter, baseType); } // TODO: Add qualifiers here. Type typeFromDeclarator = declarator.accept(typeTreeGetter, baseType); return typeFromDeclarator; } public static Type getTypeTree(DeclarationSpecifiers declSpec, Declarator declarator, Type inType, Scopeable scope) { // if (Misc.isTypedef(declSpec)) { // return null; // } Type baseType; ArithmeticTypeKeyCollector arithmeticTypeGetter = new ArithmeticTypeKeyCollector(scope); declSpec.accept(arithmeticTypeGetter); baseType = Type.getTypeFromArithmeticKeys(arithmeticTypeGetter.keywords); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope); if (baseType == null) { // Here, the declaration specifiers use a struct, union, enum or typedef. baseType = declSpec.accept(typeTreeGetter, inType); } // TODO: Add qualifiers here. Type typeFromDeclarator = declarator.accept(typeTreeGetter, baseType); return typeFromDeclarator; } public static Type getTypeTree(SpecifierQualifierList specQualList, Scopeable scope) { Type baseType; ArithmeticTypeKeyCollector arithmeticTypeGetter = new ArithmeticTypeKeyCollector(scope); specQualList.accept(arithmeticTypeGetter); baseType = Type.getTypeFromArithmeticKeys(arithmeticTypeGetter.keywords); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope); if (baseType == null) { // Here, the specifier-qualifier list uses a struct, union, enum or typedef. baseType = specQualList.accept(typeTreeGetter, baseType); } return baseType; } public static Type getTypeTree(SpecifierQualifierList specQualList, StructDeclarator structDecl, Scopeable scope) { Type baseType = Type.getTypeTree(specQualList, scope); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope); return structDecl.accept(typeTreeGetter, baseType); } public static Type getTypeTree(SpecifierQualifierList specQualList, AbstractDeclarator absDecl, Scopeable scope) { Type baseType = Type.getTypeTree(specQualList, scope); TypeTreeGetter typeTreeGetter = new TypeTreeGetter(scope); return absDecl.accept(typeTreeGetter, baseType); } public static Type getTypeTree(TypeName typeName, Scopeable scope) { if (!typeName.getF1().present()) { return Type.getTypeTree(typeName.getF0(), scope); } else { AbstractDeclarator absDecl = (AbstractDeclarator) typeName.getF1().getNode(); return Type.getTypeTree(typeName.getF0(), absDecl, scope); } } public static Type getTypeFromArithmeticKeys(List<ArithmeticTypeKey> arithTypeKeyList) { // Void if (arithTypeKeyList.contains(ArithmeticTypeKey.VOID)) { return VoidType.type(); } // Characters if (arithTypeKeyList.contains(ArithmeticTypeKey.CHAR)) { if (arithTypeKeyList.contains(ArithmeticTypeKey.SIGNED)) { return SignedCharType.type(); } else if (arithTypeKeyList.contains(ArithmeticTypeKey.UNSIGNED)) { return UnsignedCharType.type(); } else { return CharType.type(); } } // Short if (arithTypeKeyList.contains(ArithmeticTypeKey.SHORT)) { if (arithTypeKeyList.contains(ArithmeticTypeKey.UNSIGNED)) { return UnsignedShortIntType.type(); } else { return SignedShortIntType.type(); } } // Long's if (arithTypeKeyList.contains(ArithmeticTypeKey.LONG)) { arithTypeKeyList.remove(ArithmeticTypeKey.LONG); if (arithTypeKeyList.contains(ArithmeticTypeKey.LONG)) { arithTypeKeyList.add(ArithmeticTypeKey.LONG); // Long Long if (arithTypeKeyList.contains(ArithmeticTypeKey.UNSIGNED)) { return UnsignedLongLongIntType.type(); // return UnsignedLongIntType.type(); // Error. } else { return SignedLongLongIntType.type(); // return SignedLongIntType.type(); // Error. } } else { arithTypeKeyList.add(ArithmeticTypeKey.LONG); // Long Double and Long Double Complex if (arithTypeKeyList.contains(ArithmeticTypeKey.DOUBLE)) { if (arithTypeKeyList.contains(ArithmeticTypeKey._COMPLEX)) { return LongDoubleComplexType.type(); } else { return LongDoubleType.type(); } } // Long if (arithTypeKeyList.contains(ArithmeticTypeKey.UNSIGNED)) { return UnsignedLongIntType.type(); } else { return SignedLongIntType.type(); } } } // Int's if (arithTypeKeyList.contains(ArithmeticTypeKey.INT)) { if (arithTypeKeyList.contains(ArithmeticTypeKey.UNSIGNED)) { return UnsignedIntType.type(); } else { return SignedIntType.type(); } } if (arithTypeKeyList.contains(ArithmeticTypeKey.UNSIGNED)) { return UnsignedIntType.type(); } // _Bool if (arithTypeKeyList.contains(ArithmeticTypeKey._BOOL)) { return _BoolType.type(); } // Float's if (arithTypeKeyList.contains(ArithmeticTypeKey.FLOAT)) { if (arithTypeKeyList.contains(ArithmeticTypeKey._COMPLEX)) { return FloatComplexType.type(); } else { return FloatType.type(); } } // Double's if (arithTypeKeyList.contains(ArithmeticTypeKey.DOUBLE)) { if (arithTypeKeyList.contains(ArithmeticTypeKey._COMPLEX)) { return DoubleComplexType.type(); } else { return DoubleType.type(); } } return null; } public static Type getType(NodeToken nodeToken) { Cell cell = Misc.getSymbolOrFreeEntry(nodeToken); if (cell == null) { return null; } if (cell instanceof Symbol) { return ((Symbol) cell).getType(); } else { return null; } } /************************************************************** * Following are some of the methods that should go into the Expression * subclass of the Expression tree when we create it. */ /** * Returns the type of the expression <code>exp</code>. * * @param exp * @return * type of <code>exp</code> */ public static Type getType(Expression exp) { ExpressionTypeGetter typeGetter = new ExpressionTypeGetter(); Type retType = exp.accept(typeGetter); return retType; } /** * Obtain the type of the given base syntax expression. * * @param baseSyntax * @return */ public static Type getType(BaseSyntax baseSyntax) { if (baseSyntax.primExp == null) { return null; } Type primType = Type.getType(baseSyntax.primExp); if (baseSyntax.postFixOps == null || baseSyntax.postFixOps.isEmpty()) { return primType; } int derefCount = baseSyntax.postFixOps.size(); while (derefCount != 0) { if (primType instanceof PointerType) { PointerType ptrType = (PointerType) primType; primType = ptrType.getPointeeType(); } else if (primType instanceof ArrayType) { ArrayType arrType = (ArrayType) primType; primType = arrType.getElementType(); } else { assert (false) : "Incorrect type obtained for " + baseSyntax; } derefCount--; } return primType; } /** * Returns the Type entry which defines the type named "tag", * and is present in either an enclosing struct/union, or in an * enclosing CompoundStatement, FunctionDefinition or TranslationUnit. * * @param name * @param scope * @return */ public static Type getTypeEntry(String tag, Scopeable scope) { if (scope instanceof StructType || scope instanceof UnionType) { if (scope instanceof StructType) { StructType structType = (StructType) scope; if (structType.getTypeTable().containsKey(tag)) { return structType.getTypeTable().get(tag); } return Type.getTypeEntry(tag, structType.getDefiningScope()); } else { UnionType unionType = (UnionType) scope; if (unionType.getTypeTable().containsKey(tag)) { return unionType.getTypeTable().get(tag); } return Type.getTypeEntry(tag, unionType.getDefiningScope()); } } else if (scope instanceof Node) { return Type.getTypeEntry(tag, (Node) scope); } return null; } /** * Returns reference to the Type object that represents a struct, * union or an enum with the specified <code>tag</code> as visible in the * node <code>node</code>. * * @param tag * @param node * @return */ private static Type getTypeEntry(String tag, Node node) { if (node == null) { return null; } Node scopeChoice = node; while (scopeChoice != null) { if (scopeChoice instanceof TranslationUnit) { HashMap<String, Type> typeTable = ((RootInfo) scopeChoice.getInfo()).getTypeTable(); if (typeTable.containsKey(tag)) { return typeTable.get(tag); } } else if (scopeChoice instanceof CompoundStatement) { HashMap<String, Type> typeTable = ((CompoundStatementInfo) scopeChoice.getInfo()).getTypeTable(); if (typeTable.containsKey(tag)) { return typeTable.get(tag); } } else if (scopeChoice instanceof FunctionDefinition) { HashMap<String, Type> typeTable = ((FunctionDefinitionInfo) scopeChoice.getInfo()).getTypeTable(); if (typeTable.containsKey(tag)) { return typeTable.get(tag); } } scopeChoice = (Node) Misc.getEnclosingBlock(scopeChoice); } // System.out.println("Could not find the type " + tag + " in " + // node.getInfo().getString() + " at line #" + Misc.getLineNum(node)); return null; } /** * Returns the type with specified tag, if present in the given scope, * or any of the nested scope. * * @param tag * @param scope * @return */ public static Type getTypeFromScope(String tag, Scopeable scope) { return Type.getTypeEntry(tag, scope); } /** * Checks whether the given {@link CastExpressionTyped} node performs * an incompatible type cast between pointers/arrays. * <br> * Note that this method <i>ignores</i> type casts that are done on type * {@code (void *)}. * (We cannot ignore type casts <i>to</i> {@code (void *)} as well, since * these together can be then used to perform any desired incompatible type * cast without getting caught by this method.) * * @param castExp * a {@link CastExpressionTyped} expression to be tested. * @return * true, if the given expression performs an incompatible type cast. */ public static boolean hasIncompatibleTypeCastOfPointers(CastExpressionTyped cet) { Scopeable scope = Misc.getEnclosingBlock(cet); if (scope == null) { return false; } Type castType = Type.getTypeTree(cet.getF1(), scope); Type expType = Type.getType(cet.getF3()); if (!(castType instanceof ArrayType) && !(castType instanceof PointerType)) { return false; } if (!(expType instanceof ArrayType) && !(expType instanceof PointerType)) { return false; } if (expType instanceof PointerType) { PointerType pType = (PointerType) expType; if (pType.getPointeeType() == VoidType.type()) { return false; } } if (!castType.toString().equals(expType.toString())) { return true; } else { return false; } } /** * Enters the provided tag and type key-value pair into the * typeTable of the specified scope, if the type is not already * present in the complete state. * * @param scope * @param tag * @param newType * @return * type which is finally present in the typeTable of scope, for the * given tag. */ public static Type putTypeToScope(Scopeable scope, String tag, Type newType) { assert (newType instanceof StructType || newType instanceof UnionType || newType instanceof EnumType); HashMap<String, Type> typeTable = scope.getTypeTable(); // Future code. Can be thought about later. // if (!deletedTypes.isEmpty()) { // System.out.println(deletedTypes + " still " + tag + "."); // } // Type oldType = typeTable.get(tag); if (oldType == null) { typeTable.put(tag, newType); return newType; } else if (!oldType.isComplete()) { typeTable.put(tag, newType); return newType; } else { if (!newType.isComplete()) { return oldType; } else { if (newType instanceof StructType) { StructType newStructType = (StructType) newType; StructType oldStructType = (StructType) oldType; if (newStructType.getDeclaringNode() == oldStructType.getDeclaringNode()) { return oldStructType; } } else if (newType instanceof UnionType) { UnionType newUnionType = (UnionType) newType; UnionType oldUnionType = (UnionType) oldType; if (newUnionType.getDeclaringNode() == oldUnionType.getDeclaringNode()) { return oldUnionType; } } else if (newType instanceof EnumType) { EnumType newEnumType = (EnumType) newType; EnumType oldEnumType = (EnumType) oldType; if (newEnumType.getDeclaringNode() == oldEnumType.getDeclaringNode()) { return oldEnumType; } } Misc.warnDueToLackOfFeature( "Attempting to redefine a complete type. Please look into the declarations of type " + newType, Program.getRoot()); // assert (false); // typeTable.put(tag, newType); return oldType; } } } public static Type removeTypeFromScope(Scopeable scope, String tag, Type type) { assert (type instanceof StructType || type instanceof UnionType || type instanceof EnumType); HashMap<String, Type> typeTable = scope.getTypeTable(); Type oldType = typeTable.get(tag); if (oldType != null) { Type.deletedTypes.add(oldType); } typeTable.remove(tag); return type; } /** * Obtain a set of all those types which have been used somewhere within the * declaration of the receiver type. * This set would contain the receiver type as well. * * @return * set of all those types which have been used somewhere within the * declaration of the receiver type. */ public abstract Set<Type> getAllTypes(); }
[ "public", "abstract", "class", "Type", "{", "public", "List", "<", "StorageClass", ">", "storageClasses", ";", "private", "static", "Set", "<", "Type", ">", "deletedTypes", "=", "new", "HashSet", "<", ">", "(", ")", ";", "public", "static", "void", "resetStaticFields", "(", ")", "{", "Type", ".", "deletedTypes", "=", "new", "HashSet", "<", ">", "(", ")", ";", "}", "/**\n\t * This method is overridden at appropriate subclasses\n\t * to return true.\n\t * \n\t * @return\n\t */", "public", "boolean", "isComplete", "(", ")", "{", "return", "true", ";", "}", "/**\n\t * This method is overridden at appropriate subclasses\n\t * to return true.\n\t * \n\t * @return\n\t */", "public", "boolean", "isCharacterType", "(", ")", "{", "return", "false", ";", "}", "/**\n\t * This method is overridden at appropriate subclasses\n\t * to return true.\n\t * \n\t * @return\n\t */", "public", "boolean", "isBasicType", "(", ")", "{", "return", "false", ";", "}", "/**\n\t * This method is overridden at appropriate subclasses\n\t * to return true.\n\t * \n\t * @return\n\t */", "public", "boolean", "isRealType", "(", ")", "{", "return", "false", ";", "}", "public", "boolean", "isScalarType", "(", ")", "{", "if", "(", "this", "instanceof", "ArithmeticType", ")", "{", "return", "true", ";", "}", "else", "if", "(", "this", "instanceof", "PointerType", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "/**\n\t * Note that unions are not aggregate types.\n\t * \n\t * @return\n\t */", "public", "boolean", "isAggregateType", "(", ")", "{", "if", "(", "this", "instanceof", "ArrayType", ")", "{", "return", "true", ";", "}", "else", "if", "(", "this", "instanceof", "StructType", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "public", "abstract", "boolean", "isKnownConstantSized", "(", ")", ";", "public", "boolean", "isDerivedDeclaratorType", "(", ")", "{", "if", "(", "this", "instanceof", "ArrayType", "||", "this", "instanceof", "FunctionType", "||", "this", "instanceof", "PointerType", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "public", "Type", "getIntegerPromotedType", "(", ")", "{", "if", "(", "this", "instanceof", "IntegerType", ")", "{", "IntegerType", "integerType", "=", "(", "IntegerType", ")", "this", ";", "if", "(", "integerType", ".", "getIntegerConversionRank", "(", ")", "<=", "SignedIntType", ".", "type", "(", ")", ".", "getIntegerConversionRank", "(", ")", ")", "{", "return", "SignedIntType", ".", "type", "(", ")", ";", "}", "}", "return", "this", ";", "}", "/**\n\t * Returns the type domain of the types.\n\t * Needs to be overridden by the complex types.\n\t * \n\t * @return\n\t */", "public", "TypeDomain", "getTypeDomain", "(", ")", "{", "return", "TypeDomain", ".", "REAL", ";", "}", "/**\n\t * Returns the corresponding real type for the current object.\n\t * Should be overridden by complex types.\n\t * \n\t * @return\n\t */", "public", "Type", "getRealType", "(", ")", "{", "return", "this", ";", "}", "/**\n\t * Returns the corresponding complex type for the current object.\n\t * Should be overridden by those real types which have a complex\n\t * counterpart.\n\t * \n\t * @return\n\t */", "public", "Type", "getComplexType", "(", ")", "{", "return", "this", ";", "}", "public", "boolean", "hasConstQualifier", "(", ")", "{", "return", "false", ";", "}", "protected", "abstract", "String", "preDeclarationString", "(", ")", ";", "protected", "abstract", "String", "postDeclarationString", "(", ")", ";", "/**\n\t * Returns a declaration for <code>tempName</code> with this type,\n\t * such that {@code tempName} can be used to hold a value of any object of\n\t * this type.\n\t * \n\t * @param tempName\n\t * @return\n\t */", "public", "Declaration", "getDeclaration", "(", "String", "tempName", ")", "{", "Declaration", "decl", "=", "FrontEnd", ".", "parseAlone", "(", "this", ".", "preDeclarationString", "(", ")", "+", "\"", " ", "\"", "+", "tempName", "+", "\"", " ", "\"", "+", "this", ".", "postDeclarationString", "(", ")", "+", "\"", ";", "\"", ",", "Declaration", ".", "class", ")", ";", "return", "decl", ";", "}", "/**\n\t * Returns a declaration for <code>tempName</code> with this type,\n\t * without any pointer conversions. Do not use this method if you are\n\t * creating temporaries that should be able to hold the value of any object\n\t * of this type.\n\t * \n\t * @param tempName\n\t * @return\n\t */", "public", "Declaration", "getExactDeclarationWithoutInit", "(", "String", "tempName", ")", "{", "Declaration", "decl", "=", "FrontEnd", ".", "parseAlone", "(", "this", ".", "preString", "(", ")", "+", "\"", " ", "\"", "+", "tempName", "+", "\"", " ", "\"", "+", "this", ".", "postString", "(", ")", "+", "\"", ";", "\"", ",", "Declaration", ".", "class", ")", ";", "return", "decl", ";", "}", "public", "abstract", "boolean", "isCompatibleWith", "(", "Type", "t", ")", ";", "protected", "abstract", "String", "preString", "(", ")", ";", "protected", "abstract", "String", "postString", "(", ")", ";", "protected", "String", "preStringForCopy", "(", ")", "{", "return", "this", ".", "preString", "(", ")", ";", "}", "protected", "String", "postStringForCopy", "(", ")", "{", "return", "this", ".", "postString", "(", ")", ";", "}", "/**\n\t * Returns a string of an abstract declaration of this type.\n\t * \n\t * @return\n\t */", "@", "Override", "public", "final", "String", "toString", "(", ")", "{", "return", "this", ".", "preString", "(", ")", "+", "\"", " ", "\"", "+", "this", ".", "postString", "(", ")", ";", "}", "public", "final", "String", "toString", "(", "String", "idName", ")", "{", "return", "this", ".", "preString", "(", ")", "+", "\"", " ", "\"", "+", "idName", "+", "\"", " ", "\"", "+", "this", ".", "postString", "(", ")", ";", "}", "public", "static", "FunctionType", "getTypeTree", "(", "FunctionDefinition", "funcDef", ",", "Scopeable", "scope", ")", "{", "if", "(", "!", "funcDef", ".", "getF0", "(", ")", ".", "present", "(", ")", ")", "{", "Misc", ".", "exitDueToError", "(", "\"", "Could not find the return type (int) of : ", "\"", "+", "funcDef", ".", "getInfo", "(", ")", ".", "getFunctionName", "(", ")", ")", ";", "}", "return", "(", "FunctionType", ")", "Type", ".", "getTypeTree", "(", "(", "DeclarationSpecifiers", ")", "funcDef", ".", "getF0", "(", ")", ".", "getNode", "(", ")", ",", "funcDef", ".", "getF1", "(", ")", ",", "scope", ")", ";", "}", "public", "static", "List", "<", "Type", ">", "getTypeTree", "(", "Declaration", "declaration", ",", "Scopeable", "scope", ",", "boolean", "deleteUserDefinedTypes", ")", "{", "List", "<", "String", ">", "ids", "=", "declaration", ".", "getInfo", "(", ")", ".", "getIDNameList", "(", ")", ";", "List", "<", "Type", ">", "typeList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "String", "name", ":", "ids", ")", "{", "Type", "tempType", "=", "getTypeTree", "(", "declaration", ",", "name", ",", "scope", ",", "deleteUserDefinedTypes", ")", ";", "if", "(", "tempType", "!=", "null", ")", "{", "typeList", ".", "add", "(", "tempType", ")", ";", "}", "}", "return", "typeList", ";", "}", "public", "static", "List", "<", "Type", ">", "getTypeTree", "(", "Declaration", "declaration", ",", "Scopeable", "scope", ")", "{", "List", "<", "String", ">", "ids", "=", "declaration", ".", "getInfo", "(", ")", ".", "getIDNameList", "(", ")", ";", "List", "<", "Type", ">", "typeList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "if", "(", "ids", ".", "isEmpty", "(", ")", ")", "{", "getTypeTree", "(", "declaration", ".", "getF0", "(", ")", ",", "scope", ")", ";", "}", "for", "(", "String", "name", ":", "ids", ")", "{", "Type", "tempType", "=", "getTypeTree", "(", "declaration", ",", "name", ",", "scope", ")", ";", "if", "(", "tempType", "!=", "null", ")", "{", "typeList", ".", "add", "(", "tempType", ")", ";", "}", "}", "return", "typeList", ";", "}", "public", "static", "List", "<", "Type", ">", "getTypeTree", "(", "ParameterTypeList", "paramTypeList", ",", "Scopeable", "scope", ")", "{", "ParameterList", "paramList", "=", "paramTypeList", ".", "getF0", "(", ")", ";", "List", "<", "Type", ">", "typeList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "typeList", ".", "add", "(", "getTypeTree", "(", "paramList", ".", "getF0", "(", ")", ",", "scope", ")", ")", ";", "for", "(", "Node", "nodeSeqNode", ":", "paramList", ".", "getF1", "(", ")", ".", "getNodes", "(", ")", ")", "{", "NodeSequence", "nodeSeq", "=", "(", "NodeSequence", ")", "nodeSeqNode", ";", "typeList", ".", "add", "(", "getTypeTree", "(", "(", "ParameterDeclaration", ")", "nodeSeq", ".", "getNodes", "(", ")", ".", "get", "(", "1", ")", ",", "scope", ")", ")", ";", "}", "return", "typeList", ";", "}", "public", "static", "Type", "getTypeTree", "(", "Declaration", "declaration", ",", "String", "name", ",", "Scopeable", "scope", ",", "boolean", "deleteUserDefinedTypes", ")", "{", "Declarator", "declarator", "=", "declaration", ".", "getInfo", "(", ")", ".", "getDeclarator", "(", "name", ")", ";", "return", "getTypeTree", "(", "declaration", ".", "getF0", "(", ")", ",", "declarator", ",", "scope", ",", "deleteUserDefinedTypes", ")", ";", "}", "public", "static", "Type", "getTypeTree", "(", "Declaration", "declaration", ",", "String", "name", ",", "Scopeable", "scope", ")", "{", "Declarator", "declarator", "=", "declaration", ".", "getInfo", "(", ")", ".", "getDeclarator", "(", "name", ")", ";", "return", "getTypeTree", "(", "declaration", ".", "getF0", "(", ")", ",", "declarator", ",", "scope", ")", ";", "}", "public", "static", "Type", "getTypeTree", "(", "Declaration", "declaration", ",", "String", "name", ",", "Type", "inType", ",", "Scopeable", "scope", ")", "{", "Declarator", "declarator", "=", "declaration", ".", "getInfo", "(", ")", ".", "getDeclarator", "(", "name", ")", ";", "return", "getTypeTree", "(", "declaration", ".", "getF0", "(", ")", ",", "declarator", ",", "inType", ",", "scope", ")", ";", "}", "public", "static", "List", "<", "Type", ">", "getTypeTree", "(", "StructDeclaration", "structDeclaration", ",", "Scopeable", "scope", ")", "{", "List", "<", "String", ">", "ids", "=", "new", "ArrayList", "<", ">", "(", "DeclarationInfo", ".", "getIdNameList", "(", "structDeclaration", ")", ")", ";", "List", "<", "Type", ">", "typeList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "String", "name", ":", "ids", ")", "{", "typeList", ".", "add", "(", "getTypeTree", "(", "structDeclaration", ",", "name", ",", "scope", ")", ")", ";", "}", "return", "typeList", ";", "}", "public", "static", "Type", "getTypeTree", "(", "StructDeclaration", "structDeclaration", ",", "String", "name", ",", "Scopeable", "scope", ")", "{", "Declarator", "declarator", "=", "DeclarationInfo", ".", "getDeclarator", "(", "structDeclaration", ",", "name", ")", ";", "return", "getTypeTree", "(", "structDeclaration", ".", "getF0", "(", ")", ",", "declarator", ",", "scope", ")", ";", "}", "public", "static", "Type", "getTypeTree", "(", "ParameterDeclaration", "paramDecl", ",", "Scopeable", "scope", ")", "{", "Type", "paramType", "=", "getTypeTree", "(", "paramDecl", ".", "getF0", "(", ")", ",", "paramDecl", ".", "getF1", "(", ")", ",", "scope", ")", ";", "if", "(", "paramType", "instanceof", "ArrayType", ")", "{", "ArrayType", "arrType", "=", "(", "ArrayType", ")", "paramType", ";", "paramType", "=", "new", "PointerType", "(", "arrType", ".", "getElementType", "(", ")", ")", ";", "}", "return", "paramType", ";", "}", "public", "static", "Type", "getTypeTree", "(", "DeclarationSpecifiers", "declSpec", ",", "ParameterAbstraction", "paramAbs", ",", "Scopeable", "scope", ")", "{", "Type", "baseType", ";", "ArithmeticTypeKeyCollector", "arithmeticTypeGetter", "=", "new", "ArithmeticTypeKeyCollector", "(", "scope", ")", ";", "declSpec", ".", "accept", "(", "arithmeticTypeGetter", ")", ";", "baseType", "=", "Type", ".", "getTypeFromArithmeticKeys", "(", "arithmeticTypeGetter", ".", "keywords", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ")", ";", "if", "(", "baseType", "==", "null", ")", "{", "baseType", "=", "declSpec", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "Type", "typeFromDeclarator", "=", "paramAbs", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "return", "typeFromDeclarator", ";", "}", "public", "static", "Type", "getTypeTree", "(", "DeclarationSpecifiers", "declSpec", ",", "Scopeable", "scope", ",", "boolean", "deleteUserSpecifiedTypes", ")", "{", "Type", "baseType", ";", "ArithmeticTypeKeyCollector", "arithmeticTypeGetter", "=", "new", "ArithmeticTypeKeyCollector", "(", "scope", ")", ";", "declSpec", ".", "accept", "(", "arithmeticTypeGetter", ")", ";", "baseType", "=", "Type", ".", "getTypeFromArithmeticKeys", "(", "arithmeticTypeGetter", ".", "keywords", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ",", "deleteUserSpecifiedTypes", ")", ";", "if", "(", "baseType", "==", "null", ")", "{", "baseType", "=", "declSpec", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "return", "baseType", ";", "}", "public", "static", "Type", "getTypeTree", "(", "DeclarationSpecifiers", "declSpec", ",", "Scopeable", "scope", ")", "{", "Type", "baseType", ";", "ArithmeticTypeKeyCollector", "arithmeticTypeGetter", "=", "new", "ArithmeticTypeKeyCollector", "(", "scope", ")", ";", "declSpec", ".", "accept", "(", "arithmeticTypeGetter", ")", ";", "baseType", "=", "Type", ".", "getTypeFromArithmeticKeys", "(", "arithmeticTypeGetter", ".", "keywords", ")", ";", "if", "(", "baseType", "==", "null", ")", "{", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ")", ";", "baseType", "=", "declSpec", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "return", "baseType", ";", "}", "public", "static", "Type", "getTypeTree", "(", "DeclarationSpecifiers", "declSpec", ",", "Declarator", "declarator", ",", "Scopeable", "scope", ",", "boolean", "deleteUserDefinedType", ")", "{", "Type", "baseType", ";", "ArithmeticTypeKeyCollector", "arithmeticTypeGetter", "=", "new", "ArithmeticTypeKeyCollector", "(", "scope", ")", ";", "declSpec", ".", "accept", "(", "arithmeticTypeGetter", ")", ";", "baseType", "=", "Type", ".", "getTypeFromArithmeticKeys", "(", "arithmeticTypeGetter", ".", "keywords", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ",", "deleteUserDefinedType", ")", ";", "if", "(", "baseType", "==", "null", ")", "{", "baseType", "=", "declSpec", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "Type", "typeFromDeclarator", "=", "declarator", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "return", "typeFromDeclarator", ";", "}", "public", "static", "Type", "getTypeTree", "(", "DeclarationSpecifiers", "declSpec", ",", "Declarator", "declarator", ",", "Scopeable", "scope", ")", "{", "Type", "baseType", ";", "ArithmeticTypeKeyCollector", "arithmeticTypeGetter", "=", "new", "ArithmeticTypeKeyCollector", "(", "scope", ")", ";", "declSpec", ".", "accept", "(", "arithmeticTypeGetter", ")", ";", "baseType", "=", "Type", ".", "getTypeFromArithmeticKeys", "(", "arithmeticTypeGetter", ".", "keywords", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ")", ";", "if", "(", "baseType", "==", "null", ")", "{", "baseType", "=", "declSpec", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "Type", "typeFromDeclarator", "=", "declarator", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "return", "typeFromDeclarator", ";", "}", "public", "static", "Type", "getTypeTree", "(", "SpecifierQualifierList", "specQualList", ",", "Declarator", "declarator", ",", "Scopeable", "scope", ")", "{", "Type", "baseType", ";", "ArithmeticTypeKeyCollector", "arithmeticTypeGetter", "=", "new", "ArithmeticTypeKeyCollector", "(", "scope", ")", ";", "specQualList", ".", "accept", "(", "arithmeticTypeGetter", ")", ";", "baseType", "=", "Type", ".", "getTypeFromArithmeticKeys", "(", "arithmeticTypeGetter", ".", "keywords", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ")", ";", "if", "(", "baseType", "==", "null", ")", "{", "baseType", "=", "specQualList", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "Type", "typeFromDeclarator", "=", "declarator", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "return", "typeFromDeclarator", ";", "}", "public", "static", "Type", "getTypeTree", "(", "DeclarationSpecifiers", "declSpec", ",", "Declarator", "declarator", ",", "Type", "inType", ",", "Scopeable", "scope", ")", "{", "Type", "baseType", ";", "ArithmeticTypeKeyCollector", "arithmeticTypeGetter", "=", "new", "ArithmeticTypeKeyCollector", "(", "scope", ")", ";", "declSpec", ".", "accept", "(", "arithmeticTypeGetter", ")", ";", "baseType", "=", "Type", ".", "getTypeFromArithmeticKeys", "(", "arithmeticTypeGetter", ".", "keywords", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ")", ";", "if", "(", "baseType", "==", "null", ")", "{", "baseType", "=", "declSpec", ".", "accept", "(", "typeTreeGetter", ",", "inType", ")", ";", "}", "Type", "typeFromDeclarator", "=", "declarator", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "return", "typeFromDeclarator", ";", "}", "public", "static", "Type", "getTypeTree", "(", "SpecifierQualifierList", "specQualList", ",", "Scopeable", "scope", ")", "{", "Type", "baseType", ";", "ArithmeticTypeKeyCollector", "arithmeticTypeGetter", "=", "new", "ArithmeticTypeKeyCollector", "(", "scope", ")", ";", "specQualList", ".", "accept", "(", "arithmeticTypeGetter", ")", ";", "baseType", "=", "Type", ".", "getTypeFromArithmeticKeys", "(", "arithmeticTypeGetter", ".", "keywords", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ")", ";", "if", "(", "baseType", "==", "null", ")", "{", "baseType", "=", "specQualList", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "return", "baseType", ";", "}", "public", "static", "Type", "getTypeTree", "(", "SpecifierQualifierList", "specQualList", ",", "StructDeclarator", "structDecl", ",", "Scopeable", "scope", ")", "{", "Type", "baseType", "=", "Type", ".", "getTypeTree", "(", "specQualList", ",", "scope", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ")", ";", "return", "structDecl", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "public", "static", "Type", "getTypeTree", "(", "SpecifierQualifierList", "specQualList", ",", "AbstractDeclarator", "absDecl", ",", "Scopeable", "scope", ")", "{", "Type", "baseType", "=", "Type", ".", "getTypeTree", "(", "specQualList", ",", "scope", ")", ";", "TypeTreeGetter", "typeTreeGetter", "=", "new", "TypeTreeGetter", "(", "scope", ")", ";", "return", "absDecl", ".", "accept", "(", "typeTreeGetter", ",", "baseType", ")", ";", "}", "public", "static", "Type", "getTypeTree", "(", "TypeName", "typeName", ",", "Scopeable", "scope", ")", "{", "if", "(", "!", "typeName", ".", "getF1", "(", ")", ".", "present", "(", ")", ")", "{", "return", "Type", ".", "getTypeTree", "(", "typeName", ".", "getF0", "(", ")", ",", "scope", ")", ";", "}", "else", "{", "AbstractDeclarator", "absDecl", "=", "(", "AbstractDeclarator", ")", "typeName", ".", "getF1", "(", ")", ".", "getNode", "(", ")", ";", "return", "Type", ".", "getTypeTree", "(", "typeName", ".", "getF0", "(", ")", ",", "absDecl", ",", "scope", ")", ";", "}", "}", "public", "static", "Type", "getTypeFromArithmeticKeys", "(", "List", "<", "ArithmeticTypeKey", ">", "arithTypeKeyList", ")", "{", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "VOID", ")", ")", "{", "return", "VoidType", ".", "type", "(", ")", ";", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "CHAR", ")", ")", "{", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "SIGNED", ")", ")", "{", "return", "SignedCharType", ".", "type", "(", ")", ";", "}", "else", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "UNSIGNED", ")", ")", "{", "return", "UnsignedCharType", ".", "type", "(", ")", ";", "}", "else", "{", "return", "CharType", ".", "type", "(", ")", ";", "}", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "SHORT", ")", ")", "{", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "UNSIGNED", ")", ")", "{", "return", "UnsignedShortIntType", ".", "type", "(", ")", ";", "}", "else", "{", "return", "SignedShortIntType", ".", "type", "(", ")", ";", "}", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "LONG", ")", ")", "{", "arithTypeKeyList", ".", "remove", "(", "ArithmeticTypeKey", ".", "LONG", ")", ";", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "LONG", ")", ")", "{", "arithTypeKeyList", ".", "add", "(", "ArithmeticTypeKey", ".", "LONG", ")", ";", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "UNSIGNED", ")", ")", "{", "return", "UnsignedLongLongIntType", ".", "type", "(", ")", ";", "}", "else", "{", "return", "SignedLongLongIntType", ".", "type", "(", ")", ";", "}", "}", "else", "{", "arithTypeKeyList", ".", "add", "(", "ArithmeticTypeKey", ".", "LONG", ")", ";", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "DOUBLE", ")", ")", "{", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "_COMPLEX", ")", ")", "{", "return", "LongDoubleComplexType", ".", "type", "(", ")", ";", "}", "else", "{", "return", "LongDoubleType", ".", "type", "(", ")", ";", "}", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "UNSIGNED", ")", ")", "{", "return", "UnsignedLongIntType", ".", "type", "(", ")", ";", "}", "else", "{", "return", "SignedLongIntType", ".", "type", "(", ")", ";", "}", "}", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "INT", ")", ")", "{", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "UNSIGNED", ")", ")", "{", "return", "UnsignedIntType", ".", "type", "(", ")", ";", "}", "else", "{", "return", "SignedIntType", ".", "type", "(", ")", ";", "}", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "UNSIGNED", ")", ")", "{", "return", "UnsignedIntType", ".", "type", "(", ")", ";", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "_BOOL", ")", ")", "{", "return", "_BoolType", ".", "type", "(", ")", ";", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "FLOAT", ")", ")", "{", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "_COMPLEX", ")", ")", "{", "return", "FloatComplexType", ".", "type", "(", ")", ";", "}", "else", "{", "return", "FloatType", ".", "type", "(", ")", ";", "}", "}", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "DOUBLE", ")", ")", "{", "if", "(", "arithTypeKeyList", ".", "contains", "(", "ArithmeticTypeKey", ".", "_COMPLEX", ")", ")", "{", "return", "DoubleComplexType", ".", "type", "(", ")", ";", "}", "else", "{", "return", "DoubleType", ".", "type", "(", ")", ";", "}", "}", "return", "null", ";", "}", "public", "static", "Type", "getType", "(", "NodeToken", "nodeToken", ")", "{", "Cell", "cell", "=", "Misc", ".", "getSymbolOrFreeEntry", "(", "nodeToken", ")", ";", "if", "(", "cell", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "cell", "instanceof", "Symbol", ")", "{", "return", "(", "(", "Symbol", ")", "cell", ")", ".", "getType", "(", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}", "/**************************************************************\n\t * Following are some of the methods that should go into the Expression\n\t * subclass of the Expression tree when we create it.\n\t */", "/**\n\t * Returns the type of the expression <code>exp</code>.\n\t * \n\t * @param exp\n\t * @return\n\t * type of <code>exp</code>\n\t */", "public", "static", "Type", "getType", "(", "Expression", "exp", ")", "{", "ExpressionTypeGetter", "typeGetter", "=", "new", "ExpressionTypeGetter", "(", ")", ";", "Type", "retType", "=", "exp", ".", "accept", "(", "typeGetter", ")", ";", "return", "retType", ";", "}", "/**\n\t * Obtain the type of the given base syntax expression.\n\t * \n\t * @param baseSyntax\n\t * @return\n\t */", "public", "static", "Type", "getType", "(", "BaseSyntax", "baseSyntax", ")", "{", "if", "(", "baseSyntax", ".", "primExp", "==", "null", ")", "{", "return", "null", ";", "}", "Type", "primType", "=", "Type", ".", "getType", "(", "baseSyntax", ".", "primExp", ")", ";", "if", "(", "baseSyntax", ".", "postFixOps", "==", "null", "||", "baseSyntax", ".", "postFixOps", ".", "isEmpty", "(", ")", ")", "{", "return", "primType", ";", "}", "int", "derefCount", "=", "baseSyntax", ".", "postFixOps", ".", "size", "(", ")", ";", "while", "(", "derefCount", "!=", "0", ")", "{", "if", "(", "primType", "instanceof", "PointerType", ")", "{", "PointerType", "ptrType", "=", "(", "PointerType", ")", "primType", ";", "primType", "=", "ptrType", ".", "getPointeeType", "(", ")", ";", "}", "else", "if", "(", "primType", "instanceof", "ArrayType", ")", "{", "ArrayType", "arrType", "=", "(", "ArrayType", ")", "primType", ";", "primType", "=", "arrType", ".", "getElementType", "(", ")", ";", "}", "else", "{", "assert", "(", "false", ")", ":", "\"", "Incorrect type obtained for ", "\"", "+", "baseSyntax", ";", "}", "derefCount", "--", ";", "}", "return", "primType", ";", "}", "/**\n\t * Returns the Type entry which defines the type named \"tag\",\n\t * and is present in either an enclosing struct/union, or in an\n\t * enclosing CompoundStatement, FunctionDefinition or TranslationUnit.\n\t * \n\t * @param name\n\t * @param scope\n\t * @return\n\t */", "public", "static", "Type", "getTypeEntry", "(", "String", "tag", ",", "Scopeable", "scope", ")", "{", "if", "(", "scope", "instanceof", "StructType", "||", "scope", "instanceof", "UnionType", ")", "{", "if", "(", "scope", "instanceof", "StructType", ")", "{", "StructType", "structType", "=", "(", "StructType", ")", "scope", ";", "if", "(", "structType", ".", "getTypeTable", "(", ")", ".", "containsKey", "(", "tag", ")", ")", "{", "return", "structType", ".", "getTypeTable", "(", ")", ".", "get", "(", "tag", ")", ";", "}", "return", "Type", ".", "getTypeEntry", "(", "tag", ",", "structType", ".", "getDefiningScope", "(", ")", ")", ";", "}", "else", "{", "UnionType", "unionType", "=", "(", "UnionType", ")", "scope", ";", "if", "(", "unionType", ".", "getTypeTable", "(", ")", ".", "containsKey", "(", "tag", ")", ")", "{", "return", "unionType", ".", "getTypeTable", "(", ")", ".", "get", "(", "tag", ")", ";", "}", "return", "Type", ".", "getTypeEntry", "(", "tag", ",", "unionType", ".", "getDefiningScope", "(", ")", ")", ";", "}", "}", "else", "if", "(", "scope", "instanceof", "Node", ")", "{", "return", "Type", ".", "getTypeEntry", "(", "tag", ",", "(", "Node", ")", "scope", ")", ";", "}", "return", "null", ";", "}", "/**\n\t * Returns reference to the Type object that represents a struct,\n\t * union or an enum with the specified <code>tag</code> as visible in the\n\t * node <code>node</code>.\n\t * \n\t * @param tag\n\t * @param node\n\t * @return\n\t */", "private", "static", "Type", "getTypeEntry", "(", "String", "tag", ",", "Node", "node", ")", "{", "if", "(", "node", "==", "null", ")", "{", "return", "null", ";", "}", "Node", "scopeChoice", "=", "node", ";", "while", "(", "scopeChoice", "!=", "null", ")", "{", "if", "(", "scopeChoice", "instanceof", "TranslationUnit", ")", "{", "HashMap", "<", "String", ",", "Type", ">", "typeTable", "=", "(", "(", "RootInfo", ")", "scopeChoice", ".", "getInfo", "(", ")", ")", ".", "getTypeTable", "(", ")", ";", "if", "(", "typeTable", ".", "containsKey", "(", "tag", ")", ")", "{", "return", "typeTable", ".", "get", "(", "tag", ")", ";", "}", "}", "else", "if", "(", "scopeChoice", "instanceof", "CompoundStatement", ")", "{", "HashMap", "<", "String", ",", "Type", ">", "typeTable", "=", "(", "(", "CompoundStatementInfo", ")", "scopeChoice", ".", "getInfo", "(", ")", ")", ".", "getTypeTable", "(", ")", ";", "if", "(", "typeTable", ".", "containsKey", "(", "tag", ")", ")", "{", "return", "typeTable", ".", "get", "(", "tag", ")", ";", "}", "}", "else", "if", "(", "scopeChoice", "instanceof", "FunctionDefinition", ")", "{", "HashMap", "<", "String", ",", "Type", ">", "typeTable", "=", "(", "(", "FunctionDefinitionInfo", ")", "scopeChoice", ".", "getInfo", "(", ")", ")", ".", "getTypeTable", "(", ")", ";", "if", "(", "typeTable", ".", "containsKey", "(", "tag", ")", ")", "{", "return", "typeTable", ".", "get", "(", "tag", ")", ";", "}", "}", "scopeChoice", "=", "(", "Node", ")", "Misc", ".", "getEnclosingBlock", "(", "scopeChoice", ")", ";", "}", "return", "null", ";", "}", "/**\n\t * Returns the type with specified tag, if present in the given scope,\n\t * or any of the nested scope.\n\t * \n\t * @param tag\n\t * @param scope\n\t * @return\n\t */", "public", "static", "Type", "getTypeFromScope", "(", "String", "tag", ",", "Scopeable", "scope", ")", "{", "return", "Type", ".", "getTypeEntry", "(", "tag", ",", "scope", ")", ";", "}", "/**\n\t * Checks whether the given {@link CastExpressionTyped} node performs\n\t * an incompatible type cast between pointers/arrays.\n\t * <br>\n\t * Note that this method <i>ignores</i> type casts that are done on type\n\t * {@code (void *)}.\n\t * (We cannot ignore type casts <i>to</i> {@code (void *)} as well, since\n\t * these together can be then used to perform any desired incompatible type\n\t * cast without getting caught by this method.)\n\t * \n\t * @param castExp\n\t * a {@link CastExpressionTyped} expression to be tested.\n\t * @return\n\t * true, if the given expression performs an incompatible type cast.\n\t */", "public", "static", "boolean", "hasIncompatibleTypeCastOfPointers", "(", "CastExpressionTyped", "cet", ")", "{", "Scopeable", "scope", "=", "Misc", ".", "getEnclosingBlock", "(", "cet", ")", ";", "if", "(", "scope", "==", "null", ")", "{", "return", "false", ";", "}", "Type", "castType", "=", "Type", ".", "getTypeTree", "(", "cet", ".", "getF1", "(", ")", ",", "scope", ")", ";", "Type", "expType", "=", "Type", ".", "getType", "(", "cet", ".", "getF3", "(", ")", ")", ";", "if", "(", "!", "(", "castType", "instanceof", "ArrayType", ")", "&&", "!", "(", "castType", "instanceof", "PointerType", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "(", "expType", "instanceof", "ArrayType", ")", "&&", "!", "(", "expType", "instanceof", "PointerType", ")", ")", "{", "return", "false", ";", "}", "if", "(", "expType", "instanceof", "PointerType", ")", "{", "PointerType", "pType", "=", "(", "PointerType", ")", "expType", ";", "if", "(", "pType", ".", "getPointeeType", "(", ")", "==", "VoidType", ".", "type", "(", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "!", "castType", ".", "toString", "(", ")", ".", "equals", "(", "expType", ".", "toString", "(", ")", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "/**\n\t * Enters the provided tag and type key-value pair into the\n\t * typeTable of the specified scope, if the type is not already\n\t * present in the complete state.\n\t * \n\t * @param scope\n\t * @param tag\n\t * @param newType\n\t * @return\n\t * type which is finally present in the typeTable of scope, for the\n\t * given tag.\n\t */", "public", "static", "Type", "putTypeToScope", "(", "Scopeable", "scope", ",", "String", "tag", ",", "Type", "newType", ")", "{", "assert", "(", "newType", "instanceof", "StructType", "||", "newType", "instanceof", "UnionType", "||", "newType", "instanceof", "EnumType", ")", ";", "HashMap", "<", "String", ",", "Type", ">", "typeTable", "=", "scope", ".", "getTypeTable", "(", ")", ";", "Type", "oldType", "=", "typeTable", ".", "get", "(", "tag", ")", ";", "if", "(", "oldType", "==", "null", ")", "{", "typeTable", ".", "put", "(", "tag", ",", "newType", ")", ";", "return", "newType", ";", "}", "else", "if", "(", "!", "oldType", ".", "isComplete", "(", ")", ")", "{", "typeTable", ".", "put", "(", "tag", ",", "newType", ")", ";", "return", "newType", ";", "}", "else", "{", "if", "(", "!", "newType", ".", "isComplete", "(", ")", ")", "{", "return", "oldType", ";", "}", "else", "{", "if", "(", "newType", "instanceof", "StructType", ")", "{", "StructType", "newStructType", "=", "(", "StructType", ")", "newType", ";", "StructType", "oldStructType", "=", "(", "StructType", ")", "oldType", ";", "if", "(", "newStructType", ".", "getDeclaringNode", "(", ")", "==", "oldStructType", ".", "getDeclaringNode", "(", ")", ")", "{", "return", "oldStructType", ";", "}", "}", "else", "if", "(", "newType", "instanceof", "UnionType", ")", "{", "UnionType", "newUnionType", "=", "(", "UnionType", ")", "newType", ";", "UnionType", "oldUnionType", "=", "(", "UnionType", ")", "oldType", ";", "if", "(", "newUnionType", ".", "getDeclaringNode", "(", ")", "==", "oldUnionType", ".", "getDeclaringNode", "(", ")", ")", "{", "return", "oldUnionType", ";", "}", "}", "else", "if", "(", "newType", "instanceof", "EnumType", ")", "{", "EnumType", "newEnumType", "=", "(", "EnumType", ")", "newType", ";", "EnumType", "oldEnumType", "=", "(", "EnumType", ")", "oldType", ";", "if", "(", "newEnumType", ".", "getDeclaringNode", "(", ")", "==", "oldEnumType", ".", "getDeclaringNode", "(", ")", ")", "{", "return", "oldEnumType", ";", "}", "}", "Misc", ".", "warnDueToLackOfFeature", "(", "\"", "Attempting to redefine a complete type. Please look into the declarations of type ", "\"", "+", "newType", ",", "Program", ".", "getRoot", "(", ")", ")", ";", "return", "oldType", ";", "}", "}", "}", "public", "static", "Type", "removeTypeFromScope", "(", "Scopeable", "scope", ",", "String", "tag", ",", "Type", "type", ")", "{", "assert", "(", "type", "instanceof", "StructType", "||", "type", "instanceof", "UnionType", "||", "type", "instanceof", "EnumType", ")", ";", "HashMap", "<", "String", ",", "Type", ">", "typeTable", "=", "scope", ".", "getTypeTable", "(", ")", ";", "Type", "oldType", "=", "typeTable", ".", "get", "(", "tag", ")", ";", "if", "(", "oldType", "!=", "null", ")", "{", "Type", ".", "deletedTypes", ".", "add", "(", "oldType", ")", ";", "}", "typeTable", ".", "remove", "(", "tag", ")", ";", "return", "type", ";", "}", "/**\n\t * Obtain a set of all those types which have been used somewhere within the\n\t * declaration of the receiver type.\n\t * This set would contain the receiver type as well.\n\t * \n\t * @return\n\t * set of all those types which have been used somewhere within the\n\t * declaration of the receiver type.\n\t */", "public", "abstract", "Set", "<", "Type", ">", "getAllTypes", "(", ")", ";", "}" ]
This is the superclass for all the various Types supported by IMOP.
[ "This", "is", "the", "superclass", "for", "all", "the", "various", "Types", "supported", "by", "IMOP", "." ]
[ "// public boolean isKnownConstantSized() {", "// if (this.isComplete()) {", "// if (this instanceof ArrayType && ((ArrayType) this).isVariableLengthed()) {", "// return false;", "// } else {", "// return true;", "// }", "// } else {", "// return false;", "// }", "// }", "// TODO: Ensure that later when we know the size of various types,", "// we should return the more appropriate type of int -- unsigned or signed.", "// Till then, we send SignedIntType for all.", "// TODO: Code here.", "// protected String getDeclarationPostString(String tempName, boolean", "// isFullDeclarator) {", "// String retString = \" \" + tempName + \" \";", "// return retString;", "// }", "// protected String postDeclarationString(String tempName) {", "// return this.getDeclarationPostString(tempName, true);", "// }", "// protected String postDeclarationString(String tempName) {", "// return this.getDeclarationPostString(tempName, true);", "// }", "// protected String postDeclarationString(String tempName) {", "// return this.getDeclarationPostString(tempName, true);", "// }", "// Ensure that all functions with unspecified return type have been", "// pre-processed to return int.", "// if (Misc.isTypedef(declaration)) {", "// return null;", "// }", "// if (Misc.isTypedef(declaration)) {", "// return null;", "// }", "// if (Misc.isTypedef(declaration)) {", "// return null;", "// }", "// if (Misc.isTypedef(declaration)) {", "// return null;", "// }", "// if (Misc.isTypedef(declaration)) {", "// return null;", "// }", "// System.out.println(paramDecl + \" is a \" + paramType + \" now.\");", "// Here, the declaration specifiers use a struct, union, enum or typedef.", "// System.out.println(\"Found a \" + baseType + \" for \" +", "// declSpec.getInfo().getString());", "// TODO: Add qualifiers here.", "// if (Misc.isTypedef(declSpec)) {", "// return null;", "// }", "// Here, the declaration specifiers use a struct, union, enum or typedef.", "// if (Misc.isTypedef(declSpec)) {", "// return null;", "// }", "// Here, the declaration specifiers use a struct, union, enum or typedef.", "// if (Misc.isTypedef(declSpec)) {", "// return null;", "// }", "// Here, the declaration specifiers use a struct, union, enum or typedef.", "// TODO: Add qualifiers here.", "// if (Misc.isTypedef(declSpec)) {", "// return null;", "// }", "// Here, the declaration specifiers use a struct, union, enum or typedef.", "// TODO: Add qualifiers here.", "// Here, the specifier-qualifier list uses a struct, union, enum or typedef.", "// TODO: Add qualifiers here.", "// if (Misc.isTypedef(declSpec)) {", "// return null;", "// }", "// Here, the declaration specifiers use a struct, union, enum or typedef.", "// TODO: Add qualifiers here.", "// Here, the specifier-qualifier list uses a struct, union, enum or typedef.", "// Void", "// Characters", "// Short", "// Long's", "// Long Long", "// return UnsignedLongIntType.type(); // Error.", "// return SignedLongIntType.type(); // Error.", "// Long Double and Long Double Complex", "// Long", "// Int's", "// _Bool", "// Float's", "// Double's", "// System.out.println(\"Could not find the type \" + tag + \" in \" +", "// node.getInfo().getString() + \" at line #\" + Misc.getLineNum(node));", "// Future code. Can be thought about later.", "// if (!deletedTypes.isEmpty()) {", "// System.out.println(deletedTypes + \" still \" + tag + \".\");", "// }", "//", "// assert (false);", "// typeTable.put(tag, newType);" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
33faa09c8a47be572a053a095efda7022b724a0e
xresch/CoreFramework
src/main/java/com/xresch/cfw/validation/AbstractValidatable.java
[ "MIT", "BSD-2-Clause", "CC0-1.0", "Apache-2.0" ]
Java
AbstractValidatable
/************************************************************************************************************** * * @author Reto Scheiwiller, (c) Copyright 2019 * @license MIT-License **************************************************************************************************************/
@author Reto Scheiwiller, (c) Copyright 2019 @license MIT-License
[ "@author", "Reto", "Scheiwiller", "(", "c", ")", "Copyright", "2019", "@license", "MIT", "-", "License" ]
public abstract class AbstractValidatable<T> implements IValidatable<T> { private ArrayList<IValidator> validatorArray = new ArrayList<IValidator>(); private String label = ""; protected T value; private ArrayList<String> invalidMessages; /************************************************************************* * Executes all validators added to this instance and validates the current * value. * * @return true if all validators returned true, false otherwise *************************************************************************/ public boolean validate(){ boolean isValid = true; invalidMessages = new ArrayList<String>(); for(IValidator validator : validatorArray){ if(!validator.validate(value)){ invalidMessages.add(validator.getInvalidMessage()); isValid=false; } } return isValid; } /************************************************************************* * Executes all validators added to the instance of this class. * * @return true if all validators returned true, false otherwise *************************************************************************/ public boolean validateValue(Object value){ boolean isValid = true; invalidMessages = new ArrayList<String>(); for(IValidator validator : validatorArray){ if(!validator.validate(value)){ invalidMessages.add(validator.getInvalidMessage()); isValid=false; } } return isValid; } /************************************************************************* * Returns all the InvalidMessages from the last validation execution. *************************************************************************/ public ArrayList<String> getInvalidMessages() { return invalidMessages; } public IValidatable<T> addValidator(IValidator validator) { if(!validatorArray.contains(validator)) { validatorArray.add(validator); } return this; } public boolean removeValidator(IValidator o) { return validatorArray.remove(o); } public IValidatable<T> setLabel(String propertyName) { this.label = propertyName; return this; } public String getLabel() { return label; } public boolean setValueValidated(T value) { if(this.validateValue(value)) { this.value = value; return true; } return false; } public T getValue() { return value; } }
[ "public", "abstract", "class", "AbstractValidatable", "<", "T", ">", "implements", "IValidatable", "<", "T", ">", "{", "private", "ArrayList", "<", "IValidator", ">", "validatorArray", "=", "new", "ArrayList", "<", "IValidator", ">", "(", ")", ";", "private", "String", "label", "=", "\"", "\"", ";", "protected", "T", "value", ";", "private", "ArrayList", "<", "String", ">", "invalidMessages", ";", "/*************************************************************************\n\t * Executes all validators added to this instance and validates the current\n\t * value.\n\t * \n\t * @return true if all validators returned true, false otherwise\n\t *************************************************************************/", "public", "boolean", "validate", "(", ")", "{", "boolean", "isValid", "=", "true", ";", "invalidMessages", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "IValidator", "validator", ":", "validatorArray", ")", "{", "if", "(", "!", "validator", ".", "validate", "(", "value", ")", ")", "{", "invalidMessages", ".", "add", "(", "validator", ".", "getInvalidMessage", "(", ")", ")", ";", "isValid", "=", "false", ";", "}", "}", "return", "isValid", ";", "}", "/*************************************************************************\n\t * Executes all validators added to the instance of this class.\n\t * \n\t * @return true if all validators returned true, false otherwise\n\t *************************************************************************/", "public", "boolean", "validateValue", "(", "Object", "value", ")", "{", "boolean", "isValid", "=", "true", ";", "invalidMessages", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "IValidator", "validator", ":", "validatorArray", ")", "{", "if", "(", "!", "validator", ".", "validate", "(", "value", ")", ")", "{", "invalidMessages", ".", "add", "(", "validator", ".", "getInvalidMessage", "(", ")", ")", ";", "isValid", "=", "false", ";", "}", "}", "return", "isValid", ";", "}", "/*************************************************************************\n\t * Returns all the InvalidMessages from the last validation execution. \n\t *************************************************************************/", "public", "ArrayList", "<", "String", ">", "getInvalidMessages", "(", ")", "{", "return", "invalidMessages", ";", "}", "public", "IValidatable", "<", "T", ">", "addValidator", "(", "IValidator", "validator", ")", "{", "if", "(", "!", "validatorArray", ".", "contains", "(", "validator", ")", ")", "{", "validatorArray", ".", "add", "(", "validator", ")", ";", "}", "return", "this", ";", "}", "public", "boolean", "removeValidator", "(", "IValidator", "o", ")", "{", "return", "validatorArray", ".", "remove", "(", "o", ")", ";", "}", "public", "IValidatable", "<", "T", ">", "setLabel", "(", "String", "propertyName", ")", "{", "this", ".", "label", "=", "propertyName", ";", "return", "this", ";", "}", "public", "String", "getLabel", "(", ")", "{", "return", "label", ";", "}", "public", "boolean", "setValueValidated", "(", "T", "value", ")", "{", "if", "(", "this", ".", "validateValue", "(", "value", ")", ")", "{", "this", ".", "value", "=", "value", ";", "return", "true", ";", "}", "return", "false", ";", "}", "public", "T", "getValue", "(", ")", "{", "return", "value", ";", "}", "}" ]
@author Reto Scheiwiller, (c) Copyright 2019 @license MIT-License
[ "@author", "Reto", "Scheiwiller", "(", "c", ")", "Copyright", "2019", "@license", "MIT", "-", "License" ]
[]
[ { "param": "IValidatable<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IValidatable<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33fb9095bc49f0131ff99f4f851cff5dfb3928ab
renicl/SubMicroTrading
OM/src/com/rr/om/model/id/AnnualBase32IDGenerator.java
[ "Apache-2.0" ]
Java
AnnualBase32IDGenerator
/** * in effect the counter will be the number of millisends from start of year to the last midnight. * this gives 24 * 60 * 60 * 1000 = 86,400,000 ids per day unique over the year * max id is 365 * 86,400,000 = 31,536,000,000 * in base 32, a length of seven is enough for 34,359,738,368 combinations */
in effect the counter will be the number of millisends from start of year to the last midnight.
[ "in", "effect", "the", "counter", "will", "be", "the", "number", "of", "millisends", "from", "start", "of", "year", "to", "the", "last", "midnight", "." ]
public class AnnualBase32IDGenerator extends AbstractBase32IDGenerator { /** * @param processInstanceSeed * @param len length of non seed component */ public AnnualBase32IDGenerator( ZString processInstanceSeed, int len ) { super( processInstanceSeed, len ); } @Override protected long seed() { Calendar c = new GregorianCalendar(); c.set( Calendar.HOUR_OF_DAY, 0 ); c.set( Calendar.MINUTE, 0 ); c.set( Calendar.SECOND, 0 ); c.set( Calendar.MILLISECOND, 0 ); c.set( Calendar.DAY_OF_MONTH, 1 ); c.set( Calendar.MONTH, 0 ); return System.currentTimeMillis() - c.getTimeInMillis(); } }
[ "public", "class", "AnnualBase32IDGenerator", "extends", "AbstractBase32IDGenerator", "{", "/**\n * @param processInstanceSeed \n * @param len length of non seed component\n */", "public", "AnnualBase32IDGenerator", "(", "ZString", "processInstanceSeed", ",", "int", "len", ")", "{", "super", "(", "processInstanceSeed", ",", "len", ")", ";", "}", "@", "Override", "protected", "long", "seed", "(", ")", "{", "Calendar", "c", "=", "new", "GregorianCalendar", "(", ")", ";", "c", ".", "set", "(", "Calendar", ".", "HOUR_OF_DAY", ",", "0", ")", ";", "c", ".", "set", "(", "Calendar", ".", "MINUTE", ",", "0", ")", ";", "c", ".", "set", "(", "Calendar", ".", "SECOND", ",", "0", ")", ";", "c", ".", "set", "(", "Calendar", ".", "MILLISECOND", ",", "0", ")", ";", "c", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "1", ")", ";", "c", ".", "set", "(", "Calendar", ".", "MONTH", ",", "0", ")", ";", "return", "System", ".", "currentTimeMillis", "(", ")", "-", "c", ".", "getTimeInMillis", "(", ")", ";", "}", "}" ]
in effect the counter will be the number of millisends from start of year to the last midnight.
[ "in", "effect", "the", "counter", "will", "be", "the", "number", "of", "millisends", "from", "start", "of", "year", "to", "the", "last", "midnight", "." ]
[]
[ { "param": "AbstractBase32IDGenerator", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractBase32IDGenerator", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33fd460034ba0df74d14b1468fbf81fd01de7415
IUST-DMLab/farsbase
raw/JHazm/core/src/test/java/ir/ac/iust/nlp/jhazm/Test/SentenceTokenizerTests.java
[ "Apache-2.0" ]
Java
SentenceTokenizerTests
/** * * @author Mojtaba Khallash */
@author Mojtaba Khallash
[ "@author", "Mojtaba", "Khallash" ]
public class SentenceTokenizerTests { @Test public void tokenizeTest() { SentenceTokenizer senTokenizer = new SentenceTokenizer(); String input = "جدا کردن ساده است. تقریبا البته!"; System.out.println("input: " + input); String[] expected = new String[] { "جدا کردن ساده است.", "تقریبا البته!" }; System.out.println("actual: "); List<String> actual = senTokenizer.tokenize(input); assertEquals("Failed to tokenize sentences of '" + input + "' passage", expected.length, actual.size()); for (int i = 0; i < actual.size(); i++) { String sentence = actual.get(i); System.out.println("\t" + sentence); assertEquals("Failed to tokenize sentences of '" + input + "' passage", expected[i], actual.get(i)); } } }
[ "public", "class", "SentenceTokenizerTests", "{", "@", "Test", "public", "void", "tokenizeTest", "(", ")", "{", "SentenceTokenizer", "senTokenizer", "=", "new", "SentenceTokenizer", "(", ")", ";", "String", "input", "=", "\"", "جدا کردن ساده است. تقریبا البته!\";", "", "", "System", ".", "out", ".", "println", "(", "\"", "input: ", "\"", "+", "input", ")", ";", "String", "[", "]", "expected", "=", "new", "String", "[", "]", "{", "\"", "جدا کردن ساده است.\", \"تقریبا الب", "ت", "ه", "\"", " };", "", "", "", "System", ".", "out", ".", "println", "(", "\"", "actual: ", "\"", ")", ";", "List", "<", "String", ">", "actual", "=", "senTokenizer", ".", "tokenize", "(", "input", ")", ";", "assertEquals", "(", "\"", "Failed to tokenize sentences of '", "\"", "+", "input", "+", "\"", "' passage", "\"", ",", "expected", ".", "length", ",", "actual", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "actual", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "sentence", "=", "actual", ".", "get", "(", "i", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "\\t", "\"", "+", "sentence", ")", ";", "assertEquals", "(", "\"", "Failed to tokenize sentences of '", "\"", "+", "input", "+", "\"", "' passage", "\"", ",", "expected", "[", "i", "]", ",", "actual", ".", "get", "(", "i", ")", ")", ";", "}", "}", "}" ]
@author Mojtaba Khallash
[ "@author", "Mojtaba", "Khallash" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
d505253af35158ee7f0e98c178401eecfd905b1c
sunsara/cloudy-torrent
cloudy-services/src/main/java/com/sachin/cloudy/services/services/impl/AdminServiceImpl.java
[ "MIT" ]
Java
AdminServiceImpl
/** * Created by sachinhooda on 24/8/17. */
Created by sachinhooda on 24/8/17.
[ "Created", "by", "sachinhooda", "on", "24", "/", "8", "/", "17", "." ]
@Service @Transactional public class AdminServiceImpl implements AdminService { private UserRepository userRepository; private RoleRepository roleRepository; @Autowired public AdminServiceImpl(UserRepository userRepository, RoleRepository roleRepository) { this.userRepository = userRepository; this.roleRepository = roleRepository; } @Override public User save(User user) throws CloudyServiceException { try { Role role = roleRepository.findOne(RoleConstants.ROLE_ADMIN); user.getRoles().add(role); user = userRepository.save(user); return user; } catch (Exception e) { throw new CloudyServiceException(e.getMessage(), e); } } @Override public User getByEmailId(String email) throws CloudyServiceException { try { User user = null; user = userRepository.findByEmail(email); return user; } catch (Exception e) { throw new CloudyServiceException(e.getMessage(), e); } } }
[ "@", "Service", "@", "Transactional", "public", "class", "AdminServiceImpl", "implements", "AdminService", "{", "private", "UserRepository", "userRepository", ";", "private", "RoleRepository", "roleRepository", ";", "@", "Autowired", "public", "AdminServiceImpl", "(", "UserRepository", "userRepository", ",", "RoleRepository", "roleRepository", ")", "{", "this", ".", "userRepository", "=", "userRepository", ";", "this", ".", "roleRepository", "=", "roleRepository", ";", "}", "@", "Override", "public", "User", "save", "(", "User", "user", ")", "throws", "CloudyServiceException", "{", "try", "{", "Role", "role", "=", "roleRepository", ".", "findOne", "(", "RoleConstants", ".", "ROLE_ADMIN", ")", ";", "user", ".", "getRoles", "(", ")", ".", "add", "(", "role", ")", ";", "user", "=", "userRepository", ".", "save", "(", "user", ")", ";", "return", "user", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "CloudyServiceException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "@", "Override", "public", "User", "getByEmailId", "(", "String", "email", ")", "throws", "CloudyServiceException", "{", "try", "{", "User", "user", "=", "null", ";", "user", "=", "userRepository", ".", "findByEmail", "(", "email", ")", ";", "return", "user", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "CloudyServiceException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}" ]
Created by sachinhooda on 24/8/17.
[ "Created", "by", "sachinhooda", "on", "24", "/", "8", "/", "17", "." ]
[]
[ { "param": "AdminService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AdminService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
d505c386c7d6e3adaccbebbe5f0bec4bf6c485a9
wjiec/leetcode-solution
leetcode-java/src/problem/p1437checkifall1sareatleastlengthkplacesaway/Solution.java
[ "MIT" ]
Java
Solution
/** * 1437. Check If All 1's Are at Least Length K Places Away * * https://leetcode-cn.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ * * Given an array nums of 0s and 1s and an integer k, * return True if all 1's are at least k places away from each other, * otherwise return False. */
1437. Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.
[ "1437", ".", "Given", "an", "array", "nums", "of", "0s", "and", "1s", "and", "an", "integer", "k", "return", "True", "if", "all", "1", "'", "s", "are", "at", "least", "k", "places", "away", "from", "each", "other", "otherwise", "return", "False", "." ]
public class Solution { public boolean kLengthApart(int[] nums, int k) { int l = nums.length, prev = -1; for (int i = 0; i < l; i++) { if (nums[i] == 1) { if (prev != -1) { if (i - prev - 1 < k) return false; } prev = i; } } return true; } public static void main(String[] args) { assert new Solution().kLengthApart(new int[]{1,0,0,0,1,0,0,1}, 2); assert !new Solution().kLengthApart(new int[]{1,0,0,1,0,1}, 2); assert new Solution().kLengthApart(new int[]{1,1,1,1,1}, 0); assert new Solution().kLengthApart(new int[]{0,1,0,1}, 1); } }
[ "public", "class", "Solution", "{", "public", "boolean", "kLengthApart", "(", "int", "[", "]", "nums", ",", "int", "k", ")", "{", "int", "l", "=", "nums", ".", "length", ",", "prev", "=", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "nums", "[", "i", "]", "==", "1", ")", "{", "if", "(", "prev", "!=", "-", "1", ")", "{", "if", "(", "i", "-", "prev", "-", "1", "<", "k", ")", "return", "false", ";", "}", "prev", "=", "i", ";", "}", "}", "return", "true", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "assert", "new", "Solution", "(", ")", ".", "kLengthApart", "(", "new", "int", "[", "]", "{", "1", ",", "0", ",", "0", ",", "0", ",", "1", ",", "0", ",", "0", ",", "1", "}", ",", "2", ")", ";", "assert", "!", "new", "Solution", "(", ")", ".", "kLengthApart", "(", "new", "int", "[", "]", "{", "1", ",", "0", ",", "0", ",", "1", ",", "0", ",", "1", "}", ",", "2", ")", ";", "assert", "new", "Solution", "(", ")", ".", "kLengthApart", "(", "new", "int", "[", "]", "{", "1", ",", "1", ",", "1", ",", "1", ",", "1", "}", ",", "0", ")", ";", "assert", "new", "Solution", "(", ")", ".", "kLengthApart", "(", "new", "int", "[", "]", "{", "0", ",", "1", ",", "0", ",", "1", "}", ",", "1", ")", ";", "}", "}" ]
1437.
[ "1437", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
d50baf478432c052c2b5cef34b208e3406b4aafd
samuelnp/mvc_game_sdk
src/com/game/engine/KeyboardInputEvent.java
[ "MIT" ]
Java
KeyboardInputEvent
/** * Custom InputEvent to encapsulate Keyboard inputs * Add keyboard key activated */
Custom InputEvent to encapsulate Keyboard inputs Add keyboard key activated
[ "Custom", "InputEvent", "to", "encapsulate", "Keyboard", "inputs", "Add", "keyboard", "key", "activated" ]
public class KeyboardInputEvent extends InputEvent{ private String key; public KeyboardInputEvent() { super(); key = null; } public KeyboardInputEvent(InputEvent inputEvent) { super(); setStatus(inputEvent.getStatus()); } public String getKey() { return key; } public void setKey(char key) { this.key = new StringBuffer().append(key).toString(); } }
[ "public", "class", "KeyboardInputEvent", "extends", "InputEvent", "{", "private", "String", "key", ";", "public", "KeyboardInputEvent", "(", ")", "{", "super", "(", ")", ";", "key", "=", "null", ";", "}", "public", "KeyboardInputEvent", "(", "InputEvent", "inputEvent", ")", "{", "super", "(", ")", ";", "setStatus", "(", "inputEvent", ".", "getStatus", "(", ")", ")", ";", "}", "public", "String", "getKey", "(", ")", "{", "return", "key", ";", "}", "public", "void", "setKey", "(", "char", "key", ")", "{", "this", ".", "key", "=", "new", "StringBuffer", "(", ")", ".", "append", "(", "key", ")", ".", "toString", "(", ")", ";", "}", "}" ]
Custom InputEvent to encapsulate Keyboard inputs Add keyboard key activated
[ "Custom", "InputEvent", "to", "encapsulate", "Keyboard", "inputs", "Add", "keyboard", "key", "activated" ]
[]
[ { "param": "InputEvent", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "InputEvent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
d50ea2602a3946956e88689d87349424a2e13fe5
neha-b2001/wildfly-core
cli/src/main/java/org/jboss/as/cli/impl/aesh/cmd/security/model/PropertiesRealmConfiguration.java
[ "Apache-2.0" ]
Java
PropertiesRealmConfiguration
/** * A configuration for a new properties realm. * * @author jdenise@redhat.com */
A configuration for a new properties realm.
[ "A", "configuration", "for", "a", "new", "properties", "realm", "." ]
public class PropertiesRealmConfiguration implements MechanismConfiguration { private String realmName; private final String relativeTo; private final String userPropertiesFile; private final String groupPropertiesFile; private final String exposedRealmName; private final boolean plainText; private String realmMapper; public PropertiesRealmConfiguration(String exposedRealmName, RelativeFile userPropertiesFile, RelativeFile groupPropertiesFile, String relativeTo, boolean plainText) throws IOException { this.exposedRealmName = exposedRealmName; this.userPropertiesFile = relativeTo != null ? userPropertiesFile.getOriginalPath() : userPropertiesFile.getCanonicalPath(); this.groupPropertiesFile = groupPropertiesFile == null ? null : relativeTo != null ? groupPropertiesFile.getOriginalPath() : groupPropertiesFile.getCanonicalPath(); this.relativeTo = relativeTo; this.plainText = plainText; } public PropertiesRealmConfiguration(String name) throws IOException { this(null, null, null, null, false); } /** * @return the realmName */ @Override public String getExposedRealmName() { return exposedRealmName; } /** * @return the realmName */ @Override public String getRealmName() { return realmName; } /** * @return the relativeTo */ public String getRelativeTo() { return relativeTo; } /** * @return the plainText */ public boolean getPlainText() { return plainText; } /** * @return the userPropertiesFile * @throws java.io.IOException */ public String getUserPropertiesFile() throws IOException { return userPropertiesFile; } /** * @return the groupPropertiesFile * @throws java.io.IOException */ public String getGroupPropertiesFile() throws IOException { return groupPropertiesFile; } @Override public String getRoleDecoder() { return Util.GROUPS_TO_ROLES; } @Override public String getRealmMapper() { return realmMapper; } @Override public String getRoleMapper() { return null; } @Override public void setRealmMapperName(String realmMapper) { this.realmMapper = realmMapper; } }
[ "public", "class", "PropertiesRealmConfiguration", "implements", "MechanismConfiguration", "{", "private", "String", "realmName", ";", "private", "final", "String", "relativeTo", ";", "private", "final", "String", "userPropertiesFile", ";", "private", "final", "String", "groupPropertiesFile", ";", "private", "final", "String", "exposedRealmName", ";", "private", "final", "boolean", "plainText", ";", "private", "String", "realmMapper", ";", "public", "PropertiesRealmConfiguration", "(", "String", "exposedRealmName", ",", "RelativeFile", "userPropertiesFile", ",", "RelativeFile", "groupPropertiesFile", ",", "String", "relativeTo", ",", "boolean", "plainText", ")", "throws", "IOException", "{", "this", ".", "exposedRealmName", "=", "exposedRealmName", ";", "this", ".", "userPropertiesFile", "=", "relativeTo", "!=", "null", "?", "userPropertiesFile", ".", "getOriginalPath", "(", ")", ":", "userPropertiesFile", ".", "getCanonicalPath", "(", ")", ";", "this", ".", "groupPropertiesFile", "=", "groupPropertiesFile", "==", "null", "?", "null", ":", "relativeTo", "!=", "null", "?", "groupPropertiesFile", ".", "getOriginalPath", "(", ")", ":", "groupPropertiesFile", ".", "getCanonicalPath", "(", ")", ";", "this", ".", "relativeTo", "=", "relativeTo", ";", "this", ".", "plainText", "=", "plainText", ";", "}", "public", "PropertiesRealmConfiguration", "(", "String", "name", ")", "throws", "IOException", "{", "this", "(", "null", ",", "null", ",", "null", ",", "null", ",", "false", ")", ";", "}", "/**\n * @return the realmName\n */", "@", "Override", "public", "String", "getExposedRealmName", "(", ")", "{", "return", "exposedRealmName", ";", "}", "/**\n * @return the realmName\n */", "@", "Override", "public", "String", "getRealmName", "(", ")", "{", "return", "realmName", ";", "}", "/**\n * @return the relativeTo\n */", "public", "String", "getRelativeTo", "(", ")", "{", "return", "relativeTo", ";", "}", "/**\n * @return the plainText\n */", "public", "boolean", "getPlainText", "(", ")", "{", "return", "plainText", ";", "}", "/**\n * @return the userPropertiesFile\n * @throws java.io.IOException\n */", "public", "String", "getUserPropertiesFile", "(", ")", "throws", "IOException", "{", "return", "userPropertiesFile", ";", "}", "/**\n * @return the groupPropertiesFile\n * @throws java.io.IOException\n */", "public", "String", "getGroupPropertiesFile", "(", ")", "throws", "IOException", "{", "return", "groupPropertiesFile", ";", "}", "@", "Override", "public", "String", "getRoleDecoder", "(", ")", "{", "return", "Util", ".", "GROUPS_TO_ROLES", ";", "}", "@", "Override", "public", "String", "getRealmMapper", "(", ")", "{", "return", "realmMapper", ";", "}", "@", "Override", "public", "String", "getRoleMapper", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "void", "setRealmMapperName", "(", "String", "realmMapper", ")", "{", "this", ".", "realmMapper", "=", "realmMapper", ";", "}", "}" ]
A configuration for a new properties realm.
[ "A", "configuration", "for", "a", "new", "properties", "realm", "." ]
[]
[ { "param": "MechanismConfiguration", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MechanismConfiguration", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
d510f9a417cdc3aa14a31aa0104b3362e1b2de0e
JordanLongstaff/Artemis-Messenger
src/com/walkertribe/ian/protocol/core/setup/AllShipSettingsPacket.java
[ "MIT" ]
Java
AllShipSettingsPacket
/** * Sent by the server to update the names, types and drives for each ship. * @author dhleong */
Sent by the server to update the names, types and drives for each ship. @author dhleong
[ "Sent", "by", "the", "server", "to", "update", "the", "names", "types", "and", "drives", "for", "each", "ship", ".", "@author", "dhleong" ]
@Packet(origin = Origin.SERVER, type = CorePacketType.SIMPLE_EVENT, subtype = SimpleEventPacket.Subtype.SHIP_SETTINGS) public class AllShipSettingsPacket extends SimpleEventPacket { public static class Ship { private CharSequence mName; private int mShipType; public Ship(CharSequence name, int shipType) { setName(name); setShipType(shipType); } /** * The name of the ship */ public CharSequence getName() { return mName; } public void setName(CharSequence name) { if (!Util.isBlank(name)) mName = name; } /** * The hullId for this ship */ public int getShipType() { return mShipType; } public void setShipType(int shipType) { mShipType = shipType; } /** * Returns the Vessel identified by the ship's hull ID, or null if no such Vessel can be found. */ public Vessel getVessel(ArtemisContext ctx) { return ctx.getVesselData().getVessel(mShipType); } public void setVessel(Vessel vessel) { setShipType(vessel.getId()); } @Override public String toString() { return mName + ": (type #" + mShipType + ")"; } } private static final Version COLOR_VERSION = new Version("2.4.0"); private final Ship[] mShips; public AllShipSettingsPacket(PacketReader reader) { super(reader); mShips = new Ship[Artemis.SHIP_COUNT]; for (int i = 0; i < Artemis.SHIP_COUNT; i++) { reader.readInt(); int hullId = reader.readInt(); if (reader.getVersion().ge(COLOR_VERSION)) reader.readFloat(); CharSequence name = null; if (reader.readInt() != 0) name = reader.readString(); mShips[i] = new Ship(name, hullId); } } public AllShipSettingsPacket(Ship[] ships) { super(Subtype.SHIP_SETTINGS); if (ships == null) throw new IllegalArgumentException("Ship array cannot be null"); if (ships.length != Artemis.SHIP_COUNT) throw new IllegalArgumentException("Must specify exactly " + Artemis.SHIP_COUNT + " ships"); for (int i = 0; i < ships.length; i++) { Ship ship = ships[i]; if (ship == null) throw new IllegalArgumentException("Ships in array cannot be null"); } mShips = ships; } /** * Returns the ship with the given index (0-based). */ public Ship getShip(int shipIndex) { return mShips[shipIndex]; } @Override protected void writePayload(PacketWriter writer) { super.writePayload(writer); for (Ship ship: mShips) { writer .writeInt(0) .writeInt(ship.mShipType); if (writer.getVersion().ge(COLOR_VERSION)) writer.writeFloat(0f); if (ship.mName == null) writer.writeInt(0); else writer.writeInt(1).writeString(ship.mName); } } @Override protected void appendPacketDetail(StringBuilder b) { for (int i = 0; i < Artemis.SHIP_COUNT; i++) b.append("\n\t").append(mShips[i]); } }
[ "@", "Packet", "(", "origin", "=", "Origin", ".", "SERVER", ",", "type", "=", "CorePacketType", ".", "SIMPLE_EVENT", ",", "subtype", "=", "SimpleEventPacket", ".", "Subtype", ".", "SHIP_SETTINGS", ")", "public", "class", "AllShipSettingsPacket", "extends", "SimpleEventPacket", "{", "public", "static", "class", "Ship", "{", "private", "CharSequence", "mName", ";", "private", "int", "mShipType", ";", "public", "Ship", "(", "CharSequence", "name", ",", "int", "shipType", ")", "{", "setName", "(", "name", ")", ";", "setShipType", "(", "shipType", ")", ";", "}", "/**\n\t\t * The name of the ship\n\t\t */", "public", "CharSequence", "getName", "(", ")", "{", "return", "mName", ";", "}", "public", "void", "setName", "(", "CharSequence", "name", ")", "{", "if", "(", "!", "Util", ".", "isBlank", "(", "name", ")", ")", "mName", "=", "name", ";", "}", "/**\n\t\t * The hullId for this ship\n\t\t */", "public", "int", "getShipType", "(", ")", "{", "return", "mShipType", ";", "}", "public", "void", "setShipType", "(", "int", "shipType", ")", "{", "mShipType", "=", "shipType", ";", "}", "/**\n\t\t * Returns the Vessel identified by the ship's hull ID, or null if no such Vessel can be found.\n\t\t */", "public", "Vessel", "getVessel", "(", "ArtemisContext", "ctx", ")", "{", "return", "ctx", ".", "getVesselData", "(", ")", ".", "getVessel", "(", "mShipType", ")", ";", "}", "public", "void", "setVessel", "(", "Vessel", "vessel", ")", "{", "setShipType", "(", "vessel", ".", "getId", "(", ")", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "mName", "+", "\"", ": (type #", "\"", "+", "mShipType", "+", "\"", ")", "\"", ";", "}", "}", "private", "static", "final", "Version", "COLOR_VERSION", "=", "new", "Version", "(", "\"", "2.4.0", "\"", ")", ";", "private", "final", "Ship", "[", "]", "mShips", ";", "public", "AllShipSettingsPacket", "(", "PacketReader", "reader", ")", "{", "super", "(", "reader", ")", ";", "mShips", "=", "new", "Ship", "[", "Artemis", ".", "SHIP_COUNT", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "Artemis", ".", "SHIP_COUNT", ";", "i", "++", ")", "{", "reader", ".", "readInt", "(", ")", ";", "int", "hullId", "=", "reader", ".", "readInt", "(", ")", ";", "if", "(", "reader", ".", "getVersion", "(", ")", ".", "ge", "(", "COLOR_VERSION", ")", ")", "reader", ".", "readFloat", "(", ")", ";", "CharSequence", "name", "=", "null", ";", "if", "(", "reader", ".", "readInt", "(", ")", "!=", "0", ")", "name", "=", "reader", ".", "readString", "(", ")", ";", "mShips", "[", "i", "]", "=", "new", "Ship", "(", "name", ",", "hullId", ")", ";", "}", "}", "public", "AllShipSettingsPacket", "(", "Ship", "[", "]", "ships", ")", "{", "super", "(", "Subtype", ".", "SHIP_SETTINGS", ")", ";", "if", "(", "ships", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Ship array cannot be null", "\"", ")", ";", "if", "(", "ships", ".", "length", "!=", "Artemis", ".", "SHIP_COUNT", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Must specify exactly ", "\"", "+", "Artemis", ".", "SHIP_COUNT", "+", "\"", " ships", "\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ships", ".", "length", ";", "i", "++", ")", "{", "Ship", "ship", "=", "ships", "[", "i", "]", ";", "if", "(", "ship", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Ships in array cannot be null", "\"", ")", ";", "}", "mShips", "=", "ships", ";", "}", "/**\n * Returns the ship with the given index (0-based).\n */", "public", "Ship", "getShip", "(", "int", "shipIndex", ")", "{", "return", "mShips", "[", "shipIndex", "]", ";", "}", "@", "Override", "protected", "void", "writePayload", "(", "PacketWriter", "writer", ")", "{", "super", ".", "writePayload", "(", "writer", ")", ";", "for", "(", "Ship", "ship", ":", "mShips", ")", "{", "writer", ".", "writeInt", "(", "0", ")", ".", "writeInt", "(", "ship", ".", "mShipType", ")", ";", "if", "(", "writer", ".", "getVersion", "(", ")", ".", "ge", "(", "COLOR_VERSION", ")", ")", "writer", ".", "writeFloat", "(", "0f", ")", ";", "if", "(", "ship", ".", "mName", "==", "null", ")", "writer", ".", "writeInt", "(", "0", ")", ";", "else", "writer", ".", "writeInt", "(", "1", ")", ".", "writeString", "(", "ship", ".", "mName", ")", ";", "}", "}", "@", "Override", "protected", "void", "appendPacketDetail", "(", "StringBuilder", "b", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "Artemis", ".", "SHIP_COUNT", ";", "i", "++", ")", "b", ".", "append", "(", "\"", "\\n", "\\t", "\"", ")", ".", "append", "(", "mShips", "[", "i", "]", ")", ";", "}", "}" ]
Sent by the server to update the names, types and drives for each ship.
[ "Sent", "by", "the", "server", "to", "update", "the", "names", "types", "and", "drives", "for", "each", "ship", "." ]
[]
[ { "param": "SimpleEventPacket", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SimpleEventPacket", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b20b0b03f96b4e34591abdfece91ec037972542
mashintsev/marklet
src/main/java/io/github/atlascommunity/marklet/pages/PackagePage.java
[ "Apache-2.0" ]
Java
PackagePage
/** Index of package elements */
Index of package elements
[ "Index", "of", "package", "elements" ]
@RequiredArgsConstructor public class PackagePage implements DocumentPage { /** Package information */ private final PackageDoc packageDoc; /** Package path */ private final Path packageDirectory; /** Doclet options */ private final Options options; /** * Build document and write it to the selected folder * * @throws IOException something went wrong during write operation */ @Override public void build() throws IOException { String packageHeader = String.format("%s %s", PACKAGE, packageDoc.name()); StringBuilder packagePage = new StringBuilder().append(new Heading(packageHeader)).append("\n"); Arrays.stream(packageDoc.inlineTags()) .forEach( tag -> { String formattedTag = new MarkdownTag(tag, options.getFileEnding()).create(); packagePage.append(formattedTag); packagePage.append("\n").append(new HorizontalRule()).append("\n"); }); createPackageIndexes(packagePage); writeFile(packagePage); } /** * Generate index tables for package annotations, enums, interfaces and classes * * @param packagePage string representation of package page content */ private void createPackageIndexes(StringBuilder packagePage) { AnnotationTypeDoc[] packageAnnotations = packageDoc.annotationTypes(); if (ArrayUtils.isNotEmpty(packageAnnotations)) { generateTable(ANNOTATIONS, packageAnnotations, packagePage); } ClassDoc[] packageEnums = packageDoc.enums(); if (ArrayUtils.isNotEmpty(packageEnums)) { generateTable(ENUMERATIONS, packageEnums, packagePage); } ClassDoc[] packageInterfaces = packageDoc.interfaces(); if (ArrayUtils.isNotEmpty(packageInterfaces)) { generateTable(INTERFACES, packageInterfaces, packagePage); } ClassDoc[] packageClasses = packageDoc.allClasses(); if (ArrayUtils.isNotEmpty(packageClasses)) { generateTable(CLASSES, packageClasses, packagePage); } } /** * Generate index table * * @param tableLabel table name * @param docs elements to work with * @param packagePage string representation of package page content */ private void generateTable(String tableLabel, ClassDoc[] docs, StringBuilder packagePage) { packagePage.append(new Heading(tableLabel, 1)).append("\n"); Table.Builder table = new Table.Builder() .withAlignments(Table.ALIGN_LEFT) .withRowLimit(docs.length + 1) .addRow("Name"); Arrays.stream(docs) .forEach( d -> { String linkName = d.simpleTypeName(); String linkUrl = d.name().replace(".", "/") + "." + options.getFileEnding(); table.addRow(new Link(linkName, linkUrl)); }); packagePage.append(table.build()).append("\n"); } /** * Write file to the selected folder * * @param pageContent file content * @throws IOException something went wrong during write operation */ private void writeFile(StringBuilder pageContent) throws IOException { FileOutputStream savePath = new FileOutputStream(packageDirectory.resolve(PACKAGE_INDEX_FILE).toString()); try (Writer readmeFile = new OutputStreamWriter(savePath, StandardCharsets.UTF_8)) { readmeFile.write(pageContent.toString()); } } }
[ "@", "RequiredArgsConstructor", "public", "class", "PackagePage", "implements", "DocumentPage", "{", "/** Package information */", "private", "final", "PackageDoc", "packageDoc", ";", "/** Package path */", "private", "final", "Path", "packageDirectory", ";", "/** Doclet options */", "private", "final", "Options", "options", ";", "/**\n * Build document and write it to the selected folder\n *\n * @throws IOException something went wrong during write operation\n */", "@", "Override", "public", "void", "build", "(", ")", "throws", "IOException", "{", "String", "packageHeader", "=", "String", ".", "format", "(", "\"", "%s %s", "\"", ",", "PACKAGE", ",", "packageDoc", ".", "name", "(", ")", ")", ";", "StringBuilder", "packagePage", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "new", "Heading", "(", "packageHeader", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "Arrays", ".", "stream", "(", "packageDoc", ".", "inlineTags", "(", ")", ")", ".", "forEach", "(", "tag", "->", "{", "String", "formattedTag", "=", "new", "MarkdownTag", "(", "tag", ",", "options", ".", "getFileEnding", "(", ")", ")", ".", "create", "(", ")", ";", "packagePage", ".", "append", "(", "formattedTag", ")", ";", "packagePage", ".", "append", "(", "\"", "\\n", "\"", ")", ".", "append", "(", "new", "HorizontalRule", "(", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "}", ")", ";", "createPackageIndexes", "(", "packagePage", ")", ";", "writeFile", "(", "packagePage", ")", ";", "}", "/**\n * Generate index tables for package annotations, enums, interfaces and classes\n *\n * @param packagePage string representation of package page content\n */", "private", "void", "createPackageIndexes", "(", "StringBuilder", "packagePage", ")", "{", "AnnotationTypeDoc", "[", "]", "packageAnnotations", "=", "packageDoc", ".", "annotationTypes", "(", ")", ";", "if", "(", "ArrayUtils", ".", "isNotEmpty", "(", "packageAnnotations", ")", ")", "{", "generateTable", "(", "ANNOTATIONS", ",", "packageAnnotations", ",", "packagePage", ")", ";", "}", "ClassDoc", "[", "]", "packageEnums", "=", "packageDoc", ".", "enums", "(", ")", ";", "if", "(", "ArrayUtils", ".", "isNotEmpty", "(", "packageEnums", ")", ")", "{", "generateTable", "(", "ENUMERATIONS", ",", "packageEnums", ",", "packagePage", ")", ";", "}", "ClassDoc", "[", "]", "packageInterfaces", "=", "packageDoc", ".", "interfaces", "(", ")", ";", "if", "(", "ArrayUtils", ".", "isNotEmpty", "(", "packageInterfaces", ")", ")", "{", "generateTable", "(", "INTERFACES", ",", "packageInterfaces", ",", "packagePage", ")", ";", "}", "ClassDoc", "[", "]", "packageClasses", "=", "packageDoc", ".", "allClasses", "(", ")", ";", "if", "(", "ArrayUtils", ".", "isNotEmpty", "(", "packageClasses", ")", ")", "{", "generateTable", "(", "CLASSES", ",", "packageClasses", ",", "packagePage", ")", ";", "}", "}", "/**\n * Generate index table\n *\n * @param tableLabel table name\n * @param docs elements to work with\n * @param packagePage string representation of package page content\n */", "private", "void", "generateTable", "(", "String", "tableLabel", ",", "ClassDoc", "[", "]", "docs", ",", "StringBuilder", "packagePage", ")", "{", "packagePage", ".", "append", "(", "new", "Heading", "(", "tableLabel", ",", "1", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "Table", ".", "Builder", "table", "=", "new", "Table", ".", "Builder", "(", ")", ".", "withAlignments", "(", "Table", ".", "ALIGN_LEFT", ")", ".", "withRowLimit", "(", "docs", ".", "length", "+", "1", ")", ".", "addRow", "(", "\"", "Name", "\"", ")", ";", "Arrays", ".", "stream", "(", "docs", ")", ".", "forEach", "(", "d", "->", "{", "String", "linkName", "=", "d", ".", "simpleTypeName", "(", ")", ";", "String", "linkUrl", "=", "d", ".", "name", "(", ")", ".", "replace", "(", "\"", ".", "\"", ",", "\"", "/", "\"", ")", "+", "\"", ".", "\"", "+", "options", ".", "getFileEnding", "(", ")", ";", "table", ".", "addRow", "(", "new", "Link", "(", "linkName", ",", "linkUrl", ")", ")", ";", "}", ")", ";", "packagePage", ".", "append", "(", "table", ".", "build", "(", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "}", "/**\n * Write file to the selected folder\n *\n * @param pageContent file content\n * @throws IOException something went wrong during write operation\n */", "private", "void", "writeFile", "(", "StringBuilder", "pageContent", ")", "throws", "IOException", "{", "FileOutputStream", "savePath", "=", "new", "FileOutputStream", "(", "packageDirectory", ".", "resolve", "(", "PACKAGE_INDEX_FILE", ")", ".", "toString", "(", ")", ")", ";", "try", "(", "Writer", "readmeFile", "=", "new", "OutputStreamWriter", "(", "savePath", ",", "StandardCharsets", ".", "UTF_8", ")", ")", "{", "readmeFile", ".", "write", "(", "pageContent", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
Index of package elements
[ "Index", "of", "package", "elements" ]
[]
[ { "param": "DocumentPage", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DocumentPage", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b23087fb8b963ca72bac63716c43034c90e842f
bawse/se206-project-fx
src/com/softeng206/vidivox/concurrency/audio/FestivalMp3Worker.java
[ "CC-BY-4.0" ]
Java
FestivalMp3Worker
/** * @author Jay Pandya */
@author Jay Pandya
[ "@author", "Jay", "Pandya" ]
public class FestivalMp3Worker extends BashWorker { private File destination; private String message; public FestivalMp3Worker(String message, File destination) { this.destination = destination; this.message = message; } protected String getBashCommand() { // If we get here, the overwrite option in the file chooser was accepted if (destination.exists()) { destination.delete(); } // FFMPEG command from Nasser's followup to https://piazza.com/class/icl94md3xuv6n9?cid=92 // Makes temporary wav with text2wave, then converts to MP3 using ffmpeg return "rm -f /tmp/vidivoxout.wav && echo \"" + escapeChars(message) + "\" | text2wave -o /tmp/vidivoxout.wav && " + "ffmpeg -i /tmp/vidivoxout.wav -f mp3 \"" + escapeChars(destination.getAbsolutePath()) + "\" && rm /tmp/vidivoxout.wav"; } protected int getKillPID(int mainPid) { return mainPid; } }
[ "public", "class", "FestivalMp3Worker", "extends", "BashWorker", "{", "private", "File", "destination", ";", "private", "String", "message", ";", "public", "FestivalMp3Worker", "(", "String", "message", ",", "File", "destination", ")", "{", "this", ".", "destination", "=", "destination", ";", "this", ".", "message", "=", "message", ";", "}", "protected", "String", "getBashCommand", "(", ")", "{", "if", "(", "destination", ".", "exists", "(", ")", ")", "{", "destination", ".", "delete", "(", ")", ";", "}", "return", "\"", "rm -f /tmp/vidivoxout.wav && echo ", "\\\"", "\"", "+", "escapeChars", "(", "message", ")", "+", "\"", "\\\"", " | text2wave -o /tmp/vidivoxout.wav && ", "\"", "+", "\"", "ffmpeg -i /tmp/vidivoxout.wav -f mp3 ", "\\\"", "\"", "+", "escapeChars", "(", "destination", ".", "getAbsolutePath", "(", ")", ")", "+", "\"", "\\\"", " && rm /tmp/vidivoxout.wav", "\"", ";", "}", "protected", "int", "getKillPID", "(", "int", "mainPid", ")", "{", "return", "mainPid", ";", "}", "}" ]
@author Jay Pandya
[ "@author", "Jay", "Pandya" ]
[ "// If we get here, the overwrite option in the file chooser was accepted", "// FFMPEG command from Nasser's followup to https://piazza.com/class/icl94md3xuv6n9?cid=92", "// Makes temporary wav with text2wave, then converts to MP3 using ffmpeg" ]
[ { "param": "BashWorker", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BashWorker", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b267afae97f15f90dcc644c95c38c95d2bb5b73
Shashi-rk/azure-sdk-for-java
sdk/logic/azure-resourcemanager-logic/src/main/java/com/azure/resourcemanager/logic/models/IpAddressRange.java
[ "MIT" ]
Java
IpAddressRange
/** The ip address range. */
The ip address range.
[ "The", "ip", "address", "range", "." ]
@Fluent public final class IpAddressRange { @JsonIgnore private final ClientLogger logger = new ClientLogger(IpAddressRange.class); /* * The IP address range. */ @JsonProperty(value = "addressRange") private String addressRange; /** * Get the addressRange property: The IP address range. * * @return the addressRange value. */ public String addressRange() { return this.addressRange; } /** * Set the addressRange property: The IP address range. * * @param addressRange the addressRange value to set. * @return the IpAddressRange object itself. */ public IpAddressRange withAddressRange(String addressRange) { this.addressRange = addressRange; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
[ "@", "Fluent", "public", "final", "class", "IpAddressRange", "{", "@", "JsonIgnore", "private", "final", "ClientLogger", "logger", "=", "new", "ClientLogger", "(", "IpAddressRange", ".", "class", ")", ";", "/*\n * The IP address range.\n */", "@", "JsonProperty", "(", "value", "=", "\"", "addressRange", "\"", ")", "private", "String", "addressRange", ";", "/**\n * Get the addressRange property: The IP address range.\n *\n * @return the addressRange value.\n */", "public", "String", "addressRange", "(", ")", "{", "return", "this", ".", "addressRange", ";", "}", "/**\n * Set the addressRange property: The IP address range.\n *\n * @param addressRange the addressRange value to set.\n * @return the IpAddressRange object itself.\n */", "public", "IpAddressRange", "withAddressRange", "(", "String", "addressRange", ")", "{", "this", ".", "addressRange", "=", "addressRange", ";", "return", "this", ";", "}", "/**\n * Validates the instance.\n *\n * @throws IllegalArgumentException thrown if the instance is not valid.\n */", "public", "void", "validate", "(", ")", "{", "}", "}" ]
The ip address range.
[ "The", "ip", "address", "range", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b27a5ac2d83bc9b96bd63ece89fd454e178c96d
northleafup/spring-2.0-sourcecode
src/org/springframework/aop/framework/adapter/AfterReturningAdviceInterceptor.java
[ "Apache-2.0" ]
Java
AfterReturningAdviceInterceptor
/** * Interceptor to wrap a MethodAfterReturningAdvice. In future we may also offer * a more efficient alternative solution in cases where there is no interception * advice and therefore no need to create a MethodInvocation object. * * <p>Used internally by the AOP framework: Application developers should not need * to use this class directly. * * <p>You can also use this class to wrap Spring AfterReturningAdvice implementations * for use in other AOP frameworks supporting the AOP Alliance interfaces. * * @author Rod Johnson */
Interceptor to wrap a MethodAfterReturningAdvice. In future we may also offer a more efficient alternative solution in cases where there is no interception advice and therefore no need to create a MethodInvocation object. Used internally by the AOP framework: Application developers should not need to use this class directly. You can also use this class to wrap Spring AfterReturningAdvice implementations for use in other AOP frameworks supporting the AOP Alliance interfaces. @author Rod Johnson
[ "Interceptor", "to", "wrap", "a", "MethodAfterReturningAdvice", ".", "In", "future", "we", "may", "also", "offer", "a", "more", "efficient", "alternative", "solution", "in", "cases", "where", "there", "is", "no", "interception", "advice", "and", "therefore", "no", "need", "to", "create", "a", "MethodInvocation", "object", ".", "Used", "internally", "by", "the", "AOP", "framework", ":", "Application", "developers", "should", "not", "need", "to", "use", "this", "class", "directly", ".", "You", "can", "also", "use", "this", "class", "to", "wrap", "Spring", "AfterReturningAdvice", "implementations", "for", "use", "in", "other", "AOP", "frameworks", "supporting", "the", "AOP", "Alliance", "interfaces", ".", "@author", "Rod", "Johnson" ]
public final class AfterReturningAdviceInterceptor implements MethodInterceptor, Serializable { private final AfterReturningAdvice advice; public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) { this.advice = advice; } /** * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation) */ public Object invoke(MethodInvocation mi) throws Throwable { Object retVal = mi.proceed(); this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis()); return retVal; } }
[ "public", "final", "class", "AfterReturningAdviceInterceptor", "implements", "MethodInterceptor", ",", "Serializable", "{", "private", "final", "AfterReturningAdvice", "advice", ";", "public", "AfterReturningAdviceInterceptor", "(", "AfterReturningAdvice", "advice", ")", "{", "this", ".", "advice", "=", "advice", ";", "}", "/**\n\t * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)\n\t */", "public", "Object", "invoke", "(", "MethodInvocation", "mi", ")", "throws", "Throwable", "{", "Object", "retVal", "=", "mi", ".", "proceed", "(", ")", ";", "this", ".", "advice", ".", "afterReturning", "(", "retVal", ",", "mi", ".", "getMethod", "(", ")", ",", "mi", ".", "getArguments", "(", ")", ",", "mi", ".", "getThis", "(", ")", ")", ";", "return", "retVal", ";", "}", "}" ]
Interceptor to wrap a MethodAfterReturningAdvice.
[ "Interceptor", "to", "wrap", "a", "MethodAfterReturningAdvice", "." ]
[]
[ { "param": "MethodInterceptor, Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MethodInterceptor, Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b30f5f42a3a1567fd2cade1f36c2231b6f42680
farindk/android-library
src/com/owncloud/android/lib/common/Quota.java
[ "MIT" ]
Java
Quota
/** * Quota data model */
Quota data model
[ "Quota", "data", "model" ]
@Parcel public class Quota { @SerializedName("free") public long free; @SerializedName("used") public long used; @SerializedName("total") public long total; @SerializedName("quota") public long quota; @SerializedName("relative") public double relative; public Quota() { } public Quota(long free, long used, long total, double relative, long quota) { this.free = free; this.used = used; this.total = total; this.quota = quota; this.relative = relative; } public long getFree() { return free; } public void setFree(long free) { this.free = free; } public long getUsed() { return used; } public void setUsed(long used) { this.used = used; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public long getQuota() { return quota; } public void setQuota(long quota) { this.quota = quota; } public double getRelative() { return relative; } public void setRelative(double relative) { this.relative = relative; } }
[ "@", "Parcel", "public", "class", "Quota", "{", "@", "SerializedName", "(", "\"", "free", "\"", ")", "public", "long", "free", ";", "@", "SerializedName", "(", "\"", "used", "\"", ")", "public", "long", "used", ";", "@", "SerializedName", "(", "\"", "total", "\"", ")", "public", "long", "total", ";", "@", "SerializedName", "(", "\"", "quota", "\"", ")", "public", "long", "quota", ";", "@", "SerializedName", "(", "\"", "relative", "\"", ")", "public", "double", "relative", ";", "public", "Quota", "(", ")", "{", "}", "public", "Quota", "(", "long", "free", ",", "long", "used", ",", "long", "total", ",", "double", "relative", ",", "long", "quota", ")", "{", "this", ".", "free", "=", "free", ";", "this", ".", "used", "=", "used", ";", "this", ".", "total", "=", "total", ";", "this", ".", "quota", "=", "quota", ";", "this", ".", "relative", "=", "relative", ";", "}", "public", "long", "getFree", "(", ")", "{", "return", "free", ";", "}", "public", "void", "setFree", "(", "long", "free", ")", "{", "this", ".", "free", "=", "free", ";", "}", "public", "long", "getUsed", "(", ")", "{", "return", "used", ";", "}", "public", "void", "setUsed", "(", "long", "used", ")", "{", "this", ".", "used", "=", "used", ";", "}", "public", "long", "getTotal", "(", ")", "{", "return", "total", ";", "}", "public", "void", "setTotal", "(", "long", "total", ")", "{", "this", ".", "total", "=", "total", ";", "}", "public", "long", "getQuota", "(", ")", "{", "return", "quota", ";", "}", "public", "void", "setQuota", "(", "long", "quota", ")", "{", "this", ".", "quota", "=", "quota", ";", "}", "public", "double", "getRelative", "(", ")", "{", "return", "relative", ";", "}", "public", "void", "setRelative", "(", "double", "relative", ")", "{", "this", ".", "relative", "=", "relative", ";", "}", "}" ]
Quota data model
[ "Quota", "data", "model" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b341ec9bca47e190b6354624aaa2de749b544a5
farisdurrani/TFTP-UDP-Protocol
TFTP-UDP-Server/Client.java
[ "CC-BY-4.0" ]
Java
Client
/** * This class keeps and processes the states of each Client in process. * TFTPServerThread will call on the this class when processing each Client. * * @author 223459 afd22@sussex.ac.uk * @version 1.0 %G%, %U%. * */
This class keeps and processes the states of each Client in process. TFTPServerThread will call on the this class when processing each Client.
[ "This", "class", "keeps", "and", "processes", "the", "states", "of", "each", "Client", "in", "process", ".", "TFTPServerThread", "will", "call", "on", "the", "this", "class", "when", "processing", "each", "Client", "." ]
public class Client { /** RRQ: Block number currently in attempt to be sent to Client in a read * request. Increases by one unit for each successful acknowledgement. */ private int blockNumber = -1; /** RRQ: Expected acknowledgement number (block number of received ACK * packet) to be received in a read request. Must always be equal to * 'blockNumber'. */ private int expectedAck = -1; /** WRQ: Expected block number to be received in a write request. */ private int blockExpected = -1; /** Port number of this Client. */ private final int clientPort; /** Internet address of this Client. */ private final InetAddress clientAddr; /** Either a read or write request that this Client is prompting. */ private final Opcode requestOpcode; /** RRQ: BufferedReader to read and send char buffers from requested file * in a read request. */ private BufferedReader rdr; /** WRQ: Whether the final DATA packet has been successfully received. */ private boolean writeRequestCompleted = false; /** Name of file in request. */ private final String filename; /** RRQ: Reading file in 512 bytes and sending the read buffer in blocks. */ private char[] readBuf = new char[DEFAULT_DATA_SIZE]; // = 512 /** WRQ: Current content of file successfully received in a WRQ. */ private StringBuilder fileContent; /** Sole slave socket of this Server. */ private final DatagramSocket slaveSocket = TFTPServerThread.slaveSocket; /** Default size of a single DATA block content. */ private static final int DEFAULT_DATA_SIZE = Constants.DEFAULT_DATA_SIZE; /** Limit to how many times a packet can be sent before returning. */ private static final int LOOP_LIMIT = Constants.FINAL_LOOP_LIMIT; /** * Sole functional constructor. * * @param op either a WRQ or RRQ depending on this Client's initial prompt. * @param socAddr Socket Internet Address of this Client. * @param nameOfFile filename in request. * */ public Client(Opcode op, InetSocketAddress socAddr, String nameOfFile) { clientPort = socAddr.getPort(); clientAddr = socAddr.getAddress(); requestOpcode = op; filename = nameOfFile; if (op == Opcode.RRQ) { blockNumber = 1; expectedAck = blockNumber; } else if (op == Opcode.WRQ) { blockExpected = 1; fileContent = new StringBuilder(DEFAULT_DATA_SIZE + 4); } else { System.out.println("ERROR 227\n"); System.exit(-1); } } /** * Throw-away constructor solely to enable external usage of methods. * */ protected Client() { filename = null; clientAddr = null; clientPort = -1; requestOpcode = Opcode.BLANK; } /** * RRQ: Initialises the BufferedReader to read and send file content to * Client in a RRQ. * * @throws IOException if an I/O error occurs. * */ protected void makeBuffer() throws IOException { // makes a BufferedReader to read content of file rdr = new BufferedReader(new FileReader(filename)); } /** * RRQ: The main read method on the Server side. Processes a single * request to read a file from the server. DATA packets in octet mode are * sent one at a time, waiting for respective acknowledgements before * another is sent. * * This process terminates once the final acknowledgement is received, or if * the final DATA packet has been sent above FINAL_LOOP_COUNT times, when * the server is presumed to have received the packet and kept failing to * send the final acknowledgement. * * Socket timeouts are initialized and handled here. * * @throws IOException if an I/O error occurs. * */ protected void readFile() throws IOException { slaveSocket.setSoTimeout(Constants.TIMEOUT); // if a packet was sent but timeout before the ACK is received, // resend the packet once more. move on to next client at timeout or // receipt of the ACK if (blockNumber != expectedAck) { System.out.println("ERROR 567: blockNumber " + blockNumber + " != expectedAck " + expectedAck + "."); rdr.close(); slaveSocket.close(); System.exit(-1); } int readCount; if ((readCount = rdr.read(readBuf, 0, readBuf.length)) > 0) { slaveSocket.setSoTimeout(Constants.TIMEOUT); int loopCount = 0; // sends DATA repeatedly until an ACK is received while (true) { try { // sends a packet filled with 516-byte-or-less file data DatagramPacket packetInLine = produceDataPacket(readBuf, readCount, blockNumber); packetInLine.setPort(clientPort); packetInLine.setAddress(clientAddr); udtSend(packetInLine, clientPort, clientAddr); if (readCount < DEFAULT_DATA_SIZE) { System.out.println("Last data packet " + blockNumber + " sent [" + slaveSocket.getLocalPort() + ", " + clientPort + "].\n"); } else { System.out.println("Data packet " + blockNumber + " sent [" + slaveSocket.getLocalPort() + ", " + clientPort + "].\n"); } // necessary to 'stimulate' the process, otherwise // readBuf somehow won't send DO NOT DELETE char randomChar = readBuf[readBuf.length / 2]; // DO NOT DEL // receive ACK for sent data byte[] bufAck = (receiveAck(expectedAck, packetInLine)).getData(); int blockReceived = fromByteToInt(new byte[]{bufAck[2], bufAck[3]}); // correct ACK received: move on to next Client if (blockReceived == expectedAck) { blockNumber++; expectedAck++; break; } } catch (SocketTimeoutException soe) { // repeat cycle until receive ACK System.out.println("NOTE 868: Timeout. Resending block " + blockNumber + ".\n"); // if final data block is consistently not acknowledged, // presumed Client is terminated & all data received. // Thread will be terminated. // else if non-final data block is consistently not // acknowledged, move on to next Client if (readCount < DEFAULT_DATA_SIZE) { // final block if (loopCount > LOOP_LIMIT) { // > 20 System.out.println("\nloopCount = " + loopCount); System.out.println("\nLast block sent too " + "frequently." + " Server presumed terminated.\n"); break; } } else { // readCount == 512 if (loopCount > LOOP_LIMIT / 2) { // > 10 break; } } } loopCount++; } slaveSocket.setSoTimeout(0); } // if the characters read is less than 512 bytes, then either the // file size is a multiple of 512 bytes meaning we have to send a // 0-byte DATA packet or that it's the end of the file and // read process is completed if (readCount == DEFAULT_DATA_SIZE) { // at end of while loop, one block has been acknowledged and move // on to next client slaveSocket.setSoTimeout(0); return; } else if (readCount < DEFAULT_DATA_SIZE) { // if file size multiple of 512 bytes, a last packet of 0-byte data // size will be sent i.e. move on to next client and send the // last packet later. Else, file successfully sent. boolean fileMultipleOfBlockSize = (new File(filename)).length() % DEFAULT_DATA_SIZE == 0; if (fileMultipleOfBlockSize) { sendZeroData(); } // file transmission successful. terminate thread rdr.close(); removeFromStatus(clientAddr, clientPort); slaveSocket.setSoTimeout(0); return; } slaveSocket.setSoTimeout(0); } /** * RRQ: Sends a single DATA packet with zero content to the Client in an * RRQ. Called when the size of the transmitted file contents is a multiple * of DEFAULT_DATA_SIZE as the last DATA packet to be sent. * * @throws IOException if an I/O error occurs. * */ private void sendZeroData() throws IOException { System.out.println("NOTE 908: File size multiple of " + DEFAULT_DATA_SIZE + " bytes."); readBuf = new char[0]; DatagramPacket packetInLine = produceDataPacket(readBuf, 0, blockNumber); packetInLine.setPort(clientPort); packetInLine.setAddress(clientAddr); // how many times server sent final data packet int loopCount = 0; // resend until ACK received while (true) { try { udtSend(packetInLine, clientPort, clientAddr); System.out.println("Last data packet with block number " + blockNumber + " sent [" + slaveSocket.getLocalPort() + ", " + clientPort + "].\n"); // receive ACK for sent data receiveAck(expectedAck, packetInLine); break; } catch (SocketTimeoutException soe) { System.out.println("NOTE 304: Timeout. Resending block " + blockNumber + "."); // if final data block is consistently not acknowledged, // presumed Client is terminated & all data received System.out.println("\nloopCount = " + loopCount); if (loopCount > LOOP_LIMIT) { System.out.println("\nLast block sent too frequently." + " Client presumed terminated.\n"); break; } } loopCount++; } } /** * Sends a single ACK with block number 0 to Client as acknowledgement of * WRQ request. * * @throws IOException if an I/O error occurs. * */ protected void sendFirstAck() throws IOException { if (requestOpcode != Opcode.WRQ) { System.out.println("ERROR 706\n"); System.exit(-1); } sendACK(0, clientPort, clientAddr); } /** * WRQ: The main write method on the Server side. Processes a single request * to write a file to the server. DATA packets in octet mode are received * and separate acknowledgements are received for each before another DATA * packet can be received. An acknowledgement to write was previously sent * to Client. Will attempt to receive DATA 1 from Client afterwards but at * timeout will send ACK 0 indefinitely until DATA 1 received. Returns so * TFTPServerThread can process next Client. At receipt of DATA, the * corresponding ACK will be sent and this includes DATA already * acknowledged (duplicates). * * Repeats receipt and return for subsequent DATA packets until the final * (size < DEFAULT_DATA_SIZE bytes) is received. Then, writes made * StringBuilder to file and returns. Returns after one ACK sent (unless if * it is ACK 0). * * Dallying is used where this Server Thread keeps open for 10 * TIMEOUT * after receiving final ACK to listen to incoming final DATA packets if * Client hasn't received acknowledgement. Removes this Client from * TFTPServer.mainStatus after timeout. * * Socket timeouts are initialized and handled here. * * @throws IOException if an I/O error occurs. */ protected void receiveWrittenFile() throws IOException { byte[] totalBuf = new byte[DEFAULT_DATA_SIZE + 4]; // keep receiving the duplicate of the final DATA packet if the // Client hasn't received the final ACK until timeout when Client // presumed to have received the final ACK and terminated if (writeRequestCompleted) { slaveSocket.setSoTimeout(10 * Constants.TIMEOUT); while (true) { try { DatagramPacket finalDuplicate = new DatagramPacket(totalBuf, totalBuf.length); slaveSocket.receive(finalDuplicate); if (verifySocAddr(finalDuplicate, clientAddr, clientPort) && verifyPacketOpcode(finalDuplicate, Opcode.DATA)) { byte[] blockEncoded = {totalBuf[2], totalBuf[3]}; int blockReceived = fromByteToInt(blockEncoded); System.out.println("NOTE 544: Received duplicate of " + "final" + " DATA block " + blockReceived + ".\n"); sendACK(blockReceived, clientPort, clientAddr); } } catch (SocketTimeoutException soe) { slaveSocket.setSoTimeout(0); System.out.println("Thread terminated.\n"); removeFromStatus(clientAddr, clientPort); return; } } } DatagramPacket received = new DatagramPacket(totalBuf, totalBuf.length); // if ACK 0 was received, expect to receive a DATA 1 packet. If no // DATA packet received from the correct source, keep receiving. if (blockExpected == 1) { slaveSocket.setSoTimeout(Constants.TIMEOUT); while (true) { try { slaveSocket.receive(received); if (verifySocAddr(received, clientAddr, clientPort) && verifyPacketOpcode(received, Opcode.DATA)) { break; } } catch (SocketTimeoutException soe) { sendFirstAck(); } } slaveSocket.setSoTimeout(0); } else { // DATA 1 has been received before while (true) { // if ACK 0 successfully received and subsequent DATA packets is // being sent, wait indefinitely until next DATA is received slaveSocket.receive(received); // if received packet not of correct source or not DATA, // keep receiving if (verifySocAddr(received, clientAddr, clientPort) && verifyPacketOpcode(received, Opcode.DATA)) { break; } } } // send ACK after verifying block number; if less than // expected, resend ACK; if more than expected, declare // missing block and exit byte[] blockEncoded = {totalBuf[2], totalBuf[3]}; int blockReceived = fromByteToInt(blockEncoded); if (blockReceived == blockExpected) { sendACK(blockReceived, clientPort, clientAddr); // building file content String dataReceived = new String(received.getData(), 0, received.getLength()); fileContent.append(dataReceived.substring(4)); blockExpected++; } else if (blockReceived < blockExpected) { System.out.println("NOTE 648: Duplicate. Packet's block " + "received " + blockReceived + " < block " + "expected " + blockExpected + "."); sendACK(blockReceived, clientPort, clientAddr); } else { // blockReceived > blockExpected System.err.println("ERROR 301: A previous block of " + "data is missing."); System.out.println("blockReceived = " + blockReceived); System.out.println("blockExpected = " + blockExpected + "\n"); slaveSocket.close(); System.exit(-1); } // if last block, end transmission if (received.getLength() < DEFAULT_DATA_SIZE + 4) { System.out.println("Block " + blockReceived + " received " + "[" + received.getPort() + ", " + slaveSocket.getLocalPort() + "]." + " Final ACK " + blockReceived + " sent [" + slaveSocket.getLocalPort() + ", " + clientPort + "].\n"); // write file that was read FileWriter myWriter = new FileWriter(filename); myWriter.write(String.valueOf(fileContent)); myWriter.close(); System.out.println("File " + filename + " successfully received " + "and written. Terminating thread."); System.out.println(); writeRequestCompleted = true; } else { System.out.println("Block " + blockReceived + " received " + "[" + received.getPort() + ", " + slaveSocket.getLocalPort() + "]." + " ACK " + blockReceived + " sent [" + slaveSocket.getLocalPort() + ", " + clientPort + "].\n"); } slaveSocket.setSoTimeout(0); } //=========================helper methods=================================== /** * Returns the opcode of a TFTP operation in byte[] form, based on RFC 1350. * * @param opcode the operation in request. * @return opcode of operation. * @see Opcode * */ private byte[] generateOpcode(Opcode opcode) { byte[] rrq = {0, (byte) Opcode.RRQ.ordinal()}; // {0, 1} byte[] wrq = {0, (byte) Opcode.WRQ.ordinal()}; // {0, 2} byte[] data = {0, (byte) Opcode.DATA.ordinal()}; // {0, 3} byte[] ack = {0, (byte) Opcode.ACK.ordinal()}; // {0, 4} byte[] error = {0, (byte) Opcode.ERROR.ordinal()}; // {0, 5} byte[] none = {Byte.MIN_VALUE, Byte.MIN_VALUE}; // {-128, -128} switch (opcode) { case RRQ: return rrq; case WRQ: return wrq; case DATA: return data; case ACK: return ack; case ERROR: return error; default: System.err.println("ERROR 760: Opcode not recognized."); slaveSocket.close(); System.exit(-1); return none; } } /** * Concatenates two byte arrays in order and returns the result. * * @param array1 byte array to appear first. * @param array2 byte array to appear last. * @return concatenated result of array1 and array2 in that order. * */ private byte[] combineArr(byte[] array1, byte[] array2) { int aLen = array1.length; int bLen = array2.length; byte[] result = new byte[aLen + bLen]; System.arraycopy(array1, 0, result, 0, aLen); System.arraycopy(array2, 0, result, aLen, bLen); return result; } /** * Converts the number stored in 2-tuple byte array base-256 into the * base-10 integer equivalent. b must be 2-tuple as b was initially * constructed in fromIntToByte(int) with checking mechanisms. * Block Number = (b[1] + 128) + 256 * (b[0] + 128), max = 65535. * {-128, -128} = 0 * {-128, 0} = 128 * {-128, 127} = 255 * {-127, -128} = 256 * {127, 127} = 65535 * * @param b the byte array holding the 2-tuple base-256 bytes. * @return b in base-10 int format. * */ private int fromByteToInt(byte[] b) { int base = Byte.MAX_VALUE + (-1 * Byte.MIN_VALUE) + 1; // 256 // ans = b[1] + 128 + 256 * (b[0] + 128) return (b[1] + (-1 * Byte.MIN_VALUE) + base * (b[0] + (-1 * Byte.MIN_VALUE))); } /** * Converts the number stored in integer base-10 format into a 2-tuple * Byte array, with both bytes in base-256 from min -128 to max 127. * Block Number = (b[1] + 128) + 256 * (b[0] + 128), max = 65535. * {-128, -128} = 0 * {-128, 0} = 128 * {-128, 127} = 255 * {-127, -128} = 256 * {127, 127} = 65535 * * @param i number in base-10 integer format. * @return i in 2-tuple Byte array in base-256 (range of Byte) format. * Error if i is out of range (i < 0 or i > 65535). * */ private byte[] fromIntToByte(int i) throws IOException { int base = Byte.MAX_VALUE + (-1 * Byte.MIN_VALUE) + 1; // 256 int max = base * (base - 1) + (base - 1); // 65535 byte zerothDigit = (byte) (i / base + Byte.MIN_VALUE); // i / 256 - 128 byte firstDigit = (byte) ((i % base) + Byte.MIN_VALUE); // i % 256 - 128 if (i >= 0 && i <= max) { return new byte[]{zerothDigit, firstDigit}; } else { System.out.println("ERROR 461: Block number out of range " + "[0, 65535]. "); System.out.println("Terminating thread.\n"); terminatePrematurely("ERROR 461 raised.\n"); return null; } } /** * Generates a DatagramPacket DATA packet with the given input contents of * the packet, with length equalling the actual used space which may be * 516 bytes (DEFAULT_DATA_SIZE + 4) or lower to a minimum of 4 bytes. * * @param buf character buffer of the DATA contents. * @param readCount number of characters in character buffer. * @param numberOfBlock block number of this DATA packet. * @return DATA packet with contents and block number. * */ private DatagramPacket produceDataPacket(char[] buf, int readCount, int numberOfBlock) throws IOException { byte[] dataBuf = new byte[DEFAULT_DATA_SIZE]; // if only reading less than 512 chars, the read contents will be // the last content of the file. dataBuf readjusted to reflect final // content length if (readCount < DEFAULT_DATA_SIZE) { dataBuf = new byte[readCount]; } // copying readBuf into dataBuf for (int i = 0; i < readCount; i++) { dataBuf[i] = (byte) buf[i]; } // generating opcode for DATA byte[] dataOpcode = generateOpcode(Opcode.DATA); // generating block number in byte[] form byte[] block = fromIntToByte(numberOfBlock); // dataBuf = opcode + block number + data(original dataBuf) assert block != null; byte[] opcodeAndBlock = combineArr(dataOpcode, block); dataBuf = combineArr(opcodeAndBlock, dataBuf); // produce the DatagramPacket return new DatagramPacket(dataBuf, dataBuf.length); } /** * Returns the filename from a write request (WRQ) or read request (RRQ). * Exits system if mode is not octet (and indirectly if the packet's * contents do not resemble that of a WRQ or RRQ). * * @param packetContents raw content of received WRQ or RRQ. * @return filename kept inside the WRQ or RRQ. * */ protected String getFilename(byte[] packetContents) { // getting the locations of the three zero bytes // filename is located in index 2 : 2nd zero // mode is located in index (2nd zero + 1) : 3rd zero // per RFC: | 01/02 | Filename | 0 | Mode | 0 | int index2ndZero = 0; int index3rdZero = 0; int index = 0; for (byte b : packetContents) { if (index > 0) { if (b == 0) { if (index2ndZero == 0) { index2ndZero = index; } else { index3rdZero = index; break; } } } index++; } String nameOfFile = (new String(packetContents)).substring(2, index2ndZero); // ensuring mode is octet String octet = (new String(packetContents)).substring((index2ndZero + 1), index3rdZero); if (!octet.equals("octet")) { System.out.println("ERROR 522: mode is not octet."); slaveSocket.close(); System.exit(-1); } return nameOfFile; } /** * A blocking call to receive an acknowledgement packet (ACK). If an ACK * with the expected block number is not received, the packet in line is * resent. If non-ACK packet received, this method remains open and * blocking until an ACK is received. * * Timeout is not initiated or handled here. * * @param expectedAcknowNum expected block number of incoming ACK. * @param packetInLine packet to be sent if the expected ACK is not * received. * @return received acknowledgement packet. * @throws IOException if an I/O error occurs. * */ private DatagramPacket receiveAck(int expectedAcknowNum, DatagramPacket packetInLine) throws IOException { // fixing port number of client // int clientPort = packetInLine.getPort(); // InetAddress clientAddr = packetInLine.getAddress(); // create buffer to receive ACK packet byte[] bufACK = new byte[4]; DatagramPacket ackPacket = new DatagramPacket(bufACK, bufACK.length); // receive and verify opcode is ACK and from clientPort do { slaveSocket.receive(ackPacket); } while (!verifySocAddr(ackPacket, clientAddr, clientPort) || !verifyPacketOpcode(ackPacket, Opcode.ACK)); // verifying expected ACK block number byte[] blockReceived = {bufACK[2], bufACK[3]}; int ackReceived = fromByteToInt(blockReceived); if (ackReceived < expectedAcknowNum) { System.out.println("NOTE 002: ackReceived " + ackReceived + " < expectedAcknowNum " + expectedAcknowNum + ". DATA lost in network. "); udtSend(packetInLine, clientPort, clientAddr); } else if (ackReceived == expectedAcknowNum) { if (packetInLine.getLength() < DEFAULT_DATA_SIZE + 4) { System.out.println("Final data block " + ackReceived + " successfully acknowledged. Terminating thread."); } else { System.out.println("Data block " + ackReceived + " successfully acknowledged. Sending next block."); } System.out.println(); } else { System.out.println("ERROR 004: ackReceived " + ackReceived + " > expectedAcknowNum " + expectedAcknowNum + "."); slaveSocket.close(); System.exit(-1); } return ackPacket; } /** * Sends a DatagramPacket to the given port and internet address. * * @param packet packet to be sent. * @param port port number of destination remote host. * @param addr internet address of destination remote host. * */ private void udtSend(DatagramPacket packet, int port, InetAddress addr) throws IOException { packet.setAddress(addr); packet.setPort(port); // Unnecessary random variable to invoke lost packet simulations double random = Math.random(); // System.out.println(Constants.LOST_PROBABILITY); if (random < (1 - Constants.LOST_PROBABILITY)) { try { slaveSocket.send(packet); } catch (IllegalArgumentException ioe) { System.out.println(ioe.getMessage() + "\n"); } } else { System.out.println("Packet made lost."); } } /** * Ensures a packet has the expected opcode. Returns true if the expected * opcode matches packet's opcode. False otherwise. Exits the system if a * packet's opcode is ERROR but the expected opcode is not ERROR, for * example, if a WRQ packet is responded with a FILE_NOT_FOUND error. * * @param recv packet whose opcode is to be compared. * @param op expected opcode. * @return true if packet's opcode is the expected opcode. False * otherwise. Exits the system if packet's opcode is ERROR when expected * opcode is not ERROR. * */ private boolean verifyPacketOpcode(DatagramPacket recv, Opcode op) throws IOException { byte[] recvBuf = recv.getData(); boolean isRRQ = ((generateOpcode(Opcode.RRQ)[1]) == recvBuf[1]); boolean isWRQ = ((generateOpcode(Opcode.WRQ)[1]) == recvBuf[1]); boolean isData = ((generateOpcode(Opcode.DATA)[1]) == recvBuf[1]); boolean isError = ((generateOpcode(Opcode.ERROR)[1]) == recvBuf[1]); boolean isAck = ((generateOpcode(Opcode.ACK)[1]) == recvBuf[1]); switch (op) { case RRQ: if (isRRQ) { System.out.println("Request received: RRQ from " + "addr " + recv.getAddress() + " port " + recv.getPort() + "."); return true; } break; case WRQ: if (isWRQ) { System.out.println("Request received: WRQ from " + "addr " + recv.getAddress() + " port " + recv.getPort() + "."); return true; } break; case DATA: if (isData) { return true; } break; case ERROR: if (isError) { int errorCode = recvBuf[3]; String dataReceived = new String(recvBuf); String errMsg = dataReceived.substring(4, recv.getLength() - 1); System.out.println("ERROR 454: Expected error code " + errorCode + " with message: " + errMsg); System.out.println(); return true; } break; case ACK: if (isAck) { return true; } break; default: System.out.println("ERROR 631: Unknown opcode of data " + "received: " + recvBuf[1]); System.out.println(); System.out.println("Terminating server..."); slaveSocket.close(); System.exit(-1); } if (isError) { int errorCode = recvBuf[3]; String dataReceived = new String(recvBuf); try { String errMsg = dataReceived.substring(4, recv.getLength() - 1); System.out.println("ERROR 978: Unexpected error code 0" + errorCode + " with message: " + errMsg + ".\n"); } catch (IndexOutOfBoundsException ioe) { System.out.println(ioe.getMessage() + "\n"); } if (errorCode != Error.UNKNOWN_TID.ordinal()) { System.out.println("Terminating thread.\n"); terminatePrematurely("ERROR 977 raised.\n"); } } return false; } /** * Sends an acknowledgement packet (ACK) with the specified block number to * the server. * * @param block block number of DATA packet to be acknowledged. * @param port port number of client. * @param addr internet address of client. * @throws IOException if an I/O error occurs. * */ private void sendACK(int block, int port, InetAddress addr) throws IOException { byte[] blockInBytes = fromIntToByte(block); assert blockInBytes != null; byte[] packetContents = combineArr(generateOpcode(Opcode.ACK), blockInBytes); DatagramPacket ackToSend = new DatagramPacket(packetContents, packetContents.length); udtSend(ackToSend, port, addr); } /** * Sends an ERROR packet with a FILE_NOT_FOUND error message to the * remote Client. Called when a read request (RRQ) is received and the * file requested is not found. No acknowledgements expected but this * method is repeatedly called by the caller as long as the read * request is received again. * * @param received received read request packet. * @throws IOException if an I/O error occurs. * */ protected void sendFileNotFoundError(DatagramPacket received) throws IOException { sendErrorPacket(Error.FILE_NOT_FOUND, received); } /** * Sends an ERROR packet to the sender upon receipt of unexpected packet * or a request which cannot be fulfilled including because of a * file-not-found error. Terminates (exits) client where necessary. Error * codes are based on RFC 1350. * * @param op error code of this error. * @param received packet received which raised this error. * @throws IOException if an I/O error occurs. * @see Error * */ protected void sendErrorPacket(Error op, DatagramPacket received) throws IOException { byte[] opcode = generateOpcode(Opcode.ERROR); byte[] errCode = {Byte.MIN_VALUE, Byte.MIN_VALUE}; byte[] errMsg; byte[] zero = {0}; String message; boolean terminate = false; switch (op) { case NOT_DEFINED: // {0, 0} errCode = new byte[]{0, (byte) Error.NOT_DEFINED.ordinal()}; message = "Not defined."; terminate = true; break; case FILE_NOT_FOUND: // {0, 1} errCode = new byte[]{0, (byte) Error.FILE_NOT_FOUND.ordinal()}; String nameOfFile = getFilename(received.getData()); message = "File " + nameOfFile + " not found."; terminate = true; break; case ACCESS_VIOLATION: // {0, 2} errCode = new byte[]{0, (byte) Error.ACCESS_VIOLATION .ordinal()}; message = "Access Violation."; terminate = true; break; case DISK_FULL: // {0, 3} errCode = new byte[]{0, (byte) Error.DISK_FULL.ordinal()}; message = "Disk full or allocation exceeded."; terminate = true; break; case ILLEGAL_OPERATION: // {0, 4} errCode = new byte[]{0, (byte) Error.ILLEGAL_OPERATION .ordinal()}; message = "Illegal TFTP operation. Expecting a Write Request " + "or Read Request."; terminate = true; break; case UNKNOWN_TID: // {0, 5} errCode = new byte[]{0, (byte) Error.UNKNOWN_TID.ordinal()}; message = "Unknown Transfer ID " + received.getPort() + ". This connection is already used."; // terminate = false break; case FILE_ALREADY_EXISTS: // {0, 6} errCode = new byte[]{0, (byte) Error.FILE_ALREADY_EXISTS .ordinal()}; message = "File already exists."; terminate = true; break; case NO_SUCH_USER: // {0, 7} errCode = new byte[]{0, (byte) Error.NO_SUCH_USER.ordinal()}; message = "Mo such user."; terminate = true; break; default: message = "Not defined."; System.out.println("ERROR 993: Unknown Error Opcode."); terminate = true; } errMsg = (message).getBytes(); System.out.println("ERROR 0" + errCode[1] + ": " + message + "\n"); byte[] first = combineArr(opcode, errCode); byte[] second = combineArr(first, errMsg); byte[] third = combineArr(second, zero); DatagramPacket packet = new DatagramPacket(third, third.length); udtSend(packet, received.getPort(), received.getAddress()); if (terminate) { System.out.println("Terminating thread.\n"); removeFromStatus(clientAddr, clientPort); } } /** * Verifies the source port number of a received packet is equal to the * expected port number. * * @param received received packet. * @param port expected port number. * @return true if received's port is equal to expected port. False * otherwise. * */ private boolean verifyPort(DatagramPacket received, int port) { if (received.getPort() != port) { //System.out.println("received's port " + received.getPort() + " // != " // + " clientPort " + port + ". slavePort = " // + slaveSocket.getLocalPort() ); // sendConnectionUsedError(received); return false; } else { return true; } } /** Returns true if source address and port of received packet is equal * to the address and port input. False otherwise. * * @param received received packet to be verified. * @param addr Internet address of source Client. * @param port port number of source Client. * @return true if port and address input matches that of the packet's. * False otherwise. * */ private boolean verifySocAddr(DatagramPacket received, InetAddress addr, int port) { if (!verifyPort(received, port)) { return false; } return received.getAddress().equals(addr); } /** * Removes client from the mainStatus in TFTPServer after all processes * with client is done and connection closes with that client. * * @param addr internet address of client to be removed. * @param port port of client to be removed * */ private void removeFromStatus(InetAddress addr, int port) { InetSocketAddress toRemove = null; for (Map.Entry<InetSocketAddress, Client> i : TFTPServer.mainStatusPending.entrySet()) { InetSocketAddress current = i.getKey(); if (current.equals(new InetSocketAddress(addr, port))) { toRemove = current; } } if (toRemove != null) { TFTPServer.mainStatusPending.remove(toRemove); } } /** * Terminates this Client (remove from TFTPServer.mainStatus). Called if * a terminating error is raised. Does not close slaveSocket. * * @param errMsg error message raised. * * @throws IOException if an I/O error occurs. * */ private void terminatePrematurely(String errMsg) throws IOException { removeFromStatus(clientAddr, clientPort); throw new IOException(errMsg); } /** * Generates either a write request (WRQ) packet or read request (RRQ) * packet filled with a nameOfFile. Packet is without a predefined address * or port number. * * @param opcode opcode of operation, whether WRQ or RRQ. * @param nameOfFile name of file to be read or written. * @param addr Internet address of source Client of this request. * @param port port number of source Client of this request. * @return WRQ or RRQ for file in question without address or port number. * */ protected DatagramPacket generateRequestPacket(Opcode opcode, String nameOfFile, InetAddress addr, int port) { byte[] opcodeInByte = {Byte.MIN_VALUE, Byte.MIN_VALUE}; if (opcode == Opcode.RRQ) { // getting opcode opcodeInByte = generateOpcode(Opcode.RRQ); } else if (opcode == Opcode.WRQ) { // getting opcode opcodeInByte = generateOpcode(Opcode.WRQ); } else { System.out.println("ERROR 005: Opcode is not RRQ or WRQ."); slaveSocket.close(); System.exit(-1); } // getting mode, here remaining as octet String mode = "octet"; // producing RRQ byte[] firstContentInBytes = combineArr(opcodeInByte, nameOfFile.getBytes()); byte[] zero = {0}; byte[] secondContentInBytes = combineArr(firstContentInBytes, zero); byte[] thirdContentInBytes = combineArr(secondContentInBytes, mode.getBytes()); byte[] finalContentInBytes = combineArr(thirdContentInBytes, zero); return new DatagramPacket(finalContentInBytes, finalContentInBytes.length, addr, port); } // getters and setters------------------------------------------------------ /** * RRQ: Returns current block number being sent in an RRQ. * @return current block number being sent. * */ public int getBlockNumber() { return blockNumber; } /** * Returns the initial request of the Client, whether a WRQ or RRQ. * @return main request of this Client. * */ public Opcode getRequestOpcode() { return requestOpcode; } /** * Returns filename of file in request. * @return name of file in request. * */ public String getFilename() { return filename; } /** * Returns port number of this Client. * @return port of Client. * */ public int getClientPort() { return clientPort; } /** * Returns internet address of this Client. * @return internet address of Client. * */ public InetAddress getClientAddr() { return clientAddr; } /** * WRQ: Returns expected DATA block number to be received in a WRQ. * @return expected DATA block to be received. * */ public int getBlockExpected() { return blockExpected; } // END OF FILE }
[ "public", "class", "Client", "{", "/** RRQ: Block number currently in attempt to be sent to Client in a read\n * request. Increases by one unit for each successful acknowledgement. */", "private", "int", "blockNumber", "=", "-", "1", ";", "/** RRQ: Expected acknowledgement number (block number of received ACK\n * packet) to be received in a read request. Must always be equal to\n * 'blockNumber'. */", "private", "int", "expectedAck", "=", "-", "1", ";", "/** WRQ: Expected block number to be received in a write request. */", "private", "int", "blockExpected", "=", "-", "1", ";", "/** Port number of this Client. */", "private", "final", "int", "clientPort", ";", "/** Internet address of this Client. */", "private", "final", "InetAddress", "clientAddr", ";", "/** Either a read or write request that this Client is prompting. */", "private", "final", "Opcode", "requestOpcode", ";", "/** RRQ: BufferedReader to read and send char buffers from requested file\n * in a read request. */", "private", "BufferedReader", "rdr", ";", "/** WRQ: Whether the final DATA packet has been successfully received. */", "private", "boolean", "writeRequestCompleted", "=", "false", ";", "/** Name of file in request. */", "private", "final", "String", "filename", ";", "/** RRQ: Reading file in 512 bytes and sending the read buffer in blocks. */", "private", "char", "[", "]", "readBuf", "=", "new", "char", "[", "DEFAULT_DATA_SIZE", "]", ";", "/** WRQ: Current content of file successfully received in a WRQ. */", "private", "StringBuilder", "fileContent", ";", "/** Sole slave socket of this Server. */", "private", "final", "DatagramSocket", "slaveSocket", "=", "TFTPServerThread", ".", "slaveSocket", ";", "/** Default size of a single DATA block content. */", "private", "static", "final", "int", "DEFAULT_DATA_SIZE", "=", "Constants", ".", "DEFAULT_DATA_SIZE", ";", "/** Limit to how many times a packet can be sent before returning. */", "private", "static", "final", "int", "LOOP_LIMIT", "=", "Constants", ".", "FINAL_LOOP_LIMIT", ";", "/**\n * Sole functional constructor.\n *\n * @param op either a WRQ or RRQ depending on this Client's initial prompt.\n * @param socAddr Socket Internet Address of this Client.\n * @param nameOfFile filename in request.\n * */", "public", "Client", "(", "Opcode", "op", ",", "InetSocketAddress", "socAddr", ",", "String", "nameOfFile", ")", "{", "clientPort", "=", "socAddr", ".", "getPort", "(", ")", ";", "clientAddr", "=", "socAddr", ".", "getAddress", "(", ")", ";", "requestOpcode", "=", "op", ";", "filename", "=", "nameOfFile", ";", "if", "(", "op", "==", "Opcode", ".", "RRQ", ")", "{", "blockNumber", "=", "1", ";", "expectedAck", "=", "blockNumber", ";", "}", "else", "if", "(", "op", "==", "Opcode", ".", "WRQ", ")", "{", "blockExpected", "=", "1", ";", "fileContent", "=", "new", "StringBuilder", "(", "DEFAULT_DATA_SIZE", "+", "4", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "ERROR 227", "\\n", "\"", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "}", "/**\n * Throw-away constructor solely to enable external usage of methods.\n * */", "protected", "Client", "(", ")", "{", "filename", "=", "null", ";", "clientAddr", "=", "null", ";", "clientPort", "=", "-", "1", ";", "requestOpcode", "=", "Opcode", ".", "BLANK", ";", "}", "/**\n * RRQ: Initialises the BufferedReader to read and send file content to\n * Client in a RRQ.\n *\n * @throws IOException if an I/O error occurs.\n * */", "protected", "void", "makeBuffer", "(", ")", "throws", "IOException", "{", "rdr", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "filename", ")", ")", ";", "}", "/**\n * RRQ: The main read method on the Server side. Processes a single\n * request to read a file from the server. DATA packets in octet mode are\n * sent one at a time, waiting for respective acknowledgements before\n * another is sent.\n *\n * This process terminates once the final acknowledgement is received, or if\n * the final DATA packet has been sent above FINAL_LOOP_COUNT times, when\n * the server is presumed to have received the packet and kept failing to\n * send the final acknowledgement.\n *\n * Socket timeouts are initialized and handled here.\n *\n * @throws IOException if an I/O error occurs.\n * */", "protected", "void", "readFile", "(", ")", "throws", "IOException", "{", "slaveSocket", ".", "setSoTimeout", "(", "Constants", ".", "TIMEOUT", ")", ";", "if", "(", "blockNumber", "!=", "expectedAck", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "ERROR 567: blockNumber ", "\"", "+", "blockNumber", "+", "\"", " != expectedAck ", "\"", "+", "expectedAck", "+", "\"", ".", "\"", ")", ";", "rdr", ".", "close", "(", ")", ";", "slaveSocket", ".", "close", "(", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "int", "readCount", ";", "if", "(", "(", "readCount", "=", "rdr", ".", "read", "(", "readBuf", ",", "0", ",", "readBuf", ".", "length", ")", ")", ">", "0", ")", "{", "slaveSocket", ".", "setSoTimeout", "(", "Constants", ".", "TIMEOUT", ")", ";", "int", "loopCount", "=", "0", ";", "while", "(", "true", ")", "{", "try", "{", "DatagramPacket", "packetInLine", "=", "produceDataPacket", "(", "readBuf", ",", "readCount", ",", "blockNumber", ")", ";", "packetInLine", ".", "setPort", "(", "clientPort", ")", ";", "packetInLine", ".", "setAddress", "(", "clientAddr", ")", ";", "udtSend", "(", "packetInLine", ",", "clientPort", ",", "clientAddr", ")", ";", "if", "(", "readCount", "<", "DEFAULT_DATA_SIZE", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Last data packet ", "\"", "+", "blockNumber", "+", "\"", " sent [", "\"", "+", "slaveSocket", ".", "getLocalPort", "(", ")", "+", "\"", ", ", "\"", "+", "clientPort", "+", "\"", "].", "\\n", "\"", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Data packet ", "\"", "+", "blockNumber", "+", "\"", " sent [", "\"", "+", "slaveSocket", ".", "getLocalPort", "(", ")", "+", "\"", ", ", "\"", "+", "clientPort", "+", "\"", "].", "\\n", "\"", ")", ";", "}", "char", "randomChar", "=", "readBuf", "[", "readBuf", ".", "length", "/", "2", "]", ";", "byte", "[", "]", "bufAck", "=", "(", "receiveAck", "(", "expectedAck", ",", "packetInLine", ")", ")", ".", "getData", "(", ")", ";", "int", "blockReceived", "=", "fromByteToInt", "(", "new", "byte", "[", "]", "{", "bufAck", "[", "2", "]", ",", "bufAck", "[", "3", "]", "}", ")", ";", "if", "(", "blockReceived", "==", "expectedAck", ")", "{", "blockNumber", "++", ";", "expectedAck", "++", ";", "break", ";", "}", "}", "catch", "(", "SocketTimeoutException", "soe", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "NOTE 868: Timeout. Resending block ", "\"", "+", "blockNumber", "+", "\"", ".", "\\n", "\"", ")", ";", "if", "(", "readCount", "<", "DEFAULT_DATA_SIZE", ")", "{", "if", "(", "loopCount", ">", "LOOP_LIMIT", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "\\n", "loopCount = ", "\"", "+", "loopCount", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "\\n", "Last block sent too ", "\"", "+", "\"", "frequently.", "\"", "+", "\"", " Server presumed terminated.", "\\n", "\"", ")", ";", "break", ";", "}", "}", "else", "{", "if", "(", "loopCount", ">", "LOOP_LIMIT", "/", "2", ")", "{", "break", ";", "}", "}", "}", "loopCount", "++", ";", "}", "slaveSocket", ".", "setSoTimeout", "(", "0", ")", ";", "}", "if", "(", "readCount", "==", "DEFAULT_DATA_SIZE", ")", "{", "slaveSocket", ".", "setSoTimeout", "(", "0", ")", ";", "return", ";", "}", "else", "if", "(", "readCount", "<", "DEFAULT_DATA_SIZE", ")", "{", "boolean", "fileMultipleOfBlockSize", "=", "(", "new", "File", "(", "filename", ")", ")", ".", "length", "(", ")", "%", "DEFAULT_DATA_SIZE", "==", "0", ";", "if", "(", "fileMultipleOfBlockSize", ")", "{", "sendZeroData", "(", ")", ";", "}", "rdr", ".", "close", "(", ")", ";", "removeFromStatus", "(", "clientAddr", ",", "clientPort", ")", ";", "slaveSocket", ".", "setSoTimeout", "(", "0", ")", ";", "return", ";", "}", "slaveSocket", ".", "setSoTimeout", "(", "0", ")", ";", "}", "/**\n * RRQ: Sends a single DATA packet with zero content to the Client in an\n * RRQ. Called when the size of the transmitted file contents is a multiple\n * of DEFAULT_DATA_SIZE as the last DATA packet to be sent.\n *\n * @throws IOException if an I/O error occurs.\n * */", "private", "void", "sendZeroData", "(", ")", "throws", "IOException", "{", "System", ".", "out", ".", "println", "(", "\"", "NOTE 908: File size multiple of ", "\"", "+", "DEFAULT_DATA_SIZE", "+", "\"", " bytes.", "\"", ")", ";", "readBuf", "=", "new", "char", "[", "0", "]", ";", "DatagramPacket", "packetInLine", "=", "produceDataPacket", "(", "readBuf", ",", "0", ",", "blockNumber", ")", ";", "packetInLine", ".", "setPort", "(", "clientPort", ")", ";", "packetInLine", ".", "setAddress", "(", "clientAddr", ")", ";", "int", "loopCount", "=", "0", ";", "while", "(", "true", ")", "{", "try", "{", "udtSend", "(", "packetInLine", ",", "clientPort", ",", "clientAddr", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Last data packet with block number ", "\"", "+", "blockNumber", "+", "\"", " sent [", "\"", "+", "slaveSocket", ".", "getLocalPort", "(", ")", "+", "\"", ", ", "\"", "+", "clientPort", "+", "\"", "].", "\\n", "\"", ")", ";", "receiveAck", "(", "expectedAck", ",", "packetInLine", ")", ";", "break", ";", "}", "catch", "(", "SocketTimeoutException", "soe", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "NOTE 304: Timeout. Resending block ", "\"", "+", "blockNumber", "+", "\"", ".", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "\\n", "loopCount = ", "\"", "+", "loopCount", ")", ";", "if", "(", "loopCount", ">", "LOOP_LIMIT", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "\\n", "Last block sent too frequently.", "\"", "+", "\"", " Client presumed terminated.", "\\n", "\"", ")", ";", "break", ";", "}", "}", "loopCount", "++", ";", "}", "}", "/**\n * Sends a single ACK with block number 0 to Client as acknowledgement of\n * WRQ request.\n *\n * @throws IOException if an I/O error occurs.\n * */", "protected", "void", "sendFirstAck", "(", ")", "throws", "IOException", "{", "if", "(", "requestOpcode", "!=", "Opcode", ".", "WRQ", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "ERROR 706", "\\n", "\"", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "sendACK", "(", "0", ",", "clientPort", ",", "clientAddr", ")", ";", "}", "/**\n * WRQ: The main write method on the Server side. Processes a single request\n * to write a file to the server. DATA packets in octet mode are received\n * and separate acknowledgements are received for each before another DATA\n * packet can be received. An acknowledgement to write was previously sent\n * to Client. Will attempt to receive DATA 1 from Client afterwards but at\n * timeout will send ACK 0 indefinitely until DATA 1 received. Returns so\n * TFTPServerThread can process next Client. At receipt of DATA, the\n * corresponding ACK will be sent and this includes DATA already\n * acknowledged (duplicates).\n *\n * Repeats receipt and return for subsequent DATA packets until the final\n * (size < DEFAULT_DATA_SIZE bytes) is received. Then, writes made\n * StringBuilder to file and returns. Returns after one ACK sent (unless if\n * it is ACK 0).\n *\n * Dallying is used where this Server Thread keeps open for 10 * TIMEOUT\n * after receiving final ACK to listen to incoming final DATA packets if\n * Client hasn't received acknowledgement. Removes this Client from\n * TFTPServer.mainStatus after timeout.\n *\n * Socket timeouts are initialized and handled here.\n *\n * @throws IOException if an I/O error occurs.\n */", "protected", "void", "receiveWrittenFile", "(", ")", "throws", "IOException", "{", "byte", "[", "]", "totalBuf", "=", "new", "byte", "[", "DEFAULT_DATA_SIZE", "+", "4", "]", ";", "if", "(", "writeRequestCompleted", ")", "{", "slaveSocket", ".", "setSoTimeout", "(", "10", "*", "Constants", ".", "TIMEOUT", ")", ";", "while", "(", "true", ")", "{", "try", "{", "DatagramPacket", "finalDuplicate", "=", "new", "DatagramPacket", "(", "totalBuf", ",", "totalBuf", ".", "length", ")", ";", "slaveSocket", ".", "receive", "(", "finalDuplicate", ")", ";", "if", "(", "verifySocAddr", "(", "finalDuplicate", ",", "clientAddr", ",", "clientPort", ")", "&&", "verifyPacketOpcode", "(", "finalDuplicate", ",", "Opcode", ".", "DATA", ")", ")", "{", "byte", "[", "]", "blockEncoded", "=", "{", "totalBuf", "[", "2", "]", ",", "totalBuf", "[", "3", "]", "}", ";", "int", "blockReceived", "=", "fromByteToInt", "(", "blockEncoded", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "NOTE 544: Received duplicate of ", "\"", "+", "\"", "final", "\"", "+", "\"", " DATA block ", "\"", "+", "blockReceived", "+", "\"", ".", "\\n", "\"", ")", ";", "sendACK", "(", "blockReceived", ",", "clientPort", ",", "clientAddr", ")", ";", "}", "}", "catch", "(", "SocketTimeoutException", "soe", ")", "{", "slaveSocket", ".", "setSoTimeout", "(", "0", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Thread terminated.", "\\n", "\"", ")", ";", "removeFromStatus", "(", "clientAddr", ",", "clientPort", ")", ";", "return", ";", "}", "}", "}", "DatagramPacket", "received", "=", "new", "DatagramPacket", "(", "totalBuf", ",", "totalBuf", ".", "length", ")", ";", "if", "(", "blockExpected", "==", "1", ")", "{", "slaveSocket", ".", "setSoTimeout", "(", "Constants", ".", "TIMEOUT", ")", ";", "while", "(", "true", ")", "{", "try", "{", "slaveSocket", ".", "receive", "(", "received", ")", ";", "if", "(", "verifySocAddr", "(", "received", ",", "clientAddr", ",", "clientPort", ")", "&&", "verifyPacketOpcode", "(", "received", ",", "Opcode", ".", "DATA", ")", ")", "{", "break", ";", "}", "}", "catch", "(", "SocketTimeoutException", "soe", ")", "{", "sendFirstAck", "(", ")", ";", "}", "}", "slaveSocket", ".", "setSoTimeout", "(", "0", ")", ";", "}", "else", "{", "while", "(", "true", ")", "{", "slaveSocket", ".", "receive", "(", "received", ")", ";", "if", "(", "verifySocAddr", "(", "received", ",", "clientAddr", ",", "clientPort", ")", "&&", "verifyPacketOpcode", "(", "received", ",", "Opcode", ".", "DATA", ")", ")", "{", "break", ";", "}", "}", "}", "byte", "[", "]", "blockEncoded", "=", "{", "totalBuf", "[", "2", "]", ",", "totalBuf", "[", "3", "]", "}", ";", "int", "blockReceived", "=", "fromByteToInt", "(", "blockEncoded", ")", ";", "if", "(", "blockReceived", "==", "blockExpected", ")", "{", "sendACK", "(", "blockReceived", ",", "clientPort", ",", "clientAddr", ")", ";", "String", "dataReceived", "=", "new", "String", "(", "received", ".", "getData", "(", ")", ",", "0", ",", "received", ".", "getLength", "(", ")", ")", ";", "fileContent", ".", "append", "(", "dataReceived", ".", "substring", "(", "4", ")", ")", ";", "blockExpected", "++", ";", "}", "else", "if", "(", "blockReceived", "<", "blockExpected", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "NOTE 648: Duplicate. Packet's block ", "\"", "+", "\"", "received ", "\"", "+", "blockReceived", "+", "\"", " < block ", "\"", "+", "\"", "expected ", "\"", "+", "blockExpected", "+", "\"", ".", "\"", ")", ";", "sendACK", "(", "blockReceived", ",", "clientPort", ",", "clientAddr", ")", ";", "}", "else", "{", "System", ".", "err", ".", "println", "(", "\"", "ERROR 301: A previous block of ", "\"", "+", "\"", "data is missing.", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "blockReceived = ", "\"", "+", "blockReceived", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "blockExpected = ", "\"", "+", "blockExpected", "+", "\"", "\\n", "\"", ")", ";", "slaveSocket", ".", "close", "(", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "if", "(", "received", ".", "getLength", "(", ")", "<", "DEFAULT_DATA_SIZE", "+", "4", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Block ", "\"", "+", "blockReceived", "+", "\"", " received ", "\"", "+", "\"", "[", "\"", "+", "received", ".", "getPort", "(", ")", "+", "\"", ", ", "\"", "+", "slaveSocket", ".", "getLocalPort", "(", ")", "+", "\"", "].", "\"", "+", "\"", " Final ACK ", "\"", "+", "blockReceived", "+", "\"", " sent [", "\"", "+", "slaveSocket", ".", "getLocalPort", "(", ")", "+", "\"", ", ", "\"", "+", "clientPort", "+", "\"", "].", "\\n", "\"", ")", ";", "FileWriter", "myWriter", "=", "new", "FileWriter", "(", "filename", ")", ";", "myWriter", ".", "write", "(", "String", ".", "valueOf", "(", "fileContent", ")", ")", ";", "myWriter", ".", "close", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "File ", "\"", "+", "filename", "+", "\"", " successfully received ", "\"", "+", "\"", "and written. Terminating thread.", "\"", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "writeRequestCompleted", "=", "true", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Block ", "\"", "+", "blockReceived", "+", "\"", " received ", "\"", "+", "\"", "[", "\"", "+", "received", ".", "getPort", "(", ")", "+", "\"", ", ", "\"", "+", "slaveSocket", ".", "getLocalPort", "(", ")", "+", "\"", "].", "\"", "+", "\"", " ACK ", "\"", "+", "blockReceived", "+", "\"", " sent [", "\"", "+", "slaveSocket", ".", "getLocalPort", "(", ")", "+", "\"", ", ", "\"", "+", "clientPort", "+", "\"", "].", "\\n", "\"", ")", ";", "}", "slaveSocket", ".", "setSoTimeout", "(", "0", ")", ";", "}", "/**\n * Returns the opcode of a TFTP operation in byte[] form, based on RFC 1350.\n *\n * @param opcode the operation in request.\n * @return opcode of operation.\n * @see Opcode\n * */", "private", "byte", "[", "]", "generateOpcode", "(", "Opcode", "opcode", ")", "{", "byte", "[", "]", "rrq", "=", "{", "0", ",", "(", "byte", ")", "Opcode", ".", "RRQ", ".", "ordinal", "(", ")", "}", ";", "byte", "[", "]", "wrq", "=", "{", "0", ",", "(", "byte", ")", "Opcode", ".", "WRQ", ".", "ordinal", "(", ")", "}", ";", "byte", "[", "]", "data", "=", "{", "0", ",", "(", "byte", ")", "Opcode", ".", "DATA", ".", "ordinal", "(", ")", "}", ";", "byte", "[", "]", "ack", "=", "{", "0", ",", "(", "byte", ")", "Opcode", ".", "ACK", ".", "ordinal", "(", ")", "}", ";", "byte", "[", "]", "error", "=", "{", "0", ",", "(", "byte", ")", "Opcode", ".", "ERROR", ".", "ordinal", "(", ")", "}", ";", "byte", "[", "]", "none", "=", "{", "Byte", ".", "MIN_VALUE", ",", "Byte", ".", "MIN_VALUE", "}", ";", "switch", "(", "opcode", ")", "{", "case", "RRQ", ":", "return", "rrq", ";", "case", "WRQ", ":", "return", "wrq", ";", "case", "DATA", ":", "return", "data", ";", "case", "ACK", ":", "return", "ack", ";", "case", "ERROR", ":", "return", "error", ";", "default", ":", "System", ".", "err", ".", "println", "(", "\"", "ERROR 760: Opcode not recognized.", "\"", ")", ";", "slaveSocket", ".", "close", "(", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "return", "none", ";", "}", "}", "/**\n * Concatenates two byte arrays in order and returns the result.\n *\n * @param array1 byte array to appear first.\n * @param array2 byte array to appear last.\n * @return concatenated result of array1 and array2 in that order.\n * */", "private", "byte", "[", "]", "combineArr", "(", "byte", "[", "]", "array1", ",", "byte", "[", "]", "array2", ")", "{", "int", "aLen", "=", "array1", ".", "length", ";", "int", "bLen", "=", "array2", ".", "length", ";", "byte", "[", "]", "result", "=", "new", "byte", "[", "aLen", "+", "bLen", "]", ";", "System", ".", "arraycopy", "(", "array1", ",", "0", ",", "result", ",", "0", ",", "aLen", ")", ";", "System", ".", "arraycopy", "(", "array2", ",", "0", ",", "result", ",", "aLen", ",", "bLen", ")", ";", "return", "result", ";", "}", "/**\n * Converts the number stored in 2-tuple byte array base-256 into the\n * base-10 integer equivalent. b must be 2-tuple as b was initially\n * constructed in fromIntToByte(int) with checking mechanisms.\n * Block Number = (b[1] + 128) + 256 * (b[0] + 128), max = 65535.\n * {-128, -128} = 0\n * {-128, 0} = 128\n * {-128, 127} = 255\n * {-127, -128} = 256\n * {127, 127} = 65535\n *\n * @param b the byte array holding the 2-tuple base-256 bytes.\n * @return b in base-10 int format.\n * */", "private", "int", "fromByteToInt", "(", "byte", "[", "]", "b", ")", "{", "int", "base", "=", "Byte", ".", "MAX_VALUE", "+", "(", "-", "1", "*", "Byte", ".", "MIN_VALUE", ")", "+", "1", ";", "return", "(", "b", "[", "1", "]", "+", "(", "-", "1", "*", "Byte", ".", "MIN_VALUE", ")", "+", "base", "*", "(", "b", "[", "0", "]", "+", "(", "-", "1", "*", "Byte", ".", "MIN_VALUE", ")", ")", ")", ";", "}", "/**\n * Converts the number stored in integer base-10 format into a 2-tuple\n * Byte array, with both bytes in base-256 from min -128 to max 127.\n * Block Number = (b[1] + 128) + 256 * (b[0] + 128), max = 65535.\n * {-128, -128} = 0\n * {-128, 0} = 128\n * {-128, 127} = 255\n * {-127, -128} = 256\n * {127, 127} = 65535\n *\n * @param i number in base-10 integer format.\n * @return i in 2-tuple Byte array in base-256 (range of Byte) format.\n * Error if i is out of range (i < 0 or i > 65535).\n * */", "private", "byte", "[", "]", "fromIntToByte", "(", "int", "i", ")", "throws", "IOException", "{", "int", "base", "=", "Byte", ".", "MAX_VALUE", "+", "(", "-", "1", "*", "Byte", ".", "MIN_VALUE", ")", "+", "1", ";", "int", "max", "=", "base", "*", "(", "base", "-", "1", ")", "+", "(", "base", "-", "1", ")", ";", "byte", "zerothDigit", "=", "(", "byte", ")", "(", "i", "/", "base", "+", "Byte", ".", "MIN_VALUE", ")", ";", "byte", "firstDigit", "=", "(", "byte", ")", "(", "(", "i", "%", "base", ")", "+", "Byte", ".", "MIN_VALUE", ")", ";", "if", "(", "i", ">=", "0", "&&", "i", "<=", "max", ")", "{", "return", "new", "byte", "[", "]", "{", "zerothDigit", ",", "firstDigit", "}", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "ERROR 461: Block number out of range ", "\"", "+", "\"", "[0, 65535]. ", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Terminating thread.", "\\n", "\"", ")", ";", "terminatePrematurely", "(", "\"", "ERROR 461 raised.", "\\n", "\"", ")", ";", "return", "null", ";", "}", "}", "/**\n * Generates a DatagramPacket DATA packet with the given input contents of\n * the packet, with length equalling the actual used space which may be\n * 516 bytes (DEFAULT_DATA_SIZE + 4) or lower to a minimum of 4 bytes.\n *\n * @param buf character buffer of the DATA contents.\n * @param readCount number of characters in character buffer.\n * @param numberOfBlock block number of this DATA packet.\n * @return DATA packet with contents and block number.\n * */", "private", "DatagramPacket", "produceDataPacket", "(", "char", "[", "]", "buf", ",", "int", "readCount", ",", "int", "numberOfBlock", ")", "throws", "IOException", "{", "byte", "[", "]", "dataBuf", "=", "new", "byte", "[", "DEFAULT_DATA_SIZE", "]", ";", "if", "(", "readCount", "<", "DEFAULT_DATA_SIZE", ")", "{", "dataBuf", "=", "new", "byte", "[", "readCount", "]", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "readCount", ";", "i", "++", ")", "{", "dataBuf", "[", "i", "]", "=", "(", "byte", ")", "buf", "[", "i", "]", ";", "}", "byte", "[", "]", "dataOpcode", "=", "generateOpcode", "(", "Opcode", ".", "DATA", ")", ";", "byte", "[", "]", "block", "=", "fromIntToByte", "(", "numberOfBlock", ")", ";", "assert", "block", "!=", "null", ";", "byte", "[", "]", "opcodeAndBlock", "=", "combineArr", "(", "dataOpcode", ",", "block", ")", ";", "dataBuf", "=", "combineArr", "(", "opcodeAndBlock", ",", "dataBuf", ")", ";", "return", "new", "DatagramPacket", "(", "dataBuf", ",", "dataBuf", ".", "length", ")", ";", "}", "/**\n * Returns the filename from a write request (WRQ) or read request (RRQ).\n * Exits system if mode is not octet (and indirectly if the packet's\n * contents do not resemble that of a WRQ or RRQ).\n *\n * @param packetContents raw content of received WRQ or RRQ.\n * @return filename kept inside the WRQ or RRQ.\n * */", "protected", "String", "getFilename", "(", "byte", "[", "]", "packetContents", ")", "{", "int", "index2ndZero", "=", "0", ";", "int", "index3rdZero", "=", "0", ";", "int", "index", "=", "0", ";", "for", "(", "byte", "b", ":", "packetContents", ")", "{", "if", "(", "index", ">", "0", ")", "{", "if", "(", "b", "==", "0", ")", "{", "if", "(", "index2ndZero", "==", "0", ")", "{", "index2ndZero", "=", "index", ";", "}", "else", "{", "index3rdZero", "=", "index", ";", "break", ";", "}", "}", "}", "index", "++", ";", "}", "String", "nameOfFile", "=", "(", "new", "String", "(", "packetContents", ")", ")", ".", "substring", "(", "2", ",", "index2ndZero", ")", ";", "String", "octet", "=", "(", "new", "String", "(", "packetContents", ")", ")", ".", "substring", "(", "(", "index2ndZero", "+", "1", ")", ",", "index3rdZero", ")", ";", "if", "(", "!", "octet", ".", "equals", "(", "\"", "octet", "\"", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "ERROR 522: mode is not octet.", "\"", ")", ";", "slaveSocket", ".", "close", "(", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "return", "nameOfFile", ";", "}", "/**\n * A blocking call to receive an acknowledgement packet (ACK). If an ACK\n * with the expected block number is not received, the packet in line is\n * resent. If non-ACK packet received, this method remains open and\n * blocking until an ACK is received.\n *\n * Timeout is not initiated or handled here.\n *\n * @param expectedAcknowNum expected block number of incoming ACK.\n * @param packetInLine packet to be sent if the expected ACK is not\n * received.\n * @return received acknowledgement packet.\n * @throws IOException if an I/O error occurs.\n * */", "private", "DatagramPacket", "receiveAck", "(", "int", "expectedAcknowNum", ",", "DatagramPacket", "packetInLine", ")", "throws", "IOException", "{", "byte", "[", "]", "bufACK", "=", "new", "byte", "[", "4", "]", ";", "DatagramPacket", "ackPacket", "=", "new", "DatagramPacket", "(", "bufACK", ",", "bufACK", ".", "length", ")", ";", "do", "{", "slaveSocket", ".", "receive", "(", "ackPacket", ")", ";", "}", "while", "(", "!", "verifySocAddr", "(", "ackPacket", ",", "clientAddr", ",", "clientPort", ")", "||", "!", "verifyPacketOpcode", "(", "ackPacket", ",", "Opcode", ".", "ACK", ")", ")", ";", "byte", "[", "]", "blockReceived", "=", "{", "bufACK", "[", "2", "]", ",", "bufACK", "[", "3", "]", "}", ";", "int", "ackReceived", "=", "fromByteToInt", "(", "blockReceived", ")", ";", "if", "(", "ackReceived", "<", "expectedAcknowNum", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "NOTE 002: ackReceived ", "\"", "+", "ackReceived", "+", "\"", " < expectedAcknowNum ", "\"", "+", "expectedAcknowNum", "+", "\"", ". DATA lost in network. ", "\"", ")", ";", "udtSend", "(", "packetInLine", ",", "clientPort", ",", "clientAddr", ")", ";", "}", "else", "if", "(", "ackReceived", "==", "expectedAcknowNum", ")", "{", "if", "(", "packetInLine", ".", "getLength", "(", ")", "<", "DEFAULT_DATA_SIZE", "+", "4", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Final data block ", "\"", "+", "ackReceived", "+", "\"", " successfully acknowledged. Terminating thread.", "\"", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Data block ", "\"", "+", "ackReceived", "+", "\"", " successfully acknowledged. Sending next block.", "\"", ")", ";", "}", "System", ".", "out", ".", "println", "(", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "ERROR 004: ackReceived ", "\"", "+", "ackReceived", "+", "\"", " > expectedAcknowNum ", "\"", "+", "expectedAcknowNum", "+", "\"", ".", "\"", ")", ";", "slaveSocket", ".", "close", "(", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "return", "ackPacket", ";", "}", "/**\n * Sends a DatagramPacket to the given port and internet address.\n *\n * @param packet packet to be sent.\n * @param port port number of destination remote host.\n * @param addr internet address of destination remote host.\n * */", "private", "void", "udtSend", "(", "DatagramPacket", "packet", ",", "int", "port", ",", "InetAddress", "addr", ")", "throws", "IOException", "{", "packet", ".", "setAddress", "(", "addr", ")", ";", "packet", ".", "setPort", "(", "port", ")", ";", "double", "random", "=", "Math", ".", "random", "(", ")", ";", "if", "(", "random", "<", "(", "1", "-", "Constants", ".", "LOST_PROBABILITY", ")", ")", "{", "try", "{", "slaveSocket", ".", "send", "(", "packet", ")", ";", "}", "catch", "(", "IllegalArgumentException", "ioe", ")", "{", "System", ".", "out", ".", "println", "(", "ioe", ".", "getMessage", "(", ")", "+", "\"", "\\n", "\"", ")", ";", "}", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Packet made lost.", "\"", ")", ";", "}", "}", "/**\n * Ensures a packet has the expected opcode. Returns true if the expected\n * opcode matches packet's opcode. False otherwise. Exits the system if a\n * packet's opcode is ERROR but the expected opcode is not ERROR, for\n * example, if a WRQ packet is responded with a FILE_NOT_FOUND error.\n *\n * @param recv packet whose opcode is to be compared.\n * @param op expected opcode.\n * @return true if packet's opcode is the expected opcode. False\n * otherwise. Exits the system if packet's opcode is ERROR when expected\n * opcode is not ERROR.\n * */", "private", "boolean", "verifyPacketOpcode", "(", "DatagramPacket", "recv", ",", "Opcode", "op", ")", "throws", "IOException", "{", "byte", "[", "]", "recvBuf", "=", "recv", ".", "getData", "(", ")", ";", "boolean", "isRRQ", "=", "(", "(", "generateOpcode", "(", "Opcode", ".", "RRQ", ")", "[", "1", "]", ")", "==", "recvBuf", "[", "1", "]", ")", ";", "boolean", "isWRQ", "=", "(", "(", "generateOpcode", "(", "Opcode", ".", "WRQ", ")", "[", "1", "]", ")", "==", "recvBuf", "[", "1", "]", ")", ";", "boolean", "isData", "=", "(", "(", "generateOpcode", "(", "Opcode", ".", "DATA", ")", "[", "1", "]", ")", "==", "recvBuf", "[", "1", "]", ")", ";", "boolean", "isError", "=", "(", "(", "generateOpcode", "(", "Opcode", ".", "ERROR", ")", "[", "1", "]", ")", "==", "recvBuf", "[", "1", "]", ")", ";", "boolean", "isAck", "=", "(", "(", "generateOpcode", "(", "Opcode", ".", "ACK", ")", "[", "1", "]", ")", "==", "recvBuf", "[", "1", "]", ")", ";", "switch", "(", "op", ")", "{", "case", "RRQ", ":", "if", "(", "isRRQ", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Request received: RRQ from ", "\"", "+", "\"", "addr ", "\"", "+", "recv", ".", "getAddress", "(", ")", "+", "\"", " port ", "\"", "+", "recv", ".", "getPort", "(", ")", "+", "\"", ".", "\"", ")", ";", "return", "true", ";", "}", "break", ";", "case", "WRQ", ":", "if", "(", "isWRQ", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Request received: WRQ from ", "\"", "+", "\"", "addr ", "\"", "+", "recv", ".", "getAddress", "(", ")", "+", "\"", " port ", "\"", "+", "recv", ".", "getPort", "(", ")", "+", "\"", ".", "\"", ")", ";", "return", "true", ";", "}", "break", ";", "case", "DATA", ":", "if", "(", "isData", ")", "{", "return", "true", ";", "}", "break", ";", "case", "ERROR", ":", "if", "(", "isError", ")", "{", "int", "errorCode", "=", "recvBuf", "[", "3", "]", ";", "String", "dataReceived", "=", "new", "String", "(", "recvBuf", ")", ";", "String", "errMsg", "=", "dataReceived", ".", "substring", "(", "4", ",", "recv", ".", "getLength", "(", ")", "-", "1", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "ERROR 454: Expected error code ", "\"", "+", "errorCode", "+", "\"", " with message: ", "\"", "+", "errMsg", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "return", "true", ";", "}", "break", ";", "case", "ACK", ":", "if", "(", "isAck", ")", "{", "return", "true", ";", "}", "break", ";", "default", ":", "System", ".", "out", ".", "println", "(", "\"", "ERROR 631: Unknown opcode of data ", "\"", "+", "\"", "received: ", "\"", "+", "recvBuf", "[", "1", "]", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Terminating server...", "\"", ")", ";", "slaveSocket", ".", "close", "(", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "if", "(", "isError", ")", "{", "int", "errorCode", "=", "recvBuf", "[", "3", "]", ";", "String", "dataReceived", "=", "new", "String", "(", "recvBuf", ")", ";", "try", "{", "String", "errMsg", "=", "dataReceived", ".", "substring", "(", "4", ",", "recv", ".", "getLength", "(", ")", "-", "1", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "ERROR 978: Unexpected error code 0", "\"", "+", "errorCode", "+", "\"", " with message: ", "\"", "+", "errMsg", "+", "\"", ".", "\\n", "\"", ")", ";", "}", "catch", "(", "IndexOutOfBoundsException", "ioe", ")", "{", "System", ".", "out", ".", "println", "(", "ioe", ".", "getMessage", "(", ")", "+", "\"", "\\n", "\"", ")", ";", "}", "if", "(", "errorCode", "!=", "Error", ".", "UNKNOWN_TID", ".", "ordinal", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Terminating thread.", "\\n", "\"", ")", ";", "terminatePrematurely", "(", "\"", "ERROR 977 raised.", "\\n", "\"", ")", ";", "}", "}", "return", "false", ";", "}", "/**\n * Sends an acknowledgement packet (ACK) with the specified block number to\n * the server.\n *\n * @param block block number of DATA packet to be acknowledged.\n * @param port port number of client.\n * @param addr internet address of client.\n * @throws IOException if an I/O error occurs.\n * */", "private", "void", "sendACK", "(", "int", "block", ",", "int", "port", ",", "InetAddress", "addr", ")", "throws", "IOException", "{", "byte", "[", "]", "blockInBytes", "=", "fromIntToByte", "(", "block", ")", ";", "assert", "blockInBytes", "!=", "null", ";", "byte", "[", "]", "packetContents", "=", "combineArr", "(", "generateOpcode", "(", "Opcode", ".", "ACK", ")", ",", "blockInBytes", ")", ";", "DatagramPacket", "ackToSend", "=", "new", "DatagramPacket", "(", "packetContents", ",", "packetContents", ".", "length", ")", ";", "udtSend", "(", "ackToSend", ",", "port", ",", "addr", ")", ";", "}", "/**\n * Sends an ERROR packet with a FILE_NOT_FOUND error message to the\n * remote Client. Called when a read request (RRQ) is received and the\n * file requested is not found. No acknowledgements expected but this\n * method is repeatedly called by the caller as long as the read\n * request is received again.\n *\n * @param received received read request packet.\n * @throws IOException if an I/O error occurs.\n * */", "protected", "void", "sendFileNotFoundError", "(", "DatagramPacket", "received", ")", "throws", "IOException", "{", "sendErrorPacket", "(", "Error", ".", "FILE_NOT_FOUND", ",", "received", ")", ";", "}", "/**\n * Sends an ERROR packet to the sender upon receipt of unexpected packet\n * or a request which cannot be fulfilled including because of a\n * file-not-found error. Terminates (exits) client where necessary. Error\n * codes are based on RFC 1350.\n *\n * @param op error code of this error.\n * @param received packet received which raised this error.\n * @throws IOException if an I/O error occurs.\n * @see Error\n * */", "protected", "void", "sendErrorPacket", "(", "Error", "op", ",", "DatagramPacket", "received", ")", "throws", "IOException", "{", "byte", "[", "]", "opcode", "=", "generateOpcode", "(", "Opcode", ".", "ERROR", ")", ";", "byte", "[", "]", "errCode", "=", "{", "Byte", ".", "MIN_VALUE", ",", "Byte", ".", "MIN_VALUE", "}", ";", "byte", "[", "]", "errMsg", ";", "byte", "[", "]", "zero", "=", "{", "0", "}", ";", "String", "message", ";", "boolean", "terminate", "=", "false", ";", "switch", "(", "op", ")", "{", "case", "NOT_DEFINED", ":", "errCode", "=", "new", "byte", "[", "]", "{", "0", ",", "(", "byte", ")", "Error", ".", "NOT_DEFINED", ".", "ordinal", "(", ")", "}", ";", "message", "=", "\"", "Not defined.", "\"", ";", "terminate", "=", "true", ";", "break", ";", "case", "FILE_NOT_FOUND", ":", "errCode", "=", "new", "byte", "[", "]", "{", "0", ",", "(", "byte", ")", "Error", ".", "FILE_NOT_FOUND", ".", "ordinal", "(", ")", "}", ";", "String", "nameOfFile", "=", "getFilename", "(", "received", ".", "getData", "(", ")", ")", ";", "message", "=", "\"", "File ", "\"", "+", "nameOfFile", "+", "\"", " not found.", "\"", ";", "terminate", "=", "true", ";", "break", ";", "case", "ACCESS_VIOLATION", ":", "errCode", "=", "new", "byte", "[", "]", "{", "0", ",", "(", "byte", ")", "Error", ".", "ACCESS_VIOLATION", ".", "ordinal", "(", ")", "}", ";", "message", "=", "\"", "Access Violation.", "\"", ";", "terminate", "=", "true", ";", "break", ";", "case", "DISK_FULL", ":", "errCode", "=", "new", "byte", "[", "]", "{", "0", ",", "(", "byte", ")", "Error", ".", "DISK_FULL", ".", "ordinal", "(", ")", "}", ";", "message", "=", "\"", "Disk full or allocation exceeded.", "\"", ";", "terminate", "=", "true", ";", "break", ";", "case", "ILLEGAL_OPERATION", ":", "errCode", "=", "new", "byte", "[", "]", "{", "0", ",", "(", "byte", ")", "Error", ".", "ILLEGAL_OPERATION", ".", "ordinal", "(", ")", "}", ";", "message", "=", "\"", "Illegal TFTP operation. Expecting a Write Request ", "\"", "+", "\"", "or Read Request.", "\"", ";", "terminate", "=", "true", ";", "break", ";", "case", "UNKNOWN_TID", ":", "errCode", "=", "new", "byte", "[", "]", "{", "0", ",", "(", "byte", ")", "Error", ".", "UNKNOWN_TID", ".", "ordinal", "(", ")", "}", ";", "message", "=", "\"", "Unknown Transfer ID ", "\"", "+", "received", ".", "getPort", "(", ")", "+", "\"", ". This connection is already used.", "\"", ";", "break", ";", "case", "FILE_ALREADY_EXISTS", ":", "errCode", "=", "new", "byte", "[", "]", "{", "0", ",", "(", "byte", ")", "Error", ".", "FILE_ALREADY_EXISTS", ".", "ordinal", "(", ")", "}", ";", "message", "=", "\"", "File already exists.", "\"", ";", "terminate", "=", "true", ";", "break", ";", "case", "NO_SUCH_USER", ":", "errCode", "=", "new", "byte", "[", "]", "{", "0", ",", "(", "byte", ")", "Error", ".", "NO_SUCH_USER", ".", "ordinal", "(", ")", "}", ";", "message", "=", "\"", "Mo such user.", "\"", ";", "terminate", "=", "true", ";", "break", ";", "default", ":", "message", "=", "\"", "Not defined.", "\"", ";", "System", ".", "out", ".", "println", "(", "\"", "ERROR 993: Unknown Error Opcode.", "\"", ")", ";", "terminate", "=", "true", ";", "}", "errMsg", "=", "(", "message", ")", ".", "getBytes", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "ERROR 0", "\"", "+", "errCode", "[", "1", "]", "+", "\"", ": ", "\"", "+", "message", "+", "\"", "\\n", "\"", ")", ";", "byte", "[", "]", "first", "=", "combineArr", "(", "opcode", ",", "errCode", ")", ";", "byte", "[", "]", "second", "=", "combineArr", "(", "first", ",", "errMsg", ")", ";", "byte", "[", "]", "third", "=", "combineArr", "(", "second", ",", "zero", ")", ";", "DatagramPacket", "packet", "=", "new", "DatagramPacket", "(", "third", ",", "third", ".", "length", ")", ";", "udtSend", "(", "packet", ",", "received", ".", "getPort", "(", ")", ",", "received", ".", "getAddress", "(", ")", ")", ";", "if", "(", "terminate", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Terminating thread.", "\\n", "\"", ")", ";", "removeFromStatus", "(", "clientAddr", ",", "clientPort", ")", ";", "}", "}", "/**\n * Verifies the source port number of a received packet is equal to the\n * expected port number.\n *\n * @param received received packet.\n * @param port expected port number.\n * @return true if received's port is equal to expected port. False\n * otherwise.\n * */", "private", "boolean", "verifyPort", "(", "DatagramPacket", "received", ",", "int", "port", ")", "{", "if", "(", "received", ".", "getPort", "(", ")", "!=", "port", ")", "{", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}", "/** Returns true if source address and port of received packet is equal\n * to the address and port input. False otherwise.\n *\n * @param received received packet to be verified.\n * @param addr Internet address of source Client.\n * @param port port number of source Client.\n * @return true if port and address input matches that of the packet's.\n * False otherwise.\n * */", "private", "boolean", "verifySocAddr", "(", "DatagramPacket", "received", ",", "InetAddress", "addr", ",", "int", "port", ")", "{", "if", "(", "!", "verifyPort", "(", "received", ",", "port", ")", ")", "{", "return", "false", ";", "}", "return", "received", ".", "getAddress", "(", ")", ".", "equals", "(", "addr", ")", ";", "}", "/**\n * Removes client from the mainStatus in TFTPServer after all processes\n * with client is done and connection closes with that client.\n *\n * @param addr internet address of client to be removed.\n * @param port port of client to be removed\n * */", "private", "void", "removeFromStatus", "(", "InetAddress", "addr", ",", "int", "port", ")", "{", "InetSocketAddress", "toRemove", "=", "null", ";", "for", "(", "Map", ".", "Entry", "<", "InetSocketAddress", ",", "Client", ">", "i", ":", "TFTPServer", ".", "mainStatusPending", ".", "entrySet", "(", ")", ")", "{", "InetSocketAddress", "current", "=", "i", ".", "getKey", "(", ")", ";", "if", "(", "current", ".", "equals", "(", "new", "InetSocketAddress", "(", "addr", ",", "port", ")", ")", ")", "{", "toRemove", "=", "current", ";", "}", "}", "if", "(", "toRemove", "!=", "null", ")", "{", "TFTPServer", ".", "mainStatusPending", ".", "remove", "(", "toRemove", ")", ";", "}", "}", "/**\n * Terminates this Client (remove from TFTPServer.mainStatus). Called if\n * a terminating error is raised. Does not close slaveSocket.\n *\n * @param errMsg error message raised.\n *\n * @throws IOException if an I/O error occurs.\n * */", "private", "void", "terminatePrematurely", "(", "String", "errMsg", ")", "throws", "IOException", "{", "removeFromStatus", "(", "clientAddr", ",", "clientPort", ")", ";", "throw", "new", "IOException", "(", "errMsg", ")", ";", "}", "/**\n * Generates either a write request (WRQ) packet or read request (RRQ)\n * packet filled with a nameOfFile. Packet is without a predefined address\n * or port number.\n *\n * @param opcode opcode of operation, whether WRQ or RRQ.\n * @param nameOfFile name of file to be read or written.\n * @param addr Internet address of source Client of this request.\n * @param port port number of source Client of this request.\n * @return WRQ or RRQ for file in question without address or port number.\n * */", "protected", "DatagramPacket", "generateRequestPacket", "(", "Opcode", "opcode", ",", "String", "nameOfFile", ",", "InetAddress", "addr", ",", "int", "port", ")", "{", "byte", "[", "]", "opcodeInByte", "=", "{", "Byte", ".", "MIN_VALUE", ",", "Byte", ".", "MIN_VALUE", "}", ";", "if", "(", "opcode", "==", "Opcode", ".", "RRQ", ")", "{", "opcodeInByte", "=", "generateOpcode", "(", "Opcode", ".", "RRQ", ")", ";", "}", "else", "if", "(", "opcode", "==", "Opcode", ".", "WRQ", ")", "{", "opcodeInByte", "=", "generateOpcode", "(", "Opcode", ".", "WRQ", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "ERROR 005: Opcode is not RRQ or WRQ.", "\"", ")", ";", "slaveSocket", ".", "close", "(", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "String", "mode", "=", "\"", "octet", "\"", ";", "byte", "[", "]", "firstContentInBytes", "=", "combineArr", "(", "opcodeInByte", ",", "nameOfFile", ".", "getBytes", "(", ")", ")", ";", "byte", "[", "]", "zero", "=", "{", "0", "}", ";", "byte", "[", "]", "secondContentInBytes", "=", "combineArr", "(", "firstContentInBytes", ",", "zero", ")", ";", "byte", "[", "]", "thirdContentInBytes", "=", "combineArr", "(", "secondContentInBytes", ",", "mode", ".", "getBytes", "(", ")", ")", ";", "byte", "[", "]", "finalContentInBytes", "=", "combineArr", "(", "thirdContentInBytes", ",", "zero", ")", ";", "return", "new", "DatagramPacket", "(", "finalContentInBytes", ",", "finalContentInBytes", ".", "length", ",", "addr", ",", "port", ")", ";", "}", "/**\n * RRQ: Returns current block number being sent in an RRQ.\n * @return current block number being sent.\n * */", "public", "int", "getBlockNumber", "(", ")", "{", "return", "blockNumber", ";", "}", "/**\n * Returns the initial request of the Client, whether a WRQ or RRQ.\n * @return main request of this Client.\n * */", "public", "Opcode", "getRequestOpcode", "(", ")", "{", "return", "requestOpcode", ";", "}", "/**\n * Returns filename of file in request.\n * @return name of file in request.\n * */", "public", "String", "getFilename", "(", ")", "{", "return", "filename", ";", "}", "/**\n * Returns port number of this Client.\n * @return port of Client.\n * */", "public", "int", "getClientPort", "(", ")", "{", "return", "clientPort", ";", "}", "/**\n * Returns internet address of this Client.\n * @return internet address of Client.\n * */", "public", "InetAddress", "getClientAddr", "(", ")", "{", "return", "clientAddr", ";", "}", "/**\n * WRQ: Returns expected DATA block number to be received in a WRQ.\n * @return expected DATA block to be received.\n * */", "public", "int", "getBlockExpected", "(", ")", "{", "return", "blockExpected", ";", "}", "}" ]
This class keeps and processes the states of each Client in process.
[ "This", "class", "keeps", "and", "processes", "the", "states", "of", "each", "Client", "in", "process", "." ]
[ "// = 512", "// makes a BufferedReader to read content of file", "// if a packet was sent but timeout before the ACK is received,", "// resend the packet once more. move on to next client at timeout or", "// receipt of the ACK", "// sends DATA repeatedly until an ACK is received", "// sends a packet filled with 516-byte-or-less file data", "// necessary to 'stimulate' the process, otherwise", "// readBuf somehow won't send DO NOT DELETE", "// DO NOT DEL", "// receive ACK for sent data", "// correct ACK received: move on to next Client", "// repeat cycle until receive ACK", "// if final data block is consistently not acknowledged,", "// presumed Client is terminated & all data received.", "// Thread will be terminated.", "// else if non-final data block is consistently not", "// acknowledged, move on to next Client", "// final block", "// > 20", "// readCount == 512", "// > 10", "// if the characters read is less than 512 bytes, then either the", "// file size is a multiple of 512 bytes meaning we have to send a", "// 0-byte DATA packet or that it's the end of the file and", "// read process is completed", "// at end of while loop, one block has been acknowledged and move", "// on to next client", "// if file size multiple of 512 bytes, a last packet of 0-byte data", "// size will be sent i.e. move on to next client and send the", "// last packet later. Else, file successfully sent.", "// file transmission successful. terminate thread", "// how many times server sent final data packet", "// resend until ACK received", "// receive ACK for sent data", "// if final data block is consistently not acknowledged,", "// presumed Client is terminated & all data received", "// keep receiving the duplicate of the final DATA packet if the", "// Client hasn't received the final ACK until timeout when Client", "// presumed to have received the final ACK and terminated", "// if ACK 0 was received, expect to receive a DATA 1 packet. If no", "// DATA packet received from the correct source, keep receiving.", "// DATA 1 has been received before", "// if ACK 0 successfully received and subsequent DATA packets is", "// being sent, wait indefinitely until next DATA is received", "// if received packet not of correct source or not DATA,", "// keep receiving", "// send ACK after verifying block number; if less than", "// expected, resend ACK; if more than expected, declare", "// missing block and exit", "// building file content", "// blockReceived > blockExpected", "// if last block, end transmission", "// write file that was read", "//=========================helper methods===================================", "// {0, 1}", "// {0, 2}", "// {0, 3}", "// {0, 4}", "// {0, 5}", "// {-128, -128}", "// 256", "// ans = b[1] + 128 + 256 * (b[0] + 128)", "// 256", "// 65535", "// i / 256 - 128", "// i % 256 - 128", "// if only reading less than 512 chars, the read contents will be", "// the last content of the file. dataBuf readjusted to reflect final", "// content length", "// copying readBuf into dataBuf", "// generating opcode for DATA", "// generating block number in byte[] form", "// dataBuf = opcode + block number + data(original dataBuf)", "// produce the DatagramPacket", "// getting the locations of the three zero bytes", "// filename is located in index 2 : 2nd zero", "// mode is located in index (2nd zero + 1) : 3rd zero", "// per RFC: | 01/02 | Filename | 0 | Mode | 0 |", "// ensuring mode is octet", "// fixing port number of client", "// int clientPort = packetInLine.getPort();", "// InetAddress clientAddr = packetInLine.getAddress();", "// create buffer to receive ACK packet", "// receive and verify opcode is ACK and from clientPort", "// verifying expected ACK block number", "// Unnecessary random variable to invoke lost packet simulations", "// System.out.println(Constants.LOST_PROBABILITY);", "// {0, 0}", "// {0, 1}", "// {0, 2}", "// {0, 3}", "// {0, 4}", "// {0, 5}", "// terminate = false", "// {0, 6}", "// {0, 7}", "//System.out.println(\"received's port \" + received.getPort() + \"", "// != \"", "// + \" clientPort \" + port + \". slavePort = \"", "// + slaveSocket.getLocalPort() );", "// sendConnectionUsedError(received);", "// getting opcode", "// getting opcode", "// getting mode, here remaining as octet", "// producing RRQ", "// getters and setters------------------------------------------------------", "// END OF FILE" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b3545d8e8c83873ee4dba7a0a0d0d62c95223a0
MagedMilad/MovieRanker
app/src/main/java/com/example/magedmilad/movieranker/CustomGrid.java
[ "MIT" ]
Java
CustomGrid
/** * Created by magedmilad on 12/2/15. */
Created by magedmilad on 12/2/15.
[ "Created", "by", "magedmilad", "on", "12", "/", "2", "/", "15", "." ]
public class CustomGrid extends BaseAdapter{ LayoutInflater inflater; ArrayList<Movie> items; Context context; public CustomGrid(Context context , ArrayList<Movie> items){ this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.items = items; this.context=context; } @Override public int getCount() { return items.size(); } public void setInflater(LayoutInflater inflater) { this.inflater = inflater; } public void setItems(ArrayList<Movie> items) { this.items = items; } @Override public Object getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { String url = items.get(position).getPoster_path(); View view = convertView; if(view == null){ view = inflater.inflate(R.layout.grid_item, null); } ImageView item = (ImageView) view.findViewById(R.id.grid_item_image); Picasso.with(context).load("http://image.tmdb.org/t/p/w185/"+url).into(item); return view; } }
[ "public", "class", "CustomGrid", "extends", "BaseAdapter", "{", "LayoutInflater", "inflater", ";", "ArrayList", "<", "Movie", ">", "items", ";", "Context", "context", ";", "public", "CustomGrid", "(", "Context", "context", ",", "ArrayList", "<", "Movie", ">", "items", ")", "{", "this", ".", "inflater", "=", "(", "LayoutInflater", ")", "context", ".", "getSystemService", "(", "Context", ".", "LAYOUT_INFLATER_SERVICE", ")", ";", "this", ".", "items", "=", "items", ";", "this", ".", "context", "=", "context", ";", "}", "@", "Override", "public", "int", "getCount", "(", ")", "{", "return", "items", ".", "size", "(", ")", ";", "}", "public", "void", "setInflater", "(", "LayoutInflater", "inflater", ")", "{", "this", ".", "inflater", "=", "inflater", ";", "}", "public", "void", "setItems", "(", "ArrayList", "<", "Movie", ">", "items", ")", "{", "this", ".", "items", "=", "items", ";", "}", "@", "Override", "public", "Object", "getItem", "(", "int", "position", ")", "{", "return", "items", ".", "get", "(", "position", ")", ";", "}", "@", "Override", "public", "long", "getItemId", "(", "int", "position", ")", "{", "return", "position", ";", "}", "@", "Override", "public", "View", "getView", "(", "int", "position", ",", "View", "convertView", ",", "ViewGroup", "parent", ")", "{", "String", "url", "=", "items", ".", "get", "(", "position", ")", ".", "getPoster_path", "(", ")", ";", "View", "view", "=", "convertView", ";", "if", "(", "view", "==", "null", ")", "{", "view", "=", "inflater", ".", "inflate", "(", "R", ".", "layout", ".", "grid_item", ",", "null", ")", ";", "}", "ImageView", "item", "=", "(", "ImageView", ")", "view", ".", "findViewById", "(", "R", ".", "id", ".", "grid_item_image", ")", ";", "Picasso", ".", "with", "(", "context", ")", ".", "load", "(", "\"", "http://image.tmdb.org/t/p/w185/", "\"", "+", "url", ")", ".", "into", "(", "item", ")", ";", "return", "view", ";", "}", "}" ]
Created by magedmilad on 12/2/15.
[ "Created", "by", "magedmilad", "on", "12", "/", "2", "/", "15", "." ]
[]
[ { "param": "BaseAdapter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseAdapter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b3b1f6038ed0bbcdce48abbde7600ed886b8c4a
emcleod/OG-Platform
projects/OG-Master/src/main/java/com/opengamma/master/user/RoleSearchRequest.java
[ "Apache-2.0" ]
Java
RoleSearchRequest
/** * Request for searching for roles. * <p> * Documents will be returned that match the search criteria. * This class provides the ability to page the results and to search * as at a specific version and correction instant. * See {@link UserEventHistoryRequest} for more details on how history works. */
Request for searching for roles. Documents will be returned that match the search criteria. This class provides the ability to page the results and to search as at a specific version and correction instant. See UserEventHistoryRequest for more details on how history works.
[ "Request", "for", "searching", "for", "roles", ".", "Documents", "will", "be", "returned", "that", "match", "the", "search", "criteria", ".", "This", "class", "provides", "the", "ability", "to", "page", "the", "results", "and", "to", "search", "as", "at", "a", "specific", "version", "and", "correction", "instant", ".", "See", "UserEventHistoryRequest", "for", "more", "details", "on", "how", "history", "works", "." ]
@BeanDefinition public class RoleSearchRequest implements Bean { /** * The request for paging. * By default all matching items will be returned. */ @PropertyDefinition private PagingRequest _pagingRequest = PagingRequest.ALL; /** * The set of role object identifiers, null to not limit by user object identifiers. * Note that an empty list will return no users. */ @PropertyDefinition(set = "manual") private List<ObjectId> _objectIds; /** * The role name to search for, wildcards allowed, null to not match on name. */ @PropertyDefinition private String _roleName; /** * The associated role name to search for, no wildcards. * If used, only those roles which explicitly reference the role are returned. * Any roles implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getRoles()}. */ @PropertyDefinition private String _associatedRole; /** * The associated user name to search for, no wildcards. * If used, only those roles which explicitly reference the user are returned. * Any users implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getUsers()}. */ @PropertyDefinition private String _associatedUser; /** * The associated permission to search for, no wildcards. * If used, only those roles which explicitly reference the permission are returned. * Any permissions implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getPermissions()}. */ @PropertyDefinition private String _associatedPermission; /** * The sort order to use. */ @PropertyDefinition(validate = "notNull") private RoleSearchSortOrder _sortOrder = RoleSearchSortOrder.NAME_ASC; /** * Creates an instance. */ public RoleSearchRequest() { } //------------------------------------------------------------------------- /** * Adds a single user object identifier to the set. * * @param userId the user object identifier to add, not null */ public void addObjectId(ObjectIdentifiable userId) { ArgumentChecker.notNull(userId, "userId"); if (_objectIds == null) { _objectIds = new ArrayList<ObjectId>(); } _objectIds.add(userId.getObjectId()); } /** * Sets the set of user object identifiers, null to not limit by user object identifiers. * Note that an empty collection will return no securities. * * @param userIds the new user identifiers, null clears the user id search */ public void setObjectIds(Iterable<? extends ObjectIdentifiable> userIds) { if (userIds == null) { _objectIds = null; } else { _objectIds = new ArrayList<ObjectId>(); for (ObjectIdentifiable userId : userIds) { _objectIds.add(userId.getObjectId()); } } } //------------------------------------------------------------------------- /** * Checks if this search matches the specified role. * * @param role the role to match, null returns false * @return true if matches */ public boolean matches(ManageableRole role) { if (role == null) { return false; } if (getObjectIds() != null && getObjectIds().contains(role.getObjectId()) == false) { return false; } if (getRoleName() != null && RegexUtils.wildcardMatch(getRoleName(), role.getRoleName()) == false) { return false; } if (role.getAssociatedRoles().contains(getAssociatedPermission()) == false) { return false; } if (role.getAssociatedUsers().contains(getAssociatedPermission()) == false) { return false; } if (role.getAssociatedPermissions().contains(getAssociatedPermission()) == false) { return false; } return true; } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code RoleSearchRequest}. * @return the meta-bean, not null */ public static RoleSearchRequest.Meta meta() { return RoleSearchRequest.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(RoleSearchRequest.Meta.INSTANCE); } @Override public RoleSearchRequest.Meta metaBean() { return RoleSearchRequest.Meta.INSTANCE; } @Override public <R> Property<R> property(String propertyName) { return metaBean().<R>metaProperty(propertyName).createProperty(this); } @Override public Set<String> propertyNames() { return metaBean().metaPropertyMap().keySet(); } //----------------------------------------------------------------------- /** * Gets the request for paging. * By default all matching items will be returned. * @return the value of the property */ public PagingRequest getPagingRequest() { return _pagingRequest; } /** * Sets the request for paging. * By default all matching items will be returned. * @param pagingRequest the new value of the property */ public void setPagingRequest(PagingRequest pagingRequest) { this._pagingRequest = pagingRequest; } /** * Gets the the {@code pagingRequest} property. * By default all matching items will be returned. * @return the property, not null */ public final Property<PagingRequest> pagingRequest() { return metaBean().pagingRequest().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the set of role object identifiers, null to not limit by user object identifiers. * Note that an empty list will return no users. * @return the value of the property */ public List<ObjectId> getObjectIds() { return _objectIds; } /** * Gets the the {@code objectIds} property. * Note that an empty list will return no users. * @return the property, not null */ public final Property<List<ObjectId>> objectIds() { return metaBean().objectIds().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the role name to search for, wildcards allowed, null to not match on name. * @return the value of the property */ public String getRoleName() { return _roleName; } /** * Sets the role name to search for, wildcards allowed, null to not match on name. * @param roleName the new value of the property */ public void setRoleName(String roleName) { this._roleName = roleName; } /** * Gets the the {@code roleName} property. * @return the property, not null */ public final Property<String> roleName() { return metaBean().roleName().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the associated role name to search for, no wildcards. * If used, only those roles which explicitly reference the role are returned. * Any roles implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getRoles()}. * @return the value of the property */ public String getAssociatedRole() { return _associatedRole; } /** * Sets the associated role name to search for, no wildcards. * If used, only those roles which explicitly reference the role are returned. * Any roles implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getRoles()}. * @param associatedRole the new value of the property */ public void setAssociatedRole(String associatedRole) { this._associatedRole = associatedRole; } /** * Gets the the {@code associatedRole} property. * If used, only those roles which explicitly reference the role are returned. * Any roles implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getRoles()}. * @return the property, not null */ public final Property<String> associatedRole() { return metaBean().associatedRole().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the associated user name to search for, no wildcards. * If used, only those roles which explicitly reference the user are returned. * Any users implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getUsers()}. * @return the value of the property */ public String getAssociatedUser() { return _associatedUser; } /** * Sets the associated user name to search for, no wildcards. * If used, only those roles which explicitly reference the user are returned. * Any users implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getUsers()}. * @param associatedUser the new value of the property */ public void setAssociatedUser(String associatedUser) { this._associatedUser = associatedUser; } /** * Gets the the {@code associatedUser} property. * If used, only those roles which explicitly reference the user are returned. * Any users implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getUsers()}. * @return the property, not null */ public final Property<String> associatedUser() { return metaBean().associatedUser().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the associated permission to search for, no wildcards. * If used, only those roles which explicitly reference the permission are returned. * Any permissions implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getPermissions()}. * @return the value of the property */ public String getAssociatedPermission() { return _associatedPermission; } /** * Sets the associated permission to search for, no wildcards. * If used, only those roles which explicitly reference the permission are returned. * Any permissions implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getPermissions()}. * @param associatedPermission the new value of the property */ public void setAssociatedPermission(String associatedPermission) { this._associatedPermission = associatedPermission; } /** * Gets the the {@code associatedPermission} property. * If used, only those roles which explicitly reference the permission are returned. * Any permissions implied by membership of other roles are not matched. * In other words, this searches {@link ManageableRole#getPermissions()}. * @return the property, not null */ public final Property<String> associatedPermission() { return metaBean().associatedPermission().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the sort order to use. * @return the value of the property, not null */ public RoleSearchSortOrder getSortOrder() { return _sortOrder; } /** * Sets the sort order to use. * @param sortOrder the new value of the property, not null */ public void setSortOrder(RoleSearchSortOrder sortOrder) { JodaBeanUtils.notNull(sortOrder, "sortOrder"); this._sortOrder = sortOrder; } /** * Gets the the {@code sortOrder} property. * @return the property, not null */ public final Property<RoleSearchSortOrder> sortOrder() { return metaBean().sortOrder().createProperty(this); } //----------------------------------------------------------------------- @Override public RoleSearchRequest clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { RoleSearchRequest other = (RoleSearchRequest) obj; return JodaBeanUtils.equal(getPagingRequest(), other.getPagingRequest()) && JodaBeanUtils.equal(getObjectIds(), other.getObjectIds()) && JodaBeanUtils.equal(getRoleName(), other.getRoleName()) && JodaBeanUtils.equal(getAssociatedRole(), other.getAssociatedRole()) && JodaBeanUtils.equal(getAssociatedUser(), other.getAssociatedUser()) && JodaBeanUtils.equal(getAssociatedPermission(), other.getAssociatedPermission()) && JodaBeanUtils.equal(getSortOrder(), other.getSortOrder()); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash += hash * 31 + JodaBeanUtils.hashCode(getPagingRequest()); hash += hash * 31 + JodaBeanUtils.hashCode(getObjectIds()); hash += hash * 31 + JodaBeanUtils.hashCode(getRoleName()); hash += hash * 31 + JodaBeanUtils.hashCode(getAssociatedRole()); hash += hash * 31 + JodaBeanUtils.hashCode(getAssociatedUser()); hash += hash * 31 + JodaBeanUtils.hashCode(getAssociatedPermission()); hash += hash * 31 + JodaBeanUtils.hashCode(getSortOrder()); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(256); buf.append("RoleSearchRequest{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } protected void toString(StringBuilder buf) { buf.append("pagingRequest").append('=').append(JodaBeanUtils.toString(getPagingRequest())).append(',').append(' '); buf.append("objectIds").append('=').append(JodaBeanUtils.toString(getObjectIds())).append(',').append(' '); buf.append("roleName").append('=').append(JodaBeanUtils.toString(getRoleName())).append(',').append(' '); buf.append("associatedRole").append('=').append(JodaBeanUtils.toString(getAssociatedRole())).append(',').append(' '); buf.append("associatedUser").append('=').append(JodaBeanUtils.toString(getAssociatedUser())).append(',').append(' '); buf.append("associatedPermission").append('=').append(JodaBeanUtils.toString(getAssociatedPermission())).append(',').append(' '); buf.append("sortOrder").append('=').append(JodaBeanUtils.toString(getSortOrder())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code RoleSearchRequest}. */ public static class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code pagingRequest} property. */ private final MetaProperty<PagingRequest> _pagingRequest = DirectMetaProperty.ofReadWrite( this, "pagingRequest", RoleSearchRequest.class, PagingRequest.class); /** * The meta-property for the {@code objectIds} property. */ @SuppressWarnings({"unchecked", "rawtypes" }) private final MetaProperty<List<ObjectId>> _objectIds = DirectMetaProperty.ofReadWrite( this, "objectIds", RoleSearchRequest.class, (Class) List.class); /** * The meta-property for the {@code roleName} property. */ private final MetaProperty<String> _roleName = DirectMetaProperty.ofReadWrite( this, "roleName", RoleSearchRequest.class, String.class); /** * The meta-property for the {@code associatedRole} property. */ private final MetaProperty<String> _associatedRole = DirectMetaProperty.ofReadWrite( this, "associatedRole", RoleSearchRequest.class, String.class); /** * The meta-property for the {@code associatedUser} property. */ private final MetaProperty<String> _associatedUser = DirectMetaProperty.ofReadWrite( this, "associatedUser", RoleSearchRequest.class, String.class); /** * The meta-property for the {@code associatedPermission} property. */ private final MetaProperty<String> _associatedPermission = DirectMetaProperty.ofReadWrite( this, "associatedPermission", RoleSearchRequest.class, String.class); /** * The meta-property for the {@code sortOrder} property. */ private final MetaProperty<RoleSearchSortOrder> _sortOrder = DirectMetaProperty.ofReadWrite( this, "sortOrder", RoleSearchRequest.class, RoleSearchSortOrder.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "pagingRequest", "objectIds", "roleName", "associatedRole", "associatedUser", "associatedPermission", "sortOrder"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest return _pagingRequest; case -1489617159: // objectIds return _objectIds; case -266779615: // roleName return _roleName; case 217765532: // associatedRole return _associatedRole; case 217858545: // associatedUser return _associatedUser; case -1203804299: // associatedPermission return _associatedPermission; case -26774448: // sortOrder return _sortOrder; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends RoleSearchRequest> builder() { return new DirectBeanBuilder<RoleSearchRequest>(new RoleSearchRequest()); } @Override public Class<? extends RoleSearchRequest> beanType() { return RoleSearchRequest.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code pagingRequest} property. * @return the meta-property, not null */ public final MetaProperty<PagingRequest> pagingRequest() { return _pagingRequest; } /** * The meta-property for the {@code objectIds} property. * @return the meta-property, not null */ public final MetaProperty<List<ObjectId>> objectIds() { return _objectIds; } /** * The meta-property for the {@code roleName} property. * @return the meta-property, not null */ public final MetaProperty<String> roleName() { return _roleName; } /** * The meta-property for the {@code associatedRole} property. * @return the meta-property, not null */ public final MetaProperty<String> associatedRole() { return _associatedRole; } /** * The meta-property for the {@code associatedUser} property. * @return the meta-property, not null */ public final MetaProperty<String> associatedUser() { return _associatedUser; } /** * The meta-property for the {@code associatedPermission} property. * @return the meta-property, not null */ public final MetaProperty<String> associatedPermission() { return _associatedPermission; } /** * The meta-property for the {@code sortOrder} property. * @return the meta-property, not null */ public final MetaProperty<RoleSearchSortOrder> sortOrder() { return _sortOrder; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest return ((RoleSearchRequest) bean).getPagingRequest(); case -1489617159: // objectIds return ((RoleSearchRequest) bean).getObjectIds(); case -266779615: // roleName return ((RoleSearchRequest) bean).getRoleName(); case 217765532: // associatedRole return ((RoleSearchRequest) bean).getAssociatedRole(); case 217858545: // associatedUser return ((RoleSearchRequest) bean).getAssociatedUser(); case -1203804299: // associatedPermission return ((RoleSearchRequest) bean).getAssociatedPermission(); case -26774448: // sortOrder return ((RoleSearchRequest) bean).getSortOrder(); } return super.propertyGet(bean, propertyName, quiet); } @SuppressWarnings("unchecked") @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest ((RoleSearchRequest) bean).setPagingRequest((PagingRequest) newValue); return; case -1489617159: // objectIds ((RoleSearchRequest) bean).setObjectIds((List<ObjectId>) newValue); return; case -266779615: // roleName ((RoleSearchRequest) bean).setRoleName((String) newValue); return; case 217765532: // associatedRole ((RoleSearchRequest) bean).setAssociatedRole((String) newValue); return; case 217858545: // associatedUser ((RoleSearchRequest) bean).setAssociatedUser((String) newValue); return; case -1203804299: // associatedPermission ((RoleSearchRequest) bean).setAssociatedPermission((String) newValue); return; case -26774448: // sortOrder ((RoleSearchRequest) bean).setSortOrder((RoleSearchSortOrder) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } @Override protected void validate(Bean bean) { JodaBeanUtils.notNull(((RoleSearchRequest) bean)._sortOrder, "sortOrder"); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
[ "@", "BeanDefinition", "public", "class", "RoleSearchRequest", "implements", "Bean", "{", "/**\n * The request for paging.\n * By default all matching items will be returned.\n */", "@", "PropertyDefinition", "private", "PagingRequest", "_pagingRequest", "=", "PagingRequest", ".", "ALL", ";", "/**\n * The set of role object identifiers, null to not limit by user object identifiers.\n * Note that an empty list will return no users.\n */", "@", "PropertyDefinition", "(", "set", "=", "\"", "manual", "\"", ")", "private", "List", "<", "ObjectId", ">", "_objectIds", ";", "/**\n * The role name to search for, wildcards allowed, null to not match on name.\n */", "@", "PropertyDefinition", "private", "String", "_roleName", ";", "/**\n * The associated role name to search for, no wildcards.\n * If used, only those roles which explicitly reference the role are returned.\n * Any roles implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getRoles()}.\n */", "@", "PropertyDefinition", "private", "String", "_associatedRole", ";", "/**\n * The associated user name to search for, no wildcards.\n * If used, only those roles which explicitly reference the user are returned.\n * Any users implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getUsers()}.\n */", "@", "PropertyDefinition", "private", "String", "_associatedUser", ";", "/**\n * The associated permission to search for, no wildcards.\n * If used, only those roles which explicitly reference the permission are returned.\n * Any permissions implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getPermissions()}.\n */", "@", "PropertyDefinition", "private", "String", "_associatedPermission", ";", "/**\n * The sort order to use.\n */", "@", "PropertyDefinition", "(", "validate", "=", "\"", "notNull", "\"", ")", "private", "RoleSearchSortOrder", "_sortOrder", "=", "RoleSearchSortOrder", ".", "NAME_ASC", ";", "/**\n * Creates an instance.\n */", "public", "RoleSearchRequest", "(", ")", "{", "}", "/**\n * Adds a single user object identifier to the set.\n * \n * @param userId the user object identifier to add, not null\n */", "public", "void", "addObjectId", "(", "ObjectIdentifiable", "userId", ")", "{", "ArgumentChecker", ".", "notNull", "(", "userId", ",", "\"", "userId", "\"", ")", ";", "if", "(", "_objectIds", "==", "null", ")", "{", "_objectIds", "=", "new", "ArrayList", "<", "ObjectId", ">", "(", ")", ";", "}", "_objectIds", ".", "add", "(", "userId", ".", "getObjectId", "(", ")", ")", ";", "}", "/**\n * Sets the set of user object identifiers, null to not limit by user object identifiers.\n * Note that an empty collection will return no securities.\n * \n * @param userIds the new user identifiers, null clears the user id search\n */", "public", "void", "setObjectIds", "(", "Iterable", "<", "?", "extends", "ObjectIdentifiable", ">", "userIds", ")", "{", "if", "(", "userIds", "==", "null", ")", "{", "_objectIds", "=", "null", ";", "}", "else", "{", "_objectIds", "=", "new", "ArrayList", "<", "ObjectId", ">", "(", ")", ";", "for", "(", "ObjectIdentifiable", "userId", ":", "userIds", ")", "{", "_objectIds", ".", "add", "(", "userId", ".", "getObjectId", "(", ")", ")", ";", "}", "}", "}", "/**\n * Checks if this search matches the specified role.\n *\n * @param role the role to match, null returns false\n * @return true if matches\n */", "public", "boolean", "matches", "(", "ManageableRole", "role", ")", "{", "if", "(", "role", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "getObjectIds", "(", ")", "!=", "null", "&&", "getObjectIds", "(", ")", ".", "contains", "(", "role", ".", "getObjectId", "(", ")", ")", "==", "false", ")", "{", "return", "false", ";", "}", "if", "(", "getRoleName", "(", ")", "!=", "null", "&&", "RegexUtils", ".", "wildcardMatch", "(", "getRoleName", "(", ")", ",", "role", ".", "getRoleName", "(", ")", ")", "==", "false", ")", "{", "return", "false", ";", "}", "if", "(", "role", ".", "getAssociatedRoles", "(", ")", ".", "contains", "(", "getAssociatedPermission", "(", ")", ")", "==", "false", ")", "{", "return", "false", ";", "}", "if", "(", "role", ".", "getAssociatedUsers", "(", ")", ".", "contains", "(", "getAssociatedPermission", "(", ")", ")", "==", "false", ")", "{", "return", "false", ";", "}", "if", "(", "role", ".", "getAssociatedPermissions", "(", ")", ".", "contains", "(", "getAssociatedPermission", "(", ")", ")", "==", "false", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "/**\n * The meta-bean for {@code RoleSearchRequest}.\n * @return the meta-bean, not null\n */", "public", "static", "RoleSearchRequest", ".", "Meta", "meta", "(", ")", "{", "return", "RoleSearchRequest", ".", "Meta", ".", "INSTANCE", ";", "}", "static", "{", "JodaBeanUtils", ".", "registerMetaBean", "(", "RoleSearchRequest", ".", "Meta", ".", "INSTANCE", ")", ";", "}", "@", "Override", "public", "RoleSearchRequest", ".", "Meta", "metaBean", "(", ")", "{", "return", "RoleSearchRequest", ".", "Meta", ".", "INSTANCE", ";", "}", "@", "Override", "public", "<", "R", ">", "Property", "<", "R", ">", "property", "(", "String", "propertyName", ")", "{", "return", "metaBean", "(", ")", ".", "<", "R", ">", "metaProperty", "(", "propertyName", ")", ".", "createProperty", "(", "this", ")", ";", "}", "@", "Override", "public", "Set", "<", "String", ">", "propertyNames", "(", ")", "{", "return", "metaBean", "(", ")", ".", "metaPropertyMap", "(", ")", ".", "keySet", "(", ")", ";", "}", "/**\n * Gets the request for paging.\n * By default all matching items will be returned.\n * @return the value of the property\n */", "public", "PagingRequest", "getPagingRequest", "(", ")", "{", "return", "_pagingRequest", ";", "}", "/**\n * Sets the request for paging.\n * By default all matching items will be returned.\n * @param pagingRequest the new value of the property\n */", "public", "void", "setPagingRequest", "(", "PagingRequest", "pagingRequest", ")", "{", "this", ".", "_pagingRequest", "=", "pagingRequest", ";", "}", "/**\n * Gets the the {@code pagingRequest} property.\n * By default all matching items will be returned.\n * @return the property, not null\n */", "public", "final", "Property", "<", "PagingRequest", ">", "pagingRequest", "(", ")", "{", "return", "metaBean", "(", ")", ".", "pagingRequest", "(", ")", ".", "createProperty", "(", "this", ")", ";", "}", "/**\n * Gets the set of role object identifiers, null to not limit by user object identifiers.\n * Note that an empty list will return no users.\n * @return the value of the property\n */", "public", "List", "<", "ObjectId", ">", "getObjectIds", "(", ")", "{", "return", "_objectIds", ";", "}", "/**\n * Gets the the {@code objectIds} property.\n * Note that an empty list will return no users.\n * @return the property, not null\n */", "public", "final", "Property", "<", "List", "<", "ObjectId", ">", ">", "objectIds", "(", ")", "{", "return", "metaBean", "(", ")", ".", "objectIds", "(", ")", ".", "createProperty", "(", "this", ")", ";", "}", "/**\n * Gets the role name to search for, wildcards allowed, null to not match on name.\n * @return the value of the property\n */", "public", "String", "getRoleName", "(", ")", "{", "return", "_roleName", ";", "}", "/**\n * Sets the role name to search for, wildcards allowed, null to not match on name.\n * @param roleName the new value of the property\n */", "public", "void", "setRoleName", "(", "String", "roleName", ")", "{", "this", ".", "_roleName", "=", "roleName", ";", "}", "/**\n * Gets the the {@code roleName} property.\n * @return the property, not null\n */", "public", "final", "Property", "<", "String", ">", "roleName", "(", ")", "{", "return", "metaBean", "(", ")", ".", "roleName", "(", ")", ".", "createProperty", "(", "this", ")", ";", "}", "/**\n * Gets the associated role name to search for, no wildcards.\n * If used, only those roles which explicitly reference the role are returned.\n * Any roles implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getRoles()}.\n * @return the value of the property\n */", "public", "String", "getAssociatedRole", "(", ")", "{", "return", "_associatedRole", ";", "}", "/**\n * Sets the associated role name to search for, no wildcards.\n * If used, only those roles which explicitly reference the role are returned.\n * Any roles implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getRoles()}.\n * @param associatedRole the new value of the property\n */", "public", "void", "setAssociatedRole", "(", "String", "associatedRole", ")", "{", "this", ".", "_associatedRole", "=", "associatedRole", ";", "}", "/**\n * Gets the the {@code associatedRole} property.\n * If used, only those roles which explicitly reference the role are returned.\n * Any roles implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getRoles()}.\n * @return the property, not null\n */", "public", "final", "Property", "<", "String", ">", "associatedRole", "(", ")", "{", "return", "metaBean", "(", ")", ".", "associatedRole", "(", ")", ".", "createProperty", "(", "this", ")", ";", "}", "/**\n * Gets the associated user name to search for, no wildcards.\n * If used, only those roles which explicitly reference the user are returned.\n * Any users implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getUsers()}.\n * @return the value of the property\n */", "public", "String", "getAssociatedUser", "(", ")", "{", "return", "_associatedUser", ";", "}", "/**\n * Sets the associated user name to search for, no wildcards.\n * If used, only those roles which explicitly reference the user are returned.\n * Any users implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getUsers()}.\n * @param associatedUser the new value of the property\n */", "public", "void", "setAssociatedUser", "(", "String", "associatedUser", ")", "{", "this", ".", "_associatedUser", "=", "associatedUser", ";", "}", "/**\n * Gets the the {@code associatedUser} property.\n * If used, only those roles which explicitly reference the user are returned.\n * Any users implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getUsers()}.\n * @return the property, not null\n */", "public", "final", "Property", "<", "String", ">", "associatedUser", "(", ")", "{", "return", "metaBean", "(", ")", ".", "associatedUser", "(", ")", ".", "createProperty", "(", "this", ")", ";", "}", "/**\n * Gets the associated permission to search for, no wildcards.\n * If used, only those roles which explicitly reference the permission are returned.\n * Any permissions implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getPermissions()}.\n * @return the value of the property\n */", "public", "String", "getAssociatedPermission", "(", ")", "{", "return", "_associatedPermission", ";", "}", "/**\n * Sets the associated permission to search for, no wildcards.\n * If used, only those roles which explicitly reference the permission are returned.\n * Any permissions implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getPermissions()}.\n * @param associatedPermission the new value of the property\n */", "public", "void", "setAssociatedPermission", "(", "String", "associatedPermission", ")", "{", "this", ".", "_associatedPermission", "=", "associatedPermission", ";", "}", "/**\n * Gets the the {@code associatedPermission} property.\n * If used, only those roles which explicitly reference the permission are returned.\n * Any permissions implied by membership of other roles are not matched.\n * In other words, this searches {@link ManageableRole#getPermissions()}.\n * @return the property, not null\n */", "public", "final", "Property", "<", "String", ">", "associatedPermission", "(", ")", "{", "return", "metaBean", "(", ")", ".", "associatedPermission", "(", ")", ".", "createProperty", "(", "this", ")", ";", "}", "/**\n * Gets the sort order to use.\n * @return the value of the property, not null\n */", "public", "RoleSearchSortOrder", "getSortOrder", "(", ")", "{", "return", "_sortOrder", ";", "}", "/**\n * Sets the sort order to use.\n * @param sortOrder the new value of the property, not null\n */", "public", "void", "setSortOrder", "(", "RoleSearchSortOrder", "sortOrder", ")", "{", "JodaBeanUtils", ".", "notNull", "(", "sortOrder", ",", "\"", "sortOrder", "\"", ")", ";", "this", ".", "_sortOrder", "=", "sortOrder", ";", "}", "/**\n * Gets the the {@code sortOrder} property.\n * @return the property, not null\n */", "public", "final", "Property", "<", "RoleSearchSortOrder", ">", "sortOrder", "(", ")", "{", "return", "metaBean", "(", ")", ".", "sortOrder", "(", ")", ".", "createProperty", "(", "this", ")", ";", "}", "@", "Override", "public", "RoleSearchRequest", "clone", "(", ")", "{", "return", "JodaBeanUtils", ".", "cloneAlways", "(", "this", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "this", ")", "{", "return", "true", ";", "}", "if", "(", "obj", "!=", "null", "&&", "obj", ".", "getClass", "(", ")", "==", "this", ".", "getClass", "(", ")", ")", "{", "RoleSearchRequest", "other", "=", "(", "RoleSearchRequest", ")", "obj", ";", "return", "JodaBeanUtils", ".", "equal", "(", "getPagingRequest", "(", ")", ",", "other", ".", "getPagingRequest", "(", ")", ")", "&&", "JodaBeanUtils", ".", "equal", "(", "getObjectIds", "(", ")", ",", "other", ".", "getObjectIds", "(", ")", ")", "&&", "JodaBeanUtils", ".", "equal", "(", "getRoleName", "(", ")", ",", "other", ".", "getRoleName", "(", ")", ")", "&&", "JodaBeanUtils", ".", "equal", "(", "getAssociatedRole", "(", ")", ",", "other", ".", "getAssociatedRole", "(", ")", ")", "&&", "JodaBeanUtils", ".", "equal", "(", "getAssociatedUser", "(", ")", ",", "other", ".", "getAssociatedUser", "(", ")", ")", "&&", "JodaBeanUtils", ".", "equal", "(", "getAssociatedPermission", "(", ")", ",", "other", ".", "getAssociatedPermission", "(", ")", ")", "&&", "JodaBeanUtils", ".", "equal", "(", "getSortOrder", "(", ")", ",", "other", ".", "getSortOrder", "(", ")", ")", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "int", "hash", "=", "getClass", "(", ")", ".", "hashCode", "(", ")", ";", "hash", "+=", "hash", "*", "31", "+", "JodaBeanUtils", ".", "hashCode", "(", "getPagingRequest", "(", ")", ")", ";", "hash", "+=", "hash", "*", "31", "+", "JodaBeanUtils", ".", "hashCode", "(", "getObjectIds", "(", ")", ")", ";", "hash", "+=", "hash", "*", "31", "+", "JodaBeanUtils", ".", "hashCode", "(", "getRoleName", "(", ")", ")", ";", "hash", "+=", "hash", "*", "31", "+", "JodaBeanUtils", ".", "hashCode", "(", "getAssociatedRole", "(", ")", ")", ";", "hash", "+=", "hash", "*", "31", "+", "JodaBeanUtils", ".", "hashCode", "(", "getAssociatedUser", "(", ")", ")", ";", "hash", "+=", "hash", "*", "31", "+", "JodaBeanUtils", ".", "hashCode", "(", "getAssociatedPermission", "(", ")", ")", ";", "hash", "+=", "hash", "*", "31", "+", "JodaBeanUtils", ".", "hashCode", "(", "getSortOrder", "(", ")", ")", ";", "return", "hash", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "256", ")", ";", "buf", ".", "append", "(", "\"", "RoleSearchRequest{", "\"", ")", ";", "int", "len", "=", "buf", ".", "length", "(", ")", ";", "toString", "(", "buf", ")", ";", "if", "(", "buf", ".", "length", "(", ")", ">", "len", ")", "{", "buf", ".", "setLength", "(", "buf", ".", "length", "(", ")", "-", "2", ")", ";", "}", "buf", ".", "append", "(", "'}'", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}", "protected", "void", "toString", "(", "StringBuilder", "buf", ")", "{", "buf", ".", "append", "(", "\"", "pagingRequest", "\"", ")", ".", "append", "(", "'='", ")", ".", "append", "(", "JodaBeanUtils", ".", "toString", "(", "getPagingRequest", "(", ")", ")", ")", ".", "append", "(", "','", ")", ".", "append", "(", "' '", ")", ";", "buf", ".", "append", "(", "\"", "objectIds", "\"", ")", ".", "append", "(", "'='", ")", ".", "append", "(", "JodaBeanUtils", ".", "toString", "(", "getObjectIds", "(", ")", ")", ")", ".", "append", "(", "','", ")", ".", "append", "(", "' '", ")", ";", "buf", ".", "append", "(", "\"", "roleName", "\"", ")", ".", "append", "(", "'='", ")", ".", "append", "(", "JodaBeanUtils", ".", "toString", "(", "getRoleName", "(", ")", ")", ")", ".", "append", "(", "','", ")", ".", "append", "(", "' '", ")", ";", "buf", ".", "append", "(", "\"", "associatedRole", "\"", ")", ".", "append", "(", "'='", ")", ".", "append", "(", "JodaBeanUtils", ".", "toString", "(", "getAssociatedRole", "(", ")", ")", ")", ".", "append", "(", "','", ")", ".", "append", "(", "' '", ")", ";", "buf", ".", "append", "(", "\"", "associatedUser", "\"", ")", ".", "append", "(", "'='", ")", ".", "append", "(", "JodaBeanUtils", ".", "toString", "(", "getAssociatedUser", "(", ")", ")", ")", ".", "append", "(", "','", ")", ".", "append", "(", "' '", ")", ";", "buf", ".", "append", "(", "\"", "associatedPermission", "\"", ")", ".", "append", "(", "'='", ")", ".", "append", "(", "JodaBeanUtils", ".", "toString", "(", "getAssociatedPermission", "(", ")", ")", ")", ".", "append", "(", "','", ")", ".", "append", "(", "' '", ")", ";", "buf", ".", "append", "(", "\"", "sortOrder", "\"", ")", ".", "append", "(", "'='", ")", ".", "append", "(", "JodaBeanUtils", ".", "toString", "(", "getSortOrder", "(", ")", ")", ")", ".", "append", "(", "','", ")", ".", "append", "(", "' '", ")", ";", "}", "/**\n * The meta-bean for {@code RoleSearchRequest}.\n */", "public", "static", "class", "Meta", "extends", "DirectMetaBean", "{", "/**\n * The singleton instance of the meta-bean.\n */", "static", "final", "Meta", "INSTANCE", "=", "new", "Meta", "(", ")", ";", "/**\n * The meta-property for the {@code pagingRequest} property.\n */", "private", "final", "MetaProperty", "<", "PagingRequest", ">", "_pagingRequest", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "pagingRequest", "\"", ",", "RoleSearchRequest", ".", "class", ",", "PagingRequest", ".", "class", ")", ";", "/**\n * The meta-property for the {@code objectIds} property.\n */", "@", "SuppressWarnings", "(", "{", "\"", "unchecked", "\"", ",", "\"", "rawtypes", "\"", "}", ")", "private", "final", "MetaProperty", "<", "List", "<", "ObjectId", ">", ">", "_objectIds", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "objectIds", "\"", ",", "RoleSearchRequest", ".", "class", ",", "(", "Class", ")", "List", ".", "class", ")", ";", "/**\n * The meta-property for the {@code roleName} property.\n */", "private", "final", "MetaProperty", "<", "String", ">", "_roleName", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "roleName", "\"", ",", "RoleSearchRequest", ".", "class", ",", "String", ".", "class", ")", ";", "/**\n * The meta-property for the {@code associatedRole} property.\n */", "private", "final", "MetaProperty", "<", "String", ">", "_associatedRole", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "associatedRole", "\"", ",", "RoleSearchRequest", ".", "class", ",", "String", ".", "class", ")", ";", "/**\n * The meta-property for the {@code associatedUser} property.\n */", "private", "final", "MetaProperty", "<", "String", ">", "_associatedUser", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "associatedUser", "\"", ",", "RoleSearchRequest", ".", "class", ",", "String", ".", "class", ")", ";", "/**\n * The meta-property for the {@code associatedPermission} property.\n */", "private", "final", "MetaProperty", "<", "String", ">", "_associatedPermission", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "associatedPermission", "\"", ",", "RoleSearchRequest", ".", "class", ",", "String", ".", "class", ")", ";", "/**\n * The meta-property for the {@code sortOrder} property.\n */", "private", "final", "MetaProperty", "<", "RoleSearchSortOrder", ">", "_sortOrder", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "sortOrder", "\"", ",", "RoleSearchRequest", ".", "class", ",", "RoleSearchSortOrder", ".", "class", ")", ";", "/**\n * The meta-properties.\n */", "private", "final", "Map", "<", "String", ",", "MetaProperty", "<", "?", ">", ">", "_metaPropertyMap$", "=", "new", "DirectMetaPropertyMap", "(", "this", ",", "null", ",", "\"", "pagingRequest", "\"", ",", "\"", "objectIds", "\"", ",", "\"", "roleName", "\"", ",", "\"", "associatedRole", "\"", ",", "\"", "associatedUser", "\"", ",", "\"", "associatedPermission", "\"", ",", "\"", "sortOrder", "\"", ")", ";", "/**\n * Restricted constructor.\n */", "protected", "Meta", "(", ")", "{", "}", "@", "Override", "protected", "MetaProperty", "<", "?", ">", "metaPropertyGet", "(", "String", "propertyName", ")", "{", "switch", "(", "propertyName", ".", "hashCode", "(", ")", ")", "{", "case", "-", "2092032669", ":", "return", "_pagingRequest", ";", "case", "-", "1489617159", ":", "return", "_objectIds", ";", "case", "-", "266779615", ":", "return", "_roleName", ";", "case", "217765532", ":", "return", "_associatedRole", ";", "case", "217858545", ":", "return", "_associatedUser", ";", "case", "-", "1203804299", ":", "return", "_associatedPermission", ";", "case", "-", "26774448", ":", "return", "_sortOrder", ";", "}", "return", "super", ".", "metaPropertyGet", "(", "propertyName", ")", ";", "}", "@", "Override", "public", "BeanBuilder", "<", "?", "extends", "RoleSearchRequest", ">", "builder", "(", ")", "{", "return", "new", "DirectBeanBuilder", "<", "RoleSearchRequest", ">", "(", "new", "RoleSearchRequest", "(", ")", ")", ";", "}", "@", "Override", "public", "Class", "<", "?", "extends", "RoleSearchRequest", ">", "beanType", "(", ")", "{", "return", "RoleSearchRequest", ".", "class", ";", "}", "@", "Override", "public", "Map", "<", "String", ",", "MetaProperty", "<", "?", ">", ">", "metaPropertyMap", "(", ")", "{", "return", "_metaPropertyMap$", ";", "}", "/**\n * The meta-property for the {@code pagingRequest} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "PagingRequest", ">", "pagingRequest", "(", ")", "{", "return", "_pagingRequest", ";", "}", "/**\n * The meta-property for the {@code objectIds} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "List", "<", "ObjectId", ">", ">", "objectIds", "(", ")", "{", "return", "_objectIds", ";", "}", "/**\n * The meta-property for the {@code roleName} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "String", ">", "roleName", "(", ")", "{", "return", "_roleName", ";", "}", "/**\n * The meta-property for the {@code associatedRole} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "String", ">", "associatedRole", "(", ")", "{", "return", "_associatedRole", ";", "}", "/**\n * The meta-property for the {@code associatedUser} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "String", ">", "associatedUser", "(", ")", "{", "return", "_associatedUser", ";", "}", "/**\n * The meta-property for the {@code associatedPermission} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "String", ">", "associatedPermission", "(", ")", "{", "return", "_associatedPermission", ";", "}", "/**\n * The meta-property for the {@code sortOrder} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "RoleSearchSortOrder", ">", "sortOrder", "(", ")", "{", "return", "_sortOrder", ";", "}", "@", "Override", "protected", "Object", "propertyGet", "(", "Bean", "bean", ",", "String", "propertyName", ",", "boolean", "quiet", ")", "{", "switch", "(", "propertyName", ".", "hashCode", "(", ")", ")", "{", "case", "-", "2092032669", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getPagingRequest", "(", ")", ";", "case", "-", "1489617159", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getObjectIds", "(", ")", ";", "case", "-", "266779615", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getRoleName", "(", ")", ";", "case", "217765532", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getAssociatedRole", "(", ")", ";", "case", "217858545", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getAssociatedUser", "(", ")", ";", "case", "-", "1203804299", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getAssociatedPermission", "(", ")", ";", "case", "-", "26774448", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getSortOrder", "(", ")", ";", "}", "return", "super", ".", "propertyGet", "(", "bean", ",", "propertyName", ",", "quiet", ")", ";", "}", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "@", "Override", "protected", "void", "propertySet", "(", "Bean", "bean", ",", "String", "propertyName", ",", "Object", "newValue", ",", "boolean", "quiet", ")", "{", "switch", "(", "propertyName", ".", "hashCode", "(", ")", ")", "{", "case", "-", "2092032669", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setPagingRequest", "(", "(", "PagingRequest", ")", "newValue", ")", ";", "return", ";", "case", "-", "1489617159", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setObjectIds", "(", "(", "List", "<", "ObjectId", ">", ")", "newValue", ")", ";", "return", ";", "case", "-", "266779615", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setRoleName", "(", "(", "String", ")", "newValue", ")", ";", "return", ";", "case", "217765532", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setAssociatedRole", "(", "(", "String", ")", "newValue", ")", ";", "return", ";", "case", "217858545", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setAssociatedUser", "(", "(", "String", ")", "newValue", ")", ";", "return", ";", "case", "-", "1203804299", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setAssociatedPermission", "(", "(", "String", ")", "newValue", ")", ";", "return", ";", "case", "-", "26774448", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setSortOrder", "(", "(", "RoleSearchSortOrder", ")", "newValue", ")", ";", "return", ";", "}", "super", ".", "propertySet", "(", "bean", ",", "propertyName", ",", "newValue", ",", "quiet", ")", ";", "}", "@", "Override", "protected", "void", "validate", "(", "Bean", "bean", ")", "{", "JodaBeanUtils", ".", "notNull", "(", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "_sortOrder", ",", "\"", "sortOrder", "\"", ")", ";", "}", "}", "}" ]
Request for searching for roles.
[ "Request", "for", "searching", "for", "roles", "." ]
[ "//-------------------------------------------------------------------------", "//-------------------------------------------------------------------------", "//------------------------- AUTOGENERATED START -------------------------", "///CLOVER:OFF", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "// pagingRequest", "// objectIds", "// roleName", "// associatedRole", "// associatedUser", "// associatedPermission", "// sortOrder", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "// pagingRequest", "// objectIds", "// roleName", "// associatedRole", "// associatedUser", "// associatedPermission", "// sortOrder", "// pagingRequest", "// objectIds", "// roleName", "// associatedRole", "// associatedUser", "// associatedPermission", "// sortOrder", "///CLOVER:ON", "//-------------------------- AUTOGENERATED END --------------------------" ]
[ { "param": "Bean", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Bean", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b3b1f6038ed0bbcdce48abbde7600ed886b8c4a
emcleod/OG-Platform
projects/OG-Master/src/main/java/com/opengamma/master/user/RoleSearchRequest.java
[ "Apache-2.0" ]
Java
Meta
/** * The meta-bean for {@code RoleSearchRequest}. */
The meta-bean for RoleSearchRequest.
[ "The", "meta", "-", "bean", "for", "RoleSearchRequest", "." ]
public static class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code pagingRequest} property. */ private final MetaProperty<PagingRequest> _pagingRequest = DirectMetaProperty.ofReadWrite( this, "pagingRequest", RoleSearchRequest.class, PagingRequest.class); /** * The meta-property for the {@code objectIds} property. */ @SuppressWarnings({"unchecked", "rawtypes" }) private final MetaProperty<List<ObjectId>> _objectIds = DirectMetaProperty.ofReadWrite( this, "objectIds", RoleSearchRequest.class, (Class) List.class); /** * The meta-property for the {@code roleName} property. */ private final MetaProperty<String> _roleName = DirectMetaProperty.ofReadWrite( this, "roleName", RoleSearchRequest.class, String.class); /** * The meta-property for the {@code associatedRole} property. */ private final MetaProperty<String> _associatedRole = DirectMetaProperty.ofReadWrite( this, "associatedRole", RoleSearchRequest.class, String.class); /** * The meta-property for the {@code associatedUser} property. */ private final MetaProperty<String> _associatedUser = DirectMetaProperty.ofReadWrite( this, "associatedUser", RoleSearchRequest.class, String.class); /** * The meta-property for the {@code associatedPermission} property. */ private final MetaProperty<String> _associatedPermission = DirectMetaProperty.ofReadWrite( this, "associatedPermission", RoleSearchRequest.class, String.class); /** * The meta-property for the {@code sortOrder} property. */ private final MetaProperty<RoleSearchSortOrder> _sortOrder = DirectMetaProperty.ofReadWrite( this, "sortOrder", RoleSearchRequest.class, RoleSearchSortOrder.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "pagingRequest", "objectIds", "roleName", "associatedRole", "associatedUser", "associatedPermission", "sortOrder"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest return _pagingRequest; case -1489617159: // objectIds return _objectIds; case -266779615: // roleName return _roleName; case 217765532: // associatedRole return _associatedRole; case 217858545: // associatedUser return _associatedUser; case -1203804299: // associatedPermission return _associatedPermission; case -26774448: // sortOrder return _sortOrder; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends RoleSearchRequest> builder() { return new DirectBeanBuilder<RoleSearchRequest>(new RoleSearchRequest()); } @Override public Class<? extends RoleSearchRequest> beanType() { return RoleSearchRequest.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code pagingRequest} property. * @return the meta-property, not null */ public final MetaProperty<PagingRequest> pagingRequest() { return _pagingRequest; } /** * The meta-property for the {@code objectIds} property. * @return the meta-property, not null */ public final MetaProperty<List<ObjectId>> objectIds() { return _objectIds; } /** * The meta-property for the {@code roleName} property. * @return the meta-property, not null */ public final MetaProperty<String> roleName() { return _roleName; } /** * The meta-property for the {@code associatedRole} property. * @return the meta-property, not null */ public final MetaProperty<String> associatedRole() { return _associatedRole; } /** * The meta-property for the {@code associatedUser} property. * @return the meta-property, not null */ public final MetaProperty<String> associatedUser() { return _associatedUser; } /** * The meta-property for the {@code associatedPermission} property. * @return the meta-property, not null */ public final MetaProperty<String> associatedPermission() { return _associatedPermission; } /** * The meta-property for the {@code sortOrder} property. * @return the meta-property, not null */ public final MetaProperty<RoleSearchSortOrder> sortOrder() { return _sortOrder; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest return ((RoleSearchRequest) bean).getPagingRequest(); case -1489617159: // objectIds return ((RoleSearchRequest) bean).getObjectIds(); case -266779615: // roleName return ((RoleSearchRequest) bean).getRoleName(); case 217765532: // associatedRole return ((RoleSearchRequest) bean).getAssociatedRole(); case 217858545: // associatedUser return ((RoleSearchRequest) bean).getAssociatedUser(); case -1203804299: // associatedPermission return ((RoleSearchRequest) bean).getAssociatedPermission(); case -26774448: // sortOrder return ((RoleSearchRequest) bean).getSortOrder(); } return super.propertyGet(bean, propertyName, quiet); } @SuppressWarnings("unchecked") @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest ((RoleSearchRequest) bean).setPagingRequest((PagingRequest) newValue); return; case -1489617159: // objectIds ((RoleSearchRequest) bean).setObjectIds((List<ObjectId>) newValue); return; case -266779615: // roleName ((RoleSearchRequest) bean).setRoleName((String) newValue); return; case 217765532: // associatedRole ((RoleSearchRequest) bean).setAssociatedRole((String) newValue); return; case 217858545: // associatedUser ((RoleSearchRequest) bean).setAssociatedUser((String) newValue); return; case -1203804299: // associatedPermission ((RoleSearchRequest) bean).setAssociatedPermission((String) newValue); return; case -26774448: // sortOrder ((RoleSearchRequest) bean).setSortOrder((RoleSearchSortOrder) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } @Override protected void validate(Bean bean) { JodaBeanUtils.notNull(((RoleSearchRequest) bean)._sortOrder, "sortOrder"); } }
[ "public", "static", "class", "Meta", "extends", "DirectMetaBean", "{", "/**\n * The singleton instance of the meta-bean.\n */", "static", "final", "Meta", "INSTANCE", "=", "new", "Meta", "(", ")", ";", "/**\n * The meta-property for the {@code pagingRequest} property.\n */", "private", "final", "MetaProperty", "<", "PagingRequest", ">", "_pagingRequest", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "pagingRequest", "\"", ",", "RoleSearchRequest", ".", "class", ",", "PagingRequest", ".", "class", ")", ";", "/**\n * The meta-property for the {@code objectIds} property.\n */", "@", "SuppressWarnings", "(", "{", "\"", "unchecked", "\"", ",", "\"", "rawtypes", "\"", "}", ")", "private", "final", "MetaProperty", "<", "List", "<", "ObjectId", ">", ">", "_objectIds", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "objectIds", "\"", ",", "RoleSearchRequest", ".", "class", ",", "(", "Class", ")", "List", ".", "class", ")", ";", "/**\n * The meta-property for the {@code roleName} property.\n */", "private", "final", "MetaProperty", "<", "String", ">", "_roleName", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "roleName", "\"", ",", "RoleSearchRequest", ".", "class", ",", "String", ".", "class", ")", ";", "/**\n * The meta-property for the {@code associatedRole} property.\n */", "private", "final", "MetaProperty", "<", "String", ">", "_associatedRole", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "associatedRole", "\"", ",", "RoleSearchRequest", ".", "class", ",", "String", ".", "class", ")", ";", "/**\n * The meta-property for the {@code associatedUser} property.\n */", "private", "final", "MetaProperty", "<", "String", ">", "_associatedUser", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "associatedUser", "\"", ",", "RoleSearchRequest", ".", "class", ",", "String", ".", "class", ")", ";", "/**\n * The meta-property for the {@code associatedPermission} property.\n */", "private", "final", "MetaProperty", "<", "String", ">", "_associatedPermission", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "associatedPermission", "\"", ",", "RoleSearchRequest", ".", "class", ",", "String", ".", "class", ")", ";", "/**\n * The meta-property for the {@code sortOrder} property.\n */", "private", "final", "MetaProperty", "<", "RoleSearchSortOrder", ">", "_sortOrder", "=", "DirectMetaProperty", ".", "ofReadWrite", "(", "this", ",", "\"", "sortOrder", "\"", ",", "RoleSearchRequest", ".", "class", ",", "RoleSearchSortOrder", ".", "class", ")", ";", "/**\n * The meta-properties.\n */", "private", "final", "Map", "<", "String", ",", "MetaProperty", "<", "?", ">", ">", "_metaPropertyMap$", "=", "new", "DirectMetaPropertyMap", "(", "this", ",", "null", ",", "\"", "pagingRequest", "\"", ",", "\"", "objectIds", "\"", ",", "\"", "roleName", "\"", ",", "\"", "associatedRole", "\"", ",", "\"", "associatedUser", "\"", ",", "\"", "associatedPermission", "\"", ",", "\"", "sortOrder", "\"", ")", ";", "/**\n * Restricted constructor.\n */", "protected", "Meta", "(", ")", "{", "}", "@", "Override", "protected", "MetaProperty", "<", "?", ">", "metaPropertyGet", "(", "String", "propertyName", ")", "{", "switch", "(", "propertyName", ".", "hashCode", "(", ")", ")", "{", "case", "-", "2092032669", ":", "return", "_pagingRequest", ";", "case", "-", "1489617159", ":", "return", "_objectIds", ";", "case", "-", "266779615", ":", "return", "_roleName", ";", "case", "217765532", ":", "return", "_associatedRole", ";", "case", "217858545", ":", "return", "_associatedUser", ";", "case", "-", "1203804299", ":", "return", "_associatedPermission", ";", "case", "-", "26774448", ":", "return", "_sortOrder", ";", "}", "return", "super", ".", "metaPropertyGet", "(", "propertyName", ")", ";", "}", "@", "Override", "public", "BeanBuilder", "<", "?", "extends", "RoleSearchRequest", ">", "builder", "(", ")", "{", "return", "new", "DirectBeanBuilder", "<", "RoleSearchRequest", ">", "(", "new", "RoleSearchRequest", "(", ")", ")", ";", "}", "@", "Override", "public", "Class", "<", "?", "extends", "RoleSearchRequest", ">", "beanType", "(", ")", "{", "return", "RoleSearchRequest", ".", "class", ";", "}", "@", "Override", "public", "Map", "<", "String", ",", "MetaProperty", "<", "?", ">", ">", "metaPropertyMap", "(", ")", "{", "return", "_metaPropertyMap$", ";", "}", "/**\n * The meta-property for the {@code pagingRequest} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "PagingRequest", ">", "pagingRequest", "(", ")", "{", "return", "_pagingRequest", ";", "}", "/**\n * The meta-property for the {@code objectIds} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "List", "<", "ObjectId", ">", ">", "objectIds", "(", ")", "{", "return", "_objectIds", ";", "}", "/**\n * The meta-property for the {@code roleName} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "String", ">", "roleName", "(", ")", "{", "return", "_roleName", ";", "}", "/**\n * The meta-property for the {@code associatedRole} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "String", ">", "associatedRole", "(", ")", "{", "return", "_associatedRole", ";", "}", "/**\n * The meta-property for the {@code associatedUser} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "String", ">", "associatedUser", "(", ")", "{", "return", "_associatedUser", ";", "}", "/**\n * The meta-property for the {@code associatedPermission} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "String", ">", "associatedPermission", "(", ")", "{", "return", "_associatedPermission", ";", "}", "/**\n * The meta-property for the {@code sortOrder} property.\n * @return the meta-property, not null\n */", "public", "final", "MetaProperty", "<", "RoleSearchSortOrder", ">", "sortOrder", "(", ")", "{", "return", "_sortOrder", ";", "}", "@", "Override", "protected", "Object", "propertyGet", "(", "Bean", "bean", ",", "String", "propertyName", ",", "boolean", "quiet", ")", "{", "switch", "(", "propertyName", ".", "hashCode", "(", ")", ")", "{", "case", "-", "2092032669", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getPagingRequest", "(", ")", ";", "case", "-", "1489617159", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getObjectIds", "(", ")", ";", "case", "-", "266779615", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getRoleName", "(", ")", ";", "case", "217765532", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getAssociatedRole", "(", ")", ";", "case", "217858545", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getAssociatedUser", "(", ")", ";", "case", "-", "1203804299", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getAssociatedPermission", "(", ")", ";", "case", "-", "26774448", ":", "return", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "getSortOrder", "(", ")", ";", "}", "return", "super", ".", "propertyGet", "(", "bean", ",", "propertyName", ",", "quiet", ")", ";", "}", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "@", "Override", "protected", "void", "propertySet", "(", "Bean", "bean", ",", "String", "propertyName", ",", "Object", "newValue", ",", "boolean", "quiet", ")", "{", "switch", "(", "propertyName", ".", "hashCode", "(", ")", ")", "{", "case", "-", "2092032669", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setPagingRequest", "(", "(", "PagingRequest", ")", "newValue", ")", ";", "return", ";", "case", "-", "1489617159", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setObjectIds", "(", "(", "List", "<", "ObjectId", ">", ")", "newValue", ")", ";", "return", ";", "case", "-", "266779615", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setRoleName", "(", "(", "String", ")", "newValue", ")", ";", "return", ";", "case", "217765532", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setAssociatedRole", "(", "(", "String", ")", "newValue", ")", ";", "return", ";", "case", "217858545", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setAssociatedUser", "(", "(", "String", ")", "newValue", ")", ";", "return", ";", "case", "-", "1203804299", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setAssociatedPermission", "(", "(", "String", ")", "newValue", ")", ";", "return", ";", "case", "-", "26774448", ":", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "setSortOrder", "(", "(", "RoleSearchSortOrder", ")", "newValue", ")", ";", "return", ";", "}", "super", ".", "propertySet", "(", "bean", ",", "propertyName", ",", "newValue", ",", "quiet", ")", ";", "}", "@", "Override", "protected", "void", "validate", "(", "Bean", "bean", ")", "{", "JodaBeanUtils", ".", "notNull", "(", "(", "(", "RoleSearchRequest", ")", "bean", ")", ".", "_sortOrder", ",", "\"", "sortOrder", "\"", ")", ";", "}", "}" ]
The meta-bean for {@code RoleSearchRequest}.
[ "The", "meta", "-", "bean", "for", "{", "@code", "RoleSearchRequest", "}", "." ]
[ "// pagingRequest", "// objectIds", "// roleName", "// associatedRole", "// associatedUser", "// associatedPermission", "// sortOrder", "//-----------------------------------------------------------------------", "//-----------------------------------------------------------------------", "// pagingRequest", "// objectIds", "// roleName", "// associatedRole", "// associatedUser", "// associatedPermission", "// sortOrder", "// pagingRequest", "// objectIds", "// roleName", "// associatedRole", "// associatedUser", "// associatedPermission", "// sortOrder" ]
[ { "param": "DirectMetaBean", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DirectMetaBean", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b3bf6a8aca34c9da2f075481799b79f088c1b9a
aherbert/gdsc-smlm
src/main/java/uk/ac/sussex/gdsc/smlm/fitting/nonlinear/LseBaseFunctionSolver.java
[ "BSL-1.0" ]
Java
LseBaseFunctionSolver
/** * Abstract class with utility methods for the {@link LseFunctionSolver} interface. */
Abstract class with utility methods for the LseFunctionSolver interface.
[ "Abstract", "class", "with", "utility", "methods", "for", "the", "LseFunctionSolver", "interface", "." ]
public abstract class LseBaseFunctionSolver extends BaseFunctionSolver implements LseFunctionSolver { /** The total sum of squares. */ protected double totalSumOfSquares = Double.NaN; /** * Default constructor. * * @param function the function * @throws NullPointerException if the function is null */ public LseBaseFunctionSolver(GradientFunction function) { super(FunctionSolverType.LSE, function); } @Override protected void preProcess() { totalSumOfSquares = Double.NaN; } /** * Gets the total sum of squares. * * @param y the y * @return the total sum of squares */ public static double computeTotalSumOfSquares(double[] y) { double sx = 0; double ssx = 0; for (int i = y.length; i-- > 0;) { sx += y[i]; ssx += y[i] * y[i]; } return ssx - (sx * sx) / (y.length); } /** * Compute the error. * * @param value the value * @param noise the noise * @param numberOfFittedPoints the number of fitted points * @param numberOfFittedParameters the number of fitted parameters * @return the error */ public static double getError(double value, double noise, int numberOfFittedPoints, int numberOfFittedParameters) { double error = value; // Divide by the uncertainty in the individual measurements yi to get the chi-squared if (noise > 0) { error /= numberOfFittedPoints * noise * noise; } // This updates the chi-squared value to the average error for a single fitted // point using the degrees of freedom (N-M)? // Note: This matches the mean squared error output from the MatLab fitting code. // If a noise estimate was provided for individual measurements then this will be the // reduced chi-square (see http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2892436/) if (numberOfFittedPoints > numberOfFittedParameters) { error /= (numberOfFittedPoints - numberOfFittedParameters); } else { error = 0; } return error; } @Override public double getTotalSumOfSquares() { if (Double.isNaN(totalSumOfSquares) && lastY != null) { totalSumOfSquares = computeTotalSumOfSquares(lastY); } return totalSumOfSquares; } @Override public double getResidualSumOfSquares() { return value; } @Override public double getCoefficientOfDetermination() { return 1.0 - (value / getTotalSumOfSquares()); } @Override public double getAdjustedCoefficientOfDetermination() { return MathUtils.getAdjustedCoefficientOfDetermination(getResidualSumOfSquares(), getTotalSumOfSquares(), getNumberOfFittedPoints(), getNumberOfFittedParameters()); } @Override public double getMeanSquaredError() { return getResidualSumOfSquares() / (getNumberOfFittedPoints() - getNumberOfFittedParameters()); } // Allow I and E as they have special meaning in the formula. // CHECKSTYLE.OFF: ParameterName /** * Compute the covariance matrix of the parameters of the function assuming a least squares fit of * a Poisson process. * * <p>Uses the Mortensen formula (Mortensen, et al (2010) Nature Methods 7, 377-383), equation 25. * * <p>The method involves inversion of a matrix and may fail. * * <pre> * I = sum_i { Ei,a * Ei,b } * E = sum_i { Ei * Ei,a * Ei,b } * with * i the number of data points fit using least squares using a function of n variable parameters * Ei the expected value of the function at i * Ei,a the gradient the function at i with respect to parameter a * Ei,b the gradient the function at i with respect to parameter b * </pre> * * @param I the Iab matrix * @param E the Ei_Eia_Eib matrix * @return the covariance matrix (or null) */ public static double[][] covariance(double[][] I, double[][] E) { final int n = I.length; // Invert the matrix final EjmlLinearSolver solver = EjmlLinearSolver.createForInversion(1e-2); if (!solver.invert(I)) { return null; } // Note that I now refers to I^-1 in the Mortensen notation final double[][] covar = new double[n][n]; for (int a = 0; a < n; a++) { for (int b = 0; b < n; b++) { double var = 0; for (int ap = 0; ap < n; ap++) { for (int bp = 0; bp < n; bp++) { var += I[a][ap] * E[ap][bp] * I[bp][b]; } } covar[a][b] = var; } } return covar; } /** * Compute the variance of the parameters of the function assuming a least squares fit of a * Poisson process. * * <p>Uses the Mortensen formula (Mortensen, et al (2010) Nature Methods 7, 377-383), equation 25. * * <p>The method involves inversion of a matrix and may fail. * * <pre> * I = sum_i { Ei,a * Ei,b } * E = sum_i { Ei * Ei,a * Ei,b } * with * i the number of data points fit using least squares using a function of n variable parameters * Ei the expected value of the function at i * Ei,a the gradient the function at i with respect to parameter a * Ei,b the gradient the function at i with respect to parameter b * </pre> * * @param I the Iab matrix * @param E the Ei_Eia_Eib matrix * @return the variance (or null) */ public static double[] variance(double[][] I, double[][] E) { final int n = I.length; // Invert the matrix final EjmlLinearSolver solver = EjmlLinearSolver.createForInversion(1e-2); if (!solver.invert(I)) { return null; } // Note that I now refers to I^-1 in the Mortensen notation final double[] covar = new double[n]; for (int a = 0; a < n; a++) { // Note: b==a as we only do the diagonal double var = 0; for (int ap = 0; ap < n; ap++) { for (int bp = 0; bp < n; bp++) { var += I[a][ap] * E[ap][bp] * I[bp][a]; } } covar[a] = var; } return covar; } }
[ "public", "abstract", "class", "LseBaseFunctionSolver", "extends", "BaseFunctionSolver", "implements", "LseFunctionSolver", "{", "/** The total sum of squares. */", "protected", "double", "totalSumOfSquares", "=", "Double", ".", "NaN", ";", "/**\n * Default constructor.\n *\n * @param function the function\n * @throws NullPointerException if the function is null\n */", "public", "LseBaseFunctionSolver", "(", "GradientFunction", "function", ")", "{", "super", "(", "FunctionSolverType", ".", "LSE", ",", "function", ")", ";", "}", "@", "Override", "protected", "void", "preProcess", "(", ")", "{", "totalSumOfSquares", "=", "Double", ".", "NaN", ";", "}", "/**\n * Gets the total sum of squares.\n *\n * @param y the y\n * @return the total sum of squares\n */", "public", "static", "double", "computeTotalSumOfSquares", "(", "double", "[", "]", "y", ")", "{", "double", "sx", "=", "0", ";", "double", "ssx", "=", "0", ";", "for", "(", "int", "i", "=", "y", ".", "length", ";", "i", "--", ">", "0", ";", ")", "{", "sx", "+=", "y", "[", "i", "]", ";", "ssx", "+=", "y", "[", "i", "]", "*", "y", "[", "i", "]", ";", "}", "return", "ssx", "-", "(", "sx", "*", "sx", ")", "/", "(", "y", ".", "length", ")", ";", "}", "/**\n * Compute the error.\n *\n * @param value the value\n * @param noise the noise\n * @param numberOfFittedPoints the number of fitted points\n * @param numberOfFittedParameters the number of fitted parameters\n * @return the error\n */", "public", "static", "double", "getError", "(", "double", "value", ",", "double", "noise", ",", "int", "numberOfFittedPoints", ",", "int", "numberOfFittedParameters", ")", "{", "double", "error", "=", "value", ";", "if", "(", "noise", ">", "0", ")", "{", "error", "/=", "numberOfFittedPoints", "*", "noise", "*", "noise", ";", "}", "if", "(", "numberOfFittedPoints", ">", "numberOfFittedParameters", ")", "{", "error", "/=", "(", "numberOfFittedPoints", "-", "numberOfFittedParameters", ")", ";", "}", "else", "{", "error", "=", "0", ";", "}", "return", "error", ";", "}", "@", "Override", "public", "double", "getTotalSumOfSquares", "(", ")", "{", "if", "(", "Double", ".", "isNaN", "(", "totalSumOfSquares", ")", "&&", "lastY", "!=", "null", ")", "{", "totalSumOfSquares", "=", "computeTotalSumOfSquares", "(", "lastY", ")", ";", "}", "return", "totalSumOfSquares", ";", "}", "@", "Override", "public", "double", "getResidualSumOfSquares", "(", ")", "{", "return", "value", ";", "}", "@", "Override", "public", "double", "getCoefficientOfDetermination", "(", ")", "{", "return", "1.0", "-", "(", "value", "/", "getTotalSumOfSquares", "(", ")", ")", ";", "}", "@", "Override", "public", "double", "getAdjustedCoefficientOfDetermination", "(", ")", "{", "return", "MathUtils", ".", "getAdjustedCoefficientOfDetermination", "(", "getResidualSumOfSquares", "(", ")", ",", "getTotalSumOfSquares", "(", ")", ",", "getNumberOfFittedPoints", "(", ")", ",", "getNumberOfFittedParameters", "(", ")", ")", ";", "}", "@", "Override", "public", "double", "getMeanSquaredError", "(", ")", "{", "return", "getResidualSumOfSquares", "(", ")", "/", "(", "getNumberOfFittedPoints", "(", ")", "-", "getNumberOfFittedParameters", "(", ")", ")", ";", "}", "/**\n * Compute the covariance matrix of the parameters of the function assuming a least squares fit of\n * a Poisson process.\n *\n * <p>Uses the Mortensen formula (Mortensen, et al (2010) Nature Methods 7, 377-383), equation 25.\n *\n * <p>The method involves inversion of a matrix and may fail.\n *\n * <pre>\n * I = sum_i { Ei,a * Ei,b }\n * E = sum_i { Ei * Ei,a * Ei,b }\n * with\n * i the number of data points fit using least squares using a function of n variable parameters\n * Ei the expected value of the function at i\n * Ei,a the gradient the function at i with respect to parameter a\n * Ei,b the gradient the function at i with respect to parameter b\n * </pre>\n *\n * @param I the Iab matrix\n * @param E the Ei_Eia_Eib matrix\n * @return the covariance matrix (or null)\n */", "public", "static", "double", "[", "]", "[", "]", "covariance", "(", "double", "[", "]", "[", "]", "I", ",", "double", "[", "]", "[", "]", "E", ")", "{", "final", "int", "n", "=", "I", ".", "length", ";", "final", "EjmlLinearSolver", "solver", "=", "EjmlLinearSolver", ".", "createForInversion", "(", "1e-2", ")", ";", "if", "(", "!", "solver", ".", "invert", "(", "I", ")", ")", "{", "return", "null", ";", "}", "final", "double", "[", "]", "[", "]", "covar", "=", "new", "double", "[", "n", "]", "[", "n", "]", ";", "for", "(", "int", "a", "=", "0", ";", "a", "<", "n", ";", "a", "++", ")", "{", "for", "(", "int", "b", "=", "0", ";", "b", "<", "n", ";", "b", "++", ")", "{", "double", "var", "=", "0", ";", "for", "(", "int", "ap", "=", "0", ";", "ap", "<", "n", ";", "ap", "++", ")", "{", "for", "(", "int", "bp", "=", "0", ";", "bp", "<", "n", ";", "bp", "++", ")", "{", "var", "+=", "I", "[", "a", "]", "[", "ap", "]", "*", "E", "[", "ap", "]", "[", "bp", "]", "*", "I", "[", "bp", "]", "[", "b", "]", ";", "}", "}", "covar", "[", "a", "]", "[", "b", "]", "=", "var", ";", "}", "}", "return", "covar", ";", "}", "/**\n * Compute the variance of the parameters of the function assuming a least squares fit of a\n * Poisson process.\n *\n * <p>Uses the Mortensen formula (Mortensen, et al (2010) Nature Methods 7, 377-383), equation 25.\n *\n * <p>The method involves inversion of a matrix and may fail.\n *\n * <pre>\n * I = sum_i { Ei,a * Ei,b }\n * E = sum_i { Ei * Ei,a * Ei,b }\n * with\n * i the number of data points fit using least squares using a function of n variable parameters\n * Ei the expected value of the function at i\n * Ei,a the gradient the function at i with respect to parameter a\n * Ei,b the gradient the function at i with respect to parameter b\n * </pre>\n *\n * @param I the Iab matrix\n * @param E the Ei_Eia_Eib matrix\n * @return the variance (or null)\n */", "public", "static", "double", "[", "]", "variance", "(", "double", "[", "]", "[", "]", "I", ",", "double", "[", "]", "[", "]", "E", ")", "{", "final", "int", "n", "=", "I", ".", "length", ";", "final", "EjmlLinearSolver", "solver", "=", "EjmlLinearSolver", ".", "createForInversion", "(", "1e-2", ")", ";", "if", "(", "!", "solver", ".", "invert", "(", "I", ")", ")", "{", "return", "null", ";", "}", "final", "double", "[", "]", "covar", "=", "new", "double", "[", "n", "]", ";", "for", "(", "int", "a", "=", "0", ";", "a", "<", "n", ";", "a", "++", ")", "{", "double", "var", "=", "0", ";", "for", "(", "int", "ap", "=", "0", ";", "ap", "<", "n", ";", "ap", "++", ")", "{", "for", "(", "int", "bp", "=", "0", ";", "bp", "<", "n", ";", "bp", "++", ")", "{", "var", "+=", "I", "[", "a", "]", "[", "ap", "]", "*", "E", "[", "ap", "]", "[", "bp", "]", "*", "I", "[", "bp", "]", "[", "a", "]", ";", "}", "}", "covar", "[", "a", "]", "=", "var", ";", "}", "return", "covar", ";", "}", "}" ]
Abstract class with utility methods for the {@link LseFunctionSolver} interface.
[ "Abstract", "class", "with", "utility", "methods", "for", "the", "{", "@link", "LseFunctionSolver", "}", "interface", "." ]
[ "// Divide by the uncertainty in the individual measurements yi to get the chi-squared", "// This updates the chi-squared value to the average error for a single fitted", "// point using the degrees of freedom (N-M)?", "// Note: This matches the mean squared error output from the MatLab fitting code.", "// If a noise estimate was provided for individual measurements then this will be the", "// reduced chi-square (see http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2892436/)", "// Allow I and E as they have special meaning in the formula.", "// CHECKSTYLE.OFF: ParameterName", "// Invert the matrix", "// Note that I now refers to I^-1 in the Mortensen notation", "// Invert the matrix", "// Note that I now refers to I^-1 in the Mortensen notation", "// Note: b==a as we only do the diagonal" ]
[ { "param": "BaseFunctionSolver", "type": null }, { "param": "LseFunctionSolver", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseFunctionSolver", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "LseFunctionSolver", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b4108ecf04746732d6b72b6639c03ee94b09aff
LenkayHuang/Onos-PNC-for-PCEP
core/common/src/test/java/org/onosproject/codec/impl/ObjectiveJsonMatcher.java
[ "Apache-2.0" ]
Java
ObjectiveJsonMatcher
/** * Hamcrest matcher for instructions. */
Hamcrest matcher for instructions.
[ "Hamcrest", "matcher", "for", "instructions", "." ]
public final class ObjectiveJsonMatcher { final Objective objective; private ObjectiveJsonMatcher(Objective objective) { this.objective = objective; } protected boolean matchesSafely(JsonNode jsonObjective) { // check operation String jsonOp = jsonObjective.get("operation").asText(); String op = objective.op().toString(); if (!jsonOp.equals(op)) { return false; } // check permanent boolean jsonPermanent = jsonObjective.get("isPermanent").asBoolean(); boolean permanent = objective.permanent(); if (jsonPermanent != permanent) { return false; } // check priority int jsonPriority = jsonObjective.get("priority").asInt(); int priority = objective.priority(); if (jsonPriority != priority) { return false; } // check timeout int jsonTimeout = jsonObjective.get("timeout").asInt(); int timeout = objective.timeout(); if (jsonTimeout != timeout) { return false; } return true; } /** * Factory to allocate a ObjectiveJsonMatcher. * * @param objective objective object we are looking for * @return matcher */ public static ObjectiveJsonMatcher matchesObjective(Objective objective) { return new ObjectiveJsonMatcher(objective); } }
[ "public", "final", "class", "ObjectiveJsonMatcher", "{", "final", "Objective", "objective", ";", "private", "ObjectiveJsonMatcher", "(", "Objective", "objective", ")", "{", "this", ".", "objective", "=", "objective", ";", "}", "protected", "boolean", "matchesSafely", "(", "JsonNode", "jsonObjective", ")", "{", "String", "jsonOp", "=", "jsonObjective", ".", "get", "(", "\"", "operation", "\"", ")", ".", "asText", "(", ")", ";", "String", "op", "=", "objective", ".", "op", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "!", "jsonOp", ".", "equals", "(", "op", ")", ")", "{", "return", "false", ";", "}", "boolean", "jsonPermanent", "=", "jsonObjective", ".", "get", "(", "\"", "isPermanent", "\"", ")", ".", "asBoolean", "(", ")", ";", "boolean", "permanent", "=", "objective", ".", "permanent", "(", ")", ";", "if", "(", "jsonPermanent", "!=", "permanent", ")", "{", "return", "false", ";", "}", "int", "jsonPriority", "=", "jsonObjective", ".", "get", "(", "\"", "priority", "\"", ")", ".", "asInt", "(", ")", ";", "int", "priority", "=", "objective", ".", "priority", "(", ")", ";", "if", "(", "jsonPriority", "!=", "priority", ")", "{", "return", "false", ";", "}", "int", "jsonTimeout", "=", "jsonObjective", ".", "get", "(", "\"", "timeout", "\"", ")", ".", "asInt", "(", ")", ";", "int", "timeout", "=", "objective", ".", "timeout", "(", ")", ";", "if", "(", "jsonTimeout", "!=", "timeout", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "/**\r\n * Factory to allocate a ObjectiveJsonMatcher.\r\n *\r\n * @param objective objective object we are looking for\r\n * @return matcher\r\n */", "public", "static", "ObjectiveJsonMatcher", "matchesObjective", "(", "Objective", "objective", ")", "{", "return", "new", "ObjectiveJsonMatcher", "(", "objective", ")", ";", "}", "}" ]
Hamcrest matcher for instructions.
[ "Hamcrest", "matcher", "for", "instructions", "." ]
[ "// check operation\r", "// check permanent\r", "// check priority\r", "// check timeout\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b41ab8e54e9664f26bb237401745c7512b50d91
richard-vu/java-core
spring-boot/fleet-managerment/src/main/java/com/richard/app/services/impl/UserServiceImpl.java
[ "MIT" ]
Java
UserServiceImpl
/** * @author richard * @param <S> * */
@author richard @param
[ "@author", "richard", "@param" ]
@Service @Slf4j public class UserServiceImpl<S> implements UserService { @Autowired private UserRepository userRepository; @Autowired Utils utils; /** * Create User */ @Override public Notification createUser(UserDto userDto) { if (userRepository.findByEmail(userDto.getEmail()) != null) { throw new UserServiceException(HttpStatus.CONFLICT, "Record already exists"); } UserEntity userEntity = new UserEntity(); ModelMapper modelMapper = new ModelMapper(); userEntity = modelMapper.map(userDto, UserEntity.class); String publicUserId = utils.generateUserId(30); userEntity.setUserId(publicUserId); userEntity.setEncryptedPassword(MD5.getMd5(userDto.getPassword())); userEntity.setEmailVerificationStatus(false); for (AddressEntity addressEntity : userEntity.getAddresses()) { addressEntity.setUserDetails(userEntity); } userRepository.save(userEntity); return new Notification(HttpStatus.CREATED, "User was created"); } @Override public Notification createAllUser(List<UserDto> listUserDto) { Type listType = new TypeToken<List<UserEntity>>() { }.getType(); List<UserEntity> listUserEntity = new ModelMapper().map(listUserDto, listType); for (UserEntity userEntity : listUserEntity) { String publicUserId = utils.generateUserId(30); userEntity.setUserId(publicUserId); userEntity.setEncryptedPassword(MD5.getMd5("123123123")); userEntity.setEmailVerificationStatus(false); for (AddressEntity addressEntity : userEntity.getAddresses()) { addressEntity.setUserDetails(userEntity); } } userRepository.saveAll(listUserEntity); return new Notification(HttpStatus.CREATED, "List User was created"); } /** * Get All Users */ @Override public List<UserDetailsReponseModel> getAllUsers() { List<UserEntity> listUserEntity = new ArrayList<>(); userRepository.findAll().forEach(listUserEntity::add); if (listUserEntity.isEmpty()) { log.error("Database is null"); throw new UserServiceException(HttpStatus.BAD_REQUEST, "Database is null"); } // Create Conversion Type Type listType = new TypeToken<List<UserDetailsReponseModel>>() { }.getType(); // Convert List of Entity objects to a List of DTOs objects List<UserDetailsReponseModel> listUserResponse = new ModelMapper().map(listUserEntity, listType); log.info("debug enabled: {}", log.isDebugEnabled()); return listUserResponse; } @Override public UserDetailsReponseModel getUserById(Long id) { ModelMapper modelMapper = new ModelMapper(); Optional<UserEntity> userEntity = userRepository.findById(id); UserDetailsReponseModel userDetailsReponseModel = modelMapper.map(userEntity.get(), UserDetailsReponseModel.class); return userDetailsReponseModel; } @Override public Notification updateUserByUserId(String id, UserDetailsRequestEditModel userDetailsRequestEditModel) { UserEntity userEntity = userRepository.findUserByUserId(id); if (userEntity == null) { throw new UserServiceException(HttpStatus.BAD_REQUEST, "User does not exits"); } userEntity.setFirstName(userDetailsRequestEditModel.getFirstName()); userEntity.setLastName(userDetailsRequestEditModel.getLastName()); userRepository.save(userEntity); return new Notification(HttpStatus.OK, "User was update"); } @Override public Notification deleleByUserId(String id) { UserEntity userEntity = userRepository.findUserByUserId(id); if (userEntity == null) { throw new UserServiceException(HttpStatus.BAD_REQUEST, "User does not exits"); } userRepository.delete(userEntity); return new Notification(HttpStatus.OK, "User was delete"); } @Override public Notification deleleAllUser() { userRepository.deleteAll(); return new Notification(HttpStatus.OK, "Users was delete"); } }
[ "@", "Service", "@", "Slf4j", "public", "class", "UserServiceImpl", "<", "S", ">", "implements", "UserService", "{", "@", "Autowired", "private", "UserRepository", "userRepository", ";", "@", "Autowired", "Utils", "utils", ";", "/**\n * Create User\n */", "@", "Override", "public", "Notification", "createUser", "(", "UserDto", "userDto", ")", "{", "if", "(", "userRepository", ".", "findByEmail", "(", "userDto", ".", "getEmail", "(", ")", ")", "!=", "null", ")", "{", "throw", "new", "UserServiceException", "(", "HttpStatus", ".", "CONFLICT", ",", "\"", "Record already exists", "\"", ")", ";", "}", "UserEntity", "userEntity", "=", "new", "UserEntity", "(", ")", ";", "ModelMapper", "modelMapper", "=", "new", "ModelMapper", "(", ")", ";", "userEntity", "=", "modelMapper", ".", "map", "(", "userDto", ",", "UserEntity", ".", "class", ")", ";", "String", "publicUserId", "=", "utils", ".", "generateUserId", "(", "30", ")", ";", "userEntity", ".", "setUserId", "(", "publicUserId", ")", ";", "userEntity", ".", "setEncryptedPassword", "(", "MD5", ".", "getMd5", "(", "userDto", ".", "getPassword", "(", ")", ")", ")", ";", "userEntity", ".", "setEmailVerificationStatus", "(", "false", ")", ";", "for", "(", "AddressEntity", "addressEntity", ":", "userEntity", ".", "getAddresses", "(", ")", ")", "{", "addressEntity", ".", "setUserDetails", "(", "userEntity", ")", ";", "}", "userRepository", ".", "save", "(", "userEntity", ")", ";", "return", "new", "Notification", "(", "HttpStatus", ".", "CREATED", ",", "\"", "User was created", "\"", ")", ";", "}", "@", "Override", "public", "Notification", "createAllUser", "(", "List", "<", "UserDto", ">", "listUserDto", ")", "{", "Type", "listType", "=", "new", "TypeToken", "<", "List", "<", "UserEntity", ">", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "List", "<", "UserEntity", ">", "listUserEntity", "=", "new", "ModelMapper", "(", ")", ".", "map", "(", "listUserDto", ",", "listType", ")", ";", "for", "(", "UserEntity", "userEntity", ":", "listUserEntity", ")", "{", "String", "publicUserId", "=", "utils", ".", "generateUserId", "(", "30", ")", ";", "userEntity", ".", "setUserId", "(", "publicUserId", ")", ";", "userEntity", ".", "setEncryptedPassword", "(", "MD5", ".", "getMd5", "(", "\"", "123123123", "\"", ")", ")", ";", "userEntity", ".", "setEmailVerificationStatus", "(", "false", ")", ";", "for", "(", "AddressEntity", "addressEntity", ":", "userEntity", ".", "getAddresses", "(", ")", ")", "{", "addressEntity", ".", "setUserDetails", "(", "userEntity", ")", ";", "}", "}", "userRepository", ".", "saveAll", "(", "listUserEntity", ")", ";", "return", "new", "Notification", "(", "HttpStatus", ".", "CREATED", ",", "\"", "List User was created", "\"", ")", ";", "}", "/**\n * Get All Users\n */", "@", "Override", "public", "List", "<", "UserDetailsReponseModel", ">", "getAllUsers", "(", ")", "{", "List", "<", "UserEntity", ">", "listUserEntity", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "userRepository", ".", "findAll", "(", ")", ".", "forEach", "(", "listUserEntity", "::", "add", ")", ";", "if", "(", "listUserEntity", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "error", "(", "\"", "Database is null", "\"", ")", ";", "throw", "new", "UserServiceException", "(", "HttpStatus", ".", "BAD_REQUEST", ",", "\"", "Database is null", "\"", ")", ";", "}", "Type", "listType", "=", "new", "TypeToken", "<", "List", "<", "UserDetailsReponseModel", ">", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "List", "<", "UserDetailsReponseModel", ">", "listUserResponse", "=", "new", "ModelMapper", "(", ")", ".", "map", "(", "listUserEntity", ",", "listType", ")", ";", "log", ".", "info", "(", "\"", "debug enabled: {}", "\"", ",", "log", ".", "isDebugEnabled", "(", ")", ")", ";", "return", "listUserResponse", ";", "}", "@", "Override", "public", "UserDetailsReponseModel", "getUserById", "(", "Long", "id", ")", "{", "ModelMapper", "modelMapper", "=", "new", "ModelMapper", "(", ")", ";", "Optional", "<", "UserEntity", ">", "userEntity", "=", "userRepository", ".", "findById", "(", "id", ")", ";", "UserDetailsReponseModel", "userDetailsReponseModel", "=", "modelMapper", ".", "map", "(", "userEntity", ".", "get", "(", ")", ",", "UserDetailsReponseModel", ".", "class", ")", ";", "return", "userDetailsReponseModel", ";", "}", "@", "Override", "public", "Notification", "updateUserByUserId", "(", "String", "id", ",", "UserDetailsRequestEditModel", "userDetailsRequestEditModel", ")", "{", "UserEntity", "userEntity", "=", "userRepository", ".", "findUserByUserId", "(", "id", ")", ";", "if", "(", "userEntity", "==", "null", ")", "{", "throw", "new", "UserServiceException", "(", "HttpStatus", ".", "BAD_REQUEST", ",", "\"", "User does not exits", "\"", ")", ";", "}", "userEntity", ".", "setFirstName", "(", "userDetailsRequestEditModel", ".", "getFirstName", "(", ")", ")", ";", "userEntity", ".", "setLastName", "(", "userDetailsRequestEditModel", ".", "getLastName", "(", ")", ")", ";", "userRepository", ".", "save", "(", "userEntity", ")", ";", "return", "new", "Notification", "(", "HttpStatus", ".", "OK", ",", "\"", "User was update", "\"", ")", ";", "}", "@", "Override", "public", "Notification", "deleleByUserId", "(", "String", "id", ")", "{", "UserEntity", "userEntity", "=", "userRepository", ".", "findUserByUserId", "(", "id", ")", ";", "if", "(", "userEntity", "==", "null", ")", "{", "throw", "new", "UserServiceException", "(", "HttpStatus", ".", "BAD_REQUEST", ",", "\"", "User does not exits", "\"", ")", ";", "}", "userRepository", ".", "delete", "(", "userEntity", ")", ";", "return", "new", "Notification", "(", "HttpStatus", ".", "OK", ",", "\"", "User was delete", "\"", ")", ";", "}", "@", "Override", "public", "Notification", "deleleAllUser", "(", ")", "{", "userRepository", ".", "deleteAll", "(", ")", ";", "return", "new", "Notification", "(", "HttpStatus", ".", "OK", ",", "\"", "Users was delete", "\"", ")", ";", "}", "}" ]
@author richard @param <S>
[ "@author", "richard", "@param", "<S", ">" ]
[ "// Create Conversion Type", "// Convert List of Entity objects to a List of DTOs objects " ]
[ { "param": "UserService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "UserService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b441555b15774cc94d1ded3df6421ca4146bfde
hsjawanda/firestore-repository
src/main/java/com/hsjawanda/firestorerepository/util/ErrorHelper.java
[ "Apache-2.0" ]
Java
ErrorHelper
/** * @author Harshdeep S Jawanda <hsjawanda@gmail.com> * */
@author Harshdeep S Jawanda
[ "@author", "Harshdeep", "S", "Jawanda" ]
public final class ErrorHelper { private static final int INITIAL_SIZE = 200; private ErrorHelper() { } public static boolean causedBy(Exception e, Class<? extends Exception> checkAgainst) { if (null != e && null != checkAgainst) { Throwable cause = e.getCause(); if (cause != null && cause.getClass().equals(checkAgainst)) return true; } return false; } public static String logException(Throwable e, @Nullable String prefix) { StringWriter log = new StringWriter(INITIAL_SIZE); if (isNotBlank(prefix)) { log.append(prefix).append(NL); } e.printStackTrace(new PrintWriter(log)); return log.toString(); } }
[ "public", "final", "class", "ErrorHelper", "{", "private", "static", "final", "int", "INITIAL_SIZE", "=", "200", ";", "private", "ErrorHelper", "(", ")", "{", "}", "public", "static", "boolean", "causedBy", "(", "Exception", "e", ",", "Class", "<", "?", "extends", "Exception", ">", "checkAgainst", ")", "{", "if", "(", "null", "!=", "e", "&&", "null", "!=", "checkAgainst", ")", "{", "Throwable", "cause", "=", "e", ".", "getCause", "(", ")", ";", "if", "(", "cause", "!=", "null", "&&", "cause", ".", "getClass", "(", ")", ".", "equals", "(", "checkAgainst", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}", "public", "static", "String", "logException", "(", "Throwable", "e", ",", "@", "Nullable", "String", "prefix", ")", "{", "StringWriter", "log", "=", "new", "StringWriter", "(", "INITIAL_SIZE", ")", ";", "if", "(", "isNotBlank", "(", "prefix", ")", ")", "{", "log", ".", "append", "(", "prefix", ")", ".", "append", "(", "NL", ")", ";", "}", "e", ".", "printStackTrace", "(", "new", "PrintWriter", "(", "log", ")", ")", ";", "return", "log", ".", "toString", "(", ")", ";", "}", "}" ]
@author Harshdeep S Jawanda <hsjawanda@gmail.com>
[ "@author", "Harshdeep", "S", "Jawanda", "<hsjawanda@gmail", ".", "com", ">" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b4767c8716fcc890ae6bd1e4330502b51e1c7c2
xgp/scribe
flume-scribe-sink/src/test/java/org/apache/flume/sink/scribe/ScribeSinkTest.java
[ "Apache-2.0" ]
Java
ScribeSinkTest
/** * Not really a unit test */
Not really a unit test
[ "Not", "really", "a", "unit", "test" ]
@Ignore public class ScribeSinkTest { private AsyncScribeSink sink = new AsyncScribeSink(); @Before public void setUp() throws Exception { Context ctx = new Context(); ctx.put(ScribeSinkConfigurationConstants.CONFIG_SERIALIZER, EventToLogEntrySerializer.class.getName()); ctx.put(ScribeSinkConfigurationConstants.CONFIG_SCRIBE_HOST, "127.0.0.1"); ctx.put(ScribeSinkConfigurationConstants.CONFIG_SCRIBE_PORT, "1463"); ctx.put(ScribeSinkConfigurationConstants.CONFIG_SCRIBE_CATEGORY_HEADER, ScribeSinkConfigurationConstants.CONFIG_SCRIBE_CATEGORY); sink.configure(ctx); PseudoTxnMemoryChannel c = new PseudoTxnMemoryChannel(); c.configure(ctx); c.start(); sink.setChannel(c); sink.start(); } @After public void tearDown() throws Exception { Thread.sleep(1000); sink.getChannel().stop(); sink.stop(); } @Test public void testProcess() throws Exception { Event e = new SimpleEvent(); e.getHeaders().put(ScribeSinkConfigurationConstants.CONFIG_SCRIBE_CATEGORY, "default1"); e.setBody("This is test ".getBytes()); sink.getChannel().put(e); sink.process(); } public static void main(String[] argv) throws Exception { ScribeSinkTest test = new ScribeSinkTest(); test.setUp(); test.testProcess(); test.tearDown(); } }
[ "@", "Ignore", "public", "class", "ScribeSinkTest", "{", "private", "AsyncScribeSink", "sink", "=", "new", "AsyncScribeSink", "(", ")", ";", "@", "Before", "public", "void", "setUp", "(", ")", "throws", "Exception", "{", "Context", "ctx", "=", "new", "Context", "(", ")", ";", "ctx", ".", "put", "(", "ScribeSinkConfigurationConstants", ".", "CONFIG_SERIALIZER", ",", "EventToLogEntrySerializer", ".", "class", ".", "getName", "(", ")", ")", ";", "ctx", ".", "put", "(", "ScribeSinkConfigurationConstants", ".", "CONFIG_SCRIBE_HOST", ",", "\"", "127.0.0.1", "\"", ")", ";", "ctx", ".", "put", "(", "ScribeSinkConfigurationConstants", ".", "CONFIG_SCRIBE_PORT", ",", "\"", "1463", "\"", ")", ";", "ctx", ".", "put", "(", "ScribeSinkConfigurationConstants", ".", "CONFIG_SCRIBE_CATEGORY_HEADER", ",", "ScribeSinkConfigurationConstants", ".", "CONFIG_SCRIBE_CATEGORY", ")", ";", "sink", ".", "configure", "(", "ctx", ")", ";", "PseudoTxnMemoryChannel", "c", "=", "new", "PseudoTxnMemoryChannel", "(", ")", ";", "c", ".", "configure", "(", "ctx", ")", ";", "c", ".", "start", "(", ")", ";", "sink", ".", "setChannel", "(", "c", ")", ";", "sink", ".", "start", "(", ")", ";", "}", "@", "After", "public", "void", "tearDown", "(", ")", "throws", "Exception", "{", "Thread", ".", "sleep", "(", "1000", ")", ";", "sink", ".", "getChannel", "(", ")", ".", "stop", "(", ")", ";", "sink", ".", "stop", "(", ")", ";", "}", "@", "Test", "public", "void", "testProcess", "(", ")", "throws", "Exception", "{", "Event", "e", "=", "new", "SimpleEvent", "(", ")", ";", "e", ".", "getHeaders", "(", ")", ".", "put", "(", "ScribeSinkConfigurationConstants", ".", "CONFIG_SCRIBE_CATEGORY", ",", "\"", "default1", "\"", ")", ";", "e", ".", "setBody", "(", "\"", "This is test ", "\"", ".", "getBytes", "(", ")", ")", ";", "sink", ".", "getChannel", "(", ")", ".", "put", "(", "e", ")", ";", "sink", ".", "process", "(", ")", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "argv", ")", "throws", "Exception", "{", "ScribeSinkTest", "test", "=", "new", "ScribeSinkTest", "(", ")", ";", "test", ".", "setUp", "(", ")", ";", "test", ".", "testProcess", "(", ")", ";", "test", ".", "tearDown", "(", ")", ";", "}", "}" ]
Not really a unit test
[ "Not", "really", "a", "unit", "test" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b495073c217e93526638c5cbc52656ba66e6796
softwaremill/softwaremill-common
softwaremill-sqs/src/main/java/com/softwaremill/common/task/ExecuteWithRequestContext.java
[ "Apache-2.0" ]
Java
ExecuteWithRequestContext
/** * @author Adam Warski (adam at warski dot org) */
@author Adam Warski (adam at warski dot org)
[ "@author", "Adam", "Warski", "(", "adam", "at", "warski", "dot", "org", ")" ]
public class ExecuteWithRequestContext { private final Task task; public ExecuteWithRequestContext(Task task) { this.task = task; } public void execute() { doExecute(task); } private <T extends Task<T>> void doExecute(T task) { BoundRequestContext requestContext = D.inject(BoundRequestContext.class); Map<String, Object> context = new HashMap<String, Object>(); try { requestContext.associate(context); requestContext.activate(); D.inject(task.getExecutorBeanClass()).execute(task); } finally { requestContext.invalidate(); requestContext.deactivate(); requestContext.dissociate(context); } } }
[ "public", "class", "ExecuteWithRequestContext", "{", "private", "final", "Task", "task", ";", "public", "ExecuteWithRequestContext", "(", "Task", "task", ")", "{", "this", ".", "task", "=", "task", ";", "}", "public", "void", "execute", "(", ")", "{", "doExecute", "(", "task", ")", ";", "}", "private", "<", "T", "extends", "Task", "<", "T", ">", ">", "void", "doExecute", "(", "T", "task", ")", "{", "BoundRequestContext", "requestContext", "=", "D", ".", "inject", "(", "BoundRequestContext", ".", "class", ")", ";", "Map", "<", "String", ",", "Object", ">", "context", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "try", "{", "requestContext", ".", "associate", "(", "context", ")", ";", "requestContext", ".", "activate", "(", ")", ";", "D", ".", "inject", "(", "task", ".", "getExecutorBeanClass", "(", ")", ")", ".", "execute", "(", "task", ")", ";", "}", "finally", "{", "requestContext", ".", "invalidate", "(", ")", ";", "requestContext", ".", "deactivate", "(", ")", ";", "requestContext", ".", "dissociate", "(", "context", ")", ";", "}", "}", "}" ]
@author Adam Warski (adam at warski dot org)
[ "@author", "Adam", "Warski", "(", "adam", "at", "warski", "dot", "org", ")" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b4d70d85b1a51c8381d59582948adca8b88610c
atveit/vespa
config-model/src/main/java/com/yahoo/searchdefinition/RankProfileRegistry.java
[ "Apache-2.0" ]
Java
RankProfileRegistry
/** * Mapping from name to {@link RankProfile} as well as a reverse mapping of {@link RankProfile} to {@link Search}. * Having both of these mappings consolidated here make it easier to remove dependencies on these mappings at * run time, since it is essentially only used when building rank profile config at deployment time. * * TODO: Rank profiles should be stored under its owning Search instance. * * @author Ulf Lilleengen */
Mapping from name to RankProfile as well as a reverse mapping of RankProfile to Search. Having both of these mappings consolidated here make it easier to remove dependencies on these mappings at run time, since it is essentially only used when building rank profile config at deployment time. Rank profiles should be stored under its owning Search instance. @author Ulf Lilleengen
[ "Mapping", "from", "name", "to", "RankProfile", "as", "well", "as", "a", "reverse", "mapping", "of", "RankProfile", "to", "Search", ".", "Having", "both", "of", "these", "mappings", "consolidated", "here", "make", "it", "easier", "to", "remove", "dependencies", "on", "these", "mappings", "at", "run", "time", "since", "it", "is", "essentially", "only", "used", "when", "building", "rank", "profile", "config", "at", "deployment", "time", ".", "Rank", "profiles", "should", "be", "stored", "under", "its", "owning", "Search", "instance", ".", "@author", "Ulf", "Lilleengen" ]
public class RankProfileRegistry { private final Map<RankProfile, Search> rankProfileToSearch = new LinkedHashMap<>(); private final Map<Search, Map<String, RankProfile>> rankProfiles = new LinkedHashMap<>(); private final ExpressionTransforms expressionTransforms = new ExpressionTransforms(); /* These rank profiles can be overridden: 'default' rank profile, as that is documented to work. And 'unranked'. */ static final Set<String> overridableRankProfileNames = new HashSet<>(Arrays.asList("default", "unranked")); public static RankProfileRegistry createRankProfileRegistryWithBuiltinRankProfiles(Search search) { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); rankProfileRegistry.addRankProfile(new DefaultRankProfile(search, rankProfileRegistry)); rankProfileRegistry.addRankProfile(new UnrankedRankProfile(search, rankProfileRegistry)); return rankProfileRegistry; } /** * Adds a rank profile to this registry * * @param rankProfile the rank profile to add */ public void addRankProfile(RankProfile rankProfile) { if ( ! rankProfiles.containsKey(rankProfile.getSearch())) { rankProfiles.put(rankProfile.getSearch(), new LinkedHashMap<>()); } checkForDuplicateRankProfile(rankProfile); rankProfiles.get(rankProfile.getSearch()).put(rankProfile.getName(), rankProfile); rankProfileToSearch.put(rankProfile, rankProfile.getSearch()); } private void checkForDuplicateRankProfile(RankProfile rankProfile) { final String rankProfileName = rankProfile.getName(); RankProfile existingRangProfileWithSameName = rankProfiles.get(rankProfile.getSearch()).get(rankProfileName); if (existingRangProfileWithSameName == null) return; if (!overridableRankProfileNames.contains(rankProfileName)) { throw new IllegalArgumentException("Cannot add rank profile '" + rankProfileName + "' in search definition '" + rankProfile.getSearch().getName() + "', since it already exists"); } } /** * Returns a named rank profile, null if the search definition doesn't have one with the given name * * @param search The {@link Search} that owns the rank profile. * @param name The name of the rank profile * @return The RankProfile to return. */ public RankProfile getRankProfile(Search search, String name) { return rankProfiles.get(search).get(name); } /** * Rank profiles that are collected across clusters. * @return A set of global {@link RankProfile} instances. */ public Set<RankProfile> allRankProfiles() { return rankProfileToSearch.keySet(); } /** * Rank profiles that are collected for a given search definition * @param search {@link Search} to get rank profiles for. * @return A collection of local {@link RankProfile} instances. */ public Collection<RankProfile> localRankProfiles(Search search) { Map<String, RankProfile> mapping = rankProfiles.get(search); if (mapping == null) { return Collections.emptyList(); } return mapping.values(); } /** * Returns the ranking expression transforms that should be performed on all expressions in this. * This instance (and hence the instances of individual transformers) has the lifetime of a single * application package deployment. */ public ExpressionTransforms expressionTransforms() { return expressionTransforms; } }
[ "public", "class", "RankProfileRegistry", "{", "private", "final", "Map", "<", "RankProfile", ",", "Search", ">", "rankProfileToSearch", "=", "new", "LinkedHashMap", "<", ">", "(", ")", ";", "private", "final", "Map", "<", "Search", ",", "Map", "<", "String", ",", "RankProfile", ">", ">", "rankProfiles", "=", "new", "LinkedHashMap", "<", ">", "(", ")", ";", "private", "final", "ExpressionTransforms", "expressionTransforms", "=", "new", "ExpressionTransforms", "(", ")", ";", "/* These rank profiles can be overridden: 'default' rank profile, as that is documented to work. And 'unranked'. */", "static", "final", "Set", "<", "String", ">", "overridableRankProfileNames", "=", "new", "HashSet", "<", ">", "(", "Arrays", ".", "asList", "(", "\"", "default", "\"", ",", "\"", "unranked", "\"", ")", ")", ";", "public", "static", "RankProfileRegistry", "createRankProfileRegistryWithBuiltinRankProfiles", "(", "Search", "search", ")", "{", "RankProfileRegistry", "rankProfileRegistry", "=", "new", "RankProfileRegistry", "(", ")", ";", "rankProfileRegistry", ".", "addRankProfile", "(", "new", "DefaultRankProfile", "(", "search", ",", "rankProfileRegistry", ")", ")", ";", "rankProfileRegistry", ".", "addRankProfile", "(", "new", "UnrankedRankProfile", "(", "search", ",", "rankProfileRegistry", ")", ")", ";", "return", "rankProfileRegistry", ";", "}", "/**\n * Adds a rank profile to this registry\n *\n * @param rankProfile the rank profile to add\n */", "public", "void", "addRankProfile", "(", "RankProfile", "rankProfile", ")", "{", "if", "(", "!", "rankProfiles", ".", "containsKey", "(", "rankProfile", ".", "getSearch", "(", ")", ")", ")", "{", "rankProfiles", ".", "put", "(", "rankProfile", ".", "getSearch", "(", ")", ",", "new", "LinkedHashMap", "<", ">", "(", ")", ")", ";", "}", "checkForDuplicateRankProfile", "(", "rankProfile", ")", ";", "rankProfiles", ".", "get", "(", "rankProfile", ".", "getSearch", "(", ")", ")", ".", "put", "(", "rankProfile", ".", "getName", "(", ")", ",", "rankProfile", ")", ";", "rankProfileToSearch", ".", "put", "(", "rankProfile", ",", "rankProfile", ".", "getSearch", "(", ")", ")", ";", "}", "private", "void", "checkForDuplicateRankProfile", "(", "RankProfile", "rankProfile", ")", "{", "final", "String", "rankProfileName", "=", "rankProfile", ".", "getName", "(", ")", ";", "RankProfile", "existingRangProfileWithSameName", "=", "rankProfiles", ".", "get", "(", "rankProfile", ".", "getSearch", "(", ")", ")", ".", "get", "(", "rankProfileName", ")", ";", "if", "(", "existingRangProfileWithSameName", "==", "null", ")", "return", ";", "if", "(", "!", "overridableRankProfileNames", ".", "contains", "(", "rankProfileName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Cannot add rank profile '", "\"", "+", "rankProfileName", "+", "\"", "' in search definition '", "\"", "+", "rankProfile", ".", "getSearch", "(", ")", ".", "getName", "(", ")", "+", "\"", "', since it already exists", "\"", ")", ";", "}", "}", "/**\n * Returns a named rank profile, null if the search definition doesn't have one with the given name\n *\n * @param search The {@link Search} that owns the rank profile.\n * @param name The name of the rank profile\n * @return The RankProfile to return.\n */", "public", "RankProfile", "getRankProfile", "(", "Search", "search", ",", "String", "name", ")", "{", "return", "rankProfiles", ".", "get", "(", "search", ")", ".", "get", "(", "name", ")", ";", "}", "/**\n * Rank profiles that are collected across clusters.\n * @return A set of global {@link RankProfile} instances.\n */", "public", "Set", "<", "RankProfile", ">", "allRankProfiles", "(", ")", "{", "return", "rankProfileToSearch", ".", "keySet", "(", ")", ";", "}", "/**\n * Rank profiles that are collected for a given search definition\n * @param search {@link Search} to get rank profiles for.\n * @return A collection of local {@link RankProfile} instances.\n */", "public", "Collection", "<", "RankProfile", ">", "localRankProfiles", "(", "Search", "search", ")", "{", "Map", "<", "String", ",", "RankProfile", ">", "mapping", "=", "rankProfiles", ".", "get", "(", "search", ")", ";", "if", "(", "mapping", "==", "null", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "return", "mapping", ".", "values", "(", ")", ";", "}", "/**\n * Returns the ranking expression transforms that should be performed on all expressions in this.\n * This instance (and hence the instances of individual transformers) has the lifetime of a single\n * application package deployment.\n */", "public", "ExpressionTransforms", "expressionTransforms", "(", ")", "{", "return", "expressionTransforms", ";", "}", "}" ]
Mapping from name to {@link RankProfile} as well as a reverse mapping of {@link RankProfile} to {@link Search}.
[ "Mapping", "from", "name", "to", "{", "@link", "RankProfile", "}", "as", "well", "as", "a", "reverse", "mapping", "of", "{", "@link", "RankProfile", "}", "to", "{", "@link", "Search", "}", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b4e0e7223f8754ebfdef36cddb4cda0f30f9892
gzimax/plugin
src/main/java/com/unboundid/ops/models/StatusError.java
[ "Apache-2.0" ]
Java
StatusError
/** * A status error. * * @author Jacob Childress */
A status error. @author Jacob Childress
[ "A", "status", "error", ".", "@author", "Jacob", "Childress" ]
public class StatusError { private final Throwable cause; private final String message; /** * Constructor. * * @param throwable * The {@link Throwable} that this object represents. */ public StatusError(Throwable throwable) { this.cause = throwable; this.message = throwable.getMessage(); } /** * Gets the error cause. * * @return The error cause. */ public Throwable getCause() { return cause; } /** * Gets the error message. * * @return The error message. */ public String getMessage() { return message; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StatusError error = (StatusError) o; return message.equals(error.message); } /** {@inheritDoc} */ @Override public int hashCode() { return message.hashCode(); } }
[ "public", "class", "StatusError", "{", "private", "final", "Throwable", "cause", ";", "private", "final", "String", "message", ";", "/**\n * Constructor.\n *\n * @param throwable\n * The {@link Throwable} that this object represents.\n */", "public", "StatusError", "(", "Throwable", "throwable", ")", "{", "this", ".", "cause", "=", "throwable", ";", "this", ".", "message", "=", "throwable", ".", "getMessage", "(", ")", ";", "}", "/**\n * Gets the error cause.\n *\n * @return The error cause.\n */", "public", "Throwable", "getCause", "(", ")", "{", "return", "cause", ";", "}", "/**\n * Gets the error message.\n *\n * @return The error message.\n */", "public", "String", "getMessage", "(", ")", "{", "return", "message", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "return", "true", ";", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "return", "false", ";", "StatusError", "error", "=", "(", "StatusError", ")", "o", ";", "return", "message", ".", "equals", "(", "error", ".", "message", ")", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "message", ".", "hashCode", "(", ")", ";", "}", "}" ]
A status error.
[ "A", "status", "error", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b51473d75c36e2c88c934cc6431ee01a393923a
VU-libtech/OLE-INST
ole-app/olefs/src/main/java/org/kuali/ole/coa/businessobject/AccountDelegateGlobal.java
[ "ECL-2.0" ]
Java
AccountDelegateGlobal
/** * This class simply acts as a container to hold the List of Delegate Changes and the list of Account entries, for the Global * Delegate Change Document. */
This class simply acts as a container to hold the List of Delegate Changes and the list of Account entries, for the Global Delegate Change Document.
[ "This", "class", "simply", "acts", "as", "a", "container", "to", "hold", "the", "List", "of", "Delegate", "Changes", "and", "the", "list", "of", "Account", "entries", "for", "the", "Global", "Delegate", "Change", "Document", "." ]
public class AccountDelegateGlobal extends PersistableBusinessObjectBase implements GlobalBusinessObject { protected String documentNumber; protected String modelName; protected String modelChartOfAccountsCode; protected String modelOrganizationCode; protected AccountDelegateModel model; protected List<AccountGlobalDetail> accountGlobalDetails; protected List<AccountDelegateGlobalDetail> delegateGlobals; /** * Constructs a DelegateGlobal.java. */ public AccountDelegateGlobal() { super(); accountGlobalDetails = new ArrayList<AccountGlobalDetail>(); delegateGlobals = new ArrayList<AccountDelegateGlobalDetail>(); } /** * This method adds a single AccountGlobalDetail instance to the list. If one is already present in the list with the same * chartCode and accountNumber, then this new one will not be added. * * @param accountGlobalDetail - populated AccountGlobalDetail instance */ public void addAccount(AccountGlobalDetail accountGlobalDetail) { // validate the argument if (accountGlobalDetail == null) { throw new IllegalArgumentException("The accountGlobalDetail instanced passed in was null."); } else if (StringUtils.isBlank(accountGlobalDetail.getChartOfAccountsCode())) { throw new IllegalArgumentException("The chartOfAccountsCode member of the accountGlobalDetail object was not populated."); } else if (StringUtils.isBlank(accountGlobalDetail.getAccountNumber())) { throw new IllegalArgumentException("The accountNumber member of the accountGlobalDetail object was not populated."); } // add the object if one doesnt already exist, otherwise silently do nothing AccountGlobalDetail testObject = getAccount(accountGlobalDetail.getChartOfAccountsCode(), accountGlobalDetail.getAccountNumber()); if (testObject == null) { this.accountGlobalDetails.add(accountGlobalDetail); } } /** * This method retrieves the specific AccountGlobalDetail object that corresponds to your requested chartCode and accountNumber * (or a null object if there is no match). * * @param chartCode * @param accountNumber * @return returns the AccountGlobalDetail instance matching the chartCode & accountNumber passed in, or Null if none match */ public AccountGlobalDetail getAccount(String chartCode, String accountNumber) { // validate the argument if (StringUtils.isBlank(chartCode)) { throw new IllegalArgumentException("The chartCode argument was null or empty."); } else if (StringUtils.isBlank(accountNumber)) { throw new IllegalArgumentException("The accountNumber argument was null or empty."); } // walk the list of AccountGlobalDetail objects for (Iterator iter = this.accountGlobalDetails.iterator(); iter.hasNext();) { AccountGlobalDetail accountGlobalDetail = (AccountGlobalDetail) iter.next(); // if this one is a match, then quit if (chartCode.equalsIgnoreCase(accountGlobalDetail.getChartOfAccountsCode()) && accountNumber.equalsIgnoreCase(accountGlobalDetail.getAccountNumber())) { return accountGlobalDetail; } } // we return null if one is not found return null; } /** * @see org.kuali.rice.krad.document.GlobalBusinessObject#getGlobalChangesToDelete() */ public List<PersistableBusinessObject> generateDeactivationsToPersist() { BusinessObjectService boService = SpringContext.getBean(BusinessObjectService.class); // retreive all the existing delegates for these accounts List<AccountDelegate> bosToDeactivate = new ArrayList(); Map<String, Object> fieldValues; Collection existingDelegates; for (AccountGlobalDetail accountDetail : getAccountGlobalDetails()) { fieldValues = new HashMap(); fieldValues.put("chartOfAccountsCode", accountDetail.getChartOfAccountsCode()); fieldValues.put("accountNumber", accountDetail.getAccountNumber()); fieldValues.put("active", true); existingDelegates = boService.findMatching(AccountDelegate.class, fieldValues); bosToDeactivate.addAll(existingDelegates); } // mark all the delegates as inactive for (AccountDelegate accountDelegate : bosToDeactivate) { accountDelegate.setActive(false); } return new ArrayList<PersistableBusinessObject>(bosToDeactivate); } /** * @see org.kuali.rice.krad.document.GlobalBusinessObject#applyGlobalChanges(org.kuali.rice.krad.bo.BusinessObject) */ @SuppressWarnings("deprecation") public List<PersistableBusinessObject> generateGlobalChangesToPersist() { BusinessObjectService boService = SpringContext.getBean(BusinessObjectService.class); List<AccountDelegate> persistables = new ArrayList(); List<AccountDelegateGlobalDetail> changeDocuments = this.getDelegateGlobals(); List<AccountGlobalDetail> accountDetails = this.getAccountGlobalDetails(); for (AccountDelegateGlobalDetail changeDocument : changeDocuments) { for (AccountGlobalDetail accountDetail : accountDetails) { Account account = (Account) boService.findByPrimaryKey(Account.class, accountDetail.getPrimaryKeys()); // if the account doesnt exist, fail fast, as this should never happen, // the busines rules for this document should have caught this. if (account == null) { throw new RuntimeException("Account [" + accountDetail.getChartOfAccountsCode() + "-" + accountDetail.getAccountNumber() + "] was not present in the database. " + "This should never happen under normal circumstances, as an invalid account should have " + "been caught by the Business Rules infrastructure."); } // attempt to load the existing Delegate from the DB, if it exists. we do this to avoid // versionNumber conflicts if we tried to just insert a new record that already existed. Map pkMap = new HashMap(); pkMap.putAll(accountDetail.getPrimaryKeys()); // chartOfAccountsCode & accountNumber pkMap.put("financialDocumentTypeCode", changeDocument.getFinancialDocumentTypeCode()); pkMap.put("accountDelegateSystemId", changeDocument.getAccountDelegateUniversalId()); AccountDelegate delegate = (AccountDelegate) boService.findByPrimaryKey(AccountDelegate.class, pkMap); // if there is no existing Delegate with these primary keys, then we're creating a new one, // so lets populate it with the primary keys if (delegate == null) { delegate = new AccountDelegate(); delegate.setChartOfAccountsCode(accountDetail.getChartOfAccountsCode()); delegate.setAccountNumber(accountDetail.getAccountNumber()); delegate.setAccountDelegateSystemId(changeDocument.getAccountDelegateUniversalId()); delegate.setFinancialDocumentTypeCode(changeDocument.getFinancialDocumentTypeCode()); delegate.setActive(true); } else { delegate.setActive(true); } // APPROVAL FROM AMOUNT if (changeDocument.getApprovalFromThisAmount() != null) { if (!changeDocument.getApprovalFromThisAmount().equals(KualiDecimal.ZERO)) { delegate.setFinDocApprovalFromThisAmt(changeDocument.getApprovalFromThisAmount()); } } // APPROVAL TO AMOUNT if (changeDocument.getApprovalToThisAmount() != null) { if (!changeDocument.getApprovalToThisAmount().equals(KualiDecimal.ZERO)) { delegate.setFinDocApprovalToThisAmount(changeDocument.getApprovalToThisAmount()); } } // PRIMARY ROUTING delegate.setAccountsDelegatePrmrtIndicator(changeDocument.getAccountDelegatePrimaryRoutingIndicator()); // START DATE if (changeDocument.getAccountDelegateStartDate() != null) { delegate.setAccountDelegateStartDate(new Date(changeDocument.getAccountDelegateStartDate().getTime())); } persistables.add(delegate); } } return new ArrayList<PersistableBusinessObject>(persistables); } /** * @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper() */ protected LinkedHashMap toStringMapper_RICE20_REFACTORME() { LinkedHashMap m = new LinkedHashMap(); m.put(OLEPropertyConstants.DOCUMENT_NUMBER, this.documentNumber); return m; } /** * @see org.kuali.rice.krad.document.GlobalBusinessObject#getDocumentNumber() */ public String getDocumentNumber() { return documentNumber; } /** * @see org.kuali.rice.krad.document.GlobalBusinessObject#setDocumentNumber(java.lang.String) */ public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } /** * Gets the accountGlobalDetails attribute. * * @return Returns the accountGlobalDetails. */ public final List<AccountGlobalDetail> getAccountGlobalDetails() { return accountGlobalDetails; } /** * Sets the accountGlobalDetails attribute value. * * @param accountGlobalDetails The accountGlobalDetails to set. */ public final void setAccountGlobalDetails(List<AccountGlobalDetail> accountGlobalDetails) { this.accountGlobalDetails = accountGlobalDetails; } /** * Gets the delegateGlobals attribute. * * @return Returns the delegateGlobals. */ public final List<AccountDelegateGlobalDetail> getDelegateGlobals() { return delegateGlobals; } /** * Sets the delegateGlobals attribute value. * * @param delegateGlobals The delegateGlobals to set. */ public final void setDelegateGlobals(List<AccountDelegateGlobalDetail> delegateGlobals) { this.delegateGlobals = delegateGlobals; } /** * @see org.kuali.rice.krad.document.GlobalBusinessObject#isPersistable() */ public boolean isPersistable() { PersistenceStructureService persistenceStructureService = SpringContext.getBean(PersistenceStructureService.class); // fail if the PK for this object is emtpy if (StringUtils.isBlank(documentNumber)) { return false; } // fail if the PKs for any of the contained objects are empty for (AccountDelegateGlobalDetail delegateGlobals : getDelegateGlobals()) { if (!persistenceStructureService.hasPrimaryKeyFieldValues(delegateGlobals)) { return false; } } for (AccountGlobalDetail account : getAccountGlobalDetails()) { if (!persistenceStructureService.hasPrimaryKeyFieldValues(account)) { return false; } } // otherwise, its all good return true; } public String getModelName() { return modelName; } public void setModelName(String loadModelName) { this.modelName = loadModelName; } public String getModelChartOfAccountsCode() { return modelChartOfAccountsCode; } public void setModelChartOfAccountsCode(String loadModelChartOfAccountsCode) { this.modelChartOfAccountsCode = loadModelChartOfAccountsCode; } public String getModelOrganizationCode() { return modelOrganizationCode; } public void setModelOrganizationCode(String loadModelOrganizationCode) { this.modelOrganizationCode = loadModelOrganizationCode; } public AccountDelegateModel getModel() { return model; } public void setModel(AccountDelegateModel loadModel) { this.model = loadModel; } public List<? extends GlobalBusinessObjectDetail> getAllDetailObjects() { ArrayList<GlobalBusinessObjectDetail> details = new ArrayList<GlobalBusinessObjectDetail>(accountGlobalDetails.size() + delegateGlobals.size()); details.addAll(accountGlobalDetails); details.addAll(delegateGlobals); return details; } @Override public void linkEditableUserFields() { super.linkEditableUserFields(); if (this == null) { throw new IllegalArgumentException("globalDelegate parameter passed in was null"); } List<PersistableBusinessObject> bos = new ArrayList<PersistableBusinessObject>(); bos.addAll(getDelegateGlobals()); SpringContext.getBean(BusinessObjectService.class).linkUserFields(bos); } /** * @see org.kuali.rice.krad.bo.PersistableBusinessObjectBase#buildListOfDeletionAwareLists() */ @Override public List<Collection<PersistableBusinessObject>> buildListOfDeletionAwareLists() { List<Collection<PersistableBusinessObject>> managedLists = super.buildListOfDeletionAwareLists(); managedLists.add( new ArrayList<PersistableBusinessObject>( getAccountGlobalDetails() ) ); managedLists.add( new ArrayList<PersistableBusinessObject>( getDelegateGlobals() ) ); return managedLists; } }
[ "public", "class", "AccountDelegateGlobal", "extends", "PersistableBusinessObjectBase", "implements", "GlobalBusinessObject", "{", "protected", "String", "documentNumber", ";", "protected", "String", "modelName", ";", "protected", "String", "modelChartOfAccountsCode", ";", "protected", "String", "modelOrganizationCode", ";", "protected", "AccountDelegateModel", "model", ";", "protected", "List", "<", "AccountGlobalDetail", ">", "accountGlobalDetails", ";", "protected", "List", "<", "AccountDelegateGlobalDetail", ">", "delegateGlobals", ";", "/**\n * Constructs a DelegateGlobal.java.\n */", "public", "AccountDelegateGlobal", "(", ")", "{", "super", "(", ")", ";", "accountGlobalDetails", "=", "new", "ArrayList", "<", "AccountGlobalDetail", ">", "(", ")", ";", "delegateGlobals", "=", "new", "ArrayList", "<", "AccountDelegateGlobalDetail", ">", "(", ")", ";", "}", "/**\n * This method adds a single AccountGlobalDetail instance to the list. If one is already present in the list with the same\n * chartCode and accountNumber, then this new one will not be added.\n * \n * @param accountGlobalDetail - populated AccountGlobalDetail instance\n */", "public", "void", "addAccount", "(", "AccountGlobalDetail", "accountGlobalDetail", ")", "{", "if", "(", "accountGlobalDetail", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The accountGlobalDetail instanced passed in was null.", "\"", ")", ";", "}", "else", "if", "(", "StringUtils", ".", "isBlank", "(", "accountGlobalDetail", ".", "getChartOfAccountsCode", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The chartOfAccountsCode member of the accountGlobalDetail object was not populated.", "\"", ")", ";", "}", "else", "if", "(", "StringUtils", ".", "isBlank", "(", "accountGlobalDetail", ".", "getAccountNumber", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The accountNumber member of the accountGlobalDetail object was not populated.", "\"", ")", ";", "}", "AccountGlobalDetail", "testObject", "=", "getAccount", "(", "accountGlobalDetail", ".", "getChartOfAccountsCode", "(", ")", ",", "accountGlobalDetail", ".", "getAccountNumber", "(", ")", ")", ";", "if", "(", "testObject", "==", "null", ")", "{", "this", ".", "accountGlobalDetails", ".", "add", "(", "accountGlobalDetail", ")", ";", "}", "}", "/**\n * This method retrieves the specific AccountGlobalDetail object that corresponds to your requested chartCode and accountNumber\n * (or a null object if there is no match).\n * \n * @param chartCode\n * @param accountNumber\n * @return returns the AccountGlobalDetail instance matching the chartCode & accountNumber passed in, or Null if none match\n */", "public", "AccountGlobalDetail", "getAccount", "(", "String", "chartCode", ",", "String", "accountNumber", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "chartCode", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The chartCode argument was null or empty.", "\"", ")", ";", "}", "else", "if", "(", "StringUtils", ".", "isBlank", "(", "accountNumber", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The accountNumber argument was null or empty.", "\"", ")", ";", "}", "for", "(", "Iterator", "iter", "=", "this", ".", "accountGlobalDetails", ".", "iterator", "(", ")", ";", "iter", ".", "hasNext", "(", ")", ";", ")", "{", "AccountGlobalDetail", "accountGlobalDetail", "=", "(", "AccountGlobalDetail", ")", "iter", ".", "next", "(", ")", ";", "if", "(", "chartCode", ".", "equalsIgnoreCase", "(", "accountGlobalDetail", ".", "getChartOfAccountsCode", "(", ")", ")", "&&", "accountNumber", ".", "equalsIgnoreCase", "(", "accountGlobalDetail", ".", "getAccountNumber", "(", ")", ")", ")", "{", "return", "accountGlobalDetail", ";", "}", "}", "return", "null", ";", "}", "/**\n * @see org.kuali.rice.krad.document.GlobalBusinessObject#getGlobalChangesToDelete()\n */", "public", "List", "<", "PersistableBusinessObject", ">", "generateDeactivationsToPersist", "(", ")", "{", "BusinessObjectService", "boService", "=", "SpringContext", ".", "getBean", "(", "BusinessObjectService", ".", "class", ")", ";", "List", "<", "AccountDelegate", ">", "bosToDeactivate", "=", "new", "ArrayList", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "fieldValues", ";", "Collection", "existingDelegates", ";", "for", "(", "AccountGlobalDetail", "accountDetail", ":", "getAccountGlobalDetails", "(", ")", ")", "{", "fieldValues", "=", "new", "HashMap", "(", ")", ";", "fieldValues", ".", "put", "(", "\"", "chartOfAccountsCode", "\"", ",", "accountDetail", ".", "getChartOfAccountsCode", "(", ")", ")", ";", "fieldValues", ".", "put", "(", "\"", "accountNumber", "\"", ",", "accountDetail", ".", "getAccountNumber", "(", ")", ")", ";", "fieldValues", ".", "put", "(", "\"", "active", "\"", ",", "true", ")", ";", "existingDelegates", "=", "boService", ".", "findMatching", "(", "AccountDelegate", ".", "class", ",", "fieldValues", ")", ";", "bosToDeactivate", ".", "addAll", "(", "existingDelegates", ")", ";", "}", "for", "(", "AccountDelegate", "accountDelegate", ":", "bosToDeactivate", ")", "{", "accountDelegate", ".", "setActive", "(", "false", ")", ";", "}", "return", "new", "ArrayList", "<", "PersistableBusinessObject", ">", "(", "bosToDeactivate", ")", ";", "}", "/**\n * @see org.kuali.rice.krad.document.GlobalBusinessObject#applyGlobalChanges(org.kuali.rice.krad.bo.BusinessObject)\n */", "@", "SuppressWarnings", "(", "\"", "deprecation", "\"", ")", "public", "List", "<", "PersistableBusinessObject", ">", "generateGlobalChangesToPersist", "(", ")", "{", "BusinessObjectService", "boService", "=", "SpringContext", ".", "getBean", "(", "BusinessObjectService", ".", "class", ")", ";", "List", "<", "AccountDelegate", ">", "persistables", "=", "new", "ArrayList", "(", ")", ";", "List", "<", "AccountDelegateGlobalDetail", ">", "changeDocuments", "=", "this", ".", "getDelegateGlobals", "(", ")", ";", "List", "<", "AccountGlobalDetail", ">", "accountDetails", "=", "this", ".", "getAccountGlobalDetails", "(", ")", ";", "for", "(", "AccountDelegateGlobalDetail", "changeDocument", ":", "changeDocuments", ")", "{", "for", "(", "AccountGlobalDetail", "accountDetail", ":", "accountDetails", ")", "{", "Account", "account", "=", "(", "Account", ")", "boService", ".", "findByPrimaryKey", "(", "Account", ".", "class", ",", "accountDetail", ".", "getPrimaryKeys", "(", ")", ")", ";", "if", "(", "account", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Account [", "\"", "+", "accountDetail", ".", "getChartOfAccountsCode", "(", ")", "+", "\"", "-", "\"", "+", "accountDetail", ".", "getAccountNumber", "(", ")", "+", "\"", "] was not present in the database. ", "\"", "+", "\"", "This should never happen under normal circumstances, as an invalid account should have ", "\"", "+", "\"", "been caught by the Business Rules infrastructure.", "\"", ")", ";", "}", "Map", "pkMap", "=", "new", "HashMap", "(", ")", ";", "pkMap", ".", "putAll", "(", "accountDetail", ".", "getPrimaryKeys", "(", ")", ")", ";", "pkMap", ".", "put", "(", "\"", "financialDocumentTypeCode", "\"", ",", "changeDocument", ".", "getFinancialDocumentTypeCode", "(", ")", ")", ";", "pkMap", ".", "put", "(", "\"", "accountDelegateSystemId", "\"", ",", "changeDocument", ".", "getAccountDelegateUniversalId", "(", ")", ")", ";", "AccountDelegate", "delegate", "=", "(", "AccountDelegate", ")", "boService", ".", "findByPrimaryKey", "(", "AccountDelegate", ".", "class", ",", "pkMap", ")", ";", "if", "(", "delegate", "==", "null", ")", "{", "delegate", "=", "new", "AccountDelegate", "(", ")", ";", "delegate", ".", "setChartOfAccountsCode", "(", "accountDetail", ".", "getChartOfAccountsCode", "(", ")", ")", ";", "delegate", ".", "setAccountNumber", "(", "accountDetail", ".", "getAccountNumber", "(", ")", ")", ";", "delegate", ".", "setAccountDelegateSystemId", "(", "changeDocument", ".", "getAccountDelegateUniversalId", "(", ")", ")", ";", "delegate", ".", "setFinancialDocumentTypeCode", "(", "changeDocument", ".", "getFinancialDocumentTypeCode", "(", ")", ")", ";", "delegate", ".", "setActive", "(", "true", ")", ";", "}", "else", "{", "delegate", ".", "setActive", "(", "true", ")", ";", "}", "if", "(", "changeDocument", ".", "getApprovalFromThisAmount", "(", ")", "!=", "null", ")", "{", "if", "(", "!", "changeDocument", ".", "getApprovalFromThisAmount", "(", ")", ".", "equals", "(", "KualiDecimal", ".", "ZERO", ")", ")", "{", "delegate", ".", "setFinDocApprovalFromThisAmt", "(", "changeDocument", ".", "getApprovalFromThisAmount", "(", ")", ")", ";", "}", "}", "if", "(", "changeDocument", ".", "getApprovalToThisAmount", "(", ")", "!=", "null", ")", "{", "if", "(", "!", "changeDocument", ".", "getApprovalToThisAmount", "(", ")", ".", "equals", "(", "KualiDecimal", ".", "ZERO", ")", ")", "{", "delegate", ".", "setFinDocApprovalToThisAmount", "(", "changeDocument", ".", "getApprovalToThisAmount", "(", ")", ")", ";", "}", "}", "delegate", ".", "setAccountsDelegatePrmrtIndicator", "(", "changeDocument", ".", "getAccountDelegatePrimaryRoutingIndicator", "(", ")", ")", ";", "if", "(", "changeDocument", ".", "getAccountDelegateStartDate", "(", ")", "!=", "null", ")", "{", "delegate", ".", "setAccountDelegateStartDate", "(", "new", "Date", "(", "changeDocument", ".", "getAccountDelegateStartDate", "(", ")", ".", "getTime", "(", ")", ")", ")", ";", "}", "persistables", ".", "add", "(", "delegate", ")", ";", "}", "}", "return", "new", "ArrayList", "<", "PersistableBusinessObject", ">", "(", "persistables", ")", ";", "}", "/**\n * @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper()\n */", "protected", "LinkedHashMap", "toStringMapper_RICE20_REFACTORME", "(", ")", "{", "LinkedHashMap", "m", "=", "new", "LinkedHashMap", "(", ")", ";", "m", ".", "put", "(", "OLEPropertyConstants", ".", "DOCUMENT_NUMBER", ",", "this", ".", "documentNumber", ")", ";", "return", "m", ";", "}", "/**\n * @see org.kuali.rice.krad.document.GlobalBusinessObject#getDocumentNumber()\n */", "public", "String", "getDocumentNumber", "(", ")", "{", "return", "documentNumber", ";", "}", "/**\n * @see org.kuali.rice.krad.document.GlobalBusinessObject#setDocumentNumber(java.lang.String)\n */", "public", "void", "setDocumentNumber", "(", "String", "documentNumber", ")", "{", "this", ".", "documentNumber", "=", "documentNumber", ";", "}", "/**\n * Gets the accountGlobalDetails attribute.\n * \n * @return Returns the accountGlobalDetails.\n */", "public", "final", "List", "<", "AccountGlobalDetail", ">", "getAccountGlobalDetails", "(", ")", "{", "return", "accountGlobalDetails", ";", "}", "/**\n * Sets the accountGlobalDetails attribute value.\n * \n * @param accountGlobalDetails The accountGlobalDetails to set.\n */", "public", "final", "void", "setAccountGlobalDetails", "(", "List", "<", "AccountGlobalDetail", ">", "accountGlobalDetails", ")", "{", "this", ".", "accountGlobalDetails", "=", "accountGlobalDetails", ";", "}", "/**\n * Gets the delegateGlobals attribute.\n * \n * @return Returns the delegateGlobals.\n */", "public", "final", "List", "<", "AccountDelegateGlobalDetail", ">", "getDelegateGlobals", "(", ")", "{", "return", "delegateGlobals", ";", "}", "/**\n * Sets the delegateGlobals attribute value.\n * \n * @param delegateGlobals The delegateGlobals to set.\n */", "public", "final", "void", "setDelegateGlobals", "(", "List", "<", "AccountDelegateGlobalDetail", ">", "delegateGlobals", ")", "{", "this", ".", "delegateGlobals", "=", "delegateGlobals", ";", "}", "/**\n * @see org.kuali.rice.krad.document.GlobalBusinessObject#isPersistable()\n */", "public", "boolean", "isPersistable", "(", ")", "{", "PersistenceStructureService", "persistenceStructureService", "=", "SpringContext", ".", "getBean", "(", "PersistenceStructureService", ".", "class", ")", ";", "if", "(", "StringUtils", ".", "isBlank", "(", "documentNumber", ")", ")", "{", "return", "false", ";", "}", "for", "(", "AccountDelegateGlobalDetail", "delegateGlobals", ":", "getDelegateGlobals", "(", ")", ")", "{", "if", "(", "!", "persistenceStructureService", ".", "hasPrimaryKeyFieldValues", "(", "delegateGlobals", ")", ")", "{", "return", "false", ";", "}", "}", "for", "(", "AccountGlobalDetail", "account", ":", "getAccountGlobalDetails", "(", ")", ")", "{", "if", "(", "!", "persistenceStructureService", ".", "hasPrimaryKeyFieldValues", "(", "account", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "public", "String", "getModelName", "(", ")", "{", "return", "modelName", ";", "}", "public", "void", "setModelName", "(", "String", "loadModelName", ")", "{", "this", ".", "modelName", "=", "loadModelName", ";", "}", "public", "String", "getModelChartOfAccountsCode", "(", ")", "{", "return", "modelChartOfAccountsCode", ";", "}", "public", "void", "setModelChartOfAccountsCode", "(", "String", "loadModelChartOfAccountsCode", ")", "{", "this", ".", "modelChartOfAccountsCode", "=", "loadModelChartOfAccountsCode", ";", "}", "public", "String", "getModelOrganizationCode", "(", ")", "{", "return", "modelOrganizationCode", ";", "}", "public", "void", "setModelOrganizationCode", "(", "String", "loadModelOrganizationCode", ")", "{", "this", ".", "modelOrganizationCode", "=", "loadModelOrganizationCode", ";", "}", "public", "AccountDelegateModel", "getModel", "(", ")", "{", "return", "model", ";", "}", "public", "void", "setModel", "(", "AccountDelegateModel", "loadModel", ")", "{", "this", ".", "model", "=", "loadModel", ";", "}", "public", "List", "<", "?", "extends", "GlobalBusinessObjectDetail", ">", "getAllDetailObjects", "(", ")", "{", "ArrayList", "<", "GlobalBusinessObjectDetail", ">", "details", "=", "new", "ArrayList", "<", "GlobalBusinessObjectDetail", ">", "(", "accountGlobalDetails", ".", "size", "(", ")", "+", "delegateGlobals", ".", "size", "(", ")", ")", ";", "details", ".", "addAll", "(", "accountGlobalDetails", ")", ";", "details", ".", "addAll", "(", "delegateGlobals", ")", ";", "return", "details", ";", "}", "@", "Override", "public", "void", "linkEditableUserFields", "(", ")", "{", "super", ".", "linkEditableUserFields", "(", ")", ";", "if", "(", "this", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "globalDelegate parameter passed in was null", "\"", ")", ";", "}", "List", "<", "PersistableBusinessObject", ">", "bos", "=", "new", "ArrayList", "<", "PersistableBusinessObject", ">", "(", ")", ";", "bos", ".", "addAll", "(", "getDelegateGlobals", "(", ")", ")", ";", "SpringContext", ".", "getBean", "(", "BusinessObjectService", ".", "class", ")", ".", "linkUserFields", "(", "bos", ")", ";", "}", "/**\n * @see org.kuali.rice.krad.bo.PersistableBusinessObjectBase#buildListOfDeletionAwareLists()\n */", "@", "Override", "public", "List", "<", "Collection", "<", "PersistableBusinessObject", ">", ">", "buildListOfDeletionAwareLists", "(", ")", "{", "List", "<", "Collection", "<", "PersistableBusinessObject", ">", ">", "managedLists", "=", "super", ".", "buildListOfDeletionAwareLists", "(", ")", ";", "managedLists", ".", "add", "(", "new", "ArrayList", "<", "PersistableBusinessObject", ">", "(", "getAccountGlobalDetails", "(", ")", ")", ")", ";", "managedLists", ".", "add", "(", "new", "ArrayList", "<", "PersistableBusinessObject", ">", "(", "getDelegateGlobals", "(", ")", ")", ")", ";", "return", "managedLists", ";", "}", "}" ]
This class simply acts as a container to hold the List of Delegate Changes and the list of Account entries, for the Global Delegate Change Document.
[ "This", "class", "simply", "acts", "as", "a", "container", "to", "hold", "the", "List", "of", "Delegate", "Changes", "and", "the", "list", "of", "Account", "entries", "for", "the", "Global", "Delegate", "Change", "Document", "." ]
[ "// validate the argument", "// add the object if one doesnt already exist, otherwise silently do nothing", "// validate the argument", "// walk the list of AccountGlobalDetail objects", "// if this one is a match, then quit", "// we return null if one is not found", "// retreive all the existing delegates for these accounts", "// mark all the delegates as inactive", "// if the account doesnt exist, fail fast, as this should never happen,", "// the busines rules for this document should have caught this.", "// attempt to load the existing Delegate from the DB, if it exists. we do this to avoid", "// versionNumber conflicts if we tried to just insert a new record that already existed.", "// chartOfAccountsCode & accountNumber", "// if there is no existing Delegate with these primary keys, then we're creating a new one,", "// so lets populate it with the primary keys", "// APPROVAL FROM AMOUNT", "// APPROVAL TO AMOUNT", "// PRIMARY ROUTING", "// START DATE", "// fail if the PK for this object is emtpy", "// fail if the PKs for any of the contained objects are empty", "// otherwise, its all good" ]
[ { "param": "PersistableBusinessObjectBase", "type": null }, { "param": "GlobalBusinessObject", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PersistableBusinessObjectBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "GlobalBusinessObject", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b524c1aa50ff53aabcca6aa8a82dee599a0d256
laserson/hellbender
src/main/java/org/broadinstitute/hellbender/tools/dataflow/transforms/PrintReadsDataflowTransform.java
[ "BSD-3-Clause" ]
Java
PrintReadsDataflowTransform
/** * Print a string representation of reads in the PCollection<String> */
Print a string representation of reads in the PCollection
[ "Print", "a", "string", "representation", "of", "reads", "in", "the", "PCollection" ]
public final class PrintReadsDataflowTransform extends PTransformSAM<String> { private static final long serialVersionUID = 1l; @Override public PCollection<String> apply(final PCollection<GATKRead> reads) { return reads.apply(ParDo.of(new DataFlowReadFn<String>(getHeader()) { private static final long serialVersionUID = 1l; @Override protected void apply(final GATKRead read) { // TODO: write a utility that can produce a SAM string for a GATK read without conversion to SAMRecord output(read.convertToSAMRecord(getHeader()).getSAMString()); } })); } }
[ "public", "final", "class", "PrintReadsDataflowTransform", "extends", "PTransformSAM", "<", "String", ">", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1l", ";", "@", "Override", "public", "PCollection", "<", "String", ">", "apply", "(", "final", "PCollection", "<", "GATKRead", ">", "reads", ")", "{", "return", "reads", ".", "apply", "(", "ParDo", ".", "of", "(", "new", "DataFlowReadFn", "<", "String", ">", "(", "getHeader", "(", ")", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1l", ";", "@", "Override", "protected", "void", "apply", "(", "final", "GATKRead", "read", ")", "{", "output", "(", "read", ".", "convertToSAMRecord", "(", "getHeader", "(", ")", ")", ".", "getSAMString", "(", ")", ")", ";", "}", "}", ")", ")", ";", "}", "}" ]
Print a string representation of reads in the PCollection<String>
[ "Print", "a", "string", "representation", "of", "reads", "in", "the", "PCollection<String", ">" ]
[ "// TODO: write a utility that can produce a SAM string for a GATK read without conversion to SAMRecord" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b53a9e329ea233361e73bd2e50b720439e6c2bf
pponec/ujorm
project-m2/ujo-tools/src/main/java/org/ujorm/tools/xml/AbstractElement.java
[ "Apache-2.0" ]
Java
AbstractElement
/** * An element model API. * * The XmlElement class implements the {@link Closeable} implementation * for an optional highlighting the tree structure in the source code. * * @see HtmlElement * @since 1.86 * @author Pavel Ponec * @deprecated Use the interface {@link ApiElement} rather. */
An element model API. The XmlElement class implements the Closeable implementation for an optional highlighting the tree structure in the source code. @see HtmlElement @since 1.86 @author Pavel Ponec @deprecated Use the interface ApiElement rather.
[ "An", "element", "model", "API", ".", "The", "XmlElement", "class", "implements", "the", "Closeable", "implementation", "for", "an", "optional", "highlighting", "the", "tree", "structure", "in", "the", "source", "code", ".", "@see", "HtmlElement", "@since", "1", ".", "86", "@author", "Pavel", "Ponec", "@deprecated", "Use", "the", "interface", "ApiElement", "rather", "." ]
@Deprecated public abstract class AbstractElement<E extends AbstractElement<?>> implements ApiElement<E> { @Nonnull protected final String name; public AbstractElement(@Nonnull final String name) { this.name = Assert.hasLength(name, "name"); } @Override public String getName() { return name; } }
[ "@", "Deprecated", "public", "abstract", "class", "AbstractElement", "<", "E", "extends", "AbstractElement", "<", "?", ">", ">", "implements", "ApiElement", "<", "E", ">", "{", "@", "Nonnull", "protected", "final", "String", "name", ";", "public", "AbstractElement", "(", "@", "Nonnull", "final", "String", "name", ")", "{", "this", ".", "name", "=", "Assert", ".", "hasLength", "(", "name", ",", "\"", "name", "\"", ")", ";", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "name", ";", "}", "}" ]
An element model API.
[ "An", "element", "model", "API", "." ]
[]
[ { "param": "ApiElement<E>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ApiElement<E>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b5924dc993a5aa5feebcdbc7906805843246932
KrzychuJedi/jdal
swing/src/main/java/org/jdal/swing/table/PageableTableAction.java
[ "Apache-2.0" ]
Java
PageableTableAction
/** * @author Jose Luis Martin - (jlm@joseluismartin.info) * */
@author Jose Luis Martin - (jlm@joseluismartin.info)
[ "@author", "Jose", "Luis", "Martin", "-", "(", "jlm@joseluismartin", ".", "info", ")" ]
public abstract class PageableTableAction extends BeanAction { private PageableTable<?> table; public PageableTableAction() { } /** * @param pageableTable */ public PageableTableAction(PageableTable<?> pageableTable) { this(pageableTable, null, null); } public PageableTableAction(PageableTable<?> pageableTable, String name) { this(pageableTable, name, null); } public PageableTableAction(PageableTable<?> pageableTable, String name, Icon icon) { this.table = pageableTable; setName(name); setIcon(icon); } /** * @return the table */ public PageableTable<?> getTable() { return table; } /** * @param table the table to set */ public void setTable(PageableTable<?> table) { this.table = table; } /** * {@inheritDoc} */ abstract public void actionPerformed(ActionEvent e); }
[ "public", "abstract", "class", "PageableTableAction", "extends", "BeanAction", "{", "private", "PageableTable", "<", "?", ">", "table", ";", "public", "PageableTableAction", "(", ")", "{", "}", "/**\n\t * @param pageableTable\n\t */", "public", "PageableTableAction", "(", "PageableTable", "<", "?", ">", "pageableTable", ")", "{", "this", "(", "pageableTable", ",", "null", ",", "null", ")", ";", "}", "public", "PageableTableAction", "(", "PageableTable", "<", "?", ">", "pageableTable", ",", "String", "name", ")", "{", "this", "(", "pageableTable", ",", "name", ",", "null", ")", ";", "}", "public", "PageableTableAction", "(", "PageableTable", "<", "?", ">", "pageableTable", ",", "String", "name", ",", "Icon", "icon", ")", "{", "this", ".", "table", "=", "pageableTable", ";", "setName", "(", "name", ")", ";", "setIcon", "(", "icon", ")", ";", "}", "/**\n\t * @return the table\n\t */", "public", "PageableTable", "<", "?", ">", "getTable", "(", ")", "{", "return", "table", ";", "}", "/**\n\t * @param table the table to set\n\t */", "public", "void", "setTable", "(", "PageableTable", "<", "?", ">", "table", ")", "{", "this", ".", "table", "=", "table", ";", "}", "/**\n\t * {@inheritDoc}\n\t */", "abstract", "public", "void", "actionPerformed", "(", "ActionEvent", "e", ")", ";", "}" ]
@author Jose Luis Martin - (jlm@joseluismartin.info)
[ "@author", "Jose", "Luis", "Martin", "-", "(", "jlm@joseluismartin", ".", "info", ")" ]
[]
[ { "param": "BeanAction", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BeanAction", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b5a821250f49b5e5450b196201b62d668f64d48
QuantFinEcon/java-learn
Maven/RestfulJaveEE/src/main/java/controllers/HelloWorld.java
[ "Unlicense" ]
Java
HelloWorld
/** * Created by nhancao on 3/9/16. */
Created by nhancao on 3/9/16.
[ "Created", "by", "nhancao", "on", "3", "/", "9", "/", "16", "." ]
@WebServlet( name = "hello", urlPatterns = "/" ) public class HelloWorld extends HttpServlet { @Override protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { resp.getWriter().write( "hi, :)" ); } }
[ "@", "WebServlet", "(", "name", "=", "\"", "hello", "\"", ",", "urlPatterns", "=", "\"", "/", "\"", ")", "public", "class", "HelloWorld", "extends", "HttpServlet", "{", "@", "Override", "protected", "void", "doGet", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "resp", ")", "throws", "ServletException", ",", "IOException", "{", "resp", ".", "getWriter", "(", ")", ".", "write", "(", "\"", "hi, :)", "\"", ")", ";", "}", "}" ]
Created by nhancao on 3/9/16.
[ "Created", "by", "nhancao", "on", "3", "/", "9", "/", "16", "." ]
[]
[ { "param": "HttpServlet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HttpServlet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b66999ccb8bf3c2fa61dee82ce090e3e2f2b00b
Student-Management-System/SubmissionCheck
src/main/java/net/ssehub/teaching/submission_check/svn/TransactionInfo.java
[ "Apache-2.0" ]
Java
TransactionInfo
/** * Information about the transaction that the submission hook is running for. * * @author Adam */
Information about the transaction that the submission hook is running for. @author Adam
[ "Information", "about", "the", "transaction", "that", "the", "submission", "hook", "is", "running", "for", ".", "@author", "Adam" ]
public class TransactionInfo { /** * Phases of a transaction. */ public enum Phase { PRE_COMMIT, POST_COMMIT, } private File repository; private String author; private String transactionId; private Phase phase; /** * Creates a {@link TransactionInfo}. * * @param repository The path of the SVN repository that the transaction belongs to. * @param author The name of the author of the transaction. * @param transactionId The ID of the transaction; depends on the {@link Phase}. * @param phase The {@link Phase} of this transaction. */ public TransactionInfo(File repository, String author, String transactionId, Phase phase) { this.repository = repository; this.author = author; this.transactionId = transactionId; this.phase = phase; } /** * Returns the path of the SVN repository that the transaction belongs to. * * @return The path of the SVN repository. */ public File getRepository() { return repository; } /** * Returns the name of the author of this transaction. * * @return The author name. */ public String getAuthor() { return author; } /** * Returns the ID of the transaction. Content depends on the {@link Phase}: * <ul> * <li>for {@link Phase#PRE_COMMIT} this is the SVN transaction ID</li> * <li>for {@link Phase#POST_COMMIT} this is the SVN revision number</li> * </ul> * * @return The ID of the transaction. */ public String getTransactionId() { return transactionId; } /** * The phase of this transaction. * * @return The phase of this transaction. */ public Phase getPhase() { return phase; } @Override public int hashCode() { return Objects.hash(author, phase, repository, transactionId); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TransactionInfo)) { return false; } TransactionInfo other = (TransactionInfo) obj; return Objects.equals(author, other.author) && phase == other.phase && Objects.equals(repository, other.repository) && Objects.equals(transactionId, other.transactionId); } }
[ "public", "class", "TransactionInfo", "{", "/**\n * Phases of a transaction.\n */", "public", "enum", "Phase", "{", "PRE_COMMIT", ",", "POST_COMMIT", ",", "}", "private", "File", "repository", ";", "private", "String", "author", ";", "private", "String", "transactionId", ";", "private", "Phase", "phase", ";", "/**\n * Creates a {@link TransactionInfo}.\n * \n * @param repository The path of the SVN repository that the transaction belongs to.\n * @param author The name of the author of the transaction.\n * @param transactionId The ID of the transaction; depends on the {@link Phase}.\n * @param phase The {@link Phase} of this transaction.\n */", "public", "TransactionInfo", "(", "File", "repository", ",", "String", "author", ",", "String", "transactionId", ",", "Phase", "phase", ")", "{", "this", ".", "repository", "=", "repository", ";", "this", ".", "author", "=", "author", ";", "this", ".", "transactionId", "=", "transactionId", ";", "this", ".", "phase", "=", "phase", ";", "}", "/**\n * Returns the path of the SVN repository that the transaction belongs to.\n * \n * @return The path of the SVN repository.\n */", "public", "File", "getRepository", "(", ")", "{", "return", "repository", ";", "}", "/**\n * Returns the name of the author of this transaction.\n * \n * @return The author name.\n */", "public", "String", "getAuthor", "(", ")", "{", "return", "author", ";", "}", "/**\n * Returns the ID of the transaction. Content depends on the {@link Phase}:\n * <ul>\n * <li>for {@link Phase#PRE_COMMIT} this is the SVN transaction ID</li>\n * <li>for {@link Phase#POST_COMMIT} this is the SVN revision number</li>\n * </ul>\n * \n * @return The ID of the transaction.\n */", "public", "String", "getTransactionId", "(", ")", "{", "return", "transactionId", ";", "}", "/**\n * The phase of this transaction.\n * \n * @return The phase of this transaction.\n */", "public", "Phase", "getPhase", "(", ")", "{", "return", "phase", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "Objects", ".", "hash", "(", "author", ",", "phase", ",", "repository", ",", "transactionId", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "this", "==", "obj", ")", "{", "return", "true", ";", "}", "if", "(", "!", "(", "obj", "instanceof", "TransactionInfo", ")", ")", "{", "return", "false", ";", "}", "TransactionInfo", "other", "=", "(", "TransactionInfo", ")", "obj", ";", "return", "Objects", ".", "equals", "(", "author", ",", "other", ".", "author", ")", "&&", "phase", "==", "other", ".", "phase", "&&", "Objects", ".", "equals", "(", "repository", ",", "other", ".", "repository", ")", "&&", "Objects", ".", "equals", "(", "transactionId", ",", "other", ".", "transactionId", ")", ";", "}", "}" ]
Information about the transaction that the submission hook is running for.
[ "Information", "about", "the", "transaction", "that", "the", "submission", "hook", "is", "running", "for", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b685558a90ad18676ceb77d40bb5ca89c56480d
dcwu/pentago
src/main/java/util/IOUtil.java
[ "MIT" ]
Java
EndGameDbIO
/** * The files will be stored with dates as titles */
The files will be stored with dates as titles
[ "The", "files", "will", "be", "stored", "with", "dates", "as", "titles" ]
public static class EndGameDbIO { private final int depth; public EndGameDbIO(int depth) { this.depth = depth; } //define Format private final DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); private File getEndGameDbDir() { final File endGameDbDirFile = new File(getEndGameDbDirPath()); // Make the directory if needed endGameDbDirFile.mkdir(); return endGameDbDirFile; } private File getSpecificDepthDir() { final File endGameDbDir = getEndGameDbDir(); final File specificDepthDir = new File(endGameDbDir, String.valueOf(depth)); // Make the directory if needed specificDepthDir.mkdir(); return specificDepthDir; } private String getEndGameDbDirPath() { return new File(getCurrentDirectoryPath(), ENDGAME_DB_DIR).getAbsolutePath(); } public File getNextEndGameDbFile() { final Date now = new Date(); final String newFileName = formatter.format(now); return new File(getSpecificDepthDir(), newFileName); } public File[] getEndGameDbFiles() { final File specificDepthDir = getSpecificDepthDir(); final String[] filenames = specificDepthDir.list(); final File[] files = new File[filenames.length]; for (int index = 0; index < filenames.length; index++) { final String filename = filenames[index]; files[index] = new File(specificDepthDir, filename); } return files; } }
[ "public", "static", "class", "EndGameDbIO", "{", "private", "final", "int", "depth", ";", "public", "EndGameDbIO", "(", "int", "depth", ")", "{", "this", ".", "depth", "=", "depth", ";", "}", "private", "final", "DateFormat", "formatter", "=", "new", "SimpleDateFormat", "(", "\"", "yyyyMMddHHmmss", "\"", ")", ";", "private", "File", "getEndGameDbDir", "(", ")", "{", "final", "File", "endGameDbDirFile", "=", "new", "File", "(", "getEndGameDbDirPath", "(", ")", ")", ";", "endGameDbDirFile", ".", "mkdir", "(", ")", ";", "return", "endGameDbDirFile", ";", "}", "private", "File", "getSpecificDepthDir", "(", ")", "{", "final", "File", "endGameDbDir", "=", "getEndGameDbDir", "(", ")", ";", "final", "File", "specificDepthDir", "=", "new", "File", "(", "endGameDbDir", ",", "String", ".", "valueOf", "(", "depth", ")", ")", ";", "specificDepthDir", ".", "mkdir", "(", ")", ";", "return", "specificDepthDir", ";", "}", "private", "String", "getEndGameDbDirPath", "(", ")", "{", "return", "new", "File", "(", "getCurrentDirectoryPath", "(", ")", ",", "ENDGAME_DB_DIR", ")", ".", "getAbsolutePath", "(", ")", ";", "}", "public", "File", "getNextEndGameDbFile", "(", ")", "{", "final", "Date", "now", "=", "new", "Date", "(", ")", ";", "final", "String", "newFileName", "=", "formatter", ".", "format", "(", "now", ")", ";", "return", "new", "File", "(", "getSpecificDepthDir", "(", ")", ",", "newFileName", ")", ";", "}", "public", "File", "[", "]", "getEndGameDbFiles", "(", ")", "{", "final", "File", "specificDepthDir", "=", "getSpecificDepthDir", "(", ")", ";", "final", "String", "[", "]", "filenames", "=", "specificDepthDir", ".", "list", "(", ")", ";", "final", "File", "[", "]", "files", "=", "new", "File", "[", "filenames", ".", "length", "]", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "filenames", ".", "length", ";", "index", "++", ")", "{", "final", "String", "filename", "=", "filenames", "[", "index", "]", ";", "files", "[", "index", "]", "=", "new", "File", "(", "specificDepthDir", ",", "filename", ")", ";", "}", "return", "files", ";", "}", "}" ]
The files will be stored with dates as titles
[ "The", "files", "will", "be", "stored", "with", "dates", "as", "titles" ]
[ "//define Format\r", "// Make the directory if needed\r", "// Make the directory if needed\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b687bb937ab65f2e6a78975b629053e2455161e
guobingwei/car-intelligent-hardware
src/main/java/com/autocar/intelligent/hardware/provider/socket/tcp/test/SocketClient.java
[ "Apache-2.0" ]
Java
SocketClient
/** * Created by guobingwei on 18/5/11. */
Created by guobingwei on 18/5/11.
[ "Created", "by", "guobingwei", "on", "18", "/", "5", "/", "11", "." ]
public class SocketClient { public static void main(String[] args) { try { //1.建立客户端socket连接,指定服务器位置及端口 Socket socket = new Socket("localhost", 8900); //2.得到socket读写流 OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); //输入流 InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); //3.利用流按照一定的操作,对socket进行读写操作 CarDataUploadParam carDataUploadParam = new CarDataUploadParam(); carDataUploadParam.setBackDistance(111.11); carDataUploadParam.setTemperature(213.5); pw.write(JSON.toJSONString(carDataUploadParam)); pw.flush(); socket.shutdownOutput(); //接收服务器的相应 String reply = null; while (!((reply = br.readLine()) == null)) { System.out.println("接收服务器的信息:" + reply); } //4.关闭资源 br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
[ "public", "class", "SocketClient", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "try", "{", "Socket", "socket", "=", "new", "Socket", "(", "\"", "localhost", "\"", ",", "8900", ")", ";", "OutputStream", "os", "=", "socket", ".", "getOutputStream", "(", ")", ";", "PrintWriter", "pw", "=", "new", "PrintWriter", "(", "os", ")", ";", "InputStream", "is", "=", "socket", ".", "getInputStream", "(", ")", ";", "BufferedReader", "br", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "is", ")", ")", ";", "CarDataUploadParam", "carDataUploadParam", "=", "new", "CarDataUploadParam", "(", ")", ";", "carDataUploadParam", ".", "setBackDistance", "(", "111.11", ")", ";", "carDataUploadParam", ".", "setTemperature", "(", "213.5", ")", ";", "pw", ".", "write", "(", "JSON", ".", "toJSONString", "(", "carDataUploadParam", ")", ")", ";", "pw", ".", "flush", "(", ")", ";", "socket", ".", "shutdownOutput", "(", ")", ";", "String", "reply", "=", "null", ";", "while", "(", "!", "(", "(", "reply", "=", "br", ".", "readLine", "(", ")", ")", "==", "null", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "接收服务器的信息:\" + reply);", "", "", "", "", "", "}", "br", ".", "close", "(", ")", ";", "is", ".", "close", "(", ")", ";", "pw", ".", "close", "(", ")", ";", "os", ".", "close", "(", ")", ";", "socket", ".", "close", "(", ")", ";", "}", "catch", "(", "UnknownHostException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}" ]
Created by guobingwei on 18/5/11.
[ "Created", "by", "guobingwei", "on", "18", "/", "5", "/", "11", "." ]
[ "//1.建立客户端socket连接,指定服务器位置及端口", "//2.得到socket读写流", "//输入流", "//3.利用流按照一定的操作,对socket进行读写操作", "//接收服务器的相应", "//4.关闭资源" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b6987ee48359d0be0ee1fe7f11d405ac0bef7ad
Robb-Greathouse/fsi-real-time-payments
rtp-services/domain-model/src/main/java/rtp/demo/domain/account/OBBCAData1OtherFeesCharges.java
[ "Apache-2.0" ]
Java
OBBCAData1OtherFeesCharges
/** * Contains details of fees and charges which are not associated with either Overdraft or features/benefits */
Contains details of fees and charges which are not associated with either Overdraft or features/benefits
[ "Contains", "details", "of", "fees", "and", "charges", "which", "are", "not", "associated", "with", "either", "Overdraft", "or", "features", "/", "benefits" ]
@ApiModel(description = "Contains details of fees and charges which are not associated with either Overdraft or features/benefits") @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-07-20T02:23:06.926-04:00[America/New_York]") public class OBBCAData1OtherFeesCharges { /** * TariffType which defines the fee and charges. */ public enum TariffTypeEnum { ELECTRONIC("Electronic"), MIXED("Mixed"), OTHER("Other"); private String value; TariffTypeEnum(String value) { this.value = value; } @Override @JsonValue public String toString() { return String.valueOf(value); } @JsonCreator public static TariffTypeEnum fromValue(String text) { for (TariffTypeEnum b : TariffTypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("TariffType") private TariffTypeEnum tariffType = null; @JsonProperty("TariffName") private String tariffName = null; @JsonProperty("OtherTariffType") private OtherTariffType otherTariffType = null; @JsonProperty("FeeChargeDetail") @Valid private List<OBBCAData1FeeChargeDetail> feeChargeDetail = new ArrayList<OBBCAData1FeeChargeDetail>(); @JsonProperty("FeeChargeCap") @Valid private List<OBBCAData1FeeChargeCap> feeChargeCap = null; public OBBCAData1OtherFeesCharges tariffType(TariffTypeEnum tariffType) { this.tariffType = tariffType; return this; } /** * TariffType which defines the fee and charges. * @return tariffType **/ @ApiModelProperty(value = "TariffType which defines the fee and charges.") public TariffTypeEnum getTariffType() { return tariffType; } public void setTariffType(TariffTypeEnum tariffType) { this.tariffType = tariffType; } public OBBCAData1OtherFeesCharges tariffName(String tariffName) { this.tariffName = tariffName; return this; } /** * Name of the tariff * @return tariffName **/ @ApiModelProperty(value = "Name of the tariff") @Size(min=1,max=350) public String getTariffName() { return tariffName; } public void setTariffName(String tariffName) { this.tariffName = tariffName; } public OBBCAData1OtherFeesCharges otherTariffType(OtherTariffType otherTariffType) { this.otherTariffType = otherTariffType; return this; } /** * Get otherTariffType * @return otherTariffType **/ @ApiModelProperty(value = "") @Valid public OtherTariffType getOtherTariffType() { return otherTariffType; } public void setOtherTariffType(OtherTariffType otherTariffType) { this.otherTariffType = otherTariffType; } public OBBCAData1OtherFeesCharges feeChargeDetail(List<OBBCAData1FeeChargeDetail> feeChargeDetail) { this.feeChargeDetail = feeChargeDetail; return this; } public OBBCAData1OtherFeesCharges addFeeChargeDetailItem(OBBCAData1FeeChargeDetail feeChargeDetailItem) { this.feeChargeDetail.add(feeChargeDetailItem); return this; } /** * Other fees/charges details * @return feeChargeDetail **/ @ApiModelProperty(required = true, value = "Other fees/charges details") @NotNull @Valid @Size(min=1) public List<OBBCAData1FeeChargeDetail> getFeeChargeDetail() { return feeChargeDetail; } public void setFeeChargeDetail(List<OBBCAData1FeeChargeDetail> feeChargeDetail) { this.feeChargeDetail = feeChargeDetail; } public OBBCAData1OtherFeesCharges feeChargeCap(List<OBBCAData1FeeChargeCap> feeChargeCap) { this.feeChargeCap = feeChargeCap; return this; } public OBBCAData1OtherFeesCharges addFeeChargeCapItem(OBBCAData1FeeChargeCap feeChargeCapItem) { if (this.feeChargeCap == null) { this.feeChargeCap = new ArrayList<OBBCAData1FeeChargeCap>(); } this.feeChargeCap.add(feeChargeCapItem); return this; } /** * Details about any caps (maximum charges) that apply to a particular or group of fee/charge * @return feeChargeCap **/ @ApiModelProperty(value = "Details about any caps (maximum charges) that apply to a particular or group of fee/charge") @Valid public List<OBBCAData1FeeChargeCap> getFeeChargeCap() { return feeChargeCap; } public void setFeeChargeCap(List<OBBCAData1FeeChargeCap> feeChargeCap) { this.feeChargeCap = feeChargeCap; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OBBCAData1OtherFeesCharges obBCAData1OtherFeesCharges = (OBBCAData1OtherFeesCharges) o; return Objects.equals(this.tariffType, obBCAData1OtherFeesCharges.tariffType) && Objects.equals(this.tariffName, obBCAData1OtherFeesCharges.tariffName) && Objects.equals(this.otherTariffType, obBCAData1OtherFeesCharges.otherTariffType) && Objects.equals(this.feeChargeDetail, obBCAData1OtherFeesCharges.feeChargeDetail) && Objects.equals(this.feeChargeCap, obBCAData1OtherFeesCharges.feeChargeCap); } @Override public int hashCode() { return Objects.hash(tariffType, tariffName, otherTariffType, feeChargeDetail, feeChargeCap); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OBBCAData1OtherFeesCharges {\n"); sb.append(" tariffType: ").append(toIndentedString(tariffType)).append("\n"); sb.append(" tariffName: ").append(toIndentedString(tariffName)).append("\n"); sb.append(" otherTariffType: ").append(toIndentedString(otherTariffType)).append("\n"); sb.append(" feeChargeDetail: ").append(toIndentedString(feeChargeDetail)).append("\n"); sb.append(" feeChargeCap: ").append(toIndentedString(feeChargeCap)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
[ "@", "ApiModel", "(", "description", "=", "\"", "Contains details of fees and charges which are not associated with either Overdraft or features/benefits", "\"", ")", "@", "Validated", "@", "javax", ".", "annotation", ".", "Generated", "(", "value", "=", "\"", "io.swagger.codegen.v3.generators.java.SpringCodegen", "\"", ",", "date", "=", "\"", "2020-07-20T02:23:06.926-04:00[America/New_York]", "\"", ")", "public", "class", "OBBCAData1OtherFeesCharges", "{", "/**\n * TariffType which defines the fee and charges.\n */", "public", "enum", "TariffTypeEnum", "{", "ELECTRONIC", "(", "\"", "Electronic", "\"", ")", ",", "MIXED", "(", "\"", "Mixed", "\"", ")", ",", "OTHER", "(", "\"", "Other", "\"", ")", ";", "private", "String", "value", ";", "TariffTypeEnum", "(", "String", "value", ")", "{", "this", ".", "value", "=", "value", ";", "}", "@", "Override", "@", "JsonValue", "public", "String", "toString", "(", ")", "{", "return", "String", ".", "valueOf", "(", "value", ")", ";", "}", "@", "JsonCreator", "public", "static", "TariffTypeEnum", "fromValue", "(", "String", "text", ")", "{", "for", "(", "TariffTypeEnum", "b", ":", "TariffTypeEnum", ".", "values", "(", ")", ")", "{", "if", "(", "String", ".", "valueOf", "(", "b", ".", "value", ")", ".", "equals", "(", "text", ")", ")", "{", "return", "b", ";", "}", "}", "return", "null", ";", "}", "}", "@", "JsonProperty", "(", "\"", "TariffType", "\"", ")", "private", "TariffTypeEnum", "tariffType", "=", "null", ";", "@", "JsonProperty", "(", "\"", "TariffName", "\"", ")", "private", "String", "tariffName", "=", "null", ";", "@", "JsonProperty", "(", "\"", "OtherTariffType", "\"", ")", "private", "OtherTariffType", "otherTariffType", "=", "null", ";", "@", "JsonProperty", "(", "\"", "FeeChargeDetail", "\"", ")", "@", "Valid", "private", "List", "<", "OBBCAData1FeeChargeDetail", ">", "feeChargeDetail", "=", "new", "ArrayList", "<", "OBBCAData1FeeChargeDetail", ">", "(", ")", ";", "@", "JsonProperty", "(", "\"", "FeeChargeCap", "\"", ")", "@", "Valid", "private", "List", "<", "OBBCAData1FeeChargeCap", ">", "feeChargeCap", "=", "null", ";", "public", "OBBCAData1OtherFeesCharges", "tariffType", "(", "TariffTypeEnum", "tariffType", ")", "{", "this", ".", "tariffType", "=", "tariffType", ";", "return", "this", ";", "}", "/**\n * TariffType which defines the fee and charges.\n * @return tariffType\n **/", "@", "ApiModelProperty", "(", "value", "=", "\"", "TariffType which defines the fee and charges.", "\"", ")", "public", "TariffTypeEnum", "getTariffType", "(", ")", "{", "return", "tariffType", ";", "}", "public", "void", "setTariffType", "(", "TariffTypeEnum", "tariffType", ")", "{", "this", ".", "tariffType", "=", "tariffType", ";", "}", "public", "OBBCAData1OtherFeesCharges", "tariffName", "(", "String", "tariffName", ")", "{", "this", ".", "tariffName", "=", "tariffName", ";", "return", "this", ";", "}", "/**\n * Name of the tariff\n * @return tariffName\n **/", "@", "ApiModelProperty", "(", "value", "=", "\"", "Name of the tariff", "\"", ")", "@", "Size", "(", "min", "=", "1", ",", "max", "=", "350", ")", "public", "String", "getTariffName", "(", ")", "{", "return", "tariffName", ";", "}", "public", "void", "setTariffName", "(", "String", "tariffName", ")", "{", "this", ".", "tariffName", "=", "tariffName", ";", "}", "public", "OBBCAData1OtherFeesCharges", "otherTariffType", "(", "OtherTariffType", "otherTariffType", ")", "{", "this", ".", "otherTariffType", "=", "otherTariffType", ";", "return", "this", ";", "}", "/**\n * Get otherTariffType\n * @return otherTariffType\n **/", "@", "ApiModelProperty", "(", "value", "=", "\"", "\"", ")", "@", "Valid", "public", "OtherTariffType", "getOtherTariffType", "(", ")", "{", "return", "otherTariffType", ";", "}", "public", "void", "setOtherTariffType", "(", "OtherTariffType", "otherTariffType", ")", "{", "this", ".", "otherTariffType", "=", "otherTariffType", ";", "}", "public", "OBBCAData1OtherFeesCharges", "feeChargeDetail", "(", "List", "<", "OBBCAData1FeeChargeDetail", ">", "feeChargeDetail", ")", "{", "this", ".", "feeChargeDetail", "=", "feeChargeDetail", ";", "return", "this", ";", "}", "public", "OBBCAData1OtherFeesCharges", "addFeeChargeDetailItem", "(", "OBBCAData1FeeChargeDetail", "feeChargeDetailItem", ")", "{", "this", ".", "feeChargeDetail", ".", "add", "(", "feeChargeDetailItem", ")", ";", "return", "this", ";", "}", "/**\n * Other fees/charges details\n * @return feeChargeDetail\n **/", "@", "ApiModelProperty", "(", "required", "=", "true", ",", "value", "=", "\"", "Other fees/charges details", "\"", ")", "@", "NotNull", "@", "Valid", "@", "Size", "(", "min", "=", "1", ")", "public", "List", "<", "OBBCAData1FeeChargeDetail", ">", "getFeeChargeDetail", "(", ")", "{", "return", "feeChargeDetail", ";", "}", "public", "void", "setFeeChargeDetail", "(", "List", "<", "OBBCAData1FeeChargeDetail", ">", "feeChargeDetail", ")", "{", "this", ".", "feeChargeDetail", "=", "feeChargeDetail", ";", "}", "public", "OBBCAData1OtherFeesCharges", "feeChargeCap", "(", "List", "<", "OBBCAData1FeeChargeCap", ">", "feeChargeCap", ")", "{", "this", ".", "feeChargeCap", "=", "feeChargeCap", ";", "return", "this", ";", "}", "public", "OBBCAData1OtherFeesCharges", "addFeeChargeCapItem", "(", "OBBCAData1FeeChargeCap", "feeChargeCapItem", ")", "{", "if", "(", "this", ".", "feeChargeCap", "==", "null", ")", "{", "this", ".", "feeChargeCap", "=", "new", "ArrayList", "<", "OBBCAData1FeeChargeCap", ">", "(", ")", ";", "}", "this", ".", "feeChargeCap", ".", "add", "(", "feeChargeCapItem", ")", ";", "return", "this", ";", "}", "/**\n * Details about any caps (maximum charges) that apply to a particular or group of fee/charge\n * @return feeChargeCap\n **/", "@", "ApiModelProperty", "(", "value", "=", "\"", "Details about any caps (maximum charges) that apply to a particular or group of fee/charge", "\"", ")", "@", "Valid", "public", "List", "<", "OBBCAData1FeeChargeCap", ">", "getFeeChargeCap", "(", ")", "{", "return", "feeChargeCap", ";", "}", "public", "void", "setFeeChargeCap", "(", "List", "<", "OBBCAData1FeeChargeCap", ">", "feeChargeCap", ")", "{", "this", ".", "feeChargeCap", "=", "feeChargeCap", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "java", ".", "lang", ".", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "{", "return", "false", ";", "}", "OBBCAData1OtherFeesCharges", "obBCAData1OtherFeesCharges", "=", "(", "OBBCAData1OtherFeesCharges", ")", "o", ";", "return", "Objects", ".", "equals", "(", "this", ".", "tariffType", ",", "obBCAData1OtherFeesCharges", ".", "tariffType", ")", "&&", "Objects", ".", "equals", "(", "this", ".", "tariffName", ",", "obBCAData1OtherFeesCharges", ".", "tariffName", ")", "&&", "Objects", ".", "equals", "(", "this", ".", "otherTariffType", ",", "obBCAData1OtherFeesCharges", ".", "otherTariffType", ")", "&&", "Objects", ".", "equals", "(", "this", ".", "feeChargeDetail", ",", "obBCAData1OtherFeesCharges", ".", "feeChargeDetail", ")", "&&", "Objects", ".", "equals", "(", "this", ".", "feeChargeCap", ",", "obBCAData1OtherFeesCharges", ".", "feeChargeCap", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "Objects", ".", "hash", "(", "tariffType", ",", "tariffName", ",", "otherTariffType", ",", "feeChargeDetail", ",", "feeChargeCap", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "class OBBCAData1OtherFeesCharges {", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " tariffType: ", "\"", ")", ".", "append", "(", "toIndentedString", "(", "tariffType", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " tariffName: ", "\"", ")", ".", "append", "(", "toIndentedString", "(", "tariffName", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " otherTariffType: ", "\"", ")", ".", "append", "(", "toIndentedString", "(", "otherTariffType", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " feeChargeDetail: ", "\"", ")", ".", "append", "(", "toIndentedString", "(", "feeChargeDetail", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " feeChargeCap: ", "\"", ")", ".", "append", "(", "toIndentedString", "(", "feeChargeCap", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", "}", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */", "private", "String", "toIndentedString", "(", "java", ".", "lang", ".", "Object", "o", ")", "{", "if", "(", "o", "==", "null", ")", "{", "return", "\"", "null", "\"", ";", "}", "return", "o", ".", "toString", "(", ")", ".", "replace", "(", "\"", "\\n", "\"", ",", "\"", "\\n", " ", "\"", ")", ";", "}", "}" ]
Contains details of fees and charges which are not associated with either Overdraft or features/benefits
[ "Contains", "details", "of", "fees", "and", "charges", "which", "are", "not", "associated", "with", "either", "Overdraft", "or", "features", "/", "benefits" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b6a5fa6640335428772666426bb785eee8ab019
vsosrc/ambari
contrib/views/files/src/main/java/org/apache/ambari/view/filebrowser/FileOperationService.java
[ "Apache-2.0" ]
Java
FileOperationService
/** * File operations service */
File operations service
[ "File", "operations", "service" ]
public class FileOperationService extends HdfsService { /** * Constructor * @param context View Context instance */ public FileOperationService(ViewContext context) { super(context); } /** * List dir * @param path path * @return response with dir content */ @GET @Path("/listdir") @Produces(MediaType.APPLICATION_JSON) public Response listdir(@QueryParam("path") String path) { try { return Response.ok( HdfsApi.fileStatusToJSON(getApi(context).listdir(path))).build(); } catch (WebApplicationException ex) { throw ex; } catch (FileNotFoundException ex) { throw new NotFoundFormattedException(ex.getMessage(), ex); } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } } /** * Rename * @param request rename request * @return response with success */ @POST @Path("/rename") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response rename(final SrcDstFileRequest request) { try { HdfsApi api = getApi(context); ResponseBuilder result; if (api.rename(request.src, request.dst)) { result = Response.ok(HdfsApi.fileStatusToJSON(api .getFileStatus(request.dst))); } else { result = Response.ok(new BoolResult(false)).status(422); } return result.build(); } catch (WebApplicationException ex) { throw ex; } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } } /** * Copy file * @param request source and destination request * @return response with success */ @POST @Path("/copy") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response copy(final SrcDstFileRequest request, @Context HttpHeaders headers, @Context UriInfo ui) { try { HdfsApi api = getApi(context); ResponseBuilder result; if (api.copy(request.src, request.dst)) { result = Response.ok(HdfsApi.fileStatusToJSON(api .getFileStatus(request.dst))); } else { result = Response.ok(new BoolResult(false)).status(422); } return result.build(); } catch (WebApplicationException ex) { throw ex; } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } } /** * Make directory * @param request make directory request * @return response with success */ @PUT @Path("/mkdir") @Produces(MediaType.APPLICATION_JSON) public Response mkdir(final MkdirRequest request) { try{ HdfsApi api = getApi(context); ResponseBuilder result; if (api.mkdir(request.path)) { result = Response.ok(HdfsApi.fileStatusToJSON(api.getFileStatus(request.path))); } else { result = Response.ok(new BoolResult(false)).status(422); } return result.build(); } catch (WebApplicationException ex) { throw ex; } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } } /** * Empty trash * @return response with success */ @DELETE @Path("/trash/emptyTrash") @Produces(MediaType.APPLICATION_JSON) public Response emptyTrash() { try { HdfsApi api = getApi(context); api.emptyTrash(); return Response.ok(new BoolResult(true)).build(); } catch (WebApplicationException ex) { throw ex; } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } } /** * Move to trash * @param request remove request * @return response with success */ @DELETE @Path("/moveToTrash") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response moveToTrash(RemoveRequest request) { try { HdfsApi api = getApi(context); ResponseBuilder result; if (api.moveToTrash(request.path)){ result = Response.ok(new BoolResult(true)).status(204); } else { result = Response.ok(new BoolResult(false)).status(422); } return result.build(); } catch (WebApplicationException ex) { throw ex; } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } } /** * Remove * @param request remove request * @return response with success */ @DELETE @Path("/remove") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response remove(RemoveRequest request, @Context HttpHeaders headers, @Context UriInfo ui) { try { HdfsApi api = getApi(context); ResponseBuilder result; if (api.delete(request.path, request.recursive)) { result = Response.ok(new BoolResult(true)).status(204); } else { result = Response.ok(new BoolResult(false)).status(422); } return result.build(); } catch (WebApplicationException ex) { throw ex; } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } } /** * Wrapper for json mapping of mkdir request */ @XmlRootElement public static class MkdirRequest { @XmlElement(nillable = false, required = true) public String path; } /** * Wrapper for json mapping of request with * source and destination */ @XmlRootElement public static class SrcDstFileRequest { @XmlElement(nillable = false, required = true) public String src; @XmlElement(nillable = false, required = true) public String dst; } /** * Wrapper for json mapping of remove request */ @XmlRootElement public static class RemoveRequest { @XmlElement(nillable = false, required = true) public String path; public boolean recursive; } }
[ "public", "class", "FileOperationService", "extends", "HdfsService", "{", "/**\n * Constructor\n * @param context View Context instance\n */", "public", "FileOperationService", "(", "ViewContext", "context", ")", "{", "super", "(", "context", ")", ";", "}", "/**\n * List dir\n * @param path path\n * @return response with dir content\n */", "@", "GET", "@", "Path", "(", "\"", "/listdir", "\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "listdir", "(", "@", "QueryParam", "(", "\"", "path", "\"", ")", "String", "path", ")", "{", "try", "{", "return", "Response", ".", "ok", "(", "HdfsApi", ".", "fileStatusToJSON", "(", "getApi", "(", "context", ")", ".", "listdir", "(", "path", ")", ")", ")", ".", "build", "(", ")", ";", "}", "catch", "(", "WebApplicationException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "FileNotFoundException", "ex", ")", "{", "throw", "new", "NotFoundFormattedException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ServiceFormattedException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "/**\n * Rename\n * @param request rename request\n * @return response with success\n */", "@", "POST", "@", "Path", "(", "\"", "/rename", "\"", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "rename", "(", "final", "SrcDstFileRequest", "request", ")", "{", "try", "{", "HdfsApi", "api", "=", "getApi", "(", "context", ")", ";", "ResponseBuilder", "result", ";", "if", "(", "api", ".", "rename", "(", "request", ".", "src", ",", "request", ".", "dst", ")", ")", "{", "result", "=", "Response", ".", "ok", "(", "HdfsApi", ".", "fileStatusToJSON", "(", "api", ".", "getFileStatus", "(", "request", ".", "dst", ")", ")", ")", ";", "}", "else", "{", "result", "=", "Response", ".", "ok", "(", "new", "BoolResult", "(", "false", ")", ")", ".", "status", "(", "422", ")", ";", "}", "return", "result", ".", "build", "(", ")", ";", "}", "catch", "(", "WebApplicationException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ServiceFormattedException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "/**\n * Copy file\n * @param request source and destination request\n * @return response with success\n */", "@", "POST", "@", "Path", "(", "\"", "/copy", "\"", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "copy", "(", "final", "SrcDstFileRequest", "request", ",", "@", "Context", "HttpHeaders", "headers", ",", "@", "Context", "UriInfo", "ui", ")", "{", "try", "{", "HdfsApi", "api", "=", "getApi", "(", "context", ")", ";", "ResponseBuilder", "result", ";", "if", "(", "api", ".", "copy", "(", "request", ".", "src", ",", "request", ".", "dst", ")", ")", "{", "result", "=", "Response", ".", "ok", "(", "HdfsApi", ".", "fileStatusToJSON", "(", "api", ".", "getFileStatus", "(", "request", ".", "dst", ")", ")", ")", ";", "}", "else", "{", "result", "=", "Response", ".", "ok", "(", "new", "BoolResult", "(", "false", ")", ")", ".", "status", "(", "422", ")", ";", "}", "return", "result", ".", "build", "(", ")", ";", "}", "catch", "(", "WebApplicationException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ServiceFormattedException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "/**\n * Make directory\n * @param request make directory request\n * @return response with success\n */", "@", "PUT", "@", "Path", "(", "\"", "/mkdir", "\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "mkdir", "(", "final", "MkdirRequest", "request", ")", "{", "try", "{", "HdfsApi", "api", "=", "getApi", "(", "context", ")", ";", "ResponseBuilder", "result", ";", "if", "(", "api", ".", "mkdir", "(", "request", ".", "path", ")", ")", "{", "result", "=", "Response", ".", "ok", "(", "HdfsApi", ".", "fileStatusToJSON", "(", "api", ".", "getFileStatus", "(", "request", ".", "path", ")", ")", ")", ";", "}", "else", "{", "result", "=", "Response", ".", "ok", "(", "new", "BoolResult", "(", "false", ")", ")", ".", "status", "(", "422", ")", ";", "}", "return", "result", ".", "build", "(", ")", ";", "}", "catch", "(", "WebApplicationException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ServiceFormattedException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "/**\n * Empty trash\n * @return response with success\n */", "@", "DELETE", "@", "Path", "(", "\"", "/trash/emptyTrash", "\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "emptyTrash", "(", ")", "{", "try", "{", "HdfsApi", "api", "=", "getApi", "(", "context", ")", ";", "api", ".", "emptyTrash", "(", ")", ";", "return", "Response", ".", "ok", "(", "new", "BoolResult", "(", "true", ")", ")", ".", "build", "(", ")", ";", "}", "catch", "(", "WebApplicationException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ServiceFormattedException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "/**\n * Move to trash\n * @param request remove request\n * @return response with success\n */", "@", "DELETE", "@", "Path", "(", "\"", "/moveToTrash", "\"", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "moveToTrash", "(", "RemoveRequest", "request", ")", "{", "try", "{", "HdfsApi", "api", "=", "getApi", "(", "context", ")", ";", "ResponseBuilder", "result", ";", "if", "(", "api", ".", "moveToTrash", "(", "request", ".", "path", ")", ")", "{", "result", "=", "Response", ".", "ok", "(", "new", "BoolResult", "(", "true", ")", ")", ".", "status", "(", "204", ")", ";", "}", "else", "{", "result", "=", "Response", ".", "ok", "(", "new", "BoolResult", "(", "false", ")", ")", ".", "status", "(", "422", ")", ";", "}", "return", "result", ".", "build", "(", ")", ";", "}", "catch", "(", "WebApplicationException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ServiceFormattedException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "/**\n * Remove\n * @param request remove request\n * @return response with success\n */", "@", "DELETE", "@", "Path", "(", "\"", "/remove", "\"", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "remove", "(", "RemoveRequest", "request", ",", "@", "Context", "HttpHeaders", "headers", ",", "@", "Context", "UriInfo", "ui", ")", "{", "try", "{", "HdfsApi", "api", "=", "getApi", "(", "context", ")", ";", "ResponseBuilder", "result", ";", "if", "(", "api", ".", "delete", "(", "request", ".", "path", ",", "request", ".", "recursive", ")", ")", "{", "result", "=", "Response", ".", "ok", "(", "new", "BoolResult", "(", "true", ")", ")", ".", "status", "(", "204", ")", ";", "}", "else", "{", "result", "=", "Response", ".", "ok", "(", "new", "BoolResult", "(", "false", ")", ")", ".", "status", "(", "422", ")", ";", "}", "return", "result", ".", "build", "(", ")", ";", "}", "catch", "(", "WebApplicationException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ServiceFormattedException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "/**\n * Wrapper for json mapping of mkdir request\n */", "@", "XmlRootElement", "public", "static", "class", "MkdirRequest", "{", "@", "XmlElement", "(", "nillable", "=", "false", ",", "required", "=", "true", ")", "public", "String", "path", ";", "}", "/**\n * Wrapper for json mapping of request with\n * source and destination\n */", "@", "XmlRootElement", "public", "static", "class", "SrcDstFileRequest", "{", "@", "XmlElement", "(", "nillable", "=", "false", ",", "required", "=", "true", ")", "public", "String", "src", ";", "@", "XmlElement", "(", "nillable", "=", "false", ",", "required", "=", "true", ")", "public", "String", "dst", ";", "}", "/**\n * Wrapper for json mapping of remove request\n */", "@", "XmlRootElement", "public", "static", "class", "RemoveRequest", "{", "@", "XmlElement", "(", "nillable", "=", "false", ",", "required", "=", "true", ")", "public", "String", "path", ";", "public", "boolean", "recursive", ";", "}", "}" ]
File operations service
[ "File", "operations", "service" ]
[]
[ { "param": "HdfsService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HdfsService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b6a5fa6640335428772666426bb785eee8ab019
vsosrc/ambari
contrib/views/files/src/main/java/org/apache/ambari/view/filebrowser/FileOperationService.java
[ "Apache-2.0" ]
Java
MkdirRequest
/** * Wrapper for json mapping of mkdir request */
Wrapper for json mapping of mkdir request
[ "Wrapper", "for", "json", "mapping", "of", "mkdir", "request" ]
@XmlRootElement public static class MkdirRequest { @XmlElement(nillable = false, required = true) public String path; }
[ "@", "XmlRootElement", "public", "static", "class", "MkdirRequest", "{", "@", "XmlElement", "(", "nillable", "=", "false", ",", "required", "=", "true", ")", "public", "String", "path", ";", "}" ]
Wrapper for json mapping of mkdir request
[ "Wrapper", "for", "json", "mapping", "of", "mkdir", "request" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b6a5fa6640335428772666426bb785eee8ab019
vsosrc/ambari
contrib/views/files/src/main/java/org/apache/ambari/view/filebrowser/FileOperationService.java
[ "Apache-2.0" ]
Java
SrcDstFileRequest
/** * Wrapper for json mapping of request with * source and destination */
Wrapper for json mapping of request with source and destination
[ "Wrapper", "for", "json", "mapping", "of", "request", "with", "source", "and", "destination" ]
@XmlRootElement public static class SrcDstFileRequest { @XmlElement(nillable = false, required = true) public String src; @XmlElement(nillable = false, required = true) public String dst; }
[ "@", "XmlRootElement", "public", "static", "class", "SrcDstFileRequest", "{", "@", "XmlElement", "(", "nillable", "=", "false", ",", "required", "=", "true", ")", "public", "String", "src", ";", "@", "XmlElement", "(", "nillable", "=", "false", ",", "required", "=", "true", ")", "public", "String", "dst", ";", "}" ]
Wrapper for json mapping of request with source and destination
[ "Wrapper", "for", "json", "mapping", "of", "request", "with", "source", "and", "destination" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b6a5fa6640335428772666426bb785eee8ab019
vsosrc/ambari
contrib/views/files/src/main/java/org/apache/ambari/view/filebrowser/FileOperationService.java
[ "Apache-2.0" ]
Java
RemoveRequest
/** * Wrapper for json mapping of remove request */
Wrapper for json mapping of remove request
[ "Wrapper", "for", "json", "mapping", "of", "remove", "request" ]
@XmlRootElement public static class RemoveRequest { @XmlElement(nillable = false, required = true) public String path; public boolean recursive; }
[ "@", "XmlRootElement", "public", "static", "class", "RemoveRequest", "{", "@", "XmlElement", "(", "nillable", "=", "false", ",", "required", "=", "true", ")", "public", "String", "path", ";", "public", "boolean", "recursive", ";", "}" ]
Wrapper for json mapping of remove request
[ "Wrapper", "for", "json", "mapping", "of", "remove", "request" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b6fb028410c7d13a0eef4b60e3ef73a2350240f
honjay88/video
app/src/main/java/honjay/common/utils/Rxbus/Event.java
[ "Apache-2.0" ]
Java
Event
/** * Created by honjayChen on 2017/3/25. */
Created by honjayChen on 2017/3/25.
[ "Created", "by", "honjayChen", "on", "2017", "/", "3", "/", "25", "." ]
public class Event { private String content; public Event(String content) { this.content = content; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
[ "public", "class", "Event", "{", "private", "String", "content", ";", "public", "Event", "(", "String", "content", ")", "{", "this", ".", "content", "=", "content", ";", "}", "public", "String", "getContent", "(", ")", "{", "return", "content", ";", "}", "public", "void", "setContent", "(", "String", "content", ")", "{", "this", ".", "content", "=", "content", ";", "}", "}" ]
Created by honjayChen on 2017/3/25.
[ "Created", "by", "honjayChen", "on", "2017", "/", "3", "/", "25", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b70407492ce7160fa3d845984d9e83df5fb45b5
TextFileDataTools/text-file-data-tools
src/main/java/stexfires/core/filter/SizeFilter.java
[ "MIT" ]
Java
SizeFilter
/** * @author Mathias Kalb * @since 0.1 */
@author Mathias Kalb @since 0.1
[ "@author", "Mathias", "Kalb", "@since", "0", ".", "1" ]
public class SizeFilter<T extends TextRecord> implements RecordFilter<T> { private final IntPredicate sizePredicate; public SizeFilter(IntPredicate sizePredicate) { Objects.requireNonNull(sizePredicate); this.sizePredicate = sizePredicate; } public static <T extends TextRecord> SizeFilter<T> compare(NumberComparisonType numberComparisonType, int compareSize) { return new SizeFilter<>(numberComparisonType.intPredicate(compareSize)); } public static <T extends TextRecord> SizeFilter<T> check(NumberCheckType numberCheckType) { return new SizeFilter<>(numberCheckType.intPredicate()); } public static <T extends TextRecord> SizeFilter<T> equalTo(int compareSize) { return compare(EQUAL_TO, compareSize); } public static <T extends TextRecord> SizeFilter<T> isEmpty() { return compare(EQUAL_TO, 0); } public static <T extends TextRecord> SizeFilter<T> containedIn(Collection<Integer> sizes) { return new SizeFilter<>(sizes::contains); } @SuppressWarnings("OverloadedVarargsMethod") public static <T extends TextRecord> SizeFilter<T> containedIn(Integer... sizes) { return containedIn(Arrays.asList(sizes)); } public static <T extends TextRecord> SizeFilter<T> between(int from, int to) { return new SizeFilter<>( GREATER_THAN_OR_EQUAL_TO.intPredicate(from) .and(LESS_THAN.intPredicate(to))); } @Override public final boolean isValid(T record) { return sizePredicate.test(record.size()); } }
[ "public", "class", "SizeFilter", "<", "T", "extends", "TextRecord", ">", "implements", "RecordFilter", "<", "T", ">", "{", "private", "final", "IntPredicate", "sizePredicate", ";", "public", "SizeFilter", "(", "IntPredicate", "sizePredicate", ")", "{", "Objects", ".", "requireNonNull", "(", "sizePredicate", ")", ";", "this", ".", "sizePredicate", "=", "sizePredicate", ";", "}", "public", "static", "<", "T", "extends", "TextRecord", ">", "SizeFilter", "<", "T", ">", "compare", "(", "NumberComparisonType", "numberComparisonType", ",", "int", "compareSize", ")", "{", "return", "new", "SizeFilter", "<", ">", "(", "numberComparisonType", ".", "intPredicate", "(", "compareSize", ")", ")", ";", "}", "public", "static", "<", "T", "extends", "TextRecord", ">", "SizeFilter", "<", "T", ">", "check", "(", "NumberCheckType", "numberCheckType", ")", "{", "return", "new", "SizeFilter", "<", ">", "(", "numberCheckType", ".", "intPredicate", "(", ")", ")", ";", "}", "public", "static", "<", "T", "extends", "TextRecord", ">", "SizeFilter", "<", "T", ">", "equalTo", "(", "int", "compareSize", ")", "{", "return", "compare", "(", "EQUAL_TO", ",", "compareSize", ")", ";", "}", "public", "static", "<", "T", "extends", "TextRecord", ">", "SizeFilter", "<", "T", ">", "isEmpty", "(", ")", "{", "return", "compare", "(", "EQUAL_TO", ",", "0", ")", ";", "}", "public", "static", "<", "T", "extends", "TextRecord", ">", "SizeFilter", "<", "T", ">", "containedIn", "(", "Collection", "<", "Integer", ">", "sizes", ")", "{", "return", "new", "SizeFilter", "<", ">", "(", "sizes", "::", "contains", ")", ";", "}", "@", "SuppressWarnings", "(", "\"", "OverloadedVarargsMethod", "\"", ")", "public", "static", "<", "T", "extends", "TextRecord", ">", "SizeFilter", "<", "T", ">", "containedIn", "(", "Integer", "...", "sizes", ")", "{", "return", "containedIn", "(", "Arrays", ".", "asList", "(", "sizes", ")", ")", ";", "}", "public", "static", "<", "T", "extends", "TextRecord", ">", "SizeFilter", "<", "T", ">", "between", "(", "int", "from", ",", "int", "to", ")", "{", "return", "new", "SizeFilter", "<", ">", "(", "GREATER_THAN_OR_EQUAL_TO", ".", "intPredicate", "(", "from", ")", ".", "and", "(", "LESS_THAN", ".", "intPredicate", "(", "to", ")", ")", ")", ";", "}", "@", "Override", "public", "final", "boolean", "isValid", "(", "T", "record", ")", "{", "return", "sizePredicate", ".", "test", "(", "record", ".", "size", "(", ")", ")", ";", "}", "}" ]
@author Mathias Kalb @since 0.1
[ "@author", "Mathias", "Kalb", "@since", "0", ".", "1" ]
[]
[ { "param": "RecordFilter<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "RecordFilter<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b734e6acc246790dae9ff22432e64ea8e8e2a1b
tqrg-bot/spring-webflow
spring-binding/src/main/java/org/springframework/binding/expression/spel/SpringELExpressionParser.java
[ "Apache-2.0" ]
Java
SpringELExpressionParser
/** * Adapt the Spring EL {@link SpelExpressionParser} to the Spring Binding * {@link ExpressionParser} contract. * * @author Rossen Stoyanchev * @since 2.1.0 */
Adapt the Spring EL SpelExpressionParser to the Spring Binding ExpressionParser contract. @author Rossen Stoyanchev @since 2.1.0
[ "Adapt", "the", "Spring", "EL", "SpelExpressionParser", "to", "the", "Spring", "Binding", "ExpressionParser", "contract", ".", "@author", "Rossen", "Stoyanchev", "@since", "2", ".", "1", ".", "0" ]
public class SpringELExpressionParser implements ExpressionParser { private final SpelExpressionParser expressionParser; private final ConversionService conversionService; private final List<PropertyAccessor> propertyAccessors = new ArrayList<>(); private final SimpleEvaluationContextFactory simpleContextFactory; public SpringELExpressionParser(SpelExpressionParser expressionParser) { this(expressionParser, new DefaultConversionService()); } public SpringELExpressionParser(SpelExpressionParser expressionParser, ConversionService conversionService) { this.expressionParser = expressionParser; this.propertyAccessors.add(new MapAccessor()); this.conversionService = conversionService; this.simpleContextFactory = new SimpleEvaluationContextFactory(this.propertyAccessors, conversionService); } public ConversionService getConversionService() { return conversionService; } public void addPropertyAccessor(PropertyAccessor propertyAccessor) { propertyAccessors.add(propertyAccessor); } public Expression parseExpression(String expression, ParserContext context) throws ParserException { Assert.hasText(expression, "The expression string to parse is required and must not be empty"); context = (context == null) ? NullParserContext.INSTANCE : context; Map<String, Expression> expressionVars = parseSpelExpressionVariables(context.getExpressionVariables()); org.springframework.expression.Expression spelExpression = parseSpelExpression(expression, context); Class<?> expectedResultType = context.getExpectedEvaluationResultType(); org.springframework.core.convert.ConversionService cs = conversionService.getDelegateConversionService(); return context instanceof SimpleParserContext ? new SpringELExpression(spelExpression, expectedResultType, simpleContextFactory) : createSpringELExpression(expressionVars, spelExpression, expectedResultType, cs); } /** * Create the {@link SpringELExpression}. * <p><strong>Note:</strong> as of 2.4.8, this method is not invoked when a * {@link SimpleParserContext} is passed in, which is mainly the case when using * SpEL for data binding. In those scenarios, the configuration options are * limited to the use of property accessors and a ConversionService. */ protected SpringELExpression createSpringELExpression(Map<String, Expression> expressionVars, org.springframework.expression.Expression spelExpression, Class<?> expectedResultType, org.springframework.core.convert.ConversionService conversionService) { return new SpringELExpression(spelExpression, expressionVars, expectedResultType, conversionService, propertyAccessors); } private org.springframework.expression.Expression parseSpelExpression(String expression, ParserContext context) { org.springframework.expression.ParserContext spelParserContext = getSpelParserContext(context); if (spelParserContext != null) { return expressionParser.parseExpression(expression, spelParserContext); } return expressionParser.parseExpression(expression); } private org.springframework.expression.ParserContext getSpelParserContext(ParserContext context) { return context.isTemplate() ? org.springframework.expression.ParserContext.TEMPLATE_EXPRESSION : null; } /** * Turn {@link ExpressionVariable}'s (pairs of variable names and string expressions) * into a map of variable names and parsed Spring EL expressions. The map will be saved * in a Spring EL {@link EvaluationContext} for later use at evaluation time. * * @param expressionVars an array of ExpressionVariable instances. * @return a Map or null if the input array is empty. */ private Map<String, Expression> parseSpelExpressionVariables(ExpressionVariable[] expressionVars) { if (expressionVars == null || expressionVars.length == 0) { return null; } Map<String, Expression> result = new HashMap<>(expressionVars.length); for (ExpressionVariable var : expressionVars) { result.put(var.getName(), parseExpression(var.getValueExpression(), var.getParserContext())); } return result; } }
[ "public", "class", "SpringELExpressionParser", "implements", "ExpressionParser", "{", "private", "final", "SpelExpressionParser", "expressionParser", ";", "private", "final", "ConversionService", "conversionService", ";", "private", "final", "List", "<", "PropertyAccessor", ">", "propertyAccessors", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "private", "final", "SimpleEvaluationContextFactory", "simpleContextFactory", ";", "public", "SpringELExpressionParser", "(", "SpelExpressionParser", "expressionParser", ")", "{", "this", "(", "expressionParser", ",", "new", "DefaultConversionService", "(", ")", ")", ";", "}", "public", "SpringELExpressionParser", "(", "SpelExpressionParser", "expressionParser", ",", "ConversionService", "conversionService", ")", "{", "this", ".", "expressionParser", "=", "expressionParser", ";", "this", ".", "propertyAccessors", ".", "add", "(", "new", "MapAccessor", "(", ")", ")", ";", "this", ".", "conversionService", "=", "conversionService", ";", "this", ".", "simpleContextFactory", "=", "new", "SimpleEvaluationContextFactory", "(", "this", ".", "propertyAccessors", ",", "conversionService", ")", ";", "}", "public", "ConversionService", "getConversionService", "(", ")", "{", "return", "conversionService", ";", "}", "public", "void", "addPropertyAccessor", "(", "PropertyAccessor", "propertyAccessor", ")", "{", "propertyAccessors", ".", "add", "(", "propertyAccessor", ")", ";", "}", "public", "Expression", "parseExpression", "(", "String", "expression", ",", "ParserContext", "context", ")", "throws", "ParserException", "{", "Assert", ".", "hasText", "(", "expression", ",", "\"", "The expression string to parse is required and must not be empty", "\"", ")", ";", "context", "=", "(", "context", "==", "null", ")", "?", "NullParserContext", ".", "INSTANCE", ":", "context", ";", "Map", "<", "String", ",", "Expression", ">", "expressionVars", "=", "parseSpelExpressionVariables", "(", "context", ".", "getExpressionVariables", "(", ")", ")", ";", "org", ".", "springframework", ".", "expression", ".", "Expression", "spelExpression", "=", "parseSpelExpression", "(", "expression", ",", "context", ")", ";", "Class", "<", "?", ">", "expectedResultType", "=", "context", ".", "getExpectedEvaluationResultType", "(", ")", ";", "org", ".", "springframework", ".", "core", ".", "convert", ".", "ConversionService", "cs", "=", "conversionService", ".", "getDelegateConversionService", "(", ")", ";", "return", "context", "instanceof", "SimpleParserContext", "?", "new", "SpringELExpression", "(", "spelExpression", ",", "expectedResultType", ",", "simpleContextFactory", ")", ":", "createSpringELExpression", "(", "expressionVars", ",", "spelExpression", ",", "expectedResultType", ",", "cs", ")", ";", "}", "/**\n\t * Create the {@link SpringELExpression}.\n\t * <p><strong>Note:</strong> as of 2.4.8, this method is not invoked when a\n\t * {@link SimpleParserContext} is passed in, which is mainly the case when using\n\t * SpEL for data binding. In those scenarios, the configuration options are\n\t * limited to the use of property accessors and a ConversionService.\n\t */", "protected", "SpringELExpression", "createSpringELExpression", "(", "Map", "<", "String", ",", "Expression", ">", "expressionVars", ",", "org", ".", "springframework", ".", "expression", ".", "Expression", "spelExpression", ",", "Class", "<", "?", ">", "expectedResultType", ",", "org", ".", "springframework", ".", "core", ".", "convert", ".", "ConversionService", "conversionService", ")", "{", "return", "new", "SpringELExpression", "(", "spelExpression", ",", "expressionVars", ",", "expectedResultType", ",", "conversionService", ",", "propertyAccessors", ")", ";", "}", "private", "org", ".", "springframework", ".", "expression", ".", "Expression", "parseSpelExpression", "(", "String", "expression", ",", "ParserContext", "context", ")", "{", "org", ".", "springframework", ".", "expression", ".", "ParserContext", "spelParserContext", "=", "getSpelParserContext", "(", "context", ")", ";", "if", "(", "spelParserContext", "!=", "null", ")", "{", "return", "expressionParser", ".", "parseExpression", "(", "expression", ",", "spelParserContext", ")", ";", "}", "return", "expressionParser", ".", "parseExpression", "(", "expression", ")", ";", "}", "private", "org", ".", "springframework", ".", "expression", ".", "ParserContext", "getSpelParserContext", "(", "ParserContext", "context", ")", "{", "return", "context", ".", "isTemplate", "(", ")", "?", "org", ".", "springframework", ".", "expression", ".", "ParserContext", ".", "TEMPLATE_EXPRESSION", ":", "null", ";", "}", "/**\n\t * Turn {@link ExpressionVariable}'s (pairs of variable names and string expressions)\n\t * into a map of variable names and parsed Spring EL expressions. The map will be saved\n\t * in a Spring EL {@link EvaluationContext} for later use at evaluation time.\n\t *\n\t * @param expressionVars an array of ExpressionVariable instances.\n\t * @return a Map or null if the input array is empty.\n\t */", "private", "Map", "<", "String", ",", "Expression", ">", "parseSpelExpressionVariables", "(", "ExpressionVariable", "[", "]", "expressionVars", ")", "{", "if", "(", "expressionVars", "==", "null", "||", "expressionVars", ".", "length", "==", "0", ")", "{", "return", "null", ";", "}", "Map", "<", "String", ",", "Expression", ">", "result", "=", "new", "HashMap", "<", ">", "(", "expressionVars", ".", "length", ")", ";", "for", "(", "ExpressionVariable", "var", ":", "expressionVars", ")", "{", "result", ".", "put", "(", "var", ".", "getName", "(", ")", ",", "parseExpression", "(", "var", ".", "getValueExpression", "(", ")", ",", "var", ".", "getParserContext", "(", ")", ")", ")", ";", "}", "return", "result", ";", "}", "}" ]
Adapt the Spring EL {@link SpelExpressionParser} to the Spring Binding {@link ExpressionParser} contract.
[ "Adapt", "the", "Spring", "EL", "{", "@link", "SpelExpressionParser", "}", "to", "the", "Spring", "Binding", "{", "@link", "ExpressionParser", "}", "contract", "." ]
[]
[ { "param": "ExpressionParser", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ExpressionParser", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }