input
stringlengths 20
285k
| output
stringlengths 20
285k
|
---|---|
public ContainerManager(ServletContext servletContext)
{
instance = this;
webResourceIntegration = new SimpleWebResourceIntegration(servletContext);
webResourceManager = new WebResourceManagerImpl(webResourceIntegration);
File pluginDir = new File(servletContext.getRealPath("/WEB-INF/plugins"));
if (!pluginDir.exists())
{
pluginDir.mkdirs();
}
moduleDescriptorFactory = new DefaultModuleDescriptorFactory();
moduleDescriptorFactory.addModuleDescriptor("servlet", SimpleServletModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-filter", SimpleFilterModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-param", ServletContextParamModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-listener", SimpleContextListenerModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("web-resource", WebResourceModuleDescriptor.class);
DefaultPackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration();
List<String> packageIncludes = new ArrayList<String>(scannerConfig.getPackageIncludes());
packageIncludes.add("org.bouncycastle*");
scannerConfig.setPackageIncludes(packageIncludes);
hostComponentProvider = new SimpleHostComponentProvider();
PluginsConfiguration config = new PluginsConfigurationBuilder()
.setPluginDirectory(pluginDir)
.setModuleDescriptorFactory(moduleDescriptorFactory)
.setPackageScannerConfiguration(scannerConfig)
.setHostComponentProvider(hostComponentProvider)
.setFrameworkBundlesDirectory(new File(servletContext.getRealPath("/WEB-INF/framework-bundles")))
.build();
plugins = new AtlassianPlugins(config);
PluginEventManager pluginEventManager = plugins.getPluginEventManager();
osgiContainerManager = plugins.getOsgiContainerManager();
servletModuleManager = new DefaultServletModuleManager(pluginEventManager);
publicContainer = new HashMap<Class,Object>();
pluginAccessor = plugins.getPluginAccessor();
publicContainer.put(PluginController.class, plugins.getPluginController());
publicContainer.put(PluginAccessor.class, pluginAccessor);
publicContainer.put(PluginEventManager.class, pluginEventManager);
publicContainer.put(Map.class, publicContainer);
try {
plugins.start();
}
catch (PluginParseException e)
{
e.printStackTrace();
}
downloadStrategies = new ArrayList<DownloadStrategy>();
PluginResourceDownload pluginDownloadStrategy = new PluginResourceDownload();
pluginDownloadStrategy.setPluginAccessor(pluginAccessor);
pluginDownloadStrategy.setContentTypeResolver(new SimpleContentTypeResolver());
pluginDownloadStrategy.setCharacterEncoding("UTF-8");
downloadStrategies.add(pluginDownloadStrategy);
}
| public ContainerManager(ServletContext servletContext)
{
instance = this;
webResourceIntegration = new SimpleWebResourceIntegration(servletContext);
webResourceManager = new WebResourceManagerImpl(webResourceIntegration);
File pluginDir = new File(servletContext.getRealPath("/WEB-INF/plugins"));
if (!pluginDir.exists())
{
pluginDir.mkdirs();
}
File bundlesDir = new File(servletContext.getRealPath("/WEB-INF/framework-bundles"));
if (!bundlesDir.exists())
{
bundlesDir.mkdirs();
}
moduleDescriptorFactory = new DefaultModuleDescriptorFactory();
moduleDescriptorFactory.addModuleDescriptor("servlet", SimpleServletModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-filter", SimpleFilterModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-param", ServletContextParamModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-listener", SimpleContextListenerModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("web-resource", WebResourceModuleDescriptor.class);
DefaultPackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration();
List<String> packageIncludes = new ArrayList<String>(scannerConfig.getPackageIncludes());
packageIncludes.add("org.bouncycastle*");
scannerConfig.setPackageIncludes(packageIncludes);
hostComponentProvider = new SimpleHostComponentProvider();
PluginsConfiguration config = new PluginsConfigurationBuilder()
.setPluginDirectory(pluginDir)
.setModuleDescriptorFactory(moduleDescriptorFactory)
.setPackageScannerConfiguration(scannerConfig)
.setHostComponentProvider(hostComponentProvider)
.setFrameworkBundlesDirectory()
.build();
plugins = new AtlassianPlugins(config);
PluginEventManager pluginEventManager = plugins.getPluginEventManager();
osgiContainerManager = plugins.getOsgiContainerManager();
servletModuleManager = new DefaultServletModuleManager(pluginEventManager);
publicContainer = new HashMap<Class,Object>();
pluginAccessor = plugins.getPluginAccessor();
publicContainer.put(PluginController.class, plugins.getPluginController());
publicContainer.put(PluginAccessor.class, pluginAccessor);
publicContainer.put(PluginEventManager.class, pluginEventManager);
publicContainer.put(Map.class, publicContainer);
try {
plugins.start();
}
catch (PluginParseException e)
{
e.printStackTrace();
}
downloadStrategies = new ArrayList<DownloadStrategy>();
PluginResourceDownload pluginDownloadStrategy = new PluginResourceDownload();
pluginDownloadStrategy.setPluginAccessor(pluginAccessor);
pluginDownloadStrategy.setContentTypeResolver(new SimpleContentTypeResolver());
pluginDownloadStrategy.setCharacterEncoding("UTF-8");
downloadStrategies.add(pluginDownloadStrategy);
}
|
protected void doDSPost(Context c, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
int groupID = UIUtil.getIntParameter(request, "group_id");
Group group = null;
if (groupID >= 0)
{
group = Group.find(c, groupID);
}
if (group != null)
{
AuthorizeManager.authorizeAction(c, group, Constants.ADD);
boolean submit_edit = (request.getParameter("submit_edit") != null);
boolean submit_group_update = (request
.getParameter("submit_group_update") != null);
boolean submit_group_delete = (request
.getParameter("submit_group_delete") != null);
if (submit_edit && !submit_group_update && !submit_group_delete)
{
request.setAttribute("group", group);
request.setAttribute("members", group.getMembers());
request.setAttribute("membergroups", group.getMemberGroups());
JSPManager.showJSP(request, response, "/tools/group-edit.jsp");
}
else if (submit_group_update)
{
String newName = request.getParameter("group_name");
if (!newName.equals(group.getName()))
{
group.setName(newName);
group.update();
}
int[] eperson_ids = UIUtil.getIntParameters(request,
"eperson_id");
int[] group_ids = UIUtil.getIntParameters(request, "group_ids");
EPerson[] members = group.getMembers();
Group[] membergroups = group.getMemberGroups();
if (eperson_ids != null)
{
Set memberSet = new HashSet();
Set epersonIDSet = new HashSet();
for (int x = 0; x < members.length; x++)
{
Integer epersonID = new Integer(members[x].getID());
memberSet.add(epersonID);
}
for (int x = 0; x < eperson_ids.length; x++)
{
epersonIDSet.add(new Integer(eperson_ids[x]));
}
Iterator i = epersonIDSet.iterator();
while (i.hasNext())
{
Integer currentID = (Integer) i.next();
if (!memberSet.contains(currentID))
{
group.addMember(EPerson.find(c, currentID
.intValue()));
}
}
for (int x = 0; x < members.length; x++)
{
EPerson e = members[x];
if (!epersonIDSet.contains(new Integer(e.getID())))
{
group.removeMember(e);
}
}
}
else
{
for (int y = 0; y < members.length; y++)
{
group.removeMember(members[y]);
}
}
if (group_ids != null)
{
Set memberSet = new HashSet();
Set groupIDSet = new HashSet();
for (int x = 0; x < membergroups.length; x++)
{
Integer myID = new Integer(membergroups[x].getID());
memberSet.add(myID);
}
for (int x = 0; x < group_ids.length; x++)
{
groupIDSet.add(new Integer(group_ids[x]));
}
Iterator i = groupIDSet.iterator();
while (i.hasNext())
{
Integer currentID = (Integer) i.next();
if (!memberSet.contains(currentID))
{
group
.addMember(Group.find(c, currentID
.intValue()));
}
}
for (int x = 0; x < membergroups.length; x++)
{
Group g = membergroups[x];
if (!groupIDSet.contains(new Integer(g.getID())))
{
group.removeMember(g);
}
}
}
else
{
for (int y = 0; y < membergroups.length; y++)
{
group.removeMember(membergroups[y]);
}
}
group.update();
request.setAttribute("group", group);
request.setAttribute("members", group.getMembers());
request.setAttribute("membergroups", group.getMemberGroups());
JSPManager.showJSP(request, response, "/tools/group-edit.jsp");
c.complete();
}
else if (submit_group_delete)
{
AuthorizeManager.authorizeAction(c, group, Constants.WRITE);
group.delete();
showMainPage(c, request, response);
c.complete();
}
else
{
request.setAttribute("group", group);
request.setAttribute("members", group.getMembers());
request.setAttribute("membergroups", group.getMemberGroups());
JSPManager.showJSP(request, response, "/tools/group-edit.jsp");
}
}
else
{
String button = UIUtil.getSubmitButton(request, "submit");
if (button.equals("submit_add"))
{
group = Group.create(c);
group.setName("new group" + group.getID());
group.update();
request.setAttribute("group", group);
request.setAttribute("members", group.getMembers());
request.setAttribute("membergroups", group.getMemberGroups());
JSPManager.showJSP(request, response, "/tools/group-edit.jsp");
c.complete();
}
else
{
showMainPage(c, request, response);
}
}
}
| protected void doDSPost(Context c, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
int groupID = UIUtil.getIntParameter(request, "group_id");
Group group = null;
if (groupID >= 0)
{
group = Group.find(c, groupID);
}
if (group != null)
{
AuthorizeManager.authorizeAction(c, group, Constants.ADD);
boolean submit_edit = (request.getParameter("submit_edit") != null);
boolean submit_group_update = (request
.getParameter("submit_group_update") != null);
boolean submit_group_delete = (request
.getParameter("submit_group_delete") != null);
if (submit_edit && !submit_group_update && !submit_group_delete)
{
request.setAttribute("group", group);
request.setAttribute("members", group.getMembers());
request.setAttribute("membergroups", group.getMemberGroups());
JSPManager.showJSP(request, response, "/tools/group-edit.jsp");
}
else if (submit_group_update)
{
String newName = request.getParameter("group_name");
if (!newName.equals(group.getName()))
{
group.setName(newName);
group.update();
}
int[] eperson_ids = UIUtil.getIntParameters(request,
"eperson_id");
int[] group_ids = UIUtil.getIntParameters(request, "group_ids");
EPerson[] members = group.getMembers();
Group[] membergroups = group.getMemberGroups();
if (eperson_ids != null)
{
Set memberSet = new HashSet();
Set epersonIDSet = new HashSet();
for (int x = 0; x < members.length; x++)
{
Integer epersonID = new Integer(members[x].getID());
memberSet.add(epersonID);
}
for (int x = 0; x < eperson_ids.length; x++)
{
epersonIDSet.add(new Integer(eperson_ids[x]));
}
Iterator i = epersonIDSet.iterator();
while (i.hasNext())
{
Integer currentID = (Integer) i.next();
if (!memberSet.contains(currentID))
{
group.addMember(EPerson.find(c, currentID
.intValue()));
}
}
for (int x = 0; x < members.length; x++)
{
EPerson e = members[x];
if (!epersonIDSet.contains(new Integer(e.getID())))
{
group.removeMember(e);
}
}
}
else
{
for (int y = 0; y < members.length; y++)
{
group.removeMember(members[y]);
}
}
if (group_ids != null)
{
Set memberSet = new HashSet();
Set groupIDSet = new HashSet();
for (int x = 0; x < membergroups.length; x++)
{
Integer myID = new Integer(membergroups[x].getID());
memberSet.add(myID);
}
for (int x = 0; x < group_ids.length; x++)
{
groupIDSet.add(new Integer(group_ids[x]));
}
Iterator i = groupIDSet.iterator();
while (i.hasNext())
{
Integer currentID = (Integer) i.next();
if (!memberSet.contains(currentID))
{
group
.addMember(Group.find(c, currentID
.intValue()));
}
}
for (int x = 0; x < membergroups.length; x++)
{
Group g = membergroups[x];
if (!groupIDSet.contains(new Integer(g.getID())))
{
group.removeMember(g);
}
}
}
else
{
for (int y = 0; y < membergroups.length; y++)
{
group.removeMember(membergroups[y]);
}
}
group.update();
request.setAttribute("group", group);
request.setAttribute("members", group.getMembers());
request.setAttribute("membergroups", group.getMemberGroups());
JSPManager.showJSP(request, response, "/tools/group-edit.jsp");
c.complete();
}
else if (submit_group_delete)
{
AuthorizeManager.authorizeAction(c, group, Constants.WRITE);
group.delete();
showMainPage(c, request, response);
}
else
{
request.setAttribute("group", group);
request.setAttribute("members", group.getMembers());
request.setAttribute("membergroups", group.getMemberGroups());
JSPManager.showJSP(request, response, "/tools/group-edit.jsp");
}
}
else
{
String button = UIUtil.getSubmitButton(request, "submit");
if (button.equals("submit_add"))
{
group = Group.create(c);
group.setName("new group" + group.getID());
group.update();
request.setAttribute("group", group);
request.setAttribute("members", group.getMembers());
request.setAttribute("membergroups", group.getMemberGroups());
JSPManager.showJSP(request, response, "/tools/group-edit.jsp");
c.complete();
}
else
{
showMainPage(c, request, response);
}
}
}
|
protected ProcessBuilder getProcessBuilder(ILaunchConfiguration config, Fixture fixture) throws CoreException {
IReadOnlyStore store = new LaunchConfigurationReadOnlyStore(config);
ProcessBuilder pb = super.getProcessBuilder(config, fixture);
List<String> list = new ArrayList<String>();
if (record.fixLintErrors.get(store)) {
list.add(record.fixjsstyleCommand.get(store));
} else {
list.add(record.gjslintCommand.get(store));
}
List<IResource> resources = record.inputResources.get(store);
if (resources.isEmpty()) {
throw new CoreException(new Status(Status.ERROR, OwJsClosurePlugin.PLUGIN_ID, messages.getString("ClosureLinterLaunchConfigurationDelegate_noInputResource")));
}
IReadOnlyStore storeForLinterOptions = store;
if (record.useProjectPropertiesForLinterChecks.get(store)) {
IProject project = ClosureCompiler.getCommonProject(resources);
if (project == null) throw new CoreException(new Status(Status.ERROR, OwJsClosurePlugin.PLUGIN_ID, messages.getString("ClosureLinterLaunchConfigurationDelegate_differentProjects")));
store = new ResourcePropertyStore(project, OwJsClosurePlugin.PLUGIN_ID);
}
String customJsDocTags = record.linterChecks.customJsdocTags.get(storeForLinterOptions);
if (customJsDocTags.length() > 0) {
list.add("--custom_jsdoc_tags");
list.add(customJsDocTags);
}
Set<String> lintErrorChecks = record.linterChecks.lintErrorChecks.get(storeForLinterOptions);
for (String lintErrorCheck: lintErrorChecks) {
list.add("--jslint_error");
list.add(lintErrorCheck);
}
list.add(record.linterChecks.strictClosureStyle.get(storeForLinterOptions) ? "--strict" : "--nostrict");
list.add(record.linterChecks.missingJsdoc.get(storeForLinterOptions) ? "--jsdoc" : "--nojsdoc");
list.add("--nobeep");
for (IFile file: ClosureCompiler.getJavaScriptFiles(resources)) {
list.add(file.getLocation().toOSString());
clearProblemMarkers(file);
}
pb.command(list);
return pb;
}
| protected ProcessBuilder getProcessBuilder(ILaunchConfiguration config, Fixture fixture) throws CoreException {
IReadOnlyStore store = new LaunchConfigurationReadOnlyStore(config);
ProcessBuilder pb = super.getProcessBuilder(config, fixture);
List<String> list = new ArrayList<String>();
boolean fixLintErrors = record.fixLintErrors.get(store);
if (fixLintErrors) {
list.add(record.fixjsstyleCommand.get(store));
} else {
list.add(record.gjslintCommand.get(store));
}
List<IResource> resources = record.inputResources.get(store);
if (resources.isEmpty()) {
throw new CoreException(new Status(Status.ERROR, OwJsClosurePlugin.PLUGIN_ID, messages.getString("ClosureLinterLaunchConfigurationDelegate_noInputResource")));
}
IReadOnlyStore storeForLinterOptions = store;
if (record.useProjectPropertiesForLinterChecks.get(store)) {
IProject project = ClosureCompiler.getCommonProject(resources);
if (project == null) throw new CoreException(new Status(Status.ERROR, OwJsClosurePlugin.PLUGIN_ID, messages.getString("ClosureLinterLaunchConfigurationDelegate_differentProjects")));
store = new ResourcePropertyStore(project, OwJsClosurePlugin.PLUGIN_ID);
}
String customJsDocTags = record.linterChecks.customJsdocTags.get(storeForLinterOptions);
if (customJsDocTags.length() > 0) {
list.add("--custom_jsdoc_tags");
list.add(customJsDocTags);
}
Set<String> lintErrorChecks = record.linterChecks.lintErrorChecks.get(storeForLinterOptions);
for (String lintErrorCheck: lintErrorChecks) {
list.add("--jslint_error");
list.add(lintErrorCheck);
}
list.add(record.linterChecks.strictClosureStyle.get(storeForLinterOptions) ? "--strict" : "--nostrict");
list.add(record.linterChecks.missingJsdoc.get(storeForLinterOptions) ? "--jsdoc" : "--nojsdoc");
if (!fixLintErrors)
list.add("--nobeep");
for (IFile file: ClosureCompiler.getJavaScriptFiles(resources)) {
list.add(file.getLocation().toOSString());
clearProblemMarkers(file);
}
pb.command(list);
return pb;
}
|
private void dispatchCases(boolean origin, boolean destination,
AbstractHalfEdge edge, Triangle t) {
lastMergeSource = null;
lastMergeTarget = null;
lastSplitted1 = null;
lastSplitted2 = null;
if (triangleProjector1.getType() == ProjectionType.OUT && !destination) {
triangleSplitter.splitApex(edge.destination(),
triangleProjector1.getProjection(),
triangleProjector1.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector1.getProjection(),
edge.origin(), edge.destination(), lastMergeTarget,
lastMergeSource, triangleProjector1.sqrTolerance);
if (l > triangleProjector1.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted1 = edge;
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (triangleProjector2.getType() == ProjectionType.OUT && !origin) {
triangleSplitter.splitApex(edge.origin(),
triangleProjector2.getProjection(),
triangleProjector2.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector2.getProjection(),
edge.destination(), edge.origin(), lastMergeTarget,
lastMergeSource, triangleProjector2.sqrTolerance);
if (l > triangleProjector2.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (origin && triangleProjector1.getType() == ProjectionType.VERTEX &&
edge.origin() != triangleProjector1.getVertex())
{
lastMergeSource = edge.origin();
lastMergeTarget = triangleProjector1.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else if (destination && triangleProjector2.getType() == ProjectionType.VERTEX &&
edge.destination() != triangleProjector2.getVertex())
{
lastMergeSource = edge.destination();
lastMergeTarget = triangleProjector2.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else if (origin && triangleProjector1.getType() == ProjectionType.FACE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.FACE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
} else if (origin && triangleProjector1.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
}
if (lastMergeSource != null && lastMergeTarget != null && !canMerge(lastMergeSource,
lastMergeTarget)) {
lastMergeTarget = null;
}
}
| private void dispatchCases(boolean origin, boolean destination,
AbstractHalfEdge edge, Triangle t) {
lastMergeSource = null;
lastMergeTarget = null;
lastSplitted1 = null;
lastSplitted2 = null;
if (triangleProjector1.getType() == ProjectionType.OUT && !destination) {
triangleSplitter.splitApex(edge.destination(),
triangleProjector1.getProjection(),
triangleProjector1.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
if(lastMergeTarget != null && !lastMergeTarget.isMutable())
lastMergeTarget = null;
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector1.getProjection(),
edge.origin(), edge.destination(), lastMergeTarget,
lastMergeSource, triangleProjector1.sqrTolerance);
if (l > triangleProjector1.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted1 = edge;
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (triangleProjector2.getType() == ProjectionType.OUT && !origin) {
triangleSplitter.splitApex(edge.origin(),
triangleProjector2.getProjection(),
triangleProjector2.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
if(lastMergeTarget != null && !lastMergeTarget.isMutable())
lastMergeTarget = null;
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector2.getProjection(),
edge.destination(), edge.origin(), lastMergeTarget,
lastMergeSource, triangleProjector2.sqrTolerance);
if (l > triangleProjector2.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (origin && triangleProjector1.getType() == ProjectionType.VERTEX &&
edge.origin() != triangleProjector1.getVertex())
{
lastMergeSource = edge.origin();
lastMergeTarget = triangleProjector1.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else if (destination && triangleProjector2.getType() == ProjectionType.VERTEX &&
edge.destination() != triangleProjector2.getVertex())
{
lastMergeSource = edge.destination();
lastMergeTarget = triangleProjector2.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else if (origin && triangleProjector1.getType() == ProjectionType.FACE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.FACE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
} else if (origin && triangleProjector1.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
}
if (lastMergeSource != null && lastMergeTarget != null && !canMerge(lastMergeSource,
lastMergeTarget)) {
lastMergeTarget = null;
}
}
|
public Track apply(@Nullable String strTitle)
{
int rankPos = strTitle.indexOf(".");
String strRank = strTitle.substring(0, rankPos);
String strArtistAndSong = strTitle.substring(rankPos + 1);
String strTempSong = strArtistAndSong.substring(0, strArtistAndSong.lastIndexOf("-"));
String strTempArtist = strArtistAndSong.substring(strArtistAndSong.lastIndexOf("-") + 1);
String strSong = strTempSong;
strSong = StringUtils.remove(strSong, String.format("(%s)", StringUtils.substringBetween(strSong, "(", ")")));
strSong = StringUtils.remove(strSong, String.format("[%s]", StringUtils.substringBetween(strSong, "[", "]")));
String strArtist = strTempArtist;
String strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "(", ")"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "[", "]"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
final Set<String> artistNames =StringTools.split(strArtist, new String[] { "Featuring", "Feat\\.","feat\\.", "&",","});
return new Track(Integer.parseInt(strRank), artistNames, strSong);
}
| public Track apply(@Nullable String strTitle)
{
int rankPos = strTitle.indexOf(".");
String strRank = strTitle.substring(0, rankPos);
String strArtistAndSong = strTitle.substring(rankPos + 1);
String strTempSong = strArtistAndSong.substring(0, strArtistAndSong.lastIndexOf(" - "));
String strTempArtist = strArtistAndSong.substring(strArtistAndSong.lastIndexOf(" - ") + 2);
String strSong = strTempSong;
strSong = StringUtils.remove(strSong, String.format("(%s)", StringUtils.substringBetween(strSong, "(", ")")));
strSong = StringUtils.remove(strSong, String.format("[%s]", StringUtils.substringBetween(strSong, "[", "]")));
String strArtist = strTempArtist;
String strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "(", ")"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "[", "]"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
final Set<String> artistNames =StringTools.split(strArtist, new String[] { "Featuring", "Feat\\.","feat\\.", "&",","});
return new Track(Integer.parseInt(strRank), artistNames, strSong);
}
|
public void onEntityDamage(EntityDamageEvent event) {
if (event.getEntity() instanceof Wolf) {
Wolf wolf = (Wolf) event.getEntity();
if (wolf.isTamed()) {
if (event instanceof EntityDamageByEntityEvent && wolf.getOwner() instanceof Player) {
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event;
Player owner = (Player) wolf.getOwner();
if (damageEvent.getDamager().equals(owner) && owner.getItemInHand().getType() == Material.BONE) {
wolf.setOwner(null);
wolf.setSitting(false);
owner.sendMessage(ChatColor.RED + "You have released your wolf!");
}
else if(damageEvent.getDamager() instanceof Player) {
Player attacker = (Player) damageEvent.getDamager();
if (attacker.isOp() && attacker.getItemInHand().getType() == Material.BONE && !owner.isOp()) {
wolf.setOwner(null);
wolf.setSitting(false);
attacker.sendMessage(ChatColor.RED + "You have released " + owner.getDisplayName() + "'s wolf!");
if (owner.isOnline())
owner.sendMessage(ChatColor.RED + attacker.getDisplayName() + " has released your wolf!");
}
}
}
event.setCancelled(true);
}
}
if (event.getEntity() instanceof Player && event instanceof EntityDamageByEntityEvent) {
Player player = (Player) event.getEntity();
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event;
if (damageEvent.getDamager() instanceof Wolf) {
Wolf wolf = (Wolf) damageEvent.getDamager();
if (wolf.isTamed() && wolf.getOwner() instanceof Player) {
Player owner = (Player) wolf.getOwner();
if (owner.equals(player)) {
wolf.setTarget(null);
event.setCancelled(true);
}
}
}
if (damageEvent.getDamager().equals(damageEvent.getEntity()))
event.setCancelled(true);
}
}
| public void onEntityDamage(EntityDamageEvent event) {
if (event.getEntity() instanceof Wolf) {
Wolf wolf = (Wolf) event.getEntity();
if (wolf.isTamed()) {
if (event instanceof EntityDamageByEntityEvent && wolf.getOwner() instanceof Player) {
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event;
Player owner = (Player) wolf.getOwner();
if (damageEvent.getDamager().equals(owner) && owner.getItemInHand().getType() == Material.BONE) {
wolf.setOwner(null);
wolf.setSitting(false);
owner.sendMessage(ChatColor.RED + "You have released your wolf!");
}
else if(damageEvent.getDamager() instanceof Player) {
Player attacker = (Player) damageEvent.getDamager();
if (attacker.isOp() && attacker.getItemInHand().getType() == Material.BONE) {
if (!owner.isOp()) {
wolf.setOwner(null);
wolf.setSitting(false);
attacker.sendMessage(ChatColor.RED + "You have released " + owner.getDisplayName() + "'s wolf!");
if (owner.isOnline())
owner.sendMessage(ChatColor.RED + attacker.getDisplayName() + " has released your wolf!");
} else {
attacker.sendMessage(ChatColor.RED + "You may not release another op's wolves!");
}
}
}
}
event.setCancelled(true);
}
}
if (event.getEntity() instanceof Player && event instanceof EntityDamageByEntityEvent) {
Player player = (Player) event.getEntity();
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event;
if (damageEvent.getDamager() instanceof Wolf) {
Wolf wolf = (Wolf) damageEvent.getDamager();
if (wolf.isTamed() && wolf.getOwner() instanceof Player) {
Player owner = (Player) wolf.getOwner();
if (owner.equals(player)) {
wolf.setTarget(null);
event.setCancelled(true);
}
}
}
if (damageEvent.getDamager().equals(damageEvent.getEntity()))
event.setCancelled(true);
}
}
|
private void createWordPinyinRelation(JdbcTemplate jdbcTemplate, int wordId, String wordName) {
if (wordName.length() == 1) {
NodeRepository observeBank = WordToPinyinClassfierFactory.apply().getClassifier().model().getObserveBank();
Node o = observeBank.get(wordName);
if (o != null) {
Emission emission = WordToPinyinClassfierFactory.apply().getClassifier().model().getEmission();
Collection stateProbByObserve = emission.getStateProbByObserve(o.getIndex());
if (null != stateProbByObserve) {
NodeRepository stateBank = WordToPinyinClassfierFactory.apply().getClassifier().model().getStateBank();
for (Object i : stateProbByObserve) {
Node state = stateBank.get(Integer.parseInt(i.toString()));
jdbcTemplate.execute("INSERT INTO Pinyins (WordId, Name) VALUES (" +
+wordId + ",'" + state.getName() + "')");
}
}
}
} else {
List<String> pinyinList = WordToPinyinClassfierFactory.apply().getClassifier().classify(wordName);
String pinyin = join(pinyinList, "'");
jdbcTemplate.update("INSERT INTO Pinyins (WordId, Name) VALUES (" +
+wordId + ", ?)", pinyin);
}
}
| private void createWordPinyinRelation(JdbcTemplate jdbcTemplate, int wordId, String wordName) {
if (wordName.length() == 1) {
NodeRepository observeBank = WordToPinyinClassfierFactory.apply().getClassifier().model().getObserveBank();
Node o = observeBank.get(wordName);
if (o != null) {
Emission emission = WordToPinyinClassfierFactory.apply().getClassifier().model().getEmission();
Collection stateProbByObserve = emission.getStatesBy(o.getIndex());
if (null != stateProbByObserve) {
NodeRepository stateBank = WordToPinyinClassfierFactory.apply().getClassifier().model().getStateBank();
for (Object i : stateProbByObserve) {
Node state = stateBank.get(Integer.parseInt(i.toString()));
jdbcTemplate.execute("INSERT INTO Pinyins (WordId, Name) VALUES (" +
+wordId + ",'" + state.getName() + "')");
}
}
}
} else {
List<String> pinyinList = WordToPinyinClassfierFactory.apply().getClassifier().classify(wordName);
String pinyin = join(pinyinList, "'");
jdbcTemplate.update("INSERT INTO Pinyins (WordId, Name) VALUES (" +
+wordId + ", ?)", pinyin);
}
}
|
public void test(TestHarness harness)
{
MyBasicLookAndFeel laf = new MyBasicLookAndFeel();
UIDefaults defaults = new UIDefaults();
laf.initComponentDefaults(defaults);
harness.checkPoint("AuditoryCues");
harness.check(defaults.get("AuditoryCues.allAuditoryCues") != null);
harness.check(defaults.get("AuditoryCues.cueList") != null);
harness.check(defaults.get("AuditoryCues.noAuditoryCues") != null);
harness.checkPoint("Button");
CompoundBorderUIResource b1 = (CompoundBorderUIResource) defaults.get("Button.border");
harness.check(b1.getInsideBorder() instanceof MarginBorder);
harness.check(b1.getOutsideBorder() instanceof ButtonBorder);
harness.check(defaults.get("Button.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Button.margin"), new InsetsUIResource(2, 14, 2, 14));
harness.check(defaults.get("Button.textIconGap"), new Integer(4));
harness.check(defaults.get("Button.textShiftOffset"), new Integer(0));
harness.check(defaults.get("Button.focusInputMap") instanceof InputMapUIResource);
Object b = UIManager.get("Button.focusInputMap");
InputMapUIResource bim = (InputMapUIResource) b;
KeyStroke[] kb = bim.keys();
harness.check(kb.length == 2);
harness.check(bim.get(KeyStroke.getKeyStroke("SPACE")), "pressed");
harness.check(bim.get(KeyStroke.getKeyStroke("released SPACE")), "released");
harness.checkPoint("CheckBox");
CompoundBorderUIResource b2 = (CompoundBorderUIResource) defaults.get("CheckBox.border");
harness.check(b2.getInsideBorder() instanceof MarginBorder);
harness.check(b2.getOutsideBorder() instanceof ButtonBorder);
harness.check(defaults.get("CheckBox.focusInputMap") instanceof InputMapUIResource);
Object c = UIManager.get("CheckBox.focusInputMap");
InputMapUIResource cim = (InputMapUIResource) c;
KeyStroke[] kc = cim.keys();
harness.check(kc.length == 2);
harness.check(cim.get(KeyStroke.getKeyStroke("SPACE")), "pressed");
harness.check(cim.get(KeyStroke.getKeyStroke("released SPACE")), "released");
harness.check(defaults.get("CheckBox.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("CheckBox.icon") instanceof Icon);
harness.check(defaults.get("CheckBox.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.check(defaults.get("CheckBox.textIconGap"), new Integer(4));
harness.check(defaults.get("CheckBox.textShiftOffset"), new Integer(0));
harness.checkPoint("CheckBoxMenuItem");
harness.check(defaults.get("CheckBoxMenuItem.acceleratorFont"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("CheckBoxMenuItem.arrowIcon") instanceof Icon);
harness.check(defaults.get("CheckBoxMenuItem.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("CheckBoxMenuItem.borderPainted"), Boolean.FALSE);
harness.check(defaults.get("CheckBoxMenuItem.checkIcon") instanceof Icon);
harness.check(defaults.get("CheckBoxMenuItem.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("CheckBoxMenuItem.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.checkPoint("ColorChooser");
harness.check(defaults.get("ColorChooser.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("ColorChooser.rgbBlueMnemonic"), new Integer(66));
harness.check(defaults.get("ColorChooser.rgbGreenMnemonic"), new Integer(78));
harness.check(defaults.get("ColorChooser.rgbRedMnemonic"), new Integer(68));
harness.check(defaults.get("ColorChooser.swatchesRecentSwatchSize"), new Dimension(10, 10));
harness.check(defaults.get("ColorChooser.swatchesSwatchSize"), new Dimension(10, 10));
harness.checkPoint("ComboBox");
harness.check(defaults.get("ComboBox.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("ComboBox.font"), new FontUIResource("SansSerif", Font.PLAIN, 12));
harness.checkPoint("Desktop");
harness.check(defaults.get("Desktop.ancestorInputMap") instanceof InputMapUIResource);
harness.checkPoint("DesktopIcon");
harness.check(defaults.get("DesktopIcon.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.checkPoint("EditorPane");
harness.check(defaults.get("EditorPane.background"), new ColorUIResource(255, 255, 255));
harness.check(defaults.get("EditorPane.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("EditorPane.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("EditorPane.font"), new FontUIResource("Serif", Font.PLAIN, 12));
harness.check(defaults.get("EditorPane.margin"), new InsetsUIResource(3, 3, 3, 3));
Object e = UIManager.get("EditorPane.focusInputMap");
InputMapUIResource eim = (InputMapUIResource) e;
KeyStroke[] ke = eim.keys();
harness.check(ke.length == 55);
harness.check(eim.get(KeyStroke.getKeyStroke("shift UP")), "selection-up");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(eim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selection-up");
harness.check(eim.get(KeyStroke.getKeyStroke("DOWN")), "caret-down");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl T")), "previous-link-action");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(eim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(eim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "selection-page-up");
harness.check(eim.get(KeyStroke.getKeyStroke("KP_UP")), "caret-up");
harness.check(eim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl HOME")), "caret-begin");
harness.check(eim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl END")), "caret-end");
harness.check(eim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(eim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(eim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "activate-link-action");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(eim.get(KeyStroke.getKeyStroke("ENTER")), "insert-break");
harness.check(eim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(eim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "selection-page-left");
harness.check(eim.get(KeyStroke.getKeyStroke("shift DOWN")), "selection-down");
harness.check(eim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "page-down");
harness.check(eim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "selection-page-right");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(eim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(eim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("KP_DOWN")), "caret-down");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(eim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selection-end");
harness.check(eim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl T")), "next-link-action");
harness.check(eim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selection-down");
harness.check(eim.get(KeyStroke.getKeyStroke("TAB")), "insert-tab");
harness.check(eim.get(KeyStroke.getKeyStroke("UP")), "caret-up");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selection-begin");
harness.check(eim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "selection-page-down");
harness.check(eim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(eim.get(KeyStroke.getKeyStroke("PAGE_UP")), "page-up");
harness.check(eim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.checkPoint("FileChooser");
harness.check(defaults.get("FileChooser.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("FileChooser.cancelButtonMnemonic"), new Integer(67));
harness.check(defaults.get("FileChooser.directoryOpenButtonMnemonic"), new Integer(79));
harness.check(defaults.get("FileChooser.helpButtonMnemonic"), new Integer(72));
harness.check(defaults.get("FileChooser.openButtonMnemonic"), new Integer(79));
harness.check(defaults.get("FileChooser.saveButtonMnemonic"), new Integer(83));
harness.check(defaults.get("FileChooser.updateButtonMnemonic"), new Integer(85));
harness.checkPoint("FileView");
harness.checkPoint("FormattedTextField");
harness.check(defaults.get("FormattedTextField.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("FormattedTextField.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("FormattedTextField.focusInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("FormattedTextField.font"), new FontUIResource("SansSerif", Font.PLAIN, 12));
harness.check(defaults.get("FormattedTextField.margin"), new InsetsUIResource(0, 0, 0, 0));
Object f = UIManager.get("FormattedTextField.focusInputMap");
InputMapUIResource fim = (InputMapUIResource) f;
KeyStroke[] kf = fim.keys();
harness.check(kf.length == 38);
harness.check(fim.get(KeyStroke.getKeyStroke("KP_UP")), "increment");
harness.check(fim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(fim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(fim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(fim.get(KeyStroke.getKeyStroke("KP_DOWN")), "decrement");
harness.check(fim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(fim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(fim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(fim.get(KeyStroke.getKeyStroke("UP")), "increment");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(fim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(fim.get(KeyStroke.getKeyStroke("ESCAPE")), "reset-field-edit");
harness.check(fim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(fim.get(KeyStroke.getKeyStroke("DOWN")), "decrement");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(fim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(fim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(fim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(fim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.check(fim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(fim.get(KeyStroke.getKeyStroke("ENTER")), "notify-field-accept");
harness.check(fim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.checkPoint("InternalFrame");
harness.check(defaults.get("InternalFrame.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.check(defaults.get("InternalFrame.closeIcon") instanceof Icon);
harness.check(defaults.get("InternalFrame.iconifyIcon") instanceof Icon);
harness.check(defaults.get("InternalFrame.maximizeIcon") instanceof Icon);
harness.check(defaults.get("InternalFrame.minimizeIcon") instanceof Icon);
harness.check(defaults.get("InternalFrame.titleFont"), new FontUIResource("Dialog", Font.BOLD, 12));
harness.check(defaults.get("InternalFrame.windowBindings") instanceof Object[]);
harness.checkPoint("Label");
harness.check(defaults.get("Label.disabledForeground"), new ColorUIResource(255, 255, 255));
harness.check(defaults.get("Label.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("List");
harness.check(defaults.get("List.cellRenderer") instanceof ListCellRenderer);
harness.check(defaults.get("List.focusCellHighlightBorder") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("List.focusInputMap") instanceof InputMapUIResource);
Object l = UIManager.get("List.focusInputMap");
InputMapUIResource lim = (InputMapUIResource) l;
KeyStroke[] kl = lim.keys();
harness.check(kl.length == 61);
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl DOWN")), "selectNextRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift UP")), "selectPreviousRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "selectNextColumnChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selectPreviousColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selectPreviousRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("DOWN")), "selectNextRow");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl UP")), "selectPreviousRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "selectPreviousColumnChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("CUT")), "cut");
harness.check(lim.get(KeyStroke.getKeyStroke("END")), "selectLastRow");
harness.check(lim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "scrollUpExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("KP_UP")), "selectPreviousRow");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl UP")), "selectPreviousRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl HOME")), "selectFirstRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift LEFT")), "selectPreviousColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl END")), "selectLastRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl PAGE_DOWN")), "scrollDownChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selectNextColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("LEFT")), "selectPreviousColumn");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl PAGE_UP")), "scrollUpChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("KP_LEFT")), "selectPreviousColumn");
harness.check(lim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selectNextColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("SPACE")), "addToSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "toggleAndAnchor");
harness.check(lim.get(KeyStroke.getKeyStroke("shift SPACE")), "extendTo");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl SPACE")), "moveSelectionTo");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl DOWN")), "selectNextRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "clearSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift HOME")), "selectFirstRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("RIGHT")), "selectNextColumn");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "scrollUpExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift DOWN")), "selectNextRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "scrollDown");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl KP_UP")), "selectPreviousRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selectPreviousColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl X")), "cut");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "scrollDownExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl SLASH")), "selectAll");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl C")), "copy");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "selectNextColumnChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift END")), "selectLastRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl KP_DOWN")), "selectNextRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "selectPreviousColumnChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("HOME")), "selectFirstRow");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl V")), "paste");
harness.check(lim.get(KeyStroke.getKeyStroke("KP_DOWN")), "selectNextRow");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl KP_DOWN")), "selectNextRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selectNextColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl A")), "selectAll");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selectLastRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("COPY")), "copy");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl KP_UP")), "selectPreviousRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selectPreviousColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selectNextRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("UP")), "selectPreviousRow");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selectFirstRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "scrollDownExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "selectNextColumn");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selectNextColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("PAGE_UP")), "scrollUp");
harness.check(lim.get(KeyStroke.getKeyStroke("PASTE")), "paste");
harness.check(defaults.get("List.focusInputMap.RightToLeft") instanceof InputMapUIResource);
harness.check(defaults.get("List.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("Menu");
harness.check(defaults.get("Menu.acceleratorFont"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Menu.arrowIcon") instanceof Icon);
harness.check(defaults.get("Menu.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("Menu.borderPainted"), Boolean.FALSE);
harness.check(defaults.get("Menu.checkIcon") instanceof Icon);
harness.check(defaults.get("Menu.crossMenuMnemonic"), Boolean.TRUE);
harness.check(defaults.get("Menu.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Menu.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.check(defaults.get("Menu.menuPopupOffsetX"), new Integer(0));
harness.check(defaults.get("Menu.menuPopupOffsetY"), new Integer(0));
int[] shortcuts = (int[]) defaults.get("Menu.shortcutKeys");
if (shortcuts == null)
shortcuts = new int[] { 999 };
harness.check(shortcuts.length, 1);
harness.check(shortcuts[0], 8);
harness.check(defaults.get("Menu.submenuPopupOffsetX"), new Integer(0));
harness.check(defaults.get("Menu.submenuPopupOffsetY"), new Integer(0));
harness.checkPoint("MenuBar");
harness.check(defaults.get("MenuBar.border") instanceof BasicBorders.MenuBarBorder);
harness.check(defaults.get("MenuBar.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("MenuBar.windowBindings") instanceof Object[]);
harness.checkPoint("MenuItem");
harness.check(defaults.get("MenuItem.acceleratorDelimiter"), "+");
harness.check(defaults.get("MenuItem.acceleratorFont"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("MenuItem.arrowIcon") instanceof Icon);
harness.check(defaults.get("MenuItem.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("MenuItem.borderPainted"), Boolean.FALSE);
harness.check(defaults.get("MenuItem.checkIcon") instanceof Icon);
harness.check(defaults.get("MenuItem.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("MenuItem.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.checkPoint("OptionPane");
harness.check(defaults.get("OptionPane.border") instanceof BorderUIResource.EmptyBorderUIResource);
harness.check(defaults.get("OptionPane.buttonAreaBorder") instanceof BorderUIResource.EmptyBorderUIResource);
harness.check(defaults.get("OptionPane.buttonClickThreshhold"), new Integer(500));
harness.check(defaults.get("OptionPane.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("OptionPane.messageAreaBorder") instanceof BorderUIResource.EmptyBorderUIResource);
harness.check(defaults.get("OptionPane.minimumSize"), new DimensionUIResource(262, 90));
harness.check(defaults.get("OptionPane.windowBindings") instanceof Object[]);
harness.checkPoint("Panel");
harness.check(defaults.get("Panel.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("PasswordField");
harness.check(defaults.get("PasswordField.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("PasswordField.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("PasswordField.font"), new FontUIResource("MonoSpaced", Font.PLAIN, 12));
harness.check(defaults.get("PasswordField.margin"), new InsetsUIResource(0, 0, 0, 0));
harness.check(UIManager.get("PasswordField.focusInputMap") instanceof InputMapUIResource);
Object o = UIManager.get("PasswordField.focusInputMap");
InputMapUIResource im = (InputMapUIResource) o;
KeyStroke[] k = im.keys();
harness.check(k.length == 33);
harness.check(im.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(im.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(im.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(im.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(im.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(im.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(im.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(im.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(im.get(KeyStroke.getKeyStroke("ENTER")), "notify-field-accept");
harness.check(im.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.checkPoint("PopupMenu");
harness.check(defaults.get("PopupMenu.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.check(defaults.get("PopupMenu.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("PopupMenu.selectedWindowInputMapBindings") instanceof Object[]);
harness.check(defaults.get("PopupMenu.selectedWindowInputMapBindings.RightToLeft") instanceof Object[]);
harness.checkPoint("ProgressBar");
harness.check(defaults.get("ProgressBar.border") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("ProgressBar.cellLength"), new Integer(1));
harness.check(defaults.get("ProgressBar.cellSpacing"), new Integer(0));
harness.check(defaults.get("ProgressBar.cycleTime"), new Integer(3000));
harness.check(defaults.get("ProgressBar.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("ProgressBar.repaintInterval"), new Integer(50));
harness.checkPoint("RadioButton");
harness.check(defaults.get("RadioButton.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.check(defaults.get("RadioButton.focusInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("RadioButton.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("RadioButton.icon") instanceof Icon);
harness.check(defaults.get("RadioButton.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.check(defaults.get("RadioButton.textIconGap"), new Integer(4));
harness.check(defaults.get("RadioButton.textShiftOffset"), new Integer(0));
harness.checkPoint("RadioButtonMenuItem");
harness.check(defaults.get("RadioButtonMenuItem.acceleratorFont"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("RadioButtonMenuItem.arrowIcon") instanceof Icon);
harness.check(defaults.get("RadioButtonMenuItem.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("RadioButtonMenuItem.borderPainted"), Boolean.FALSE);
harness.check(defaults.get("RadioButtonMenuItem.checkIcon") instanceof Icon);
harness.check(defaults.get("RadioButtonMenuItem.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("RadioButtonMenuItem.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.check(defaults.get("RootPane.defaultButtonWindowKeyBindings") instanceof Object[]);
harness.checkPoint("ScrollBar");
harness.check(defaults.get("ScrollBar.background"), new ColorUIResource(224, 224, 224));
harness.check(defaults.get("ScrollBar.focusInputMap") instanceof InputMap);
harness.check(defaults.get("ScrollBar.focusInputMap.RightToLeft") instanceof InputMap);
harness.check(defaults.get("ScrollBar.maximumThumbSize"), new DimensionUIResource(4096, 4096));
harness.check(defaults.get("ScrollBar.minimumThumbSize"), new DimensionUIResource(8, 8));
harness.check(defaults.get("ScrollBar.width"), new Integer(16));
harness.check(defaults.get("ScrollPane.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("ScrollPane.ancestorInputMap.RightToLeft") instanceof InputMapUIResource);
harness.check(defaults.get("ScrollPane.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("ScrollPane.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("Slider");
InputMap map = (InputMap) defaults.get("Slider.focusInputMap");
KeyStroke[] keys = map.keys();
InputMap focusInputMap = (InputMap) defaults.get("Slider.focusInputMap");
List keyList = Arrays.asList(keys);
harness.check(keyList.contains(KeyStroke.getKeyStroke("LEFT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("RIGHT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("UP")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("DOWN")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_LEFT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_RIGHT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_UP")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_DOWN")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("HOME")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("END")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("PAGE_UP")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("PAGE_DOWN")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("ctrl PAGE_UP")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("ctrl PAGE_DOWN")));
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("LEFT")), "negativeUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("RIGHT")), "positiveUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("UP")), "positiveUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("DOWN")), "negativeUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("KP_LEFT")), "negativeUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("KP_RIGHT")), "positiveUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("KP_UP")), "positiveUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("KP_DOWN")), "negativeUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("HOME")), "minScroll");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("END")), "maxScroll");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("PAGE_UP")), "positiveBlockIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "negativeBlockIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("ctrl PAGE_UP")), "positiveBlockIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("ctrl PAGE_DOWN")), "negativeBlockIncrement");
InputMap rightToLeftMap = (InputMap) defaults.get("Slider.focusInputMap.RightToLeft");
keys = rightToLeftMap != null ? rightToLeftMap.keys() : new KeyStroke[] {};
keyList = Arrays.asList(keys);
harness.check(keyList.contains(KeyStroke.getKeyStroke("RIGHT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_RIGHT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("LEFT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_LEFT")));
if (rightToLeftMap == null)
{
rightToLeftMap = new InputMap();
}
harness.check(rightToLeftMap.get(KeyStroke.getKeyStroke("RIGHT")), "negativeUnitIncrement");
harness.check(rightToLeftMap.get(KeyStroke.getKeyStroke("KP_RIGHT")), "negativeUnitIncrement");
harness.check(rightToLeftMap.get(KeyStroke.getKeyStroke("LEFT")), "positiveUnitIncrement");
harness.check(rightToLeftMap.get(KeyStroke.getKeyStroke("KP_LEFT")), "positiveUnitIncrement");
harness.check(defaults.get("Slider.focusInsets"), new InsetsUIResource(2, 2, 2, 2));
harness.checkPoint("Spinner");
harness.check(defaults.get("Spinner.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("Spinner.arrowButtonSize"), new DimensionUIResource(16, 5));
harness.check(defaults.get("Spinner.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("Spinner.editorBorderPainted"), Boolean.FALSE);
harness.check(defaults.get("Spinner.font"), new FontUIResource("MonoSpaced", Font.PLAIN, 12));
harness.checkPoint("SplitPane");
harness.check(defaults.get("SplitPane.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("SplitPane.border") instanceof BasicBorders.SplitPaneBorder);
harness.check(defaults.get("SplitPane.dividerSize"), new Integer(7));
harness.checkPoint("SplitPaneDivider");
harness.check(defaults.get("SplitPaneDivider.border") instanceof Border);
harness.checkPoint("TabbedPane");
harness.check(defaults.get("TabbedPane.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("TabbedPane.contentBorderInsets"), new InsetsUIResource(2, 2, 3, 3));
harness.check(defaults.get("TabbedPane.focusInputMap") instanceof InputMapUIResource);
Object tab = UIManager.get("TabbedPane.focusInputMap");
InputMapUIResource tabim = (InputMapUIResource) tab;
harness.check(tabim.keys().length == 10);
harness.check(tabim.get(KeyStroke.getKeyStroke("ctrl DOWN")),"requestFocusForVisibleComponent");
harness.check(tabim.get(KeyStroke.getKeyStroke("KP_UP")),"navigateUp");
harness.check(tabim.get(KeyStroke.getKeyStroke("LEFT")),"navigateLeft");
harness.check(tabim.get(KeyStroke.getKeyStroke("ctrl KP_DOWN")),"requestFocusForVisibleComponent");
harness.check(tabim.get(KeyStroke.getKeyStroke("UP")),"navigateUp");
harness.check(tabim.get(KeyStroke.getKeyStroke("KP_DOWN")),"navigateDown");
harness.check(tabim.get(KeyStroke.getKeyStroke("KP_LEFT")),"navigateLeft");
harness.check(tabim.get(KeyStroke.getKeyStroke("RIGHT")),"navigateRight");
harness.check(tabim.get(KeyStroke.getKeyStroke("KP_RIGHT")),"navigateRight");
harness.check(tabim.get(KeyStroke.getKeyStroke("DOWN")),"navigateDown");
harness.check(defaults.get("TabbedPane.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("TabbedPane.selectedTabPadInsets"), new InsetsUIResource(2, 2, 2, 1));
harness.check(defaults.get("TabbedPane.tabAreaInsets"), new InsetsUIResource(3, 2, 0, 2));
harness.check(defaults.get("TabbedPane.tabInsets"), new InsetsUIResource(0, 4, 1, 4));
harness.check(defaults.get("TabbedPane.tabRunOverlay"), new Integer(2));
harness.check(defaults.get("TabbedPane.textIconGap"), new Integer(4));
harness.checkPoint("Table");
harness.check(defaults.get("Table.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("Table.ancestorInputMap.RightToLeft") instanceof InputMapUIResource);
harness.check(defaults.get("Table.focusCellHighlightBorder") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("Table.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Table.gridColor"), new ColorUIResource(128, 128, 128));
harness.check(defaults.get("Table.scrollPaneBorder") instanceof BorderUIResource.BevelBorderUIResource);
harness.checkPoint("TableHeader");
harness.check(defaults.get("TableHeader.cellBorder"), null);
harness.check(defaults.get("TableHeader.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("TextArea");
harness.check(defaults.get("TextArea.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("TextArea.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("TextArea.font"), new FontUIResource("MonoSpaced", Font.PLAIN, 12));
harness.check(defaults.get("TextArea.margin"), new InsetsUIResource(0, 0, 0, 0));
harness.check(UIManager.get("TextArea.focusInputMap") instanceof InputMapUIResource);
Object ta = UIManager.get("TextArea.focusInputMap");
InputMapUIResource taim = (InputMapUIResource) ta;
harness.check(taim.keys().length == 55);
harness.check(taim.get(KeyStroke.getKeyStroke("shift UP")), "selection-up");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(taim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selection-up");
harness.check(taim.get(KeyStroke.getKeyStroke("DOWN")), "caret-down");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl T")), "previous-link-action");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(taim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(taim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "selection-page-up");
harness.check(taim.get(KeyStroke.getKeyStroke("KP_UP")), "caret-up");
harness.check(taim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl HOME")), "caret-begin");
harness.check(taim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl END")), "caret-end");
harness.check(taim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(taim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(taim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "activate-link-action");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(taim.get(KeyStroke.getKeyStroke("ENTER")), "insert-break");
harness.check(taim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(taim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "selection-page-left");
harness.check(taim.get(KeyStroke.getKeyStroke("shift DOWN")), "selection-down");
harness.check(taim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "page-down");
harness.check(taim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "selection-page-right");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(taim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(taim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("KP_DOWN")), "caret-down");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(taim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selection-end");
harness.check(taim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl T")), "next-link-action");
harness.check(taim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selection-down");
harness.check(taim.get(KeyStroke.getKeyStroke("TAB")), "insert-tab");
harness.check(taim.get(KeyStroke.getKeyStroke("UP")), "caret-up");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selection-begin");
harness.check(taim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "selection-page-down");
harness.check(taim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(taim.get(KeyStroke.getKeyStroke("PAGE_UP")), "page-up");
harness.check(taim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.checkPoint("TextField");
harness.check(defaults.get("TextField.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("TextField.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("TextField.font"), new FontUIResource("SansSerif", Font.PLAIN, 12));
harness.check(defaults.get("TextField.margin"), new InsetsUIResource(0, 0, 0, 0));
harness.check(UIManager.get("TextField.focusInputMap") instanceof InputMapUIResource);
Object tf = UIManager.get("TextField.focusInputMap");
InputMapUIResource tfim = (InputMapUIResource) tf;
harness.check(tfim.keys().length == 33);
harness.check(tfim.get(KeyStroke.getKeyStroke("ENTER")), "notify-field-accept");
harness.check(tfim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(tfim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(tfim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(tfim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(tfim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(tfim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(tfim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(tfim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(tfim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.checkPoint("TextPane");
harness.check(defaults.get("TextPane.background"), new ColorUIResource(255, 255, 255));
harness.check(defaults.get("TextPane.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("TextPane.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("TextPane.font"), new FontUIResource("Serif", Font.PLAIN, 12));
harness.check(defaults.get("TextPane.margin"), new InsetsUIResource(3, 3, 3, 3));
harness.check(UIManager.get("TextPane.focusInputMap") instanceof InputMapUIResource);
Object tp = UIManager.get("TextPane.focusInputMap");
InputMapUIResource tpim = (InputMapUIResource) tp;
harness.check(tpim.keys().length == 55);
harness.check(tpim.get(KeyStroke.getKeyStroke("shift UP")), "selection-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selection-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("DOWN")), "caret-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl T")), "previous-link-action");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "selection-page-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("KP_UP")), "caret-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl HOME")), "caret-begin");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl END")), "caret-end");
harness.check(tpim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(tpim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "activate-link-action");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(tpim.get(KeyStroke.getKeyStroke("ENTER")), "insert-break");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(tpim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "selection-page-left");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift DOWN")), "selection-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "page-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "selection-page-right");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("KP_DOWN")), "caret-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selection-end");
harness.check(tpim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl T")), "next-link-action");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selection-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("TAB")), "insert-tab");
harness.check(tpim.get(KeyStroke.getKeyStroke("UP")), "caret-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selection-begin");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "selection-page-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("PAGE_UP")), "page-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.checkPoint("TitledBorder");
harness.check(defaults.get("TitledBorder.border") instanceof BorderUIResource.EtchedBorderUIResource);
harness.check(defaults.get("TitledBorder.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("ToggleButton");
harness.check(defaults.get("ToggleButton.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.check(defaults.get("ToggleButton.focusInputMap") instanceof InputMapUIResource);
Object to = UIManager.get("ToggleButton.focusInputMap");
InputMapUIResource toim = (InputMapUIResource) to;
harness.check(toim.keys().length == 2);
harness.check(toim.get(KeyStroke.getKeyStroke("SPACE")), "pressed");
harness.check(toim.get(KeyStroke.getKeyStroke("released SPACE")), "released");
harness.check(defaults.get("ToggleButton.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("ToggleButton.margin"), new InsetsUIResource(2, 14, 2, 14));
harness.check(defaults.get("ToggleButton.textIconGap"), new Integer(4));
harness.check(defaults.get("ToggleButton.textShiftOffset"), new Integer(0));
harness.checkPoint("ToolBar");
harness.check(defaults.get("ToolBar.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("ToolBar.border") instanceof BorderUIResource.EtchedBorderUIResource);
harness.check(defaults.get("ToolBar.dockingForeground"), new ColorUIResource(255, 0, 0));
harness.check(defaults.get("ToolBar.floatingForeground"), new ColorUIResource(64, 64, 64));
harness.check(defaults.get("ToolBar.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("ToolBar.separatorSize"), new DimensionUIResource(10, 10));
harness.checkPoint("ToolTip");
harness.check(defaults.get("ToolTip.border") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("ToolTip.font"), new FontUIResource("SansSerif", Font.PLAIN, 12));
harness.checkPoint("Tree");
harness.check(defaults.get("Tree.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("Tree.changeSelectionWithFocus"), Boolean.TRUE);
harness.check(defaults.get("Tree.drawsFocusBorderAroundIcon"), Boolean.FALSE);
harness.check(defaults.get("Tree.editorBorder") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("Tree.focusInputMap") instanceof InputMapUIResource);
Object tr = UIManager.get("Tree.focusInputMap");
InputMapUIResource trim = (InputMapUIResource) tr;
harness.check(trim.keys().length == 56);
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl DOWN")), "selectNextChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("shift UP")), "selectPreviousExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "scrollRight");
harness.check(trim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selectPreviousExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("DOWN")), "selectNext");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl UP")), "selectPreviousChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "scrollLeft");
harness.check(trim.get(KeyStroke.getKeyStroke("CUT")), "cut");
harness.check(trim.get(KeyStroke.getKeyStroke("END")), "selectLast");
harness.check(trim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "scrollUpExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("KP_UP")), "selectPrevious");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl UP")), "selectPreviousExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl HOME")), "selectFirstChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl END")), "selectLastChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl PAGE_DOWN")), "scrollDownChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("LEFT")), "selectParent");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl PAGE_UP")), "scrollUpChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("KP_LEFT")), "selectParent");
harness.check(trim.get(KeyStroke.getKeyStroke("SPACE")), "addToSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "toggleAndAnchor");
harness.check(trim.get(KeyStroke.getKeyStroke("shift SPACE")), "extendTo");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl SPACE")), "moveSelectionTo");
harness.check(trim.get(KeyStroke.getKeyStroke("ADD")), "expand");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "clearSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl DOWN")), "selectNextExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift HOME")), "selectFirstExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("RIGHT")), "selectChild");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "scrollUpExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift DOWN")), "selectNextExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "scrollDownChangeSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl KP_UP")), "selectPreviousExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("SUBTRACT")), "collapse");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl X")), "cut");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "scrollDownExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl SLASH")), "selectAll");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl C")), "copy");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "scrollRight");
harness.check(trim.get(KeyStroke.getKeyStroke("shift END")), "selectLastExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl KP_DOWN")), "selectNextExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "scrollLeft");
harness.check(trim.get(KeyStroke.getKeyStroke("HOME")), "selectFirst");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl V")), "paste");
harness.check(trim.get(KeyStroke.getKeyStroke("KP_DOWN")), "selectNext");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl A")), "selectAll");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl KP_DOWN")), "selectNextChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selectLastExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("COPY")), "copy");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl KP_UP")), "selectPreviousChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selectNextExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("UP")), "selectPrevious");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selectFirstExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "scrollDownExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "selectChild");
harness.check(trim.get(KeyStroke.getKeyStroke("F2")), "startEditing");
harness.check(trim.get(KeyStroke.getKeyStroke("PAGE_UP")), "scrollUpChangeSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("PASTE")), "paste");
harness.check(defaults.get("Tree.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Tree.hash"), new ColorUIResource(128, 128, 128));
harness.check(defaults.get("Tree.leftChildIndent"), new Integer(7));
harness.check(defaults.get("Tree.rightChildIndent"), new Integer(13));
harness.check(defaults.get("Tree.rowHeight"), new Integer(16));
harness.check(defaults.get("Tree.scrollsOnExpand"), Boolean.TRUE);
harness.check(defaults.get("Tree.selectionBorderColor"), new ColorUIResource(0, 0, 0));
harness.check(defaults.get("Tree.focusInputMap.RightToLeft") instanceof InputMapUIResource);
harness.checkPoint("Viewport");
harness.check(defaults.get("Viewport.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
}
| public void test(TestHarness harness)
{
MyBasicLookAndFeel laf = new MyBasicLookAndFeel();
UIDefaults defaults = new UIDefaults();
laf.initComponentDefaults(defaults);
harness.checkPoint("AuditoryCues");
harness.check(defaults.get("AuditoryCues.allAuditoryCues") != null);
harness.check(defaults.get("AuditoryCues.cueList") != null);
harness.check(defaults.get("AuditoryCues.noAuditoryCues") != null);
harness.checkPoint("Button");
CompoundBorderUIResource b1 = (CompoundBorderUIResource) defaults.get("Button.border");
harness.check(b1.getInsideBorder() instanceof MarginBorder);
harness.check(b1.getOutsideBorder() instanceof ButtonBorder);
harness.check(defaults.get("Button.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Button.margin"), new InsetsUIResource(2, 14, 2, 14));
harness.check(defaults.get("Button.textIconGap"), new Integer(4));
harness.check(defaults.get("Button.textShiftOffset"), new Integer(0));
harness.check(defaults.get("Button.focusInputMap") instanceof InputMapUIResource);
Object b = UIManager.get("Button.focusInputMap");
InputMapUIResource bim = (InputMapUIResource) b;
KeyStroke[] kb = bim.keys();
harness.check(kb.length == 2);
harness.check(bim.get(KeyStroke.getKeyStroke("SPACE")), "pressed");
harness.check(bim.get(KeyStroke.getKeyStroke("released SPACE")), "released");
harness.checkPoint("CheckBox");
CompoundBorderUIResource b2 = (CompoundBorderUIResource) defaults.get("CheckBox.border");
harness.check(b2.getInsideBorder() instanceof MarginBorder);
harness.check(b2.getOutsideBorder() instanceof ButtonBorder);
harness.check(defaults.get("CheckBox.focusInputMap") instanceof InputMapUIResource);
Object c = UIManager.get("CheckBox.focusInputMap");
InputMapUIResource cim = (InputMapUIResource) c;
KeyStroke[] kc = cim.keys();
harness.check(kc.length == 2);
harness.check(cim.get(KeyStroke.getKeyStroke("SPACE")), "pressed");
harness.check(cim.get(KeyStroke.getKeyStroke("released SPACE")), "released");
harness.check(defaults.get("CheckBox.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("CheckBox.icon") instanceof Icon);
harness.check(defaults.get("CheckBox.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.check(defaults.get("CheckBox.textIconGap"), new Integer(4));
harness.check(defaults.get("CheckBox.textShiftOffset"), new Integer(0));
harness.checkPoint("CheckBoxMenuItem");
harness.check(defaults.get("CheckBoxMenuItem.acceleratorFont"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("CheckBoxMenuItem.arrowIcon") instanceof Icon);
harness.check(defaults.get("CheckBoxMenuItem.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("CheckBoxMenuItem.borderPainted"), Boolean.FALSE);
harness.check(defaults.get("CheckBoxMenuItem.checkIcon") instanceof Icon);
harness.check(defaults.get("CheckBoxMenuItem.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("CheckBoxMenuItem.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.checkPoint("ColorChooser");
harness.check(defaults.get("ColorChooser.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("ColorChooser.rgbBlueMnemonic"), "66");
harness.check(defaults.get("ColorChooser.rgbGreenMnemonic"), "78");
harness.check(defaults.get("ColorChooser.rgbRedMnemonic"), "68");
harness.check(defaults.get("ColorChooser.swatchesRecentSwatchSize"), new Dimension(10, 10));
harness.check(defaults.get("ColorChooser.swatchesSwatchSize"), new Dimension(10, 10));
harness.checkPoint("ComboBox");
harness.check(defaults.get("ComboBox.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("ComboBox.font"), new FontUIResource("SansSerif", Font.PLAIN, 12));
harness.checkPoint("Desktop");
harness.check(defaults.get("Desktop.ancestorInputMap") instanceof InputMapUIResource);
harness.checkPoint("DesktopIcon");
harness.check(defaults.get("DesktopIcon.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.checkPoint("EditorPane");
harness.check(defaults.get("EditorPane.background"), new ColorUIResource(255, 255, 255));
harness.check(defaults.get("EditorPane.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("EditorPane.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("EditorPane.font"), new FontUIResource("Serif", Font.PLAIN, 12));
harness.check(defaults.get("EditorPane.margin"), new InsetsUIResource(3, 3, 3, 3));
Object e = UIManager.get("EditorPane.focusInputMap");
InputMapUIResource eim = (InputMapUIResource) e;
KeyStroke[] ke = eim.keys();
harness.check(ke.length == 55);
harness.check(eim.get(KeyStroke.getKeyStroke("shift UP")), "selection-up");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(eim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selection-up");
harness.check(eim.get(KeyStroke.getKeyStroke("DOWN")), "caret-down");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl T")), "previous-link-action");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(eim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(eim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "selection-page-up");
harness.check(eim.get(KeyStroke.getKeyStroke("KP_UP")), "caret-up");
harness.check(eim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl HOME")), "caret-begin");
harness.check(eim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl END")), "caret-end");
harness.check(eim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(eim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(eim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "activate-link-action");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(eim.get(KeyStroke.getKeyStroke("ENTER")), "insert-break");
harness.check(eim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(eim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "selection-page-left");
harness.check(eim.get(KeyStroke.getKeyStroke("shift DOWN")), "selection-down");
harness.check(eim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "page-down");
harness.check(eim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "selection-page-right");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(eim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(eim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("KP_DOWN")), "caret-down");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(eim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selection-end");
harness.check(eim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(eim.get(KeyStroke.getKeyStroke("ctrl T")), "next-link-action");
harness.check(eim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selection-down");
harness.check(eim.get(KeyStroke.getKeyStroke("TAB")), "insert-tab");
harness.check(eim.get(KeyStroke.getKeyStroke("UP")), "caret-up");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selection-begin");
harness.check(eim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "selection-page-down");
harness.check(eim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(eim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(eim.get(KeyStroke.getKeyStroke("PAGE_UP")), "page-up");
harness.check(eim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.checkPoint("FileChooser");
harness.check(defaults.get("FileChooser.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("FileChooser.cancelButtonMnemonic"), "67");
harness.check(defaults.get("FileChooser.directoryOpenButtonMnemonic"), "79");
harness.check(defaults.get("FileChooser.helpButtonMnemonic"), "72");
harness.check(defaults.get("FileChooser.openButtonMnemonic"), "79");
harness.check(defaults.get("FileChooser.saveButtonMnemonic"), "83");
harness.check(defaults.get("FileChooser.updateButtonMnemonic"), "85");
harness.checkPoint("FileView");
harness.checkPoint("FormattedTextField");
harness.check(defaults.get("FormattedTextField.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("FormattedTextField.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("FormattedTextField.focusInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("FormattedTextField.font"), new FontUIResource("SansSerif", Font.PLAIN, 12));
harness.check(defaults.get("FormattedTextField.margin"), new InsetsUIResource(0, 0, 0, 0));
Object f = UIManager.get("FormattedTextField.focusInputMap");
InputMapUIResource fim = (InputMapUIResource) f;
KeyStroke[] kf = fim.keys();
harness.check(kf.length == 38);
harness.check(fim.get(KeyStroke.getKeyStroke("KP_UP")), "increment");
harness.check(fim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(fim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(fim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(fim.get(KeyStroke.getKeyStroke("KP_DOWN")), "decrement");
harness.check(fim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(fim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(fim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(fim.get(KeyStroke.getKeyStroke("UP")), "increment");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(fim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(fim.get(KeyStroke.getKeyStroke("ESCAPE")), "reset-field-edit");
harness.check(fim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(fim.get(KeyStroke.getKeyStroke("DOWN")), "decrement");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(fim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(fim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(fim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(fim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(fim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(fim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(fim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.check(fim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(fim.get(KeyStroke.getKeyStroke("ENTER")), "notify-field-accept");
harness.check(fim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.checkPoint("InternalFrame");
harness.check(defaults.get("InternalFrame.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.check(defaults.get("InternalFrame.closeIcon") instanceof Icon);
harness.check(defaults.get("InternalFrame.iconifyIcon") instanceof Icon);
harness.check(defaults.get("InternalFrame.maximizeIcon") instanceof Icon);
harness.check(defaults.get("InternalFrame.minimizeIcon") instanceof Icon);
harness.check(defaults.get("InternalFrame.titleFont"), new FontUIResource("Dialog", Font.BOLD, 12));
harness.check(defaults.get("InternalFrame.windowBindings") instanceof Object[]);
harness.checkPoint("Label");
harness.check(defaults.get("Label.disabledForeground"), new ColorUIResource(255, 255, 255));
harness.check(defaults.get("Label.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("List");
harness.check(defaults.get("List.cellRenderer") instanceof ListCellRenderer);
harness.check(defaults.get("List.focusCellHighlightBorder") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("List.focusInputMap") instanceof InputMapUIResource);
Object l = UIManager.get("List.focusInputMap");
InputMapUIResource lim = (InputMapUIResource) l;
KeyStroke[] kl = lim.keys();
harness.check(kl.length == 61);
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl DOWN")), "selectNextRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift UP")), "selectPreviousRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "selectNextColumnChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selectPreviousColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selectPreviousRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("DOWN")), "selectNextRow");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl UP")), "selectPreviousRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "selectPreviousColumnChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("CUT")), "cut");
harness.check(lim.get(KeyStroke.getKeyStroke("END")), "selectLastRow");
harness.check(lim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "scrollUpExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("KP_UP")), "selectPreviousRow");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl UP")), "selectPreviousRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl HOME")), "selectFirstRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift LEFT")), "selectPreviousColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl END")), "selectLastRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl PAGE_DOWN")), "scrollDownChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selectNextColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("LEFT")), "selectPreviousColumn");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl PAGE_UP")), "scrollUpChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("KP_LEFT")), "selectPreviousColumn");
harness.check(lim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selectNextColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("SPACE")), "addToSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "toggleAndAnchor");
harness.check(lim.get(KeyStroke.getKeyStroke("shift SPACE")), "extendTo");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl SPACE")), "moveSelectionTo");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl DOWN")), "selectNextRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "clearSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift HOME")), "selectFirstRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("RIGHT")), "selectNextColumn");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "scrollUpExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift DOWN")), "selectNextRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "scrollDown");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl KP_UP")), "selectPreviousRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selectPreviousColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl X")), "cut");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "scrollDownExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl SLASH")), "selectAll");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl C")), "copy");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "selectNextColumnChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift END")), "selectLastRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl KP_DOWN")), "selectNextRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "selectPreviousColumnChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("HOME")), "selectFirstRow");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl V")), "paste");
harness.check(lim.get(KeyStroke.getKeyStroke("KP_DOWN")), "selectNextRow");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl KP_DOWN")), "selectNextRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selectNextColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl A")), "selectAll");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selectLastRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("COPY")), "copy");
harness.check(lim.get(KeyStroke.getKeyStroke("ctrl KP_UP")), "selectPreviousRowChangeLead");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selectPreviousColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selectNextRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("UP")), "selectPreviousRow");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selectFirstRowExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "scrollDownExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "selectNextColumn");
harness.check(lim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selectNextColumnExtendSelection");
harness.check(lim.get(KeyStroke.getKeyStroke("PAGE_UP")), "scrollUp");
harness.check(lim.get(KeyStroke.getKeyStroke("PASTE")), "paste");
harness.check(defaults.get("List.focusInputMap.RightToLeft") instanceof InputMapUIResource);
harness.check(defaults.get("List.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("Menu");
harness.check(defaults.get("Menu.acceleratorFont"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Menu.arrowIcon") instanceof Icon);
harness.check(defaults.get("Menu.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("Menu.borderPainted"), Boolean.FALSE);
harness.check(defaults.get("Menu.checkIcon") instanceof Icon);
harness.check(defaults.get("Menu.crossMenuMnemonic"), Boolean.TRUE);
harness.check(defaults.get("Menu.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Menu.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.check(defaults.get("Menu.menuPopupOffsetX"), new Integer(0));
harness.check(defaults.get("Menu.menuPopupOffsetY"), new Integer(0));
int[] shortcuts = (int[]) defaults.get("Menu.shortcutKeys");
if (shortcuts == null)
shortcuts = new int[] { 999 };
harness.check(shortcuts.length, 1);
harness.check(shortcuts[0], 8);
harness.check(defaults.get("Menu.submenuPopupOffsetX"), new Integer(0));
harness.check(defaults.get("Menu.submenuPopupOffsetY"), new Integer(0));
harness.checkPoint("MenuBar");
harness.check(defaults.get("MenuBar.border") instanceof BasicBorders.MenuBarBorder);
harness.check(defaults.get("MenuBar.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("MenuBar.windowBindings") instanceof Object[]);
harness.checkPoint("MenuItem");
harness.check(defaults.get("MenuItem.acceleratorDelimiter"), "+");
harness.check(defaults.get("MenuItem.acceleratorFont"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("MenuItem.arrowIcon") instanceof Icon);
harness.check(defaults.get("MenuItem.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("MenuItem.borderPainted"), Boolean.FALSE);
harness.check(defaults.get("MenuItem.checkIcon") instanceof Icon);
harness.check(defaults.get("MenuItem.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("MenuItem.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.checkPoint("OptionPane");
harness.check(defaults.get("OptionPane.border") instanceof BorderUIResource.EmptyBorderUIResource);
harness.check(defaults.get("OptionPane.buttonAreaBorder") instanceof BorderUIResource.EmptyBorderUIResource);
harness.check(defaults.get("OptionPane.buttonClickThreshhold"), new Integer(500));
harness.check(defaults.get("OptionPane.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("OptionPane.messageAreaBorder") instanceof BorderUIResource.EmptyBorderUIResource);
harness.check(defaults.get("OptionPane.minimumSize"), new DimensionUIResource(262, 90));
harness.check(defaults.get("OptionPane.windowBindings") instanceof Object[]);
harness.checkPoint("Panel");
harness.check(defaults.get("Panel.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("PasswordField");
harness.check(defaults.get("PasswordField.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("PasswordField.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("PasswordField.font"), new FontUIResource("MonoSpaced", Font.PLAIN, 12));
harness.check(defaults.get("PasswordField.margin"), new InsetsUIResource(0, 0, 0, 0));
harness.check(UIManager.get("PasswordField.focusInputMap") instanceof InputMapUIResource);
Object o = UIManager.get("PasswordField.focusInputMap");
InputMapUIResource im = (InputMapUIResource) o;
KeyStroke[] k = im.keys();
harness.check(k.length == 33);
harness.check(im.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(im.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(im.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(im.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(im.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(im.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(im.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(im.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(im.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-begin-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(im.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-end-line");
harness.check(im.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(im.get(KeyStroke.getKeyStroke("ENTER")), "notify-field-accept");
harness.check(im.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.checkPoint("PopupMenu");
harness.check(defaults.get("PopupMenu.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.check(defaults.get("PopupMenu.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("PopupMenu.selectedWindowInputMapBindings") instanceof Object[]);
harness.check(defaults.get("PopupMenu.selectedWindowInputMapBindings.RightToLeft") instanceof Object[]);
harness.checkPoint("ProgressBar");
harness.check(defaults.get("ProgressBar.border") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("ProgressBar.cellLength"), new Integer(1));
harness.check(defaults.get("ProgressBar.cellSpacing"), new Integer(0));
harness.check(defaults.get("ProgressBar.cycleTime"), new Integer(3000));
harness.check(defaults.get("ProgressBar.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("ProgressBar.repaintInterval"), new Integer(50));
harness.checkPoint("RadioButton");
harness.check(defaults.get("RadioButton.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.check(defaults.get("RadioButton.focusInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("RadioButton.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("RadioButton.icon") instanceof Icon);
harness.check(defaults.get("RadioButton.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.check(defaults.get("RadioButton.textIconGap"), new Integer(4));
harness.check(defaults.get("RadioButton.textShiftOffset"), new Integer(0));
harness.checkPoint("RadioButtonMenuItem");
harness.check(defaults.get("RadioButtonMenuItem.acceleratorFont"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("RadioButtonMenuItem.arrowIcon") instanceof Icon);
harness.check(defaults.get("RadioButtonMenuItem.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("RadioButtonMenuItem.borderPainted"), Boolean.FALSE);
harness.check(defaults.get("RadioButtonMenuItem.checkIcon") instanceof Icon);
harness.check(defaults.get("RadioButtonMenuItem.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("RadioButtonMenuItem.margin"), new InsetsUIResource(2, 2, 2, 2));
harness.check(defaults.get("RootPane.defaultButtonWindowKeyBindings") instanceof Object[]);
harness.checkPoint("ScrollBar");
harness.check(defaults.get("ScrollBar.background"), new ColorUIResource(224, 224, 224));
harness.check(defaults.get("ScrollBar.maximumThumbSize"), new DimensionUIResource(4096, 4096));
harness.check(defaults.get("ScrollBar.minimumThumbSize"), new DimensionUIResource(8, 8));
harness.check(defaults.get("ScrollBar.width"), new Integer(16));
harness.check(defaults.get("ScrollPane.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("ScrollPane.ancestorInputMap.RightToLeft") instanceof InputMapUIResource);
harness.check(defaults.get("ScrollPane.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("ScrollPane.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("Slider");
InputMap map = (InputMap) defaults.get("Slider.focusInputMap");
KeyStroke[] keys = map.keys();
InputMap focusInputMap = (InputMap) defaults.get("Slider.focusInputMap");
List keyList = Arrays.asList(keys);
harness.check(keyList.contains(KeyStroke.getKeyStroke("LEFT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("RIGHT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("UP")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("DOWN")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_LEFT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_RIGHT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_UP")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_DOWN")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("HOME")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("END")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("PAGE_UP")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("PAGE_DOWN")));
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("LEFT")), "negativeUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("RIGHT")), "positiveUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("UP")), "positiveUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("DOWN")), "negativeUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("KP_LEFT")), "negativeUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("KP_RIGHT")), "positiveUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("KP_UP")), "positiveUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("KP_DOWN")), "negativeUnitIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("HOME")), "minScroll");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("END")), "maxScroll");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("PAGE_UP")), "positiveBlockIncrement");
harness.check(focusInputMap.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "negativeBlockIncrement");
InputMap rightToLeftMap = (InputMap) defaults.get("Slider.focusInputMap.RightToLeft");
keys = rightToLeftMap != null ? rightToLeftMap.keys() : new KeyStroke[] {};
keyList = Arrays.asList(keys);
harness.check(keyList.contains(KeyStroke.getKeyStroke("RIGHT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_RIGHT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("LEFT")));
harness.check(keyList.contains(KeyStroke.getKeyStroke("KP_LEFT")));
if (rightToLeftMap == null)
{
rightToLeftMap = new InputMap();
}
harness.check(rightToLeftMap.get(KeyStroke.getKeyStroke("RIGHT")), "negativeUnitIncrement");
harness.check(rightToLeftMap.get(KeyStroke.getKeyStroke("KP_RIGHT")), "negativeUnitIncrement");
harness.check(rightToLeftMap.get(KeyStroke.getKeyStroke("LEFT")), "positiveUnitIncrement");
harness.check(rightToLeftMap.get(KeyStroke.getKeyStroke("KP_LEFT")), "positiveUnitIncrement");
harness.check(defaults.get("Slider.focusInsets"), new InsetsUIResource(2, 2, 2, 2));
harness.checkPoint("Spinner");
harness.check(defaults.get("Spinner.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("Spinner.arrowButtonSize"), new DimensionUIResource(16, 5));
harness.check(defaults.get("Spinner.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("Spinner.editorBorderPainted"), Boolean.FALSE);
harness.check(defaults.get("Spinner.font"), new FontUIResource("MonoSpaced", Font.PLAIN, 12));
harness.checkPoint("SplitPane");
harness.check(defaults.get("SplitPane.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("SplitPane.border") instanceof BasicBorders.SplitPaneBorder);
harness.check(defaults.get("SplitPane.dividerSize"), new Integer(7));
harness.checkPoint("SplitPaneDivider");
harness.check(defaults.get("SplitPaneDivider.border") instanceof Border);
harness.checkPoint("TabbedPane");
harness.check(defaults.get("TabbedPane.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("TabbedPane.contentBorderInsets"), new InsetsUIResource(2, 2, 3, 3));
harness.check(defaults.get("TabbedPane.focusInputMap") instanceof InputMapUIResource);
Object tab = UIManager.get("TabbedPane.focusInputMap");
InputMapUIResource tabim = (InputMapUIResource) tab;
harness.check(tabim.keys().length == 10);
harness.check(tabim.get(KeyStroke.getKeyStroke("ctrl DOWN")),"requestFocusForVisibleComponent");
harness.check(tabim.get(KeyStroke.getKeyStroke("KP_UP")),"navigateUp");
harness.check(tabim.get(KeyStroke.getKeyStroke("LEFT")),"navigateLeft");
harness.check(tabim.get(KeyStroke.getKeyStroke("ctrl KP_DOWN")),"requestFocusForVisibleComponent");
harness.check(tabim.get(KeyStroke.getKeyStroke("UP")),"navigateUp");
harness.check(tabim.get(KeyStroke.getKeyStroke("KP_DOWN")),"navigateDown");
harness.check(tabim.get(KeyStroke.getKeyStroke("KP_LEFT")),"navigateLeft");
harness.check(tabim.get(KeyStroke.getKeyStroke("RIGHT")),"navigateRight");
harness.check(tabim.get(KeyStroke.getKeyStroke("KP_RIGHT")),"navigateRight");
harness.check(tabim.get(KeyStroke.getKeyStroke("DOWN")),"navigateDown");
harness.check(defaults.get("TabbedPane.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("TabbedPane.selectedTabPadInsets"), new InsetsUIResource(2, 2, 2, 1));
harness.check(defaults.get("TabbedPane.tabAreaInsets"), new InsetsUIResource(3, 2, 0, 2));
harness.check(defaults.get("TabbedPane.tabInsets"), new InsetsUIResource(0, 4, 1, 4));
harness.check(defaults.get("TabbedPane.tabRunOverlay"), new Integer(2));
harness.check(defaults.get("TabbedPane.textIconGap"), new Integer(4));
harness.checkPoint("Table");
harness.check(defaults.get("Table.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("Table.ancestorInputMap.RightToLeft") instanceof InputMapUIResource);
harness.check(defaults.get("Table.focusCellHighlightBorder") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("Table.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Table.gridColor"), new ColorUIResource(128, 128, 128));
harness.check(defaults.get("Table.scrollPaneBorder") instanceof BorderUIResource.BevelBorderUIResource);
harness.checkPoint("TableHeader");
harness.check(defaults.get("TableHeader.cellBorder"), null);
harness.check(defaults.get("TableHeader.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("TextArea");
harness.check(defaults.get("TextArea.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("TextArea.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("TextArea.font"), new FontUIResource("MonoSpaced", Font.PLAIN, 12));
harness.check(defaults.get("TextArea.margin"), new InsetsUIResource(0, 0, 0, 0));
harness.check(UIManager.get("TextArea.focusInputMap") instanceof InputMapUIResource);
Object ta = UIManager.get("TextArea.focusInputMap");
InputMapUIResource taim = (InputMapUIResource) ta;
harness.check(taim.keys().length == 55);
harness.check(taim.get(KeyStroke.getKeyStroke("shift UP")), "selection-up");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(taim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selection-up");
harness.check(taim.get(KeyStroke.getKeyStroke("DOWN")), "caret-down");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl T")), "previous-link-action");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(taim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(taim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "selection-page-up");
harness.check(taim.get(KeyStroke.getKeyStroke("KP_UP")), "caret-up");
harness.check(taim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl HOME")), "caret-begin");
harness.check(taim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl END")), "caret-end");
harness.check(taim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(taim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(taim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "activate-link-action");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(taim.get(KeyStroke.getKeyStroke("ENTER")), "insert-break");
harness.check(taim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(taim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "selection-page-left");
harness.check(taim.get(KeyStroke.getKeyStroke("shift DOWN")), "selection-down");
harness.check(taim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "page-down");
harness.check(taim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "selection-page-right");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(taim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(taim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("KP_DOWN")), "caret-down");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(taim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selection-end");
harness.check(taim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(taim.get(KeyStroke.getKeyStroke("ctrl T")), "next-link-action");
harness.check(taim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selection-down");
harness.check(taim.get(KeyStroke.getKeyStroke("TAB")), "insert-tab");
harness.check(taim.get(KeyStroke.getKeyStroke("UP")), "caret-up");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selection-begin");
harness.check(taim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "selection-page-down");
harness.check(taim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(taim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(taim.get(KeyStroke.getKeyStroke("PAGE_UP")), "page-up");
harness.check(taim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.checkPoint("TextField");
harness.check(defaults.get("TextField.border") instanceof BasicBorders.FieldBorder);
harness.check(defaults.get("TextField.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("TextField.font"), new FontUIResource("SansSerif", Font.PLAIN, 12));
harness.check(defaults.get("TextField.margin"), new InsetsUIResource(0, 0, 0, 0));
harness.check(UIManager.get("TextField.focusInputMap") instanceof InputMapUIResource);
Object tf = UIManager.get("TextField.focusInputMap");
InputMapUIResource tfim = (InputMapUIResource) tf;
harness.check(tfim.keys().length == 33);
harness.check(tfim.get(KeyStroke.getKeyStroke("ENTER")), "notify-field-accept");
harness.check(tfim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(tfim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(tfim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(tfim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(tfim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(tfim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(tfim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(tfim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(tfim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(tfim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(tfim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.checkPoint("TextPane");
harness.check(defaults.get("TextPane.background"), new ColorUIResource(255, 255, 255));
harness.check(defaults.get("TextPane.border") instanceof BasicBorders.MarginBorder);
harness.check(defaults.get("TextPane.caretBlinkRate"), new Integer(500));
harness.check(defaults.get("TextPane.font"), new FontUIResource("Serif", Font.PLAIN, 12));
harness.check(defaults.get("TextPane.margin"), new InsetsUIResource(3, 3, 3, 3));
harness.check(UIManager.get("TextPane.focusInputMap") instanceof InputMapUIResource);
Object tp = UIManager.get("TextPane.focusInputMap");
InputMapUIResource tpim = (InputMapUIResource) tp;
harness.check(tpim.keys().length == 55);
harness.check(tpim.get(KeyStroke.getKeyStroke("shift UP")), "selection-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "caret-next-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl LEFT")), "selection-previous-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selection-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("DOWN")), "caret-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl T")), "previous-link-action");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "caret-previous-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("CUT")), "cut-to-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("END")), "caret-end-line");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "selection-page-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("KP_UP")), "caret-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("DELETE")), "delete-next");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl HOME")), "caret-begin");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift LEFT")), "selection-backward");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl END")), "caret-end");
harness.check(tpim.get(KeyStroke.getKeyStroke("BACK_SPACE")), "delete-previous");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl RIGHT")), "selection-next-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("LEFT")), "caret-backward");
harness.check(tpim.get(KeyStroke.getKeyStroke("KP_LEFT")), "caret-backward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift KP_RIGHT")), "selection-forward");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "activate-link-action");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl H")), "delete-previous");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "unselect");
harness.check(tpim.get(KeyStroke.getKeyStroke("ENTER")), "insert-break");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift HOME")), "selection-begin-line");
harness.check(tpim.get(KeyStroke.getKeyStroke("RIGHT")), "caret-forward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "selection-page-left");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift DOWN")), "selection-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "page-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift KP_LEFT")), "selection-backward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl O")), "toggle-componentOrientation");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl X")), "cut-to-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "selection-page-right");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl C")), "copy-to-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "caret-next-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift END")), "selection-end-line");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "caret-previous-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("HOME")), "caret-begin-line");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl V")), "paste-from-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("KP_DOWN")), "caret-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl A")), "select-all");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift RIGHT")), "selection-forward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selection-end");
harness.check(tpim.get(KeyStroke.getKeyStroke("COPY")), "copy-to-clipboard");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl KP_LEFT")), "selection-previous-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("ctrl T")), "next-link-action");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selection-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("TAB")), "insert-tab");
harness.check(tpim.get(KeyStroke.getKeyStroke("UP")), "caret-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selection-begin");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "selection-page-down");
harness.check(tpim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "caret-forward");
harness.check(tpim.get(KeyStroke.getKeyStroke("shift ctrl KP_RIGHT")), "selection-next-word");
harness.check(tpim.get(KeyStroke.getKeyStroke("PAGE_UP")), "page-up");
harness.check(tpim.get(KeyStroke.getKeyStroke("PASTE")), "paste-from-clipboard");
harness.checkPoint("TitledBorder");
harness.check(defaults.get("TitledBorder.border") instanceof BorderUIResource.EtchedBorderUIResource);
harness.check(defaults.get("TitledBorder.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.checkPoint("ToggleButton");
harness.check(defaults.get("ToggleButton.border") instanceof BorderUIResource.CompoundBorderUIResource);
harness.check(defaults.get("ToggleButton.focusInputMap") instanceof InputMapUIResource);
Object to = UIManager.get("ToggleButton.focusInputMap");
InputMapUIResource toim = (InputMapUIResource) to;
harness.check(toim.keys().length == 2);
harness.check(toim.get(KeyStroke.getKeyStroke("SPACE")), "pressed");
harness.check(toim.get(KeyStroke.getKeyStroke("released SPACE")), "released");
harness.check(defaults.get("ToggleButton.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("ToggleButton.margin"), new InsetsUIResource(2, 14, 2, 14));
harness.check(defaults.get("ToggleButton.textIconGap"), new Integer(4));
harness.check(defaults.get("ToggleButton.textShiftOffset"), new Integer(0));
harness.checkPoint("ToolBar");
harness.check(defaults.get("ToolBar.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("ToolBar.border") instanceof BorderUIResource.EtchedBorderUIResource);
harness.check(defaults.get("ToolBar.dockingForeground"), new ColorUIResource(255, 0, 0));
harness.check(defaults.get("ToolBar.floatingForeground"), new ColorUIResource(64, 64, 64));
harness.check(defaults.get("ToolBar.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("ToolBar.separatorSize"), new DimensionUIResource(10, 10));
harness.checkPoint("ToolTip");
harness.check(defaults.get("ToolTip.border") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("ToolTip.font"), new FontUIResource("SansSerif", Font.PLAIN, 12));
harness.checkPoint("Tree");
harness.check(defaults.get("Tree.ancestorInputMap") instanceof InputMapUIResource);
harness.check(defaults.get("Tree.changeSelectionWithFocus"), Boolean.TRUE);
harness.check(defaults.get("Tree.drawsFocusBorderAroundIcon"), Boolean.FALSE);
harness.check(defaults.get("Tree.editorBorder") instanceof BorderUIResource.LineBorderUIResource);
harness.check(defaults.get("Tree.focusInputMap") instanceof InputMapUIResource);
Object tr = UIManager.get("Tree.focusInputMap");
InputMapUIResource trim = (InputMapUIResource) tr;
harness.check(trim.keys().length == 56);
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl DOWN")), "selectNextChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("shift UP")), "selectPreviousExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl RIGHT")), "scrollRight");
harness.check(trim.get(KeyStroke.getKeyStroke("shift KP_UP")), "selectPreviousExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("DOWN")), "selectNext");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl UP")), "selectPreviousChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl LEFT")), "scrollLeft");
harness.check(trim.get(KeyStroke.getKeyStroke("CUT")), "cut");
harness.check(trim.get(KeyStroke.getKeyStroke("END")), "selectLast");
harness.check(trim.get(KeyStroke.getKeyStroke("shift PAGE_UP")), "scrollUpExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("KP_UP")), "selectPrevious");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl UP")), "selectPreviousExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl HOME")), "selectFirstChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl END")), "selectLastChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl PAGE_DOWN")), "scrollDownChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("LEFT")), "selectParent");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl PAGE_UP")), "scrollUpChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("KP_LEFT")), "selectParent");
harness.check(trim.get(KeyStroke.getKeyStroke("SPACE")), "addToSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl SPACE")), "toggleAndAnchor");
harness.check(trim.get(KeyStroke.getKeyStroke("shift SPACE")), "extendTo");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl SPACE")), "moveSelectionTo");
harness.check(trim.get(KeyStroke.getKeyStroke("ADD")), "expand");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl BACK_SLASH")), "clearSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl DOWN")), "selectNextExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift HOME")), "selectFirstExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("RIGHT")), "selectChild");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_UP")), "scrollUpExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift DOWN")), "selectNextExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("PAGE_DOWN")), "scrollDownChangeSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl KP_UP")), "selectPreviousExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("SUBTRACT")), "collapse");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl X")), "cut");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl PAGE_DOWN")), "scrollDownExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl SLASH")), "selectAll");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl C")), "copy");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl KP_RIGHT")), "scrollRight");
harness.check(trim.get(KeyStroke.getKeyStroke("shift END")), "selectLastExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl KP_DOWN")), "selectNextExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl KP_LEFT")), "scrollLeft");
harness.check(trim.get(KeyStroke.getKeyStroke("HOME")), "selectFirst");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl V")), "paste");
harness.check(trim.get(KeyStroke.getKeyStroke("KP_DOWN")), "selectNext");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl A")), "selectAll");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl KP_DOWN")), "selectNextChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl END")), "selectLastExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("COPY")), "copy");
harness.check(trim.get(KeyStroke.getKeyStroke("ctrl KP_UP")), "selectPreviousChangeLead");
harness.check(trim.get(KeyStroke.getKeyStroke("shift KP_DOWN")), "selectNextExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("UP")), "selectPrevious");
harness.check(trim.get(KeyStroke.getKeyStroke("shift ctrl HOME")), "selectFirstExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("shift PAGE_DOWN")), "scrollDownExtendSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("KP_RIGHT")), "selectChild");
harness.check(trim.get(KeyStroke.getKeyStroke("F2")), "startEditing");
harness.check(trim.get(KeyStroke.getKeyStroke("PAGE_UP")), "scrollUpChangeSelection");
harness.check(trim.get(KeyStroke.getKeyStroke("PASTE")), "paste");
harness.check(defaults.get("Tree.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
harness.check(defaults.get("Tree.hash"), new ColorUIResource(128, 128, 128));
harness.check(defaults.get("Tree.leftChildIndent"), new Integer(7));
harness.check(defaults.get("Tree.rightChildIndent"), new Integer(13));
harness.check(defaults.get("Tree.rowHeight"), new Integer(16));
harness.check(defaults.get("Tree.scrollsOnExpand"), Boolean.TRUE);
harness.check(defaults.get("Tree.selectionBorderColor"), new ColorUIResource(0, 0, 0));
harness.check(defaults.get("Tree.focusInputMap.RightToLeft") instanceof InputMapUIResource);
harness.checkPoint("Viewport");
harness.check(defaults.get("Viewport.font"), new FontUIResource("Dialog", Font.PLAIN, 12));
}
|
public Suggestions getSuggestions(String query, Corpus singleCorpus, int maxSuggestions) {
if (DBG) Log.d(TAG, "getSuggestions(" + query + ")");
cancelPendingTasks();
List<Corpus> corporaToQuery = getCorporaToQuery(query, singleCorpus);
final Suggestions suggestions = new Suggestions(mPromoter,
maxSuggestions,
query,
corporaToQuery.size());
int maxShortcuts = mConfig.getMaxShortcutsReturned();
SuggestionCursor shortcuts = getShortcutsForQuery(query, singleCorpus, maxShortcuts);
if (shortcuts != null) {
suggestions.setShortcuts(shortcuts);
}
if (corporaToQuery.size() == 0) {
return suggestions;
}
int initialBatchSize = countDefaultCorpora(corporaToQuery);
initialBatchSize = Math.min(initialBatchSize, mConfig.getNumPromotedSources());
if (initialBatchSize == 0) {
initialBatchSize = mConfig.getNumPromotedSources();
}
mBatchingExecutor = new BatchingNamedTaskExecutor(mQueryExecutor);
SuggestionCursorReceiver receiver = new SuggestionCursorReceiver(
mBatchingExecutor, suggestions, initialBatchSize);
int maxResultsPerSource = mConfig.getMaxResultsPerSource();
QueryTask.startQueries(query, maxResultsPerSource, corporaToQuery, mBatchingExecutor,
mPublishThread, receiver);
mBatchingExecutor.executeNextBatch(initialBatchSize);
return suggestions;
}
| public Suggestions getSuggestions(String query, Corpus singleCorpus, int maxSuggestions) {
if (DBG) Log.d(TAG, "getSuggestions(" + query + ")");
cancelPendingTasks();
List<Corpus> corporaToQuery = getCorporaToQuery(query, singleCorpus);
final Suggestions suggestions = new Suggestions(mPromoter,
maxSuggestions,
query,
corporaToQuery.size());
int maxShortcuts = mConfig.getMaxShortcutsReturned();
SuggestionCursor shortcuts = getShortcutsForQuery(query, singleCorpus, maxShortcuts);
if (shortcuts != null) {
suggestions.setShortcuts(shortcuts);
}
if (corporaToQuery.size() == 0) {
return suggestions;
}
int initialBatchSize = countDefaultCorpora(corporaToQuery);
if (initialBatchSize == 0) {
initialBatchSize = mConfig.getNumPromotedSources();
}
mBatchingExecutor = new BatchingNamedTaskExecutor(mQueryExecutor);
SuggestionCursorReceiver receiver = new SuggestionCursorReceiver(
mBatchingExecutor, suggestions, initialBatchSize);
int maxResultsPerSource = mConfig.getMaxResultsPerSource();
QueryTask.startQueries(query, maxResultsPerSource, corporaToQuery, mBatchingExecutor,
mPublishThread, receiver);
mBatchingExecutor.executeNextBatch(initialBatchSize);
return suggestions;
}
|
public boolean fetchApp(String appUrl)
{
ConcurrentLinkedQueue<URLInfo>processQueue = new ConcurrentLinkedQueue<URLInfo>();
ConcurrentHashMap<String, Boolean> seenURLs = new ConcurrentHashMap<String, Boolean>();
Connection conn = DatabaseConfig.getInstance().getConnection();
URLInfo newURLInfo = new URLInfo(appUrl,"",0);
String outputAppDir = props.getProperty(ApperConstants.OUTPUT_APP_DIR);
String appDataDir = props.getProperty(ApperConstants.OUTPUT_DATA_DIR);
Crawler crawler = new Crawler(processQueue,seenURLs,0,outputAppDir);
String fileName = crawler.crawl(newURLInfo);
System.out.println(fileName);
if(fileName.length() == 0)
return false;
AppParser parser = new AppParser(outputAppDir + "/" + fileName);
try {
AppData appData = parser.parseWithDataMappings(dm);
String appDataFile = appDataDir + fileName;
System.out.println(appDataFile);
Utils.printToFile(appDataFile, appData.toJSON());
System.out.println("Writing to database");
DatabaseUtils.insertAppInfoIfNotExists(conn, appData);
return true;
}catch (Exception e)
{
System.out.println("Exception thrown for file" + e.getMessage());
e.printStackTrace();
}
return false;
}
| public boolean fetchApp(String appUrl)
{
ConcurrentLinkedQueue<URLInfo>processQueue = new ConcurrentLinkedQueue<URLInfo>();
ConcurrentHashMap<String, Boolean> seenURLs = new ConcurrentHashMap<String, Boolean>();
Connection conn = DatabaseConfig.getInstance().getConnection();
URLInfo newURLInfo = new URLInfo(appUrl,"",0);
String outputAppDir = props.getProperty(ApperConstants.OUTPUT_APP_DIR);
String appDataDir = props.getProperty(ApperConstants.OUTPUT_DATA_DIR);
Crawler crawler = new Crawler(processQueue,seenURLs,0,outputAppDir);
String fileName = crawler.crawl(newURLInfo);
System.out.println(fileName);
if(fileName.length() == 0)
return false;
AppParser parser = new AppParser(outputAppDir + "/" + fileName);
try {
AppData appData = parser.parseWithDataMappings(dm);
String appDataFile = appDataDir + "/" + fileName;
System.out.println(appDataFile);
Utils.printToFile(appDataFile, appData.toJSON());
System.out.println("Writing to database");
DatabaseUtils.insertAppInfoIfNotExists(conn, appData);
return true;
}catch (Exception e)
{
System.out.println("Exception thrown for file" + e.getMessage());
e.printStackTrace();
}
return false;
}
|
public String validate(final Field field) {
final String value = getValueAsString(field);
AlphaNum alphaNum = field.getAnnotation(AlphaNum.class);
if (alphaNum != null) {
final Class<?> type = field.getType();
if (type.equals(String.class)) {
if (TextUtils.isEmpty(value)) {
return null;
}
String regex = alphaNum.allowSpace() ? REGEX_WITH_SPACE : REGEX;
if (!value.matches(regex)) {
return getMessage(R.styleable.ValidatorMessages_afeErrorAlphabet,
R.string.afe__msg_validation_alphabet,
getName(field, alphaNum.nameResId()));
}
}
}
return null;
}
| public String validate(final Field field) {
final String value = getValueAsString(field);
AlphaNum alphaNum = field.getAnnotation(AlphaNum.class);
if (alphaNum != null) {
final Class<?> type = field.getType();
if (type.equals(String.class)) {
if (TextUtils.isEmpty(value)) {
return null;
}
String regex = alphaNum.allowSpace() ? REGEX_WITH_SPACE : REGEX;
if (!value.matches(regex)) {
return getMessage(R.styleable.ValidatorMessages_afeErrorAlphaNum,
R.string.afe__msg_validation_alphanum,
getName(field, alphaNum.nameResId()));
}
}
}
return null;
}
|
private RDFSClass<RDFSResource> processClass(Class<?> clazz, Session session, Map<UID, RDFSResource> resources) {
MappedClass mappedClass = configuration.getMappedClass(clazz);
OWLClass owlClass = null;
UID cuid = mappedClass.getUID();
if (cuid != null) {
if (!(exportNamespaces.isEmpty() || exportNamespaces.contains(cuid.ns()))) {
owlClass = new ReferenceClass(cuid);
} else {
owlClass = (OWLClass) resources.get(cuid);
if (owlClass == null) {
owlClass = new OWLClass(cuid);
resources.put(cuid, owlClass);
owlClass.setLabel(Locale.ROOT, cuid.getLocalName());
} else {
return owlClass;
}
if (!clazz.getSuperclass().equals(Object.class)){
addParent(clazz.getSuperclass(), owlClass, session, resources);
}
for (Class<?> iface : clazz.getInterfaces()) {
addParent(iface, owlClass, session, resources);
}
if (mappedClass.isEnum()) {
List<RDFSResource> oneOf = new ArrayList<RDFSResource>();
for (Object constant: clazz.getEnumConstants()) {
Enum enumValue = (Enum)constant;
oneOf.add(new AnyThing(new UID(cuid.ns(), enumValue.name()), owlClass, enumValue.ordinal()));
}
owlClass.setOneOf(oneOf);
}
for (MappedPath mappedPath : mappedClass.getProperties()) {
if (!mappedPath.isInherited() && mappedPath.isSimpleProperty()) {
MappedProperty<?> mappedProperty = mappedPath.getMappedProperty();
MappedPredicate mappedPredicate = mappedPath.get(0);
UID puid = mappedPredicate.getUID();
String predicateNs = puid.ns();
if (RDF.NS.equals(predicateNs) || RDFS.NS.equals(predicateNs) || OWL.NS.equals(predicateNs)) {
continue;
}
final RDFProperty property;
boolean seenProperty = resources.containsKey(puid);
if (seenProperty) {
property = (RDFProperty) resources.get(puid);
if (mappedPath.isReference()) {
if (!(property instanceof ObjectProperty)) {
throw new IllegalArgumentException("Expected ObjectProperty for: " + mappedPath);
}
} else if (!mappedProperty.isAnyResource()){
if (!(property instanceof DatatypeProperty)) {
throw new IllegalArgumentException("Expected DatatypeProperty for: " + mappedPath);
}
}
} else {
if (mappedProperty.isAnyResource()) {
property = new RDFProperty(puid);
} else if (mappedPath.isReference() || mappedProperty.isCollection()) {
property = new ObjectProperty(puid);
} else {
property = new DatatypeProperty(puid);
}
property.setLabel(Locale.ROOT, puid.getLocalName());
resources.put(puid, property);
}
final Restriction restriction = new Restriction();
restriction.setOnProperty(property);
if (mappedProperty.isCollection()) {
if (mappedProperty.isList()) {
if (property.getRange().isEmpty()) {
RDFSClass<?> componentType =
processClass(mappedProperty.getComponentType(), session, resources);
if (useTypedLists && componentType != null) {
property.addRange(new TypedList(cuid.ns(), componentType));
} else {
owlClass.setAllValuesFrom(property, (RDFSClass<RDFSResource>) resources.get(RDF.List));
}
restriction.setMaxCardinality(1);
}
} else {
RDFSClass<?> componentType =
processClass(mappedProperty.getComponentType(), session,
resources);
if (componentType != null) {
restriction.setAllValuesFrom(componentType);
}
}
} else if (mappedPath.isReference()) {
if (property.getRange().isEmpty()) {
RDFSClass<?> range = processClass(mappedProperty.getType(),
session, resources);
if (range != null) {
owlClass.setAllValuesFrom(property, range);
} else if (mappedProperty.isAnyResource()) {
owlClass.setAllValuesFrom(property, (RDFSClass<?>) resources.get(RDFS.Resource));
}
}
restriction.setMaxCardinality(1);
} else {
if (property.getRange().isEmpty()) {
UID range;
if (mappedProperty.isAnyResource()) {
range = RDFS.Resource;
}else if (mappedProperty.isLocalized()){
range = RDF.text;
} else {
range = converterRegistry.getDatatype(mappedProperty.getType());
}
if (range != null) {
owlClass.setAllValuesFrom(property, getDatatype(range, resources));
}
}
restriction.setMaxCardinality(1);
}
if (restriction.isDefined()) {
owlClass.addSuperClass(restriction);
}
if (mappedProperty.isRequired()) {
final Restriction minCardinality = new Restriction();
minCardinality.setOnProperty(property);
minCardinality.setMinCardinality(1);
owlClass.addSuperClass(minCardinality);
}
}
}
}
}
return owlClass;
}
| private RDFSClass<RDFSResource> processClass(Class<?> clazz, Session session, Map<UID, RDFSResource> resources) {
MappedClass mappedClass = configuration.getMappedClass(clazz);
OWLClass owlClass = null;
UID cuid = mappedClass.getUID();
if (cuid != null) {
if (!(exportNamespaces.isEmpty() || exportNamespaces.contains(cuid.ns()))) {
owlClass = new ReferenceClass(cuid);
} else {
owlClass = (OWLClass) resources.get(cuid);
if (owlClass == null) {
owlClass = new OWLClass(cuid);
resources.put(cuid, owlClass);
owlClass.setLabel(Locale.ROOT, cuid.getLocalName());
} else {
return owlClass;
}
if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)){
addParent(clazz.getSuperclass(), owlClass, session, resources);
}
for (Class<?> iface : clazz.getInterfaces()) {
addParent(iface, owlClass, session, resources);
}
if (mappedClass.isEnum()) {
List<RDFSResource> oneOf = new ArrayList<RDFSResource>();
for (Object constant: clazz.getEnumConstants()) {
Enum enumValue = (Enum)constant;
oneOf.add(new AnyThing(new UID(cuid.ns(), enumValue.name()), owlClass, enumValue.ordinal()));
}
owlClass.setOneOf(oneOf);
}
for (MappedPath mappedPath : mappedClass.getProperties()) {
if (!mappedPath.isInherited() && mappedPath.isSimpleProperty()) {
MappedProperty<?> mappedProperty = mappedPath.getMappedProperty();
MappedPredicate mappedPredicate = mappedPath.get(0);
UID puid = mappedPredicate.getUID();
String predicateNs = puid.ns();
if (RDF.NS.equals(predicateNs) || RDFS.NS.equals(predicateNs) || OWL.NS.equals(predicateNs)) {
continue;
}
final RDFProperty property;
boolean seenProperty = resources.containsKey(puid);
if (seenProperty) {
property = (RDFProperty) resources.get(puid);
if (mappedPath.isReference()) {
if (!(property instanceof ObjectProperty)) {
throw new IllegalArgumentException("Expected ObjectProperty for: " + mappedPath);
}
} else if (!mappedProperty.isAnyResource()){
if (!(property instanceof DatatypeProperty)) {
throw new IllegalArgumentException("Expected DatatypeProperty for: " + mappedPath);
}
}
} else {
if (mappedProperty.isAnyResource()) {
property = new RDFProperty(puid);
} else if (mappedPath.isReference() || mappedProperty.isCollection()) {
property = new ObjectProperty(puid);
} else {
property = new DatatypeProperty(puid);
}
property.setLabel(Locale.ROOT, puid.getLocalName());
resources.put(puid, property);
}
final Restriction restriction = new Restriction();
restriction.setOnProperty(property);
if (mappedProperty.isCollection()) {
if (mappedProperty.isList()) {
if (property.getRange().isEmpty()) {
RDFSClass<?> componentType =
processClass(mappedProperty.getComponentType(), session, resources);
if (useTypedLists && componentType != null) {
property.addRange(new TypedList(cuid.ns(), componentType));
} else {
owlClass.setAllValuesFrom(property, (RDFSClass<RDFSResource>) resources.get(RDF.List));
}
restriction.setMaxCardinality(1);
}
} else {
RDFSClass<?> componentType =
processClass(mappedProperty.getComponentType(), session,
resources);
if (componentType != null) {
restriction.setAllValuesFrom(componentType);
}
}
} else if (mappedPath.isReference()) {
if (property.getRange().isEmpty()) {
RDFSClass<?> range = processClass(mappedProperty.getType(),
session, resources);
if (range != null) {
owlClass.setAllValuesFrom(property, range);
} else if (mappedProperty.isAnyResource()) {
owlClass.setAllValuesFrom(property, (RDFSClass<?>) resources.get(RDFS.Resource));
}
}
restriction.setMaxCardinality(1);
} else {
if (property.getRange().isEmpty()) {
UID range;
if (mappedProperty.isAnyResource()) {
range = RDFS.Resource;
}else if (mappedProperty.isLocalized()){
range = RDF.text;
} else {
range = converterRegistry.getDatatype(mappedProperty.getType());
}
if (range != null) {
owlClass.setAllValuesFrom(property, getDatatype(range, resources));
}
}
restriction.setMaxCardinality(1);
}
if (restriction.isDefined()) {
owlClass.addSuperClass(restriction);
}
if (mappedProperty.isRequired()) {
final Restriction minCardinality = new Restriction();
minCardinality.setOnProperty(property);
minCardinality.setMinCardinality(1);
owlClass.addSuperClass(minCardinality);
}
}
}
}
}
return owlClass;
}
|
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
ScrollView v = new ScrollView(getActivity());
v.setPadding(15, 15, 15, 15);
v.addView(inflater.inflate(R.layout.filter_items_dialog, null));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
| public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
ScrollView v = new ScrollView(getActivity());
v.setPadding(15, 15, 15, 15);
v.addView(inflater.inflate(R.layout.filter_items_dialog, null));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
|
public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) {
BlockSand.instaFall = true;
int k = i * 16;
int l = j * 16;
BiomeGenBase biomegenbase = this.wcm.getBiome(k + 16, l + 16);
rand.setSeed(worldObj.getSeed());
long l1 = (rand.nextLong() / 2L) * 2L + 1L;
long l2 = (rand.nextLong() / 2L) * 2L + 1L;
rand.setSeed((long) i * l1 + (long) j * l2 ^ worldObj.getSeed());
double d = 0.25D;
if (rand.nextInt(4) == 0) {
int i1 = k + rand.nextInt(16) + 8;
int l4 = rand.nextInt(128);
int i8 = l + rand.nextInt(16) + 8;
(new WorldGenLakes(Block.WATER.id)).a(worldObj, rand, i1, l4, i8);
}
if (rand.nextInt(8) == 0) {
int j1 = k + rand.nextInt(16) + 8;
int i5 = rand.nextInt(rand.nextInt(120) + 8);
int j8 = l + rand.nextInt(16) + 8;
if (i5 < 64 || rand.nextInt(10) == 0) {
(new WorldGenLakes(Block.LAVA.id))
.a(worldObj, rand, j1, i5, j8);
}
}
for (int k1 = 0; k1 < 8; k1++) {
int j5 = k + rand.nextInt(16) + 8;
int k8 = rand.nextInt(128);
int j11 = l + rand.nextInt(16) + 8;
(new WorldGenDungeons()).a(worldObj, rand, j5, k8, j11);
}
for (int i2 = 0; i2 < 10; i2++) {
int k5 = k + rand.nextInt(16);
int l8 = rand.nextInt(128);
int k11 = l + rand.nextInt(16);
(new WorldGenClay(32)).a(worldObj, rand, k5, l8, k11);
}
for (int j2 = 0; j2 < 20; j2++) {
int l5 = k + rand.nextInt(16);
int i9 = rand.nextInt(128);
int l11 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIRT.id, 32)).a(worldObj, rand, l5, i9,
l11);
}
for (int k2 = 0; k2 < 10; k2++) {
int i6 = k + rand.nextInt(16);
int j9 = rand.nextInt(128);
int i12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GRAVEL.id, 32)).a(worldObj, rand, i6,
j9, i12);
}
for (int i3 = 0; i3 < 20; i3++) {
int j6 = k + rand.nextInt(16);
int k9 = rand.nextInt(128);
int j12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.COAL_ORE.id, 16)).a(worldObj, rand, j6,
k9, j12);
}
for (int j3 = 0; j3 < 20; j3++) {
int k6 = k + rand.nextInt(16);
int l9 = rand.nextInt(64);
int k12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.IRON_ORE.id, 8)).a(worldObj, rand, k6,
l9, k12);
}
for (int k3 = 0; k3 < 2; k3++) {
int l6 = k + rand.nextInt(16);
int i10 = rand.nextInt(32);
int l12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GOLD_ORE.id, 8)).a(worldObj, rand, l6,
i10, l12);
}
for (int l3 = 0; l3 < 8; l3++) {
int i7 = k + rand.nextInt(16);
int j10 = rand.nextInt(16);
int i13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.REDSTONE_ORE.id, 7)).a(worldObj, rand,
i7, j10, i13);
}
for (int i4 = 0; i4 < 1; i4++) {
int j7 = k + rand.nextInt(16);
int k10 = rand.nextInt(16);
int j13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIAMOND_ORE.id, 7)).a(worldObj, rand,
j7, k10, j13);
}
for (int j4 = 0; j4 < 1; j4++) {
int k7 = k + rand.nextInt(16);
int l10 = rand.nextInt(16) + rand.nextInt(16);
int k13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.LAPIS_ORE.id, 6)).a(worldObj, rand, k7,
l10, k13);
}
d = 0.5D;
int k4 = (int) ((mobSpawnerNoise.func_806_a((double) k * d, (double) l
* d)
/ 8D + rand.nextDouble() * 4D + 4D) / 3D);
int l7 = 0;
if (rand.nextInt(10) == 0) {
l7++;
}
if (biomegenbase == BiomeGenBase.forest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.rainforest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
l7 += k4 + 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.desert) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.tundra) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.plains) {
l7 -= 20;
}
for (int i11 = 0; i11 < l7; i11++) {
int l13 = k + rand.nextInt(16) + 8;
int j14 = l + rand.nextInt(16) + 8;
WorldGenerator worldgenerator = biomegenbase.a(rand);
worldgenerator.a(1.0D, 1.0D, 1.0D);
worldgenerator.a(worldObj, rand, l13,
worldObj.getHighestBlockYAt(l13, j14), j14);
}
byte byte0 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte0 = 4;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.plains) {
byte0 = 3;
}
for (int i14 = 0; i14 < byte0; i14++) {
int k14 = k + rand.nextInt(16) + 8;
int l16 = rand.nextInt(128);
int k19 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.YELLOW_FLOWER.id)).a(worldObj, rand,
k14, l16, k19);
}
byte byte1 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.rainforest) {
byte1 = 10;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte1 = 1;
}
if (biomegenbase == BiomeGenBase.plains) {
byte1 = 10;
}
for (int l14 = 0; l14 < byte1; l14++) {
byte byte2 = 1;
if (biomegenbase == BiomeGenBase.rainforest && rand.nextInt(3) != 0) {
byte2 = 2;
}
int l19 = k + rand.nextInt(16) + 8;
int k22 = rand.nextInt(128);
int j24 = l + rand.nextInt(16) + 8;
(new WorldGenTallGrass(Block.LONG_GRASS.id, byte2)).a(worldObj,
rand, l19, k22, j24);
}
byte1 = 0;
if (biomegenbase == BiomeGenBase.desert) {
byte1 = 2;
}
for (int i15 = 0; i15 < byte1; i15++) {
int i17 = k + rand.nextInt(16) + 8;
int i20 = rand.nextInt(128);
int l22 = l + rand.nextInt(16) + 8;
(new WorldGenDeadBush(Block.DEAD_BUSH.id)).a(worldObj, rand, i17,
i20, l22);
}
if (rand.nextInt(2) == 0) {
int j15 = k + rand.nextInt(16) + 8;
int j17 = rand.nextInt(128);
int j20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_ROSE.id)).a(worldObj, rand, j15,
j17, j20);
}
if (rand.nextInt(4) == 0) {
int k15 = k + rand.nextInt(16) + 8;
int k17 = rand.nextInt(128);
int k20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.BROWN_MUSHROOM.id)).a(worldObj, rand,
k15, k17, k20);
}
if (rand.nextInt(8) == 0) {
int l15 = k + rand.nextInt(16) + 8;
int l17 = rand.nextInt(128);
int l20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_MUSHROOM.id)).a(worldObj, rand, l15,
l17, l20);
}
for (int i16 = 0; i16 < 10; i16++) {
int i18 = k + rand.nextInt(16) + 8;
int i21 = rand.nextInt(128);
int i23 = l + rand.nextInt(16) + 8;
(new WorldGenReed()).a(worldObj, rand, i18, i21, i23);
}
if (rand.nextInt(32) == 0) {
int j16 = k + rand.nextInt(16) + 8;
int j18 = rand.nextInt(128);
int j21 = l + rand.nextInt(16) + 8;
(new WorldGenPumpkin()).a(worldObj, rand, j16, j18, j21);
}
int k16 = 0;
if (biomegenbase == BiomeGenBase.desert) {
k16 += 10;
}
for (int k18 = 0; k18 < k16; k18++) {
int k21 = k + rand.nextInt(16) + 8;
int j23 = rand.nextInt(128);
int k24 = l + rand.nextInt(16) + 8;
(new WorldGenCactus()).a(worldObj, rand, k21, j23, k24);
}
for (int l18 = 0; l18 < 50; l18++) {
int l21 = k + rand.nextInt(16) + 8;
int k23 = rand.nextInt(rand.nextInt(120) + 8);
int l24 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.WATER.id)).a(worldObj, rand, l21, k23,
l24);
}
for (int i19 = 0; i19 < 20; i19++) {
int i22 = k + rand.nextInt(16) + 8;
int l23 = rand.nextInt(rand.nextInt(rand.nextInt(112) + 8) + 8);
int i25 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.LAVA.id)).a(worldObj, rand, i22, l23,
i25);
}
generatedTemperatures = this.wcm.getTemperatures(generatedTemperatures,
k + 8, l + 8, 16, 16);
for (int j19 = k + 8; j19 < k + 8 + 16; j19++) {
for (int j22 = l + 8; j22 < l + 8 + 16; j22++) {
int i24 = j19 - (k + 8);
int j25 = j22 - (l + 8);
int k25 = worldObj.g(j19, j22);
double d1 = generatedTemperatures[i24 * 16 + j25]
- ((double) (k25 - 64) / 64D) * 0.29999999999999999D;
if (d1 < 0.5D
&& k25 > 0
&& k25 < 128
&& worldObj.isEmpty(j19, k25, j22)
&& worldObj.getMaterial(j19, k25 - 1, j22).isSolid()
&& worldObj.getMaterial(j19, k25 - 1, j22) != Material.ICE) {
worldObj.setTypeId(j19, k25, j22, Block.SNOW.id);
}
}
}
BlockSand.instaFall = false;
}
| public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) {
BlockSand.instaFall = true;
int k = i * 16;
int l = j * 16;
BiomeGenBase biomegenbase = this.wcm.getBiome(k + 16, l + 16);
rand.setSeed(worldObj.getSeed());
long l1 = (rand.nextLong() / 2L) * 2L + 1L;
long l2 = (rand.nextLong() / 2L) * 2L + 1L;
rand.setSeed((long) i * l1 + (long) j * l2 ^ worldObj.getSeed());
double d = 0.25D;
if (rand.nextInt(4) == 0) {
int i1 = k + rand.nextInt(16) + 8;
int l4 = rand.nextInt(128);
int i8 = l + rand.nextInt(16) + 8;
(new WorldGenLakes(Block.WATER.id)).a(worldObj, rand, i1, l4, i8);
}
if (rand.nextInt(8) == 0) {
int j1 = k + rand.nextInt(16) + 8;
int i5 = rand.nextInt(rand.nextInt(120) + 8);
int j8 = l + rand.nextInt(16) + 8;
if (i5 < 64 || rand.nextInt(10) == 0) {
(new WorldGenLakes(Block.LAVA.id))
.a(worldObj, rand, j1, i5, j8);
}
}
for (int k1 = 0; k1 < 8; k1++) {
int j5 = k + rand.nextInt(16) + 8;
int k8 = rand.nextInt(128);
int j11 = l + rand.nextInt(16) + 8;
(new WorldGenDungeons()).a(worldObj, rand, j5, k8, j11);
}
for (int i2 = 0; i2 < 10; i2++) {
int k5 = k + rand.nextInt(16);
int l8 = rand.nextInt(128);
int k11 = l + rand.nextInt(16);
(new WorldGenClay(32)).a(worldObj, rand, k5, l8, k11);
}
for (int j2 = 0; j2 < 20; j2++) {
int l5 = k + rand.nextInt(16);
int i9 = rand.nextInt(128);
int l11 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIRT.id, 32)).a(worldObj, rand, l5, i9,
l11);
}
for (int k2 = 0; k2 < 10; k2++) {
int i6 = k + rand.nextInt(16);
int j9 = rand.nextInt(128);
int i12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GRAVEL.id, 32)).a(worldObj, rand, i6,
j9, i12);
}
for (int i3 = 0; i3 < 20; i3++) {
int j6 = k + rand.nextInt(16);
int k9 = rand.nextInt(128);
int j12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.COAL_ORE.id, 16)).a(worldObj, rand, j6,
k9, j12);
}
for (int j3 = 0; j3 < 20; j3++) {
int k6 = k + rand.nextInt(16);
int l9 = rand.nextInt(64);
int k12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.IRON_ORE.id, 8)).a(worldObj, rand, k6,
l9, k12);
}
for (int k3 = 0; k3 < 2; k3++) {
int l6 = k + rand.nextInt(16);
int i10 = rand.nextInt(32);
int l12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GOLD_ORE.id, 8)).a(worldObj, rand, l6,
i10, l12);
}
for (int l3 = 0; l3 < 8; l3++) {
int i7 = k + rand.nextInt(16);
int j10 = rand.nextInt(16);
int i13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.REDSTONE_ORE.id, 7)).a(worldObj, rand,
i7, j10, i13);
}
for (int i4 = 0; i4 < 1; i4++) {
int j7 = k + rand.nextInt(16);
int k10 = rand.nextInt(16);
int j13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIAMOND_ORE.id, 7)).a(worldObj, rand,
j7, k10, j13);
}
for (int j4 = 0; j4 < 1; j4++) {
int k7 = k + rand.nextInt(16);
int l10 = rand.nextInt(16) + rand.nextInt(16);
int k13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.LAPIS_ORE.id, 6)).a(worldObj, rand, k7,
l10, k13);
}
d = 0.5D;
int k4 = (int) ((mobSpawnerNoise.func_806_a((double) k * d, (double) l
* d)
/ 8D + rand.nextDouble() * 4D + 4D) / 3D);
int l7 = 0;
if (rand.nextInt(10) == 0) {
l7++;
}
if (biomegenbase == BiomeGenBase.forest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.rainforest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
l7 += k4 + 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.desert) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.tundra) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.plains) {
l7 -= 20;
}
for (int i11 = 0; i11 < l7; i11++) {
int l13 = k + rand.nextInt(16) + 8;
int j14 = l + rand.nextInt(16) + 8;
WorldGenerator worldgenerator = biomegenbase.a(rand);
worldgenerator.a(1.0D, 1.0D, 1.0D);
worldgenerator.a(worldObj, rand, l13,
worldObj.getHighestBlockYAt(l13, j14), j14);
}
byte byte0 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte0 = 4;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.plains) {
byte0 = 3;
}
for (int i14 = 0; i14 < byte0; i14++) {
int k14 = k + rand.nextInt(16) + 8;
int l16 = rand.nextInt(128);
int k19 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.YELLOW_FLOWER.id)).a(worldObj, rand,
k14, l16, k19);
}
byte byte1 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.rainforest) {
byte1 = 10;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte1 = 1;
}
if (biomegenbase == BiomeGenBase.plains) {
byte1 = 10;
}
for (int l14 = 0; l14 < byte1; l14++) {
byte byte2 = 1;
if (biomegenbase == BiomeGenBase.rainforest && rand.nextInt(3) != 0) {
byte2 = 2;
}
int l19 = k + rand.nextInt(16) + 8;
int k22 = rand.nextInt(128);
int j24 = l + rand.nextInt(16) + 8;
(new WorldGenTallGrass(Block.LONG_GRASS.id, byte2)).a(worldObj,
rand, l19, k22, j24);
}
byte1 = 0;
if (biomegenbase == BiomeGenBase.desert) {
byte1 = 2;
}
for (int i15 = 0; i15 < byte1; i15++) {
int i17 = k + rand.nextInt(16) + 8;
int i20 = rand.nextInt(128);
int l22 = l + rand.nextInt(16) + 8;
(new WorldGenDeadBush(Block.DEAD_BUSH.id)).a(worldObj, rand, i17,
i20, l22);
}
if (rand.nextInt(2) == 0) {
int j15 = k + rand.nextInt(16) + 8;
int j17 = rand.nextInt(128);
int j20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_ROSE.id)).a(worldObj, rand, j15,
j17, j20);
}
if (rand.nextInt(4) == 0) {
int k15 = k + rand.nextInt(16) + 8;
int k17 = rand.nextInt(128);
int k20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.BROWN_MUSHROOM.id)).a(worldObj, rand,
k15, k17, k20);
}
if (rand.nextInt(8) == 0) {
int l15 = k + rand.nextInt(16) + 8;
int l17 = rand.nextInt(128);
int l20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_MUSHROOM.id)).a(worldObj, rand, l15,
l17, l20);
}
for (int i16 = 0; i16 < 10; i16++) {
int i18 = k + rand.nextInt(16) + 8;
int i21 = rand.nextInt(128);
int i23 = l + rand.nextInt(16) + 8;
(new WorldGenReed()).a(worldObj, rand, i18, i21, i23);
}
if (rand.nextInt(32) == 0) {
int j16 = k + rand.nextInt(16) + 8;
int j18 = rand.nextInt(128);
int j21 = l + rand.nextInt(16) + 8;
(new WorldGenPumpkin()).a(worldObj, rand, j16, j18, j21);
}
int k16 = 0;
if (biomegenbase == BiomeGenBase.desert) {
k16 += 10;
}
for (int k18 = 0; k18 < k16; k18++) {
int k21 = k + rand.nextInt(16) + 8;
int j23 = rand.nextInt(128);
int k24 = l + rand.nextInt(16) + 8;
(new WorldGenCactus()).a(worldObj, rand, k21, j23, k24);
}
for (int l18 = 0; l18 < 50; l18++) {
int l21 = k + rand.nextInt(16) + 8;
int k23 = rand.nextInt(rand.nextInt(120) + 8);
int l24 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.WATER.id)).a(worldObj, rand, l21, k23,
l24);
}
for (int i19 = 0; i19 < 20; i19++) {
int i22 = k + rand.nextInt(16) + 8;
int l23 = rand.nextInt(rand.nextInt(rand.nextInt(112) + 8) + 8);
int i25 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.LAVA.id)).a(worldObj, rand, i22, l23,
i25);
}
generatedTemperatures = this.wcm.getTemperatures(generatedTemperatures,
k + 8, l + 8, 16, 16);
for (int j19 = k + 8; j19 < k + 8 + 16; j19++) {
for (int j22 = l + 8; j22 < l + 8 + 16; j22++) {
int i24 = j19 - (k + 8);
int j25 = j22 - (l + 8);
int k25 = worldObj.getHighestBlockYAt(j19, j22);
double d1 = generatedTemperatures[i24 * 16 + j25]
- ((double) (k25 - 64) / 64D) * 0.29999999999999999D;
if (d1 < 0.5D
&& k25 > 0
&& k25 < 128
&& worldObj.isEmpty(j19, k25, j22)
&& worldObj.getMaterial(j19, k25 - 1, j22).isSolid()
&& worldObj.getMaterial(j19, k25 - 1, j22) != Material.ICE) {
worldObj.setTypeId(j19, k25, j22, Block.SNOW.id);
}
}
}
BlockSand.instaFall = false;
}
|
protected void execute(Exec exec, Instruction insn) {
Activation current = exec.current;
Frame frame = current.frame;
Object regs[] = frame != null ? frame.registers : null;
switch (insn.insn) {
case BIND__________:
bindPoints[bsp++] = journal.getPointInTime();
Node node0 = (Node) regs[insn.op0];
Node node1 = (Node) regs[insn.op1];
if (!Binder.bind(node0, node1, journal))
current.ip = insn.op2;
break;
case BINDUNDO______:
journal.undoBinds(bindPoints[--bsp]);
break;
case CUTBEGIN______:
regs[insn.op0] = i(cutPoints.size());
cutPoints.add(new CutPoint(current, journal.getPointInTime()));
break;
case CUTFAIL_______:
int cutPointIndex = g(regs[insn.op0]);
CutPoint cutPoint = cutPoints.get(cutPointIndex);
Util.truncate(cutPoints, cutPointIndex);
current = cutPoint.activation;
journal.undoBinds(cutPoint.journalPointer);
current.ip = insn.op1;
break;
case PROVEINTERPRET:
if (!prover.prove((Node) regs[insn.op0]))
current.ip = insn.op1;
break;
case PROVESYS______:
if (!systemPredicates.call((Node) regs[insn.op0]))
current.ip = insn.op1;
break;
default:
super.execute(exec, insn);
}
}
| protected void execute(Exec exec, Instruction insn) {
Activation current = exec.current;
Frame frame = current.frame;
Node regs[] = frame != null ? frame.registers : null;
switch (insn.insn) {
case BIND__________:
bindPoints[bsp++] = journal.getPointInTime();
Node node0 = regs[insn.op0];
Node node1 = regs[insn.op1];
if (!Binder.bind(node0, node1, journal))
current.ip = insn.op2;
break;
case BINDUNDO______:
journal.undoBinds(bindPoints[--bsp]);
break;
case CUTBEGIN______:
regs[insn.op0] = i(cutPoints.size());
cutPoints.add(new CutPoint(current, journal.getPointInTime()));
break;
case CUTFAIL_______:
int cutPointIndex = g(regs[insn.op0]);
CutPoint cutPoint = cutPoints.get(cutPointIndex);
Util.truncate(cutPoints, cutPointIndex);
current = cutPoint.activation;
journal.undoBinds(cutPoint.journalPointer);
current.ip = insn.op1;
break;
case PROVEINTERPRET:
if (!prover.prove(regs[insn.op0]))
current.ip = insn.op1;
break;
case PROVESYS______:
if (!systemPredicates.call(regs[insn.op0]))
current.ip = insn.op1;
break;
default:
super.execute(exec, insn);
}
}
|
public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tasks.tests");
suite.addTestSuite(TaskDataManagerTest.class);
suite.addTestSuite(CopyDetailsActionTest.class);
suite.addTestSuite(TaskListTest.class);
suite.addTestSuite(ProjectRepositoryAssociationTest.class);
suite.addTestSuite(TaskListDataMigrationTest.class);
suite.addTestSuite(TaskPlanningEditorTest.class);
suite.addTestSuite(TaskListManagerTest.class);
suite.addTestSuite(RepositoryTaskSynchronizationTest.class);
suite.addTestSuite(TaskRepositoryManagerTest.class);
suite.addTestSuite(TaskRepositoriesExternalizerTest.class);
suite.addTestSuite(TaskListContentProviderTest.class);
suite.addTestSuite(TaskListBackupManagerTest.class);
suite.addTestSuite(TableSorterTest.class);
suite.addTestSuite(TaskKeyComparatorTest.class);
suite.addTestSuite(TaskTest.class);
suite.addTestSuite(TaskListUiTest.class);
suite.addTestSuite(TaskListDnDTest.class);
suite.addTestSuite(TaskDataExportTest.class);
suite.addTestSuite(TaskDataImportTest.class);
suite.addTestSuite(TaskActivityViewTest.class);
suite.addTestSuite(TaskAttachmentActionsTest.class);
suite.addTestSuite(RepositorySettingsPageTest.class);
suite.addTestSuite(TaskHistoryTest.class);
suite.addTestSuite(UrlConnectionUtilTest.class);
suite.addTestSuite(CommentQuoterTest.class);
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tasks.tests");
suite.addTest(WebRepositoryConnectorTest.suite());
suite.addTestSuite(TaskDataManagerTest.class);
suite.addTestSuite(CopyDetailsActionTest.class);
suite.addTestSuite(TaskListTest.class);
suite.addTestSuite(ProjectRepositoryAssociationTest.class);
suite.addTestSuite(TaskListDataMigrationTest.class);
suite.addTestSuite(TaskPlanningEditorTest.class);
suite.addTestSuite(TaskListManagerTest.class);
suite.addTestSuite(RepositoryTaskSynchronizationTest.class);
suite.addTestSuite(TaskRepositoryManagerTest.class);
suite.addTestSuite(TaskRepositoriesExternalizerTest.class);
suite.addTestSuite(TaskListContentProviderTest.class);
suite.addTestSuite(TaskListBackupManagerTest.class);
suite.addTestSuite(TableSorterTest.class);
suite.addTestSuite(TaskKeyComparatorTest.class);
suite.addTestSuite(TaskTest.class);
suite.addTestSuite(TaskListUiTest.class);
suite.addTestSuite(TaskListDnDTest.class);
suite.addTestSuite(TaskDataExportTest.class);
suite.addTestSuite(TaskDataImportTest.class);
suite.addTestSuite(TaskActivityViewTest.class);
suite.addTestSuite(TaskAttachmentActionsTest.class);
suite.addTestSuite(RepositorySettingsPageTest.class);
suite.addTestSuite(TaskHistoryTest.class);
suite.addTestSuite(UrlConnectionUtilTest.class);
suite.addTestSuite(CommentQuoterTest.class);
return suite;
}
|
public void copyImageToDevice(File source) throws IOException {
boolean healthy = DiskUtils.checkDisk(false);
if (!healthy) {
DiskUtils.formatDevice();
healthy = DiskUtils.checkDisk(false);
}
if (!healthy) {
healthy = DiskUtils.checkDisk(true);
}
if (!healthy) {
throw new IOException("The device appears to be corrupted.");
}
DiskUtils.copyDir(source, new File(DiskUtils.TBMountDirectory));
}
| public void copyImageToDevice(File source) throws IOException {
boolean healthy = DiskUtils.checkDisk(false);
if (!healthy) {
DiskUtils.formatDevice();
healthy = DiskUtils.checkDisk(false);
}
if (!healthy) {
healthy = DiskUtils.checkDisk(true);
}
if (!healthy) {
throw new IOException("The device appears to be corrupted.");
}
DiskUtils.copy(source, new File(DiskUtils.TBMountDirectory));
}
|
public ClosureIncludesEditor(IEditorContainer container) {
super(container, 3);
record.otherLibraries.bindEditor(this);
SWTFactory.createLabel(container.getComposite(), getMessage("help"), 3);
record.externs.bindEditor(this);
record.useOnlyCustomExterns.bindEditor(this);
}
| public ClosureIncludesEditor(IEditorContainer container) {
super(container, 3);
record.otherLibraries.bindEditor(this);
SWTFactory.createLabel(container.getComposite(), getMessage("otherLibrariesHelp"), 3);
record.externs.bindEditor(this);
record.useOnlyCustomExterns.bindEditor(this);
}
|
@Override public boolean check(ErrorHandler hErr, Module module) {
boolean isValid = true;
int value;
if(this.operands.size() > 1) {
hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1);
isValid = false;
} else if(this.operands.size() < 1) {
hErr.reportError(makeError("tooFewOperands", this.getOpId()), this.lineNum, -1);
isValid = false;
}
else if(this.hasOperand("DR")) {
value = module.evaluate(this.getOperand("DR"), false, hErr, this, this.getOperandData("DR").keywordStartPosition);
isValid = OperandChecker.isValidReg(value);
if(!isValid) hErr.reportError(makeError("OORidxReg", "DR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DX")){
value = module.evaluate(this.getOperand("DX"), false, hErr, this, this.getOperandData("DX").keywordStartPosition);
isValid = OperandChecker.isValidIndex(value);
if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1);
} else{
isValid = false;
if(this.hasOperand("FR")){
hErr.reportError(makeError("operandInsWrong", "FR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM")){
hErr.reportError(makeError("operandInsWrong", "DM", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FC")){
hErr.reportError(makeError("operandInsWrong", "FC", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FL")){
hErr.reportError(makeError("operandInsWrong", "FL", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FS")){
hErr.reportError(makeError("operandInsWrong", "FS", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("LR")){
hErr.reportError(makeError("operandInsWrong", "LR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FM")){
hErr.reportError(makeError("operandInsWrong", "FM", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("EX")){
hErr.reportError(makeError("operandInsWrong", "EX", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("NW")){
hErr.reportError(makeError("operandInsWrong", "NW", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("ST")){
hErr.reportError(makeError("operandInsWrong", "ST", this.getOpId()), this.lineNum, -1);
}
}
return isValid;
}
| @Override public boolean check(ErrorHandler hErr, Module module) {
boolean isValid = true;
int value;
if(this.operands.size() > 1) {
hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1);
isValid = false;
} else if(this.operands.size() < 1) {
hErr.reportError(makeError("tooFewOperands", this.getOpId()), this.lineNum, -1);
isValid = false;
}
else if(this.hasOperand("DR")) {
value = module.evaluate(this.getOperand("DR"), false, hErr, this, this.getOperandData("DR").keywordStartPosition);
isValid = OperandChecker.isValidReg(value);
if(!isValid) hErr.reportError(makeError("OORidxReg", "DR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DX")){
value = module.evaluate(this.getOperand("DX"), false, hErr, this, this.getOperandData("DX").keywordStartPosition);
isValid = OperandChecker.isValidIndex(value);
if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1);
} else{
isValid = false;
if(this.hasOperand("FR")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "FR"), this.lineNum, -1);
} else if(this.hasOperand("DM")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "DM"), this.lineNum, -1);
} else if(this.hasOperand("FC")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "FC"), this.lineNum, -1);
} else if(this.hasOperand("FL")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "FL"), this.lineNum, -1);
} else if(this.hasOperand("FS")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "FS"), this.lineNum, -1);
} else if(this.hasOperand("LR")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "LR"), this.lineNum, -1);
} else if(this.hasOperand("FM")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "FM"), this.lineNum, -1);
} else if(this.hasOperand("EX")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "EX"), this.lineNum, -1);
} else if(this.hasOperand("NW")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "NW"), this.lineNum, -1);
} else if(this.hasOperand("ST")){
hErr.reportError(makeError("operandInsWrong", this.getOpId(), "ST"), this.lineNum, -1);
}
}
return isValid;
}
|
public void load(Object entity)
{
if (!injectionTargets.containsKey(entity.getClass()))
{
if (!injectionRequired(entity.getClass()))
{
injectionTargets.put(entity.getClass(), NULL_INJECTION_TARGET);
log.debug("Entity {} has no injection points so injection will not be enabled", entity.getClass());
}
else
{
AnnotatedTypeBuilder<?> builder = new AnnotatedTypeBuilder().readFromType(entity.getClass());
InjectionTarget<?> injectionTarget = getBeanManager().createInjectionTarget(builder.create());
injectionTargets.put(entity.getClass(), injectionTarget);
log.info("Enabling injection into entity {}", entity.getClass());
}
}
InjectionTarget it = injectionTargets.get(entity.getClass());
if (it != NULL_INJECTION_TARGET)
{
log.debug("Running CDI injection for {}", entity.getClass());
it.inject(entity, new CreationalContextImpl());
}
}
| public void load(Object entity)
{
if (!injectionTargets.containsKey(entity.getClass()))
{
if (!injectionRequired(entity.getClass()))
{
injectionTargets.put(entity.getClass(), NULL_INJECTION_TARGET);
log.debugv("Entity {} has no injection points so injection will not be enabled", entity.getClass());
}
else
{
AnnotatedTypeBuilder<?> builder = new AnnotatedTypeBuilder().readFromType(entity.getClass());
InjectionTarget<?> injectionTarget = getBeanManager().createInjectionTarget(builder.create());
injectionTargets.put(entity.getClass(), injectionTarget);
log.infov("Enabling injection into entity {}", entity.getClass());
}
}
InjectionTarget it = injectionTargets.get(entity.getClass());
if (it != NULL_INJECTION_TARGET)
{
log.debugv("Running CDI injection for {}", entity.getClass());
it.inject(entity, new CreationalContextImpl());
}
}
|
public PotPanel(final int pin, final JFrame frame) {
setSize(new Dimension(900, 780));
setMinimumSize(new Dimension(900, 780));
cntx = Context.getInstance();
this.setToolTipText("");
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 47, 186, 30, 620 };
gridBagLayout.rowHeights = new int[] {29, 450, 85, 0};
gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 1.0 };
gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0,
Double.MIN_VALUE };
setLayout(gridBagLayout);
JPanel pnlLastValues = new JPanel();
pnlLastValues.setPreferredSize(new Dimension(410, 20));
pnlLastValues.setMinimumSize(new Dimension(410, 20));
pnlLastValues.setMaximumSize(new Dimension(410, 20));
pnlLastValues
.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
pnlLastValues.setAlignmentY(Component.TOP_ALIGNMENT);
pnlLastValues.setAlignmentX(Component.LEFT_ALIGNMENT);
GridBagConstraints gbc_pnlLastValues = new GridBagConstraints();
gbc_pnlLastValues.insets = new Insets(0, 0, 5, 0);
gbc_pnlLastValues.ipady = 5;
gbc_pnlLastValues.ipadx = 5;
gbc_pnlLastValues.gridwidth = 3;
gbc_pnlLastValues.anchor = GridBagConstraints.NORTHWEST;
gbc_pnlLastValues.gridx = 1;
gbc_pnlLastValues.gridy = 0;
add(pnlLastValues, gbc_pnlLastValues);
GridBagLayout gbl_pnlLastValues = new GridBagLayout();
gbl_pnlLastValues.columnWidths = new int[] { 150, 90, 40, 120 };
gbl_pnlLastValues.rowHeights = new int[] { 20 };
gbl_pnlLastValues.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0 };
gbl_pnlLastValues.rowWeights = new double[] { 0.0 };
pnlLastValues.setLayout(gbl_pnlLastValues);
JLabel lblLastMeasruement = new JLabel("Last measurement");
lblLastMeasruement.setPreferredSize(new Dimension(130, 20));
lblLastMeasruement.setSize(new Dimension(130, 20));
lblLastMeasruement.setMinimumSize(new Dimension(130, 20));
lblLastMeasruement.setMaximumSize(new Dimension(130, 20));
lblLastMeasruement.setBorder(new CompoundBorder());
GridBagConstraints gbc_lblLastMeasruement = new GridBagConstraints();
gbc_lblLastMeasruement.anchor = GridBagConstraints.EAST;
gbc_lblLastMeasruement.fill = GridBagConstraints.VERTICAL;
gbc_lblLastMeasruement.insets = new Insets(0, 0, 0, 5);
gbc_lblLastMeasruement.gridx = 0;
gbc_lblLastMeasruement.gridy = 0;
pnlLastValues.add(lblLastMeasruement, gbc_lblLastMeasruement);
txtLastValue = new JTextField();
txtLastValue.setColumns(10);
txtLastValue.setPreferredSize(new Dimension(90, 20));
txtLastValue.setMinimumSize(new Dimension(90, 20));
txtLastValue.setMaximumSize(new Dimension(90, 20));
GridBagConstraints gbc_txtLastValue = new GridBagConstraints();
gbc_txtLastValue.fill = GridBagConstraints.BOTH;
gbc_txtLastValue.gridx = 1;
gbc_txtLastValue.gridy = 0;
pnlLastValues.add(txtLastValue, gbc_txtLastValue);
txtLastValue.setEditable(false);
JLabel lblAt = new JLabel("at");
lblAt.setPreferredSize(new Dimension(40, 20));
lblAt.setMinimumSize(new Dimension(40, 20));
lblAt.setMaximumSize(new Dimension(40, 20));
lblAt.setAlignmentX(Component.RIGHT_ALIGNMENT);
GridBagConstraints gbc_lblAt = new GridBagConstraints();
gbc_lblAt.anchor = GridBagConstraints.EAST;
gbc_lblAt.fill = GridBagConstraints.VERTICAL;
gbc_lblAt.insets = new Insets(0, 5, 0, 5);
gbc_lblAt.gridx = 2;
gbc_lblAt.gridy = 0;
pnlLastValues.add(lblAt, gbc_lblAt);
txtLastTime = new JTextField();
txtLastTime.setSize(new Dimension(120, 20));
txtLastTime.setPreferredSize(new Dimension(120, 20));
txtLastTime.setMinimumSize(new Dimension(120, 20));
txtLastTime.setMaximumSize(new Dimension(120, 20));
GridBagConstraints gbc_txtLastTime = new GridBagConstraints();
gbc_txtLastTime.fill = GridBagConstraints.BOTH;
gbc_txtLastTime.gridx = 3;
gbc_txtLastTime.gridy = 0;
pnlLastValues.add(txtLastTime, gbc_txtLastTime);
txtLastTime.setColumns(10);
txtLastTime.setEditable(false);
final JTextArea txtResults = new JTextArea();
txtResults.setEditable(false);
txtResults.setTabSize(2);
txtResults.setPreferredSize(new Dimension(120, 4000));
txtResults.setMinimumSize(new Dimension(120, 4000));
txtResults.setMaximumSize(new Dimension(120, 4000));
JScrollPane sp = new JScrollPane(txtResults);
sp.setPreferredSize(new Dimension(120, 450));
sp.setMinimumSize(new Dimension(120, 450));
sp.setMaximumSize(new Dimension(120, 450));
sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
GridBagConstraints gbc_sp = new GridBagConstraints();
gbc_sp.fill = GridBagConstraints.BOTH;
gbc_sp.insets = new Insets(0, 0, 5, 5);
gbc_sp.gridx = 1;
gbc_sp.gridy = 1;
this.add(sp, gbc_sp);
txtResults.setColumns(1);
txtResults.setRows(30);
final ChartPanel pnlChart = new ChartPanel(null);
pnlChart.setMaximumDrawWidth(2048);
pnlChart.setMinimumDrawWidth(620);
pnlChart.setMinimumSize(new Dimension(620, 450));
pnlChart.setPreferredSize(new Dimension(620, 450));
GridBagConstraints gbc_pnlChart = new GridBagConstraints();
gbc_pnlChart.fill = GridBagConstraints.BOTH;
gbc_pnlChart.insets = new Insets(0, 0, 5, 0);
gbc_pnlChart.gridx = 3;
gbc_pnlChart.gridy = 1;
add(pnlChart, gbc_pnlChart);
JPanel pnlCriteria = new JPanel();
pnlCriteria.setSize(new Dimension(500, 85));
pnlCriteria.setMinimumSize(new Dimension(500, 85));
pnlCriteria.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
pnlCriteria.setAlignmentY(Component.BOTTOM_ALIGNMENT);
pnlCriteria.setAlignmentX(Component.RIGHT_ALIGNMENT);
GridBagConstraints gbc_pnlCriteria = new GridBagConstraints();
gbc_pnlCriteria.insets = new Insets(0, 5, 0, 0);
gbc_pnlCriteria.anchor = GridBagConstraints.SOUTHEAST;
gbc_pnlCriteria.gridx = 3;
gbc_pnlCriteria.gridy = 2;
add(pnlCriteria, gbc_pnlCriteria);
pnlCriteria.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.UNRELATED_GAP_COLSPEC,
ColumnSpec.decode("60px"),
FormFactory.UNRELATED_GAP_COLSPEC,
ColumnSpec.decode("112px"),
FormFactory.UNRELATED_GAP_COLSPEC,
ColumnSpec.decode("112px"),
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.UNRELATED_GAP_COLSPEC,},
new RowSpec[] {
FormFactory.UNRELATED_GAP_ROWSPEC,
RowSpec.decode("26px"),
FormFactory.UNRELATED_GAP_ROWSPEC,
RowSpec.decode("26px"),
FormFactory.UNRELATED_GAP_ROWSPEC,}));
JLabel lblDateFrom = new JLabel("From");
pnlCriteria.add(lblDateFrom, "2, 2, fill, fill");
final JComboBox cmbMonthFrom = new JComboBox();
pnlCriteria.add(cmbMonthFrom, "4, 2, fill, fill");
JLabel lblDateTo = new JLabel("To");
pnlCriteria.add(lblDateTo, "2, 4, fill, fill");
final JComboBox cmbMonthTo = new JComboBox();
pnlCriteria.add(cmbMonthTo, "4, 4, fill, fill");
final JComboBox cmbYearTo = new JComboBox();
pnlCriteria.add(cmbYearTo, "6, 4, fill, fill");
JButton btnGet = new JButton("Get Information");
pnlCriteria.add(btnGet, "8, 4, fill, fill");
this.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
if(measurements!= null){
JFreeChart fc = ChartCreator
.createChart(measurements);
pnlChart.setChart(fc);
pnlChart.setVisible(true);
}
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
cmbMonthFrom.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
cmbMonthTo.setSelectedIndex(cmbMonthFrom.getSelectedIndex());
}
});
final JComboBox cmbYearFrom = new JComboBox();
pnlCriteria.add(cmbYearFrom, "6, 2, fill, fill");
cmbYearFrom.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
cmbYearTo.setSelectedIndex(cmbYearFrom.getSelectedIndex());
}
});
btnGet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Calendar from = Calendar.getInstance();
from.set(Calendar.MONTH, cmbMonthFrom.getSelectedIndex() + 1);
from.set(Calendar.DAY_OF_MONTH, 1);
from.set(Calendar.YEAR, Integer.parseInt((String) cmbYearFrom
.getSelectedItem()));
Calendar to = Calendar.getInstance();
to.set(Calendar.MONTH, cmbMonthTo.getSelectedIndex() + 1);
to.set(Calendar.DAY_OF_MONTH, 1);
to.set(Calendar.YEAR,
Integer.parseInt((String) cmbYearTo.getSelectedItem()));
if (from.getTime().getTime() > to.getTime().getTime()) {
JOptionPane.showMessageDialog(frame,
"The \"From\" date is after the \"To\" one",
"Warning", JOptionPane.ERROR_MESSAGE);
} else {
measurements = null;
try {
measurements = Server.GetMeasurements(from, to, pin,
cntx);
if (measurements == null || measurements.size() == 0)
JOptionPane.showMessageDialog(frame,
"Measurements not available yet",
"Warning", JOptionPane.WARNING_MESSAGE);
else {
for (int i = 0; i < measurements.size(); i++)
txtResults.setText(txtResults.getText()
+ "\n"
+ df.format(new Date(measurements
.get(i).getMoment())) + "\t"
+ measurements.get(i).getValue());
Calendar c = Calendar.getInstance();
c.setTimeInMillis((long) measurements.get(
measurements.size() - 1).getMoment());
txtLastTime.setText(df.format(c.getTime()));
txtLastValue.setText(String.valueOf(measurements
.get(measurements.size() - 1).getValue()));
JFreeChart fc = ChartCreator
.createChart(measurements);
pnlChart.setChart(fc);
pnlChart.setVisible(true);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(),
"Warning", JOptionPane.ERROR_MESSAGE);
}
}
}
});
for (int i = 0; i < availableMonths.length; i++)
cmbMonthTo.addItem(availableMonths[i]);
for (int i = 0; i < availableYears.length; i++)
cmbYearTo.addItem(availableYears[i]);
for (int i = 0; i < availableMonths.length; i++)
cmbMonthFrom.addItem(availableMonths[i]);
for (int i = 0; i < availableYears.length; i++)
cmbYearFrom.addItem(availableYears[i]);
}
| public PotPanel(final int pin, final JFrame frame) {
setSize(new Dimension(900, 780));
setMinimumSize(new Dimension(900, 780));
cntx = Context.getInstance();
this.setToolTipText("");
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 47, 186, 30, 620 };
gridBagLayout.rowHeights = new int[] {29, 450, 85, 0};
gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 1.0 };
gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0,
Double.MIN_VALUE };
setLayout(gridBagLayout);
JPanel pnlLastValues = new JPanel();
pnlLastValues.setPreferredSize(new Dimension(410, 20));
pnlLastValues.setMinimumSize(new Dimension(410, 20));
pnlLastValues.setMaximumSize(new Dimension(410, 20));
pnlLastValues
.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
pnlLastValues.setAlignmentY(Component.TOP_ALIGNMENT);
pnlLastValues.setAlignmentX(Component.LEFT_ALIGNMENT);
GridBagConstraints gbc_pnlLastValues = new GridBagConstraints();
gbc_pnlLastValues.insets = new Insets(0, 0, 5, 0);
gbc_pnlLastValues.ipady = 5;
gbc_pnlLastValues.ipadx = 5;
gbc_pnlLastValues.gridwidth = 3;
gbc_pnlLastValues.anchor = GridBagConstraints.NORTHWEST;
gbc_pnlLastValues.gridx = 1;
gbc_pnlLastValues.gridy = 0;
add(pnlLastValues, gbc_pnlLastValues);
GridBagLayout gbl_pnlLastValues = new GridBagLayout();
gbl_pnlLastValues.columnWidths = new int[] { 150, 90, 40, 120 };
gbl_pnlLastValues.rowHeights = new int[] { 20 };
gbl_pnlLastValues.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0 };
gbl_pnlLastValues.rowWeights = new double[] { 0.0 };
pnlLastValues.setLayout(gbl_pnlLastValues);
JLabel lblLastMeasruement = new JLabel("Last measurement");
lblLastMeasruement.setPreferredSize(new Dimension(130, 20));
lblLastMeasruement.setSize(new Dimension(130, 20));
lblLastMeasruement.setMinimumSize(new Dimension(130, 20));
lblLastMeasruement.setMaximumSize(new Dimension(130, 20));
lblLastMeasruement.setBorder(new CompoundBorder());
GridBagConstraints gbc_lblLastMeasruement = new GridBagConstraints();
gbc_lblLastMeasruement.anchor = GridBagConstraints.EAST;
gbc_lblLastMeasruement.fill = GridBagConstraints.VERTICAL;
gbc_lblLastMeasruement.insets = new Insets(0, 0, 0, 5);
gbc_lblLastMeasruement.gridx = 0;
gbc_lblLastMeasruement.gridy = 0;
pnlLastValues.add(lblLastMeasruement, gbc_lblLastMeasruement);
txtLastValue = new JTextField();
txtLastValue.setColumns(10);
txtLastValue.setPreferredSize(new Dimension(90, 20));
txtLastValue.setMinimumSize(new Dimension(90, 20));
txtLastValue.setMaximumSize(new Dimension(90, 20));
GridBagConstraints gbc_txtLastValue = new GridBagConstraints();
gbc_txtLastValue.fill = GridBagConstraints.BOTH;
gbc_txtLastValue.gridx = 1;
gbc_txtLastValue.gridy = 0;
pnlLastValues.add(txtLastValue, gbc_txtLastValue);
txtLastValue.setEditable(false);
JLabel lblAt = new JLabel("at");
lblAt.setPreferredSize(new Dimension(40, 20));
lblAt.setMinimumSize(new Dimension(40, 20));
lblAt.setMaximumSize(new Dimension(40, 20));
lblAt.setAlignmentX(Component.RIGHT_ALIGNMENT);
GridBagConstraints gbc_lblAt = new GridBagConstraints();
gbc_lblAt.anchor = GridBagConstraints.EAST;
gbc_lblAt.fill = GridBagConstraints.VERTICAL;
gbc_lblAt.insets = new Insets(0, 5, 0, 5);
gbc_lblAt.gridx = 2;
gbc_lblAt.gridy = 0;
pnlLastValues.add(lblAt, gbc_lblAt);
txtLastTime = new JTextField();
txtLastTime.setSize(new Dimension(120, 20));
txtLastTime.setPreferredSize(new Dimension(120, 20));
txtLastTime.setMinimumSize(new Dimension(120, 20));
txtLastTime.setMaximumSize(new Dimension(120, 20));
GridBagConstraints gbc_txtLastTime = new GridBagConstraints();
gbc_txtLastTime.fill = GridBagConstraints.BOTH;
gbc_txtLastTime.gridx = 3;
gbc_txtLastTime.gridy = 0;
pnlLastValues.add(txtLastTime, gbc_txtLastTime);
txtLastTime.setColumns(10);
txtLastTime.setEditable(false);
final JTextArea txtResults = new JTextArea();
txtResults.setEditable(false);
txtResults.setTabSize(2);
txtResults.setPreferredSize(new Dimension(120, 4000));
txtResults.setMinimumSize(new Dimension(120, 4000));
txtResults.setMaximumSize(new Dimension(120, 4000));
JScrollPane sp = new JScrollPane(txtResults);
sp.setPreferredSize(new Dimension(120, 450));
sp.setMinimumSize(new Dimension(120, 450));
sp.setMaximumSize(new Dimension(120, 450));
sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
GridBagConstraints gbc_sp = new GridBagConstraints();
gbc_sp.fill = GridBagConstraints.BOTH;
gbc_sp.insets = new Insets(0, 0, 5, 5);
gbc_sp.gridx = 1;
gbc_sp.gridy = 1;
this.add(sp, gbc_sp);
txtResults.setColumns(1);
txtResults.setRows(30);
final ChartPanel pnlChart = new ChartPanel(null);
pnlChart.setMaximumDrawWidth(2048);
pnlChart.setMinimumDrawWidth(620);
pnlChart.setMinimumSize(new Dimension(620, 450));
pnlChart.setPreferredSize(new Dimension(620, 450));
GridBagConstraints gbc_pnlChart = new GridBagConstraints();
gbc_pnlChart.fill = GridBagConstraints.BOTH;
gbc_pnlChart.insets = new Insets(0, 0, 5, 0);
gbc_pnlChart.gridx = 3;
gbc_pnlChart.gridy = 1;
add(pnlChart, gbc_pnlChart);
JPanel pnlCriteria = new JPanel();
pnlCriteria.setSize(new Dimension(500, 85));
pnlCriteria.setMinimumSize(new Dimension(500, 85));
pnlCriteria.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
pnlCriteria.setAlignmentY(Component.BOTTOM_ALIGNMENT);
pnlCriteria.setAlignmentX(Component.RIGHT_ALIGNMENT);
GridBagConstraints gbc_pnlCriteria = new GridBagConstraints();
gbc_pnlCriteria.insets = new Insets(0, 5, 0, 0);
gbc_pnlCriteria.anchor = GridBagConstraints.SOUTHEAST;
gbc_pnlCriteria.gridx = 3;
gbc_pnlCriteria.gridy = 2;
add(pnlCriteria, gbc_pnlCriteria);
pnlCriteria.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.UNRELATED_GAP_COLSPEC,
ColumnSpec.decode("60px"),
FormFactory.UNRELATED_GAP_COLSPEC,
ColumnSpec.decode("112px"),
FormFactory.UNRELATED_GAP_COLSPEC,
ColumnSpec.decode("112px"),
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.UNRELATED_GAP_COLSPEC,},
new RowSpec[] {
FormFactory.UNRELATED_GAP_ROWSPEC,
RowSpec.decode("26px"),
FormFactory.UNRELATED_GAP_ROWSPEC,
RowSpec.decode("26px"),
FormFactory.UNRELATED_GAP_ROWSPEC,}));
JLabel lblDateFrom = new JLabel("From");
pnlCriteria.add(lblDateFrom, "2, 2, fill, fill");
final JComboBox cmbMonthFrom = new JComboBox();
pnlCriteria.add(cmbMonthFrom, "4, 2, fill, fill");
JLabel lblDateTo = new JLabel("To");
pnlCriteria.add(lblDateTo, "2, 4, fill, fill");
final JComboBox cmbMonthTo = new JComboBox();
pnlCriteria.add(cmbMonthTo, "4, 4, fill, fill");
final JComboBox cmbYearTo = new JComboBox();
pnlCriteria.add(cmbYearTo, "6, 4, fill, fill");
JButton btnGet = new JButton("Get Information");
pnlCriteria.add(btnGet, "8, 4, fill, fill");
this.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
if(measurements!= null){
JFreeChart fc = ChartCreator
.createChart(measurements);
pnlChart.setChart(fc);
pnlChart.setVisible(true);
}
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
cmbMonthFrom.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
cmbMonthTo.setSelectedIndex(cmbMonthFrom.getSelectedIndex());
}
});
final JComboBox cmbYearFrom = new JComboBox();
pnlCriteria.add(cmbYearFrom, "6, 2, fill, fill");
cmbYearFrom.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
cmbYearTo.setSelectedIndex(cmbYearFrom.getSelectedIndex());
}
});
btnGet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtResults.setText("");
Calendar from = Calendar.getInstance();
from.set(Calendar.MONTH, cmbMonthFrom.getSelectedIndex() + 1);
from.set(Calendar.DAY_OF_MONTH, 1);
from.set(Calendar.YEAR, Integer.parseInt((String) cmbYearFrom
.getSelectedItem()));
Calendar to = Calendar.getInstance();
to.set(Calendar.MONTH, cmbMonthTo.getSelectedIndex() + 1);
to.set(Calendar.DAY_OF_MONTH, 1);
to.set(Calendar.YEAR,
Integer.parseInt((String) cmbYearTo.getSelectedItem()));
if (from.getTime().getTime() > to.getTime().getTime()) {
JOptionPane.showMessageDialog(frame,
"The \"From\" date is after the \"To\" one",
"Warning", JOptionPane.ERROR_MESSAGE);
} else {
measurements = null;
try {
measurements = Server.GetMeasurements(from, to, pin,
cntx);
if (measurements == null || measurements.size() == 0)
JOptionPane.showMessageDialog(frame,
"Measurements not available yet",
"Warning", JOptionPane.WARNING_MESSAGE);
else {
for (int i = 0; i < measurements.size(); i++)
txtResults.setText(txtResults.getText()
+ "\n"
+ df.format(new Date(measurements
.get(i).getMoment())) + "\t"
+ measurements.get(i).getValue());
Calendar c = Calendar.getInstance();
c.setTimeInMillis((long) measurements.get(
measurements.size() - 1).getMoment());
txtLastTime.setText(df.format(c.getTime()));
txtLastValue.setText(String.valueOf(measurements
.get(measurements.size() - 1).getValue()));
JFreeChart fc = ChartCreator
.createChart(measurements);
pnlChart.setChart(fc);
pnlChart.setVisible(true);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(),
"Warning", JOptionPane.ERROR_MESSAGE);
}
}
}
});
for (int i = 0; i < availableMonths.length; i++)
cmbMonthTo.addItem(availableMonths[i]);
for (int i = 0; i < availableYears.length; i++)
cmbYearTo.addItem(availableYears[i]);
for (int i = 0; i < availableMonths.length; i++)
cmbMonthFrom.addItem(availableMonths[i]);
for (int i = 0; i < availableYears.length; i++)
cmbYearFrom.addItem(availableYears[i]);
}
|
public static String drawWinner() {
String output = "";
String sql = "";
int winnings = 0;
String winner = "";
try {
winnings = getPot();
sql = "SELECT `username` FROM " + Settings.getMySQLPlayersTable()
+ " ORDER BY RAND() LIMIT 1";
if (!Lottery.database.Read(sql).isEmpty() || !Lottery.database.Read(sql).get(1).isEmpty() || Lottery.database.Read(sql).get(1).get(0) != null) {
winner = Lottery.database.Read(sql).get(1).get(0);
} else {
System.out.println("[Lottery] Lottery Players table is empty.");
if (Settings.isInDebug())
System.out.println("[Lottery Debug] " + Lottery.database.Read(sql));
}
} catch (Exception ex) {
ex.printStackTrace();
}
output = "<option><white>" + winner + "<gray> won <yellow>"
+ winnings + ".00 Dei!";
sql = "INSERT INTO " + Settings.getMySQLWinnersTable() + " ("
+ "`username`, `winnings`, `time`)" + "VALUES (" + "'"
+ winner + "', '" + winnings + "', NOW());";
if (!winner.isEmpty() && winner != null) {
double money = winnings;
Account account = iConomy.getAccount(winner);
if (account == null) {
System.out.println(String.format("[Lottery] %s had a null iConomy Account", winner));
return "";
}
account.getHoldings().add(money);
Lottery.database.Write(sql);
clear();
return output;
} else {
System.out.println("[Lottery] Player field was null");
return "";
}
}
| public static String drawWinner() {
String output = "";
String sql = "";
int winnings = 0;
String winner = "";
try {
winnings = getPot();
sql = "SELECT `username` FROM " + Settings.getMySQLPlayersTable()
+ " ORDER BY RAND() LIMIT 1";
if (!Lottery.database.Read(sql).isEmpty() && !Lottery.database.Read(sql).get(1).isEmpty() && Lottery.database.Read(sql).get(1).get(0) != null) {
winner = Lottery.database.Read(sql).get(1).get(0);
} else {
System.out.println("[Lottery] Lottery Players table is empty.");
if (Settings.isInDebug())
System.out.println("[Lottery Debug] " + Lottery.database.Read(sql));
}
} catch (Exception ex) {
ex.printStackTrace();
}
output = "<option><white>" + winner + "<gray> won <yellow>"
+ winnings + ".00 Dei!";
sql = "INSERT INTO " + Settings.getMySQLWinnersTable() + " ("
+ "`username`, `winnings`, `time`)" + "VALUES (" + "'"
+ winner + "', '" + winnings + "', NOW());";
if (!winner.isEmpty() && winner != null) {
double money = winnings;
Account account = iConomy.getAccount(winner);
if (account == null) {
System.out.println(String.format("[Lottery] %s had a null iConomy Account", winner));
return "";
}
account.getHoldings().add(money);
Lottery.database.Write(sql);
clear();
return output;
} else {
System.out.println("[Lottery] Player field was null");
return "";
}
}
|
public void run()
{
boolean proceed = true;
try
{
System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***");
final ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
do
{
Envelope message = (Envelope)input.readObject();
System.out.println("Request received: " + message.getMessage());
Envelope response;
if(message.getMessage().equals("GET"))
{
String username = (String)message.getObjContents().get(0);
if(username == null || !my_gs.userList.checkUser(username))
{
response = new Envelope("FAIL");
response.addObject(null);
output.writeObject(response);
}
else
{
UserToken yourToken = createToken(username);
response = new Envelope("OK");
response.addObject(yourToken);
output.writeObject(response);
}
}
else if(message.getMessage().equals("CUSER"))
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
if(createUser(username, yourToken))
{
response = new Envelope("OK");
}
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("DUSER"))
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
if(deleteUser(username, yourToken))
{
response = new Envelope("OK");
}
else response = new Envelope("You could not delete the user");
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("CGROUP"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
if(createGroup(groupName, yourToken))
{
response = new Envelope("OK");
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("DGROUP"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
if(deleteGroup(groupName, yourToken))
{
response = new Envelope("OK");
}
else response = new Envelope("You could not delete the group.");
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("LMEMBERS"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
ArrayList<String> users = listMembers(groupName, yourToken);
if(users.size() > 0)
{
response = new Envelope("OK");
response.addObject(users);
}
else
{
response = new Envelope("FAIL-NOUSERS");
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("AUSERTOGROUP"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 2)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0);
String groupName = (String)message.getObjContents().get(1);
UserToken yourToken = (UserToken)message.getObjContents().get(2);
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
if(addToGroup(userName, groupName, yourToken))
{
response = new Envelope("OK");
}
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("RUSERFROMGROUP"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0);
String groupName = (String)message.getObjContents().get(1);
UserToken yourToken = (UserToken)message.getObjContents().get(2);
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
if(removeFromGroup(userName, groupName, yourToken))
{
response = new Envelope("OK");
}
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("DISCONNECT"))
{
socket.close();
proceed = false;
}
else
{
response = new Envelope("FAIL");
output.writeObject(response);
}
}while(proceed);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
| public void run()
{
boolean proceed = true;
try
{
System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***");
final ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
do
{
Envelope message = (Envelope)input.readObject();
System.out.println("Request received: " + message.getMessage());
Envelope response;
if(message.getMessage().equals("GET"))
{
String username = (String)message.getObjContents().get(0);
if(username == null || !my_gs.userList.checkUser(username))
{
response = new Envelope("FAIL");
response.addObject(null);
output.writeObject(response);
}
else
{
UserToken yourToken = createToken(username);
response = new Envelope("OK");
response.addObject(yourToken);
output.writeObject(response);
}
}
else if(message.getMessage().equals("CUSER"))
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
if(createUser(username, yourToken))
{
response = new Envelope("OK");
}
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("DUSER"))
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
if(deleteUser(username, yourToken))
{
response = new Envelope("OK");
}
else response = new Envelope("You could not delete the user");
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("CGROUP"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
if(createGroup(groupName, yourToken))
{
response = new Envelope("OK");
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("DGROUP"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
if(deleteGroup(groupName, yourToken))
{
response = new Envelope("OK");
}
else response = new Envelope("You could not delete the group.");
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("LMEMBERS"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0);
UserToken yourToken = (UserToken)message.getObjContents().get(1);
ArrayList<String> users = listMembers(groupName, yourToken);
if(users != null && users.size() > 0)
{
response = new Envelope("OK");
response.addObject(users);
}
else
{
response = new Envelope("FAIL-NOUSERS");
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("AUSERTOGROUP"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 2)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0);
String groupName = (String)message.getObjContents().get(1);
UserToken yourToken = (UserToken)message.getObjContents().get(2);
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
if(addToGroup(userName, groupName, yourToken))
{
response = new Envelope("OK");
}
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("RUSERFROMGROUP"))
{
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0);
String groupName = (String)message.getObjContents().get(1);
UserToken yourToken = (UserToken)message.getObjContents().get(2);
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
if(removeFromGroup(userName, groupName, yourToken))
{
response = new Envelope("OK");
}
}
}
}
output.writeObject(response);
}
else if(message.getMessage().equals("DISCONNECT"))
{
socket.close();
proceed = false;
}
else
{
response = new Envelope("FAIL");
output.writeObject(response);
}
}while(proceed);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
|
private WebDriver constructWebDriver() {
log.debug("constructWebDriver called on TestEnvironment: " + this.toPrettyString());
SeleniumManager seleniumManager = SenBotContext.getSenBotContext().getSeleniumManager();
WebDriver driver = null;
if (seleniumManager.getSeleniumHub() != null) {
log.debug("Remote WebDriver should be created to run on a selenium grid for environment: " + this.toPrettyString());
if(getLocale() != null) {
throw new IllegalArgumentException("The remote driver does not support the setting of a locale");
}
DesiredCapabilities capability = DesiredCapabilities.firefox();
if (TestEnvironment.FF.equals(browser)) {
capability = DesiredCapabilities.firefox();
} else if (TestEnvironment.CH.equals(browser)) {
capability = DesiredCapabilities.chrome();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--disable-logging", "--disable-extensions"));
} else if (TestEnvironment.OP.equals(browser)) {
capability = DesiredCapabilities.opera();
} else if (TestEnvironment.IE.equals(browser)) {
capability = DesiredCapabilities.internetExplorer();
} else if (TestEnvironment.SF.equals(browser)) {
capability = DesiredCapabilities.safari();
} else if (BrowserType.PHANTOMJS.equals(browser)) {
capability = DesiredCapabilities.phantomjs();
} else {
throw new IllegalArgumentException("Browser value is not correct: " + browser);
}
capability.setCapability("selenium-version", "2.33.0");
capability.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
capability.setVersion(browserVersion);
capability.setPlatform(os);
driver = new Augmenter().augment(new RemoteWebDriver(seleniumManager.getSeleniumHub(), capability));
} else {
log.debug("Local WebDriver should be created to run on this local machine for environment: " + this.toPrettyString());
if (TestEnvironment.FF.equals(browser)) {
FirefoxProfile p = new FirefoxProfile();
p.setAssumeUntrustedCertificateIssuer(false);
if(getLocale() != null) {
p.setPreference("intl.accept_languages", getLocale().toString());
}
driver = new FirefoxDriver(p);
} else if (TestEnvironment.CH.equals(browser)) {
ChromeOptions options = new ChromeOptions();
StringBuilder switcheStringBuilder = new StringBuilder();
if(getLocale() != null) {
options.addArguments("--lang=" + getLocale().getLanguage());
}
options.addArguments("--silent");
options.addArguments("--" + CapabilityType.LOGGING_PREFS + "={driver:'FINE'}");
driver = new ChromeDriver(options);
} else if (TestEnvironment.OP.equals(browser)) {
if(getLocale() != null) {
throw new IllegalArgumentException("Opera does not support the setting of a locale at this stage");
}
driver = new OperaDriver();
} else if (TestEnvironment.IE.equals(browser)) {
if(getLocale() != null) {
throw new IllegalArgumentException("IE does not support the setting of a locale at this stage");
}
driver = new InternetExplorerDriver();
} else if (TestEnvironment.SF.equals(browser)) {
if(getLocale() != null) {
throw new IllegalArgumentException("Safari does not support the setting of a locale at this stage");
}
driver = new SafariDriver();
} else if (BrowserType.PHANTOMJS.equals(browser)) {
if(getLocale() != null) {
throw new IllegalArgumentException("PhantomJS does not support the setting of a locale at this stage");
}
try {
DesiredCapabilities phantomJsCapabilities = DesiredCapabilities.phantomjs();
phantomJsCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "target/logs/phantomjs.log");
driver = new PhantomJSDriver(
ResolvingPhantomJSDriverService.createDefaultService(),
phantomJsCapabilities);
}
catch (Exception e){
throw new RuntimeException(e);
}
} else {
throw new IllegalArgumentException("Browser value is not correct: " + browser);
}
}
if (seleniumManager.getImplicitTimeout() != null) {
int timeout = seleniumManager.getImplicitTimeout();
if (driver instanceof InternetExplorerDriver) {
timeout = timeout * 2;
}
driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
driver.manage().window().setSize(new Dimension(seleniumManager.getDefaultWindowWidth(), seleniumManager.getDefaultWindowHeight()));
return driver;
}
| private WebDriver constructWebDriver() {
log.debug("constructWebDriver called on TestEnvironment: " + this.toPrettyString());
SeleniumManager seleniumManager = SenBotContext.getSenBotContext().getSeleniumManager();
WebDriver driver = null;
if (seleniumManager.getSeleniumHub() != null) {
log.debug("Remote WebDriver should be created to run on a selenium grid for environment: " + this.toPrettyString());
if(getLocale() != null) {
throw new IllegalArgumentException("The remote driver does not support the setting of a locale");
}
DesiredCapabilities capability = DesiredCapabilities.firefox();
if (TestEnvironment.FF.equals(browser)) {
capability = DesiredCapabilities.firefox();
} else if (TestEnvironment.CH.equals(browser)) {
capability = DesiredCapabilities.chrome();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--disable-logging", "--disable-extensions"));
} else if (TestEnvironment.OP.equals(browser)) {
capability = DesiredCapabilities.opera();
} else if (TestEnvironment.IE.equals(browser)) {
capability = DesiredCapabilities.internetExplorer();
} else if (TestEnvironment.SF.equals(browser)) {
capability = DesiredCapabilities.safari();
} else if (BrowserType.PHANTOMJS.equals(browser)) {
capability = DesiredCapabilities.phantomjs();
} else {
throw new IllegalArgumentException("Browser value is not correct: " + browser);
}
capability.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
capability.setVersion(browserVersion);
capability.setPlatform(os);
driver = new Augmenter().augment(new RemoteWebDriver(seleniumManager.getSeleniumHub(), capability));
} else {
log.debug("Local WebDriver should be created to run on this local machine for environment: " + this.toPrettyString());
if (TestEnvironment.FF.equals(browser)) {
FirefoxProfile p = new FirefoxProfile();
p.setAssumeUntrustedCertificateIssuer(false);
if(getLocale() != null) {
p.setPreference("intl.accept_languages", getLocale().toString());
}
driver = new FirefoxDriver(p);
} else if (TestEnvironment.CH.equals(browser)) {
ChromeOptions options = new ChromeOptions();
StringBuilder switcheStringBuilder = new StringBuilder();
if(getLocale() != null) {
options.addArguments("--lang=" + getLocale().getLanguage());
}
options.addArguments("--silent");
options.addArguments("--" + CapabilityType.LOGGING_PREFS + "={driver:'FINE'}");
driver = new ChromeDriver(options);
} else if (TestEnvironment.OP.equals(browser)) {
if(getLocale() != null) {
throw new IllegalArgumentException("Opera does not support the setting of a locale at this stage");
}
driver = new OperaDriver();
} else if (TestEnvironment.IE.equals(browser)) {
if(getLocale() != null) {
throw new IllegalArgumentException("IE does not support the setting of a locale at this stage");
}
driver = new InternetExplorerDriver();
} else if (TestEnvironment.SF.equals(browser)) {
if(getLocale() != null) {
throw new IllegalArgumentException("Safari does not support the setting of a locale at this stage");
}
driver = new SafariDriver();
} else if (BrowserType.PHANTOMJS.equals(browser)) {
if(getLocale() != null) {
throw new IllegalArgumentException("PhantomJS does not support the setting of a locale at this stage");
}
try {
DesiredCapabilities phantomJsCapabilities = DesiredCapabilities.phantomjs();
phantomJsCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "target/logs/phantomjs.log");
driver = new PhantomJSDriver(
ResolvingPhantomJSDriverService.createDefaultService(),
phantomJsCapabilities);
}
catch (Exception e){
throw new RuntimeException(e);
}
} else {
throw new IllegalArgumentException("Browser value is not correct: " + browser);
}
}
if (seleniumManager.getImplicitTimeout() != null) {
int timeout = seleniumManager.getImplicitTimeout();
if (driver instanceof InternetExplorerDriver) {
timeout = timeout * 2;
}
driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
driver.manage().window().setSize(new Dimension(seleniumManager.getDefaultWindowWidth(), seleniumManager.getDefaultWindowHeight()));
return driver;
}
|
public void onBuild(List<String> args) {
for (String arg : args) {
if (aH.matchesValueArg("TYPE", arg, ArgumentType.Custom)) {
try {
type = ItemDropType.valueOf(aH.getStringFrom(arg));
dB.echoDebug("...type set to: " + type.name());
continue;
} catch (Exception e) { dB.echoDebug("...type " + type.name() + " is not valid."); }
} else if (aH.matchesItem(arg)) {
item = aH.getItemFrom(arg);
dB.echoDebug("...item set to: " + item);
continue;
} else if (aH.matchesValueArg("REGION", arg, ArgumentType.Custom)) {
wgregion = aH.getStringFrom(arg);
dB.echoDebug("...region set to: " + wgregion);
continue;
} else if (aH.matchesLocation(arg)) {
location = aH.getLocationFrom(arg);
dB.echoDebug("...location set to: " + location);
continue;
} else if (aH.matchesValueArg("RADIUS", arg, ArgumentType.Integer)) {
radius = aH.getIntegerFrom(arg);
dB.echoDebug("...radius set to: " + radius);
continue;
} else if (aH.matchesValueArg("DROPRATE", arg, ArgumentType.Integer)) {
dropRate = aH.getIntegerFrom(arg);
dB.echoDebug("...drop rate set to: " + dropRate + "/100");
continue;
} else if (aH.matchesValueArg("DROPSFROM", arg, ArgumentType.Custom)) {
dropper = aH.getStringFrom(arg);
dB.echoDebug("...dropper set to: " + dropper);
continue;
} else if (aH.matchesQuantity(arg)) {
quantity = aH.getIntegerFrom(arg);
dB.echoDebug("...quantity set to: " + quantity);
continue;
}
}
if (item == null) {
dB.echoDebug("...item could not be set");
cancel();
}
switch (type) {
case BLOCKPLACE:
case BLOCKBREAK:
try {
block = Material.valueOf(dropper);
dB.echoDebug("...DROPSFROM material set");
} catch (Exception e) { dB.echoDebug("...DROPSFROM is not a valid material"); }
break;
case MOBKILL:
if (aH.matchesEntityType("entity:" + dropper)) {
mob = aH.getLivingEntityFrom(dropper);
dB.echoDebug("...mob selected from DROPSFROM");
} else dB.echoDebug("...could not select mob from DROPSFROM");
break;
default:
dB.echoDebug("...error setting type");
cancel();
break;
}
}
| public void onBuild(List<String> args) {
for (String arg : args) {
if (aH.matchesValueArg("TYPE", arg, ArgumentType.Custom)) {
try {
type = ItemDropType.valueOf(aH.getStringFrom(arg));
dB.echoDebug("...type set to: " + type.name());
continue;
} catch (Exception e) { dB.echoDebug("...type " + type.name() + " is not valid."); }
} else if (aH.matchesItem(arg)) {
item = aH.getItemFrom(arg);
dB.echoDebug("...item set to: " + item);
continue;
} else if (aH.matchesValueArg("REGION", arg, ArgumentType.Custom)) {
wgregion = aH.getStringFrom(arg);
dB.echoDebug("...region set to: " + wgregion);
continue;
} else if (aH.matchesLocation(arg)) {
location = aH.getLocationFrom(arg);
dB.echoDebug("...location set to: " + location);
continue;
} else if (aH.matchesValueArg("RADIUS", arg, ArgumentType.Integer)) {
radius = aH.getIntegerFrom(arg);
dB.echoDebug("...radius set to: " + radius);
continue;
} else if (aH.matchesValueArg("DROPRATE", arg, ArgumentType.Integer)) {
dropRate = aH.getIntegerFrom(arg);
dB.echoDebug("...drop rate set to: " + dropRate + "/100");
continue;
} else if (aH.matchesValueArg("DROPSFROM", arg, ArgumentType.Custom)) {
dropper = aH.getStringFrom(arg);
dB.echoDebug("...dropper set to: " + dropper);
continue;
} else if (aH.matchesQuantity(arg)) {
quantity = aH.getIntegerFrom(arg);
dB.echoDebug("...quantity set to: " + quantity);
continue;
}
}
if (item == null) {
dB.echoDebug("...item could not be set");
cancel();
}
switch (type) {
case BLOCKPLACE:
case BLOCKBREAK:
try {
block = Material.valueOf(dropper);
dB.echoDebug("...DROPSFROM material set");
} catch (Exception e) { dB.echoDebug("...DROPSFROM is not a valid material"); }
break;
case MOBKILL:
if (aH.matchesEntityType("entity:" + dropper)) {
mob = aH.getLivingEntityFrom("entity:" + dropper);
dB.echoDebug("...mob selected from DROPSFROM");
} else dB.echoDebug("...could not select mob from DROPSFROM");
break;
default:
dB.echoDebug("...error setting type");
cancel();
break;
}
}
|
private void buildMap() {
GameMapItem map1x1 = createGameMapItemAndPutToMap(1, 1, R.drawable.map_1x1);
GameMapItem map1x2 = createGameMapItemAndPutToMap(2, 1, R.drawable.map_1x2);
GameMapItem map1x3 = createGameMapItemAndPutToMap(3, 1, R.drawable.map_1x3);
GameMapItem map1x4 = createGameMapItemAndPutToMap(4, 1, R.drawable.map_1x4);
GameMapItem map1x5 = createGameMapItemAndPutToMap(5, 1, R.drawable.map_1x5);
GameMapItem map2x1 = createGameMapItemAndPutToMap(1, 2, R.drawable.map_2x1);
GameMapItem map2x2 = createGameMapItemAndPutToMap(2, 2, R.drawable.map_2x2);
GameMapItem map2x3 = createGameMapItemAndPutToMap(3, 2, R.drawable.map_2x3);
GameMapItem map2x4 = createGameMapItemAndPutToMap(4, 2, R.drawable.map_2x4);
GameMapItem map2x5 = createGameMapItemAndPutToMap(5, 2, R.drawable.map_2x5);
GameMapItem map3x1 = createGameMapItemAndPutToMap(1, 3, R.drawable.map_3x1);
GameMapItem map3x2 = createGameMapItemAndPutToMap(2, 3, R.drawable.map_3x2);
GameMapItem map3x3 = createGameMapItemAndPutToMap(3, 3, R.drawable.map_3x3);
GameMapItem map3x4 = createGameMapItemAndPutToMap(4, 3, R.drawable.map_3x4);
GameMapItem map3x5 = createGameMapItemAndPutToMap(5, 3, R.drawable.map_3x5);
GameMapItem map4x1 = createGameMapItemAndPutToMap(1, 4, R.drawable.map_4x1);
GameMapItem map4x2 = createGameMapItemAndPutToMap(2, 4, R.drawable.map_4x2);
GameMapItem map4x3 = createGameMapItemAndPutToMap(3, 4, R.drawable.map_4x3);
GameMapItem map4x4 = createGameMapItemAndPutToMap(4, 4, R.drawable.map_4x4);
GameMapItem map4x5 = createGameMapItemAndPutToMap(5, 4, R.drawable.map_4x5);
GameMapItem map5x1 = createGameMapItemAndPutToMap(1, 5, R.drawable.map_5x1);
GameMapItem map5x2 = createGameMapItemAndPutToMap(2, 5, R.drawable.map_5x2);
GameMapItem map5x3 = createGameMapItemAndPutToMap(3, 5, R.drawable.map_5x3);
GameMapItem map5x4 = createGameMapItemAndPutToMap(4, 5, R.drawable.map_5x4);
GameMapItem map5x5 = createGameMapItemAndPutToMap(5, 5, R.drawable.map_5x5);
map1x1.setBoundaryItems(null, null, map2x1, null);
map1x2.setBoundaryItems(null, map1x3, map2x2, null);
map1x3.setBoundaryItems(null, map1x4, map2x3, map1x2);
map1x4.setBoundaryItems(null, map1x5, null, map1x3);
map1x5.setBoundaryItems(null, null, null, map1x4);
map2x1.setBoundaryItems(map1x1, map2x2, map3x1, null);
map2x2.setBoundaryItems(map1x2, null, null, map2x1);
map2x3.setBoundaryItems(map1x3, null, map3x3, null);
map2x4.setBoundaryItems(null, map2x5, null, null);
map2x5.setBoundaryItems(null, null, map3x5, map2x4);
map3x1.setBoundaryItems(map2x1, map3x2, map4x1, null);
map3x2.setBoundaryItems(null, map3x3, map4x2, null);
map3x3.setBoundaryItems(map2x3, map3x4, null, map3x2);
map3x4.setBoundaryItems(null, map3x5, map4x4, null);
map3x5.setBoundaryItems(map2x5, null, map4x5, map3x4);
map4x1.setBoundaryItems(map3x1, map4x2, map5x1, null);
map4x2.setBoundaryItems(map3x2, map4x3, null, map4x1);
map4x3.setBoundaryItems(null, null, map5x3, map4x2);
map4x4.setBoundaryItems(null, map4x5, map5x4, null);
map4x5.setBoundaryItems(map3x5, null, map5x5, map4x4);
map5x1.setBoundaryItems(map4x1, map5x2, null, null);
map5x2.setBoundaryItems(null, map5x3, null, map5x1);
map5x3.setBoundaryItems(map4x3, map5x4, null, map5x2);
map5x4.setBoundaryItems(map4x4, null, null, map5x3);
map5x5.setBoundaryItems(map4x5, null, null, null);
}
| private void buildMap() {
GameMapItem map1x1 = createGameMapItemAndPutToMap(1, 1, R.drawable.map_1x1);
GameMapItem map1x2 = createGameMapItemAndPutToMap(2, 1, R.drawable.map_1x2);
GameMapItem map1x3 = createGameMapItemAndPutToMap(3, 1, R.drawable.map_1x3);
GameMapItem map1x4 = createGameMapItemAndPutToMap(4, 1, R.drawable.map_1x4);
GameMapItem map1x5 = createGameMapItemAndPutToMap(5, 1, R.drawable.map_1x5);
GameMapItem map2x1 = createGameMapItemAndPutToMap(1, 2, R.drawable.map_2x1);
GameMapItem map2x2 = createGameMapItemAndPutToMap(2, 2, R.drawable.map_2x2);
GameMapItem map2x3 = createGameMapItemAndPutToMap(3, 2, R.drawable.map_2x3);
GameMapItem map2x4 = createGameMapItemAndPutToMap(4, 2, R.drawable.map_2x4);
GameMapItem map2x5 = createGameMapItemAndPutToMap(5, 2, R.drawable.map_2x5);
GameMapItem map3x1 = createGameMapItemAndPutToMap(1, 3, R.drawable.map_3x1);
GameMapItem map3x2 = createGameMapItemAndPutToMap(2, 3, R.drawable.map_3x2);
GameMapItem map3x3 = createGameMapItemAndPutToMap(3, 3, R.drawable.map_3x3);
GameMapItem map3x4 = createGameMapItemAndPutToMap(4, 3, R.drawable.map_3x4);
GameMapItem map3x5 = createGameMapItemAndPutToMap(5, 3, R.drawable.map_3x5);
GameMapItem map4x1 = createGameMapItemAndPutToMap(1, 4, R.drawable.map_4x1);
GameMapItem map4x2 = createGameMapItemAndPutToMap(2, 4, R.drawable.map_4x2);
GameMapItem map4x3 = createGameMapItemAndPutToMap(3, 4, R.drawable.map_4x3);
GameMapItem map4x4 = createGameMapItemAndPutToMap(4, 4, R.drawable.map_4x4);
GameMapItem map4x5 = createGameMapItemAndPutToMap(5, 4, R.drawable.map_4x5);
GameMapItem map5x1 = createGameMapItemAndPutToMap(1, 5, R.drawable.map_5x1);
GameMapItem map5x2 = createGameMapItemAndPutToMap(2, 5, R.drawable.map_5x2);
GameMapItem map5x3 = createGameMapItemAndPutToMap(3, 5, R.drawable.map_5x3);
GameMapItem map5x4 = createGameMapItemAndPutToMap(4, 5, R.drawable.map_5x4);
GameMapItem map5x5 = createGameMapItemAndPutToMap(5, 5, R.drawable.map_5x5);
map1x1.setBoundaryItems(null, null, map2x1, null);
map1x2.setBoundaryItems(null, map1x3, map2x2, null);
map1x3.setBoundaryItems(null, map1x4, map2x3, map1x2);
map1x4.setBoundaryItems(null, map1x5, null, map1x3);
map1x5.setBoundaryItems(null, null, null, map1x4);
map2x1.setBoundaryItems(map1x1, map2x2, map3x1, null);
map2x2.setBoundaryItems(map1x2, null, null, map2x1);
map2x3.setBoundaryItems(map1x3, null, map3x3, null);
map2x4.setBoundaryItems(null, map2x5, null, null);
map2x5.setBoundaryItems(null, null, map3x5, map2x4);
map3x1.setBoundaryItems(map2x1, null, map4x1, null);
map3x2.setBoundaryItems(null, map3x3, map4x2, null);
map3x3.setBoundaryItems(map2x3, map3x4, null, map3x2);
map3x4.setBoundaryItems(null, map3x5, null, map3x3);
map3x5.setBoundaryItems(map2x5, null, map4x5, map3x4);
map4x1.setBoundaryItems(map3x1, map4x2, map5x1, null);
map4x2.setBoundaryItems(map3x2, map4x3, null, map4x1);
map4x3.setBoundaryItems(null, null, map5x3, map4x2);
map4x4.setBoundaryItems(null, map4x5, map5x4, null);
map4x5.setBoundaryItems(map3x5, null, map5x5, map4x4);
map5x1.setBoundaryItems(map4x1, map5x2, null, null);
map5x2.setBoundaryItems(null, map5x3, null, map5x1);
map5x3.setBoundaryItems(map4x3, map5x4, null, map5x2);
map5x4.setBoundaryItems(map4x4, null, null, map5x3);
map5x5.setBoundaryItems(map4x5, null, null, null);
}
|
private void processRequest(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,
java.io.IOException {
String servletUrl = request.getContextPath() + request.getServletPath();
String url = request.getRequestURI().substring(servletUrl.length());
if (url.charAt(0) == '/' && url.length() > 1) {
url = url.substring(1);
}
String repositoryName = url;
String objectId = request.getParameter("h");
String l = request.getParameter("l");
int length = GitBlit.getInteger(Keys.web.syndicationEntries, 25);
if (StringUtils.isEmpty(objectId)) {
objectId = org.eclipse.jgit.lib.Constants.HEAD;
}
if (!StringUtils.isEmpty(l)) {
try {
length = Integer.parseInt(l);
} catch (NumberFormatException x) {
}
}
Repository repository = GitBlit.self().getRepository(repositoryName);
RepositoryModel model = GitBlit.self().getRepositoryModel(repositoryName);
List<RevCommit> commits = JGitUtils.getRevLog(repository, objectId, 0, length);
try {
SyndicationUtils.toRSS(HttpUtils.getGitblitURL(request), getTitle(model.name, objectId), model.description,
model.name, commits, response.getOutputStream());
} catch (Exception e) {
logger.error("An error occurred during feed generation", e);
}
}
| private void processRequest(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,
java.io.IOException {
String servletUrl = request.getContextPath() + request.getServletPath();
String url = request.getRequestURI().substring(servletUrl.length());
if (url.charAt(0) == '/' && url.length() > 1) {
url = url.substring(1);
}
String repositoryName = url;
String objectId = request.getParameter("h");
String l = request.getParameter("l");
int length = GitBlit.getInteger(Keys.web.syndicationEntries, 25);
if (StringUtils.isEmpty(objectId)) {
objectId = org.eclipse.jgit.lib.Constants.HEAD;
}
if (!StringUtils.isEmpty(l)) {
try {
length = Integer.parseInt(l);
} catch (NumberFormatException x) {
}
}
response.setContentType("application/rss+xml; charset=UTF-8");
Repository repository = GitBlit.self().getRepository(repositoryName);
RepositoryModel model = GitBlit.self().getRepositoryModel(repositoryName);
List<RevCommit> commits = JGitUtils.getRevLog(repository, objectId, 0, length);
try {
SyndicationUtils.toRSS(HttpUtils.getGitblitURL(request), getTitle(model.name, objectId), model.description,
model.name, commits, response.getOutputStream());
} catch (Exception e) {
logger.error("An error occurred during feed generation", e);
}
}
|
private void readXML(final Node root, final Login.RequestCharListCallback resultCallback) {
if (!"chars".equals(root.getNodeName()) && !NODE_NAME_ERROR.equals(root.getNodeName())) {
final NodeList children = root.getChildNodes();
final int count = children.getLength();
for (int i = 0; i < count; i++) {
readXML(children.item(i), resultCallback);
}
return;
}
if (NODE_NAME_ERROR.equals(root.getNodeName())) {
final int error = Integer.parseInt(root.getAttributes().getNamedItem("id").getNodeValue());
resultCallback.finishedRequest(error);
return;
}
final NodeList children = root.getChildNodes();
final int count = children.getLength();
final String accLang = root.getAttributes().getNamedItem("lang").getNodeValue();
if ("de".equals(accLang) && Lang.getInstance().isEnglish()) {
IllaClient.getCfg().set(Lang.LOCALE_CFG, Lang.LOCALE_CFG_GERMAN);
Lang.getInstance().recheckLocale();
} else if ("us".equals(accLang) && Lang.getInstance().isGerman()) {
IllaClient.getCfg().set(Lang.LOCALE_CFG, Lang.LOCALE_CFG_ENGLISH);
Lang.getInstance().recheckLocale();
}
charList.clear();
for (int i = 0; i < count; i++) {
final Node charNode = children.item(i);
final String charName = charNode.getTextContent();
final int status = Integer.parseInt(charNode.getAttributes().getNamedItem("status").getNodeValue());
final String charServer = charNode.getAttributes().getNamedItem("server").getNodeValue();
final Login.CharEntry addChar = new Login.CharEntry(charName, status);
switch (IllaClient.DEFAULT_SERVER) {
case testserver:
if ("testserver".equals(charServer)) {
charList.add(addChar);
}
break;
case realserver:
if ("realserver".equals(charServer)) {
charList.add(addChar);
}
break;
}
}
resultCallback.finishedRequest(0);
}
| private void readXML(final Node root, final Login.RequestCharListCallback resultCallback) {
if (!"chars".equals(root.getNodeName()) && !NODE_NAME_ERROR.equals(root.getNodeName())) {
final NodeList children = root.getChildNodes();
final int count = children.getLength();
for (int i = 0; i < count; i++) {
readXML(children.item(i), resultCallback);
}
return;
}
if (NODE_NAME_ERROR.equals(root.getNodeName())) {
final int error = Integer.parseInt(root.getAttributes().getNamedItem("id").getNodeValue());
resultCallback.finishedRequest(error);
return;
}
final NodeList children = root.getChildNodes();
final int count = children.getLength();
final String accLang = root.getAttributes().getNamedItem("lang").getNodeValue();
if ("de".equals(accLang) && Lang.getInstance().isEnglish()) {
IllaClient.getCfg().set(Lang.LOCALE_CFG, Lang.LOCALE_CFG_GERMAN);
Lang.getInstance().recheckLocale();
} else if ("us".equals(accLang) && Lang.getInstance().isGerman()) {
IllaClient.getCfg().set(Lang.LOCALE_CFG, Lang.LOCALE_CFG_ENGLISH);
Lang.getInstance().recheckLocale();
}
charList.clear();
for (int i = 0; i < count; i++) {
final Node charNode = children.item(i);
final String charName = charNode.getTextContent();
final int status = Integer.parseInt(charNode.getAttributes().getNamedItem("status").getNodeValue());
final String charServer = charNode.getAttributes().getNamedItem("server").getNodeValue();
final Login.CharEntry addChar = new Login.CharEntry(charName, status);
switch (IllaClient.DEFAULT_SERVER) {
case localserver:
charList.add(addChar);
break;
case testserver:
if ("testserver".equals(charServer)) {
charList.add(addChar);
}
break;
case realserver:
if ("illarionserver".equals(charServer)) {
charList.add(addChar);
}
break;
}
}
resultCallback.finishedRequest(0);
}
|
private CompactionStats _majorCompact(MajorCompactionReason reason) throws IOException, CompactionCanceledException {
long t1, t2, t3;
CompactionStrategy strategy = Property.createInstanceFromPropertyName(acuTableConf, Property.TABLE_COMPACTION_STRATEGY, CompactionStrategy.class, new DefaultCompactionStrategy());
strategy.init(Property.getCompactionStrategyOptions(acuTableConf));
Map<FileRef,Pair<Key,Key>> firstAndLastKeys = null;
if (reason == MajorCompactionReason.CHOP) {
firstAndLastKeys = getFirstAndLastKeys(datafileManager.getDatafileSizes());
} else if (reason != MajorCompactionReason.USER) {
MajorCompactionRequest request = new MajorCompactionRequest(extent, reason, fs, acuTableConf);
request.setFiles(datafileManager.getDatafileSizes());
strategy.gatherInformation(request);
}
Map<FileRef, DataFileValue> filesToCompact;
int maxFilesToCompact = acuTableConf.getCount(Property.TSERV_MAJC_THREAD_MAXOPEN);
CompactionStats majCStats = new CompactionStats();
CompactionPlan plan = null;
boolean propogateDeletes = false;
synchronized (this) {
t1 = System.currentTimeMillis();
majorCompactionWaitingToStart = true;
tabletMemory.waitForMinC();
t2 = System.currentTimeMillis();
majorCompactionWaitingToStart = false;
notifyAll();
if (extent.isRootTablet()) {
cleanUpFiles(fs, fs.listStatus(this.location), false);
}
SortedMap<FileRef,DataFileValue> allFiles = datafileManager.getDatafileSizes();
List<FileRef> inputFiles = new ArrayList<FileRef>();
if (reason == MajorCompactionReason.CHOP) {
inputFiles.addAll(findChopFiles(extent, firstAndLastKeys, allFiles.keySet()));
} else if (reason == MajorCompactionReason.USER) {
inputFiles.addAll(allFiles.keySet());
} else {
MajorCompactionRequest request = new MajorCompactionRequest(extent, reason, fs, acuTableConf);
request.setFiles(allFiles);
plan = strategy.getCompactionPlan(request);
if (plan != null)
inputFiles.addAll(plan.inputFiles);
}
if (inputFiles.isEmpty()) {
return majCStats;
}
Set<FileRef> droppedFiles = new HashSet<FileRef>();
droppedFiles.addAll(inputFiles);
if (plan != null)
droppedFiles.addAll(plan.deleteFiles);
propogateDeletes = droppedFiles.equals(allFiles.keySet());
log.debug("Major compaction plan: " + plan + " propogate deletes : " + propogateDeletes);
filesToCompact = new HashMap<FileRef,DataFileValue>(allFiles);
filesToCompact.keySet().retainAll(inputFiles);
t3 = System.currentTimeMillis();
datafileManager.reserveMajorCompactingFiles(filesToCompact.keySet());
}
try {
log.debug(String.format("MajC initiate lock %.2f secs, wait %.2f secs", (t3 - t2) / 1000.0, (t2 - t1) / 1000.0));
Pair<Long,List<IteratorSetting>> compactionId = null;
if (!propogateDeletes) {
try {
compactionId = getCompactionID();
} catch (NoNodeException e) {
throw new RuntimeException(e);
}
}
List<IteratorSetting> compactionIterators = new ArrayList<IteratorSetting>();
if (compactionId != null) {
if (reason == MajorCompactionReason.USER) {
if (getCompactionCancelID() >= compactionId.getFirst()) {
return majCStats;
}
synchronized (this) {
if (lastCompactID >= compactionId.getFirst())
return majCStats;
}
}
compactionIterators = compactionId.getSecond();
}
while (filesToCompact.size() > 0) {
int numToCompact = maxFilesToCompact;
if (filesToCompact.size() > maxFilesToCompact && filesToCompact.size() < 2 * maxFilesToCompact) {
numToCompact = filesToCompact.size() - maxFilesToCompact + 1;
}
Set<FileRef> smallestFiles = removeSmallest(filesToCompact, numToCompact);
FileRef fileName = getNextMapFilename((filesToCompact.size() == 0 && !propogateDeletes) ? "A" : "C");
FileRef compactTmpName = new FileRef(fileName.path().toString() + "_tmp");
AccumuloConfiguration tableConf = createTableConfiguration(acuTableConf, plan);
Span span = Trace.start("compactFiles");
try {
CompactionEnv cenv = new CompactionEnv() {
@Override
public boolean isCompactionEnabled() {
return Tablet.this.isCompactionEnabled();
}
@Override
public IteratorScope getIteratorScope() {
return IteratorScope.majc;
}
};
HashMap<FileRef,DataFileValue> copy = new HashMap<FileRef,DataFileValue>(datafileManager.getDatafileSizes());
if (!copy.keySet().containsAll(smallestFiles))
throw new IllegalStateException("Cannot find data file values for " + smallestFiles);
copy.keySet().retainAll(smallestFiles);
log.debug("Starting MajC " + extent + " (" + reason + ") " + copy.keySet() + " --> " + compactTmpName + " " + compactionIterators);
boolean lastBatch = filesToCompact.isEmpty();
Compactor compactor = new Compactor(conf, fs, copy, null, compactTmpName, lastBatch ? propogateDeletes : true, tableConf, extent,
cenv, compactionIterators, reason);
CompactionStats mcs = compactor.call();
span.data("files", "" + smallestFiles.size());
span.data("read", "" + mcs.getEntriesRead());
span.data("written", "" + mcs.getEntriesWritten());
majCStats.add(mcs);
if (lastBatch && plan != null && plan.deleteFiles != null) {
smallestFiles.addAll(plan.deleteFiles);
}
datafileManager.bringMajorCompactionOnline(smallestFiles, compactTmpName, fileName,
filesToCompact.size() == 0 && compactionId != null ? compactionId.getFirst() : null,
new DataFileValue(mcs.getFileSize(), mcs.getEntriesWritten()));
if (filesToCompact.size() > 0 && mcs.getEntriesWritten() > 0) {
filesToCompact.put(fileName, new DataFileValue(mcs.getFileSize(), mcs.getEntriesWritten()));
}
} finally {
span.stop();
}
}
return majCStats;
} finally {
synchronized (Tablet.this) {
datafileManager.clearMajorCompactingFile();
}
}
}
| private CompactionStats _majorCompact(MajorCompactionReason reason) throws IOException, CompactionCanceledException {
long t1, t2, t3;
CompactionStrategy strategy = Property.createInstanceFromPropertyName(acuTableConf, Property.TABLE_COMPACTION_STRATEGY, CompactionStrategy.class, new DefaultCompactionStrategy());
strategy.init(Property.getCompactionStrategyOptions(acuTableConf));
Map<FileRef,Pair<Key,Key>> firstAndLastKeys = null;
if (reason == MajorCompactionReason.CHOP) {
firstAndLastKeys = getFirstAndLastKeys(datafileManager.getDatafileSizes());
} else if (reason != MajorCompactionReason.USER) {
MajorCompactionRequest request = new MajorCompactionRequest(extent, reason, fs, acuTableConf);
request.setFiles(datafileManager.getDatafileSizes());
strategy.gatherInformation(request);
}
Map<FileRef, DataFileValue> filesToCompact;
int maxFilesToCompact = acuTableConf.getCount(Property.TSERV_MAJC_THREAD_MAXOPEN);
CompactionStats majCStats = new CompactionStats();
CompactionPlan plan = null;
boolean propogateDeletes = false;
synchronized (this) {
t1 = System.currentTimeMillis();
majorCompactionWaitingToStart = true;
tabletMemory.waitForMinC();
t2 = System.currentTimeMillis();
majorCompactionWaitingToStart = false;
notifyAll();
if (extent.isRootTablet()) {
cleanUpFiles(fs, fs.listStatus(this.location), false);
}
SortedMap<FileRef,DataFileValue> allFiles = datafileManager.getDatafileSizes();
List<FileRef> inputFiles = new ArrayList<FileRef>();
if (reason == MajorCompactionReason.CHOP) {
inputFiles.addAll(findChopFiles(extent, firstAndLastKeys, allFiles.keySet()));
} else if (reason == MajorCompactionReason.USER) {
inputFiles.addAll(allFiles.keySet());
} else {
MajorCompactionRequest request = new MajorCompactionRequest(extent, reason, fs, acuTableConf);
request.setFiles(allFiles);
plan = strategy.getCompactionPlan(request);
if (plan != null)
inputFiles.addAll(plan.inputFiles);
}
if (inputFiles.isEmpty()) {
return majCStats;
}
Set<FileRef> droppedFiles = new HashSet<FileRef>();
droppedFiles.addAll(inputFiles);
if (plan != null)
droppedFiles.addAll(plan.deleteFiles);
propogateDeletes = !(droppedFiles.equals(allFiles.keySet()));
log.debug("Major compaction plan: " + plan + " propogate deletes : " + propogateDeletes);
filesToCompact = new HashMap<FileRef,DataFileValue>(allFiles);
filesToCompact.keySet().retainAll(inputFiles);
t3 = System.currentTimeMillis();
datafileManager.reserveMajorCompactingFiles(filesToCompact.keySet());
}
try {
log.debug(String.format("MajC initiate lock %.2f secs, wait %.2f secs", (t3 - t2) / 1000.0, (t2 - t1) / 1000.0));
Pair<Long,List<IteratorSetting>> compactionId = null;
if (!propogateDeletes) {
try {
compactionId = getCompactionID();
} catch (NoNodeException e) {
throw new RuntimeException(e);
}
}
List<IteratorSetting> compactionIterators = new ArrayList<IteratorSetting>();
if (compactionId != null) {
if (reason == MajorCompactionReason.USER) {
if (getCompactionCancelID() >= compactionId.getFirst()) {
return majCStats;
}
synchronized (this) {
if (lastCompactID >= compactionId.getFirst())
return majCStats;
}
}
compactionIterators = compactionId.getSecond();
}
while (filesToCompact.size() > 0) {
int numToCompact = maxFilesToCompact;
if (filesToCompact.size() > maxFilesToCompact && filesToCompact.size() < 2 * maxFilesToCompact) {
numToCompact = filesToCompact.size() - maxFilesToCompact + 1;
}
Set<FileRef> smallestFiles = removeSmallest(filesToCompact, numToCompact);
FileRef fileName = getNextMapFilename((filesToCompact.size() == 0 && !propogateDeletes) ? "A" : "C");
FileRef compactTmpName = new FileRef(fileName.path().toString() + "_tmp");
AccumuloConfiguration tableConf = createTableConfiguration(acuTableConf, plan);
Span span = Trace.start("compactFiles");
try {
CompactionEnv cenv = new CompactionEnv() {
@Override
public boolean isCompactionEnabled() {
return Tablet.this.isCompactionEnabled();
}
@Override
public IteratorScope getIteratorScope() {
return IteratorScope.majc;
}
};
HashMap<FileRef,DataFileValue> copy = new HashMap<FileRef,DataFileValue>(datafileManager.getDatafileSizes());
if (!copy.keySet().containsAll(smallestFiles))
throw new IllegalStateException("Cannot find data file values for " + smallestFiles);
copy.keySet().retainAll(smallestFiles);
log.debug("Starting MajC " + extent + " (" + reason + ") " + copy.keySet() + " --> " + compactTmpName + " " + compactionIterators);
boolean lastBatch = filesToCompact.isEmpty();
Compactor compactor = new Compactor(conf, fs, copy, null, compactTmpName, lastBatch ? propogateDeletes : true, tableConf, extent,
cenv, compactionIterators, reason);
CompactionStats mcs = compactor.call();
span.data("files", "" + smallestFiles.size());
span.data("read", "" + mcs.getEntriesRead());
span.data("written", "" + mcs.getEntriesWritten());
majCStats.add(mcs);
if (lastBatch && plan != null && plan.deleteFiles != null) {
smallestFiles.addAll(plan.deleteFiles);
}
datafileManager.bringMajorCompactionOnline(smallestFiles, compactTmpName, fileName,
filesToCompact.size() == 0 && compactionId != null ? compactionId.getFirst() : null,
new DataFileValue(mcs.getFileSize(), mcs.getEntriesWritten()));
if (filesToCompact.size() > 0 && mcs.getEntriesWritten() > 0) {
filesToCompact.put(fileName, new DataFileValue(mcs.getFileSize(), mcs.getEntriesWritten()));
}
} finally {
span.stop();
}
}
return majCStats;
} finally {
synchronized (Tablet.this) {
datafileManager.clearMajorCompactingFile();
}
}
}
|
@Test public void
evaluatesToLogicialConjunctionOfMultipleMatchers() {
Matcher<String> allOf = allOf(startingWith("one"), startingWith("one two"), startingWith("one two three"));
assertThat("no match but all matchers match", allOf.matches("one two three"));
assertThat("match but one matcher does not match", !allOf.matches("one two two"));
}
| @Test public void
evaluatesToLogicalConjunctionOfMultipleMatchers() {
Matcher<String> allOf = allOf(startingWith("one"), startingWith("one two"), startingWith("one two three"));
assertThat("no match but all matchers match", allOf.matches("one two three"));
assertThat("match but one matcher does not match", !allOf.matches("one two two"));
}
|
public ExternalClassInfo getWrapperClass(final PrimitiveTypeInfo primitiveType) {
if (null == primitiveType) {
throw new NullPointerException();
}
switch (primitiveType.getType()) {
case BOOLEAN:
final ExternalClassInfo booleanClass = (ExternalClassInfo) ClassInfoManager
.getInstance().getClassInfo(new String[] { "java", "lang", "Boolean" });
return booleanClass;
case BYTE:
final ExternalClassInfo byteClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Byte" });
return byteClass;
case CHAR:
final ExternalClassInfo charClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Charactr" });
return charClass;
case DOUBLE:
final ExternalClassInfo doubleClass = (ExternalClassInfo) ClassInfoManager
.getInstance().getClassInfo(new String[] { "java", "lang", "Double" });
return doubleClass;
case FLOAT:
final ExternalClassInfo floatClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Float" });
return floatClass;
case INT:
final ExternalClassInfo intClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Integer" });
return intClass;
case LONG:
final ExternalClassInfo longClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Long" });
return longClass;
case SHORT:
final ExternalClassInfo shortClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Short" });
return shortClass;
default:
throw new IllegalArgumentException();
}
}
| public ExternalClassInfo getWrapperClass(final PrimitiveTypeInfo primitiveType) {
if (null == primitiveType) {
throw new NullPointerException();
}
switch (primitiveType.getType()) {
case BOOLEAN:
final ExternalClassInfo booleanClass = (ExternalClassInfo) ClassInfoManager
.getInstance().getClassInfo(new String[] { "java", "lang", "Boolean" });
return booleanClass;
case BYTE:
final ExternalClassInfo byteClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Byte" });
return byteClass;
case CHAR:
final ExternalClassInfo charClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Character" });
return charClass;
case DOUBLE:
final ExternalClassInfo doubleClass = (ExternalClassInfo) ClassInfoManager
.getInstance().getClassInfo(new String[] { "java", "lang", "Double" });
return doubleClass;
case FLOAT:
final ExternalClassInfo floatClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Float" });
return floatClass;
case INT:
final ExternalClassInfo intClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Integer" });
return intClass;
case LONG:
final ExternalClassInfo longClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Long" });
return longClass;
case SHORT:
final ExternalClassInfo shortClass = (ExternalClassInfo) ClassInfoManager.getInstance()
.getClassInfo(new String[] { "java", "lang", "Short" });
return shortClass;
default:
throw new IllegalArgumentException();
}
}
|
public void testConversions() {
salesAnalyst.addAccount(alice);
assertEquals(salesAnalyst.getRecentConversions(alice), 0.0, 0.0);
salesAnalyst.addConversions(alice, new Query(), 7, 2.0);
assertEquals(salesAnalyst.getRecentConversions(alice), 7.0, 0.0);
salesAnalyst.sendSalesReportToAll();
assertEquals(salesAnalyst.getRecentConversions(alice), 7.0, 0.0);
salesAnalyst.addConversions(alice, new Query(), 5, 2.0);
assertEquals(salesAnalyst.getRecentConversions(alice), 12.0, 0.0);
salesAnalyst.sendSalesReportToAll();
assertEquals(salesAnalyst.getRecentConversions(alice), 5.0, 0.0);
}
| public void testConversions() {
salesAnalyst.addAccount(alice);
assertEquals(salesAnalyst.getRecentConversions(alice), 10.0, 0.0);
salesAnalyst.addConversions(alice, new Query(), 17, 2.0);
assertEquals(salesAnalyst.getRecentConversions(alice), 27.0, 0.0);
salesAnalyst.sendSalesReportToAll();
assertEquals(salesAnalyst.getRecentConversions(alice), 22.0, 0.0);
salesAnalyst.addConversions(alice, new Query(), 5, 2.0);
assertEquals(salesAnalyst.getRecentConversions(alice), 27.0, 0.0);
salesAnalyst.sendSalesReportToAll();
assertEquals(salesAnalyst.getRecentConversions(alice), 5.0, 0.0);
}
|
protected void doPackage( String packagerName, FlexmojosAIRPackager packager )
throws MojoExecutionException
{
try
{
KeyStore keyStore = KeyStore.getInstance( storetype );
keyStore.load( new FileInputStream( keystore.getAbsolutePath() ), storepass.toCharArray() );
String alias = keyStore.aliases().nextElement();
PrivateKey key = (PrivateKey) keyStore.getKey( alias, storepass.toCharArray() );
packager.setPrivateKey( key );
String c = this.classifier == null ? "" : "-" + this.classifier;
File output =
new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + c + "." + packagerName );
packager.setOutput( output );
packager.setDescriptor( getAirDescriptor() );
Certificate certificate = keyStore.getCertificate( alias );
packager.setSignerCertificate( certificate );
Certificate[] certificateChain = keyStore.getCertificateChain( alias );
packager.setCertificateChain( certificateChain );
if ( this.timestampURL != null )
{
packager.setTimestampURL( TIMESTAMP_NONE.equals( this.timestampURL ) ? null : this.timestampURL );
}
String packaging = project.getPackaging();
if ( AIR.equals( packaging ) )
{
appendArtifacts( packager, project.getDependencyArtifacts() );
appendArtifacts( packager, project.getAttachedArtifacts() );
}
else if ( SWF.equals( packaging ) )
{
File source = project.getArtifact().getFile();
String path = source.getName();
getLog().debug( " adding source " + source + " with path " + path );
packager.addSourceWithPath( source, path );
}
else
{
throw new MojoFailureException( "Unexpected project packaging " + packaging );
}
if ( includeFiles == null && includeFileSets == null )
{
includeFileSets = resources.toArray( new FileSet[0] );
}
if ( includeFiles != null )
{
for ( final String includePath : includeFiles )
{
File directory = file( project.getBuild().getOutputDirectory() );
addSourceWithPath( packager, directory, includePath );
}
}
if ( includeFileSets != null )
{
for ( FileSet set : includeFileSets )
{
DirectoryScanner scanner;
if ( set instanceof Resource )
{
scanner = scan( (Resource) set );
}
else
{
scanner = scan( set );
}
File directory = file( set.getDirectory(), project.getBasedir() );
String[] files = scanner.getIncludedFiles();
for ( String path : files )
{
addSourceWithPath( packager, directory, path );
}
}
}
if ( classifier != null )
{
projectHelper.attachArtifact( project, packagerName, classifier, output );
}
else if ( SWF.equals( packaging ) )
{
projectHelper.attachArtifact( project, packagerName, output );
}
else
{
if ( AIR.equals( packagerName ) && AIR.equals( packaging ) )
{
project.getArtifact().setFile( output );
}
else
{
projectHelper.attachArtifact( project, packagerName, output );
}
}
final List<Message> messages = new ArrayList<Message>();
try
{
packager.setListener( new Listener()
{
public void message( final Message message )
{
messages.add( message );
}
public void progress( final int soFar, final int total )
{
getLog().info( " completed " + soFar + " of " + total );
}
} );
}
catch ( NullPointerException e )
{
if ( getLog().isDebugEnabled() )
{
getLog().error( e.getMessage() );
}
}
packager.createPackage();
if ( messages.size() > 0 )
{
for ( final Message message : messages )
{
getLog().error( " " + message.errorDescription );
}
throw new MojoExecutionException( "Error creating AIR application" );
}
else
{
getLog().info( " AIR package created: " + output.getAbsolutePath() );
}
}
catch ( MojoExecutionException e )
{
throw e;
}
catch ( Exception e )
{
throw new MojoExecutionException( "Error invoking AIR api", e );
}
finally
{
packager.close();
}
}
| protected void doPackage( String packagerName, FlexmojosAIRPackager packager )
throws MojoExecutionException
{
try
{
KeyStore keyStore = KeyStore.getInstance( storetype );
keyStore.load( new FileInputStream( keystore.getAbsolutePath() ), storepass.toCharArray() );
String alias = keyStore.aliases().nextElement();
PrivateKey key = (PrivateKey) keyStore.getKey( alias, storepass.toCharArray() );
packager.setPrivateKey( key );
String c = this.classifier == null ? "" : "-" + this.classifier;
File output =
new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + c + "." + packagerName );
packager.setOutput( output );
packager.setDescriptor( getAirDescriptor() );
Certificate certificate = keyStore.getCertificate( alias );
packager.setSignerCertificate( certificate );
Certificate[] certificateChain = keyStore.getCertificateChain( alias );
packager.setCertificateChain( certificateChain );
if ( this.timestampURL != null )
{
packager.setTimestampURL( TIMESTAMP_NONE.equals( this.timestampURL ) ? null : this.timestampURL );
}
String packaging = project.getPackaging();
if ( AIR.equals( packaging ) )
{
appendArtifacts( packager, project.getDependencyArtifacts() );
appendArtifacts( packager, project.getAttachedArtifacts() );
}
else if ( SWF.equals( packaging ) )
{
File source = project.getArtifact().getFile();
String path = source.getName();
getLog().debug( " adding source " + source + " with path " + path );
packager.addSourceWithPath( source, path );
}
else
{
throw new MojoFailureException( "Unexpected project packaging " + packaging );
}
if ( includeFiles == null && includeFileSets == null )
{
includeFileSets = resources.toArray( new FileSet[0] );
}
if ( includeFiles != null )
{
for ( final String includePath : includeFiles )
{
File directory = file( project.getBuild().getOutputDirectory() );
addSourceWithPath( packager, directory, includePath );
}
}
if ( includeFileSets != null )
{
for ( FileSet set : includeFileSets )
{
DirectoryScanner scanner;
if ( set instanceof Resource )
{
scanner = scan( (Resource) set );
}
else
{
scanner = scan( set );
}
File directory = file( set.getDirectory(), project.getBasedir() );
String[] files = scanner.getIncludedFiles();
for ( String path : files )
{
addSourceWithPath( packager, directory, path );
}
}
}
if ( classifier != null )
{
projectHelper.attachArtifact( project, packagerName, classifier, output );
}
else if ( SWF.equals( packaging ) )
{
projectHelper.attachArtifact( project, packagerName, output );
}
else
{
if ( AIR.equals( packagerName ) && AIR.equals( packaging ) )
{
project.getArtifact().setFile( output );
}
else
{
projectHelper.attachArtifact( project, packagerName, output );
}
}
final List<Message> messages = new ArrayList<Message>();
try
{
packager.setListener( new Listener()
{
public void message( final Message message )
{
messages.add( message );
}
public void progress( final int soFar, final int total )
{
getLog().info( " completed " + soFar + " of " + total );
}
} );
}
catch ( NullPointerException e )
{
if ( getLog().isDebugEnabled() )
{
getLog().error( e.getMessage() );
}
}
packager.createPackage();
if ( messages.size() > 0 )
{
for ( final Message message : messages )
{
getLog().error( " " + message.errorDescription );
}
throw new MojoExecutionException( "Error creating AIR application" );
}
else
{
getLog().info( " AIR package created: " + output.getAbsolutePath() );
}
}
catch ( MojoExecutionException e )
{
throw e;
}
catch ( Exception e )
{
if ( getLog().isDebugEnabled() )
{
getLog().error( e.getMessage(), e );
}
throw new MojoExecutionException( "Error invoking AIR api", e );
}
finally
{
packager.close();
}
}
|
public boolean doTransform(VisADGroup group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer)
throws VisADException, RemoteException {
if (data.isMissing()) return false;
int LevelOfDifficulty = adaptedShadowType.getLevelOfDifficulty();
if (LevelOfDifficulty == NOTHING_MAPPED) return false;
boolean time_flag = false;
if (renderer instanceof DefaultRendererJ2D) {
if (((DefaultRendererJ2D) renderer).time_flag) {
time_flag = true;
}
else {
if (500 < System.currentTimeMillis() -
((DefaultRendererJ2D) renderer).start_time) {
((DefaultRendererJ2D) renderer).time_flag = true;
time_flag = true;
}
}
}
if (time_flag) {
DataDisplayLink link = ((DefaultRendererJ2D) renderer).link;
if (link.peekTicks()) {
throw new DisplayInterruptException("please wait . . .");
}
Enumeration maps = link.getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.peekTicks(renderer, link)) {
throw new DisplayInterruptException("please wait . . .");
}
}
}
boolean anyContour =
((ShadowFunctionOrSetType) adaptedShadowType).getAnyContour();
boolean anyFlow =
((ShadowFunctionOrSetType) adaptedShadowType).getAnyFlow();
boolean anyShape =
((ShadowFunctionOrSetType) adaptedShadowType).getAnyShape();
if (anyShape) {
throw new UnimplementedException("ShadowFunctionOrSetTypeJ2D.doTransform" +
"Shape not yet supported");
}
int valueArrayLength = display.getValueArrayLength();
int[] valueToScalar = display.getValueToScalar();
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
float[][] display_values = new float[valueArrayLength][];
int[] inherited_values =
((ShadowFunctionOrSetType) adaptedShadowType).getInheritedValues();
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0) {
display_values[i] = new float[1];
display_values[i][0] = value_array[i];
}
}
if (adaptedShadowType.getIsTerminal() && anyContour && !anyFlow) {
boolean any_enabled = false;
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) any_enabled = true;
}
}
if (!any_enabled) return false;
}
Set domain_set = null;
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (this instanceof ShadowFunctionTypeJ2D) {
if (!(data instanceof Field)) {
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"data must be Field");
}
domain_set = ((Field) data).getDomainSet();
dataUnits = ((Function) data).getDomainUnits();
dataCoordinateSystem = ((Function) data).getDomainCoordinateSystem();
}
else if (this instanceof ShadowSetTypeJ2D) {
domain_set = (Set) data;
dataUnits = ((Set) data).getSetUnits();
dataCoordinateSystem = ((Set) data).getCoordinateSystem();
}
else {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform: " +
"must be ShadowFunctionType or ShadowSetType");
}
float[][] domain_values = null;
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
int domain_length = domain_set.getLength();
ShadowRealType[] DomainComponents =
((ShadowFunctionOrSetType) adaptedShadowType).getDomainComponents();
int alpha_index = display.getDisplayScalarIndex(Display.Alpha);
boolean isTextureMap = adaptedShadowType.getIsTextureMap() &&
default_values[alpha_index] > 0.99 &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2));
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
float[] colors = null;
int data_width = 0;
int data_height = 0;
int texture_width = 1;
int texture_height = 1;
if (isTextureMap) {
if (renderer instanceof DirectManipulationRendererJ2D) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform" +
" DirectManipulationRendererJ2D");
}
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
float value2 = 0.0f;
limits = Unit.convertTuple(limits, dataUnits, domain_units);
data_width = X.getLength();
data_height = Y.getLength();
texture_width = data_width;
texture_height = data_height;
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform" +
" domain dimension != 2");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
ScalarMap map = (ScalarMap) maps.nextElement();
limits[i] = map.scaleValues(limits[i]);
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform" +
" isTextureMap with bad tuple");
}
tuple_index[i] = real.getTupleIndex();
if (maps.hasMoreElements()) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform" +
" isTextureMap with multiple");
}
}
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
coordinates = new float[12];
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
coordinates[3 + tuple_index[0]] = limits[0][1];
coordinates[3 + tuple_index[1]] = limits[1][0];
coordinates[3 + tuple_index[2]] = value2;
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
coordinates[9 + tuple_index[0]] = limits[0][0];
coordinates[9 + tuple_index[1]] = limits[1][1];
coordinates[9 + tuple_index[2]] = value2;
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
texCoords[0] = 0.0f;
texCoords[1] = 1.0f - ratioh;
texCoords[2] = ratiow;
texCoords[3] = 1.0f - ratioh;
texCoords[4] = ratiow;
texCoords[5] = 1.0f;
texCoords[6] = 0.0f;
texCoords[7] = 1.0f;
normals = new float[12];
float n0 = ((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+1]-coordinates[0+1])) -
((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+2]-coordinates[0+2]));
float n1 = ((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+2]-coordinates[0+2])) -
((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+0]-coordinates[0+0]));
float n2 = ((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+0]-coordinates[0+0])) -
((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+1]-coordinates[0+1]));
float nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
normals[0] = n0;
normals[1] = n1;
normals[2] = n2;
normals[3] = n0;
normals[4] = n1;
normals[5] = n2;
normals[6] = n0;
normals[7] = n1;
normals[8] = n2;
normals[9] = n0;
normals[10] = n1;
normals[11] = n2;
colors = new float[12];
for (int i=0; i<12; i++) colors[i] = 0.5f;
}
else {
domain_values = domain_set.getSamples(false);
domain_values = Unit.convertTuple(domain_values, dataUnits, domain_units);
mapValues(display_values, domain_values, DomainComponents);
ShadowRealTupleType domain_reference = Domain.getReference();
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
RealTupleType ref = (RealTupleType) domain_reference.getType();
float[][] reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_values);
ShadowRealType[] DomainReferenceComponents =
((ShadowFunctionOrSetType) adaptedShadowType).
getDomainReferenceComponents();
mapValues(display_values, reference_values, DomainReferenceComponents);
reference_values = null;
}
domain_values = null;
}
if (this instanceof ShadowFunctionTypeJ2D) {
double[][] range_values = ((Field) data).getValues();
if (range_values != null) {
ShadowRealType[] RangeComponents =
((ShadowFunctionOrSetType) adaptedShadowType).getRangeComponents();
mapValues(display_values, range_values, RangeComponents);
int[] refToComponent = adaptedShadowType.getRefToComponent();
ShadowRealTupleType[] componentWithRef =
adaptedShadowType.getComponentWithRef();
int[] componentIndex = adaptedShadowType.getComponentIndex();
if (refToComponent != null) {
for (int i=0; i<refToComponent.length; i++) {
int n = componentWithRef[i].getDimension();
int start = refToComponent[i];
double[][] values = new double[n][];
for (int j=0; j<n; j++) values[j] = range_values[j + start];
ShadowRealTupleType component_reference =
componentWithRef[i].getReference();
RealTupleType ref = (RealTupleType) component_reference.getType();
Unit[] range_units;
CoordinateSystem[] range_coord_sys;
if (i == 0 && componentWithRef[i].equals(Range)) {
range_units = ((Field) data).getDefaultRangeUnits();
range_coord_sys = ((Field) data).getRangeCoordinateSystem();
}
else {
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
range_units = new Unit[n];
for (int j=0; j<n; j++) range_units[j] = dummy_units[j + start];
range_coord_sys =
((Field) data).getRangeCoordinateSystem(componentIndex[i]);
}
double[][] reference_values = null;
if (range_coord_sys.length == 1) {
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[0], range_units, null, values);
}
else {
reference_values = new double[n][domain_length];
double[][] temp = new double[n][1];
for (int j=0; j<domain_length; j++) {
for (int k=0; k<n; k++) temp[k][0] = values[k][j];
temp =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[j], range_units, null, temp);
for (int k=0; k<n; k++) reference_values[k][j] = temp[k][0];
}
}
mapValues(display_values, reference_values,
getComponents(componentWithRef[i], false));
reference_values = null;
values = null;
}
}
range_values = null;
}
}
float[][] range_select =
assembleSelect(display_values, domain_length, valueArrayLength,
valueToScalar, display);
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
if (adaptedShadowType.getIsTerminal()) {
if (!((ShadowFunctionOrSetType) adaptedShadowType).getFlat()) {
throw new DisplayException("terminal but not Flat");
}
GraphicsModeControl mode = display.getGraphicsModeControl();
boolean pointMode = mode.getPointMode();
float[][] flow1_values = new float[3][];
float[][] flow2_values = new float[3][];
float[] flowScale = new float[2];
assembleFlow(flow1_values, flow2_values, flowScale,
display_values, valueArrayLength, valueToScalar,
display, default_values, range_select);
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
float[][] spatial_values = new float[3][];
int[] spatialDimensions = new int[2];
Set spatial_set =
assembleSpatial(spatial_values, display_values, valueArrayLength,
valueToScalar, display, default_values,
inherited_values, domain_set,
((ShadowRealTupleType) Domain.adaptedShadowType).getAllSpatial(),
anyContour, spatialDimensions, range_select,
flow1_values, flow2_values, flowScale);
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
int spatialDomainDimension = spatialDimensions[0];
int spatialManifoldDimension = spatialDimensions[1];
int spatial_length = Math.min(domain_length, spatial_values[0].length);
float[][] color_values =
assembleColor(display_values, valueArrayLength, valueToScalar,
display, default_values, range_select);
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
int color_length = Math.min(domain_length, color_values[0].length);
int alpha_length = color_values[3].length;
VisADAppearance appearance;
float constant_alpha = Float.NaN;
float[] constant_color = null;
if (alpha_length == 1) {
if (color_values[3][0] != color_values[3][0]) {
return false;
}
if (color_values[3][0] > 0.999999f) {
constant_alpha = 0.0f;
float[][] c = new float[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
else {
constant_alpha = 1.0f - color_values[3][0];
}
float[][] c = new float[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
if (color_length == 1) {
if (color_values[0][0] != color_values[0][0] ||
color_values[1][0] != color_values[1][0] ||
color_values[2][0] != color_values[2][0]) {
return false;
}
constant_color = new float[] {color_values[0][0], color_values[1][0],
color_values[2][0]};
color_values = null;
}
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
if (LevelOfDifficulty == SIMPLE_FIELD) {
VisADGeometryArray array;
boolean anyFlowCreated = false;
if (anyFlow) {
array = makeFlow(flow1_values, flowScale[0], spatial_values,
color_values, range_select);
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
anyFlowCreated = true;
}
array = makeFlow(flow2_values, flowScale[1], spatial_values,
color_values, range_select);
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
anyFlowCreated = true;
}
}
boolean anyContourCreated = false;
if (anyContour) {
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
array = null;
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) {
if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || display_values[i].length == 1) break;
for (int j=0; j<len; j++) {
display_values[i][j] += range_select[0][j];
}
}
if (spatialManifoldDimension == 3) {
if (fvalues[0] == fvalues[0]) {
array = spatial_set.makeIsoSurface(fvalues[0],
display_values[i], color_values);
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
}
}
anyContourCreated = true;
}
else if (spatialManifoldDimension == 2) {
VisADGeometryArray[] arrays =
spatial_set.makeIsoLines(fvalues[1], fvalues[2], fvalues[3],
fvalues[4], display_values[i], color_values);
if (arrays != null && arrays.length != 0 && arrays[0] != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, arrays[0]);
group.addChild(appearance);
if (bvalues[1] && arrays[2] != null) {
array = arrays[2];
arrays = null;
}
else if ((!bvalues[1]) && arrays[1] != null) {
array = arrays[1];
arrays = null;
}
else {
array = null;
}
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
}
}
anyContourCreated = true;
}
}
}
}
}
if (!anyContourCreated && !anyFlowCreated) {
if (isTextureMap) {
if (color_values == null) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D." +
".doTransform: no color or alpha values");
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
for (int i=0; i<len; i++) {
if (range_select[0][i] != range_select[0][i]) {
color_values[0][i] = 0.0f;
color_values[1][i] = 0.0f;
color_values[2][i] = 0.0f;
}
}
}
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
qarray.colors = colors;
appearance = makeAppearance(mode, constant_alpha,
constant_color, qarray);
BufferedImage image = null;
int[] rgbArray = new int[texture_width * texture_height];
if (color_values.length > 3) {
int k = 0;
int r, g, b, a;
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_ARGB);
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (int) (color_values[0][k] * 255.0);
r = (r < 0) ? 0 : (r > 255) ? 255 : r;
g = (int) (color_values[1][k] * 255.0);
g = (g < 0) ? 0 : (g > 255) ? 255 : g;
b = (int) (color_values[2][k] * 255.0);
b = (b < 0) ? 0 : (b > 255) ? 255 : b;
a = (int) (color_values[3][k] * 255.0);
a = (a < 0) ? 0 : (a > 255) ? 255 : a;
image.setRGB(i, j, ((a << 24) | (r << 16) | (g << 8) | b));
k++;
}
for (int i=data_width; i<texture_width; i++) {
image.setRGB(i, j, 0);
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
image.setRGB(i, j, 0);
}
}
}
else {
int k = 0;
int r, g, b, a;
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_ARGB);
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (int) (color_values[0][k] * 255.0);
r = (r < 0) ? 0 : (r > 255) ? 255 : r;
g = (int) (color_values[1][k] * 255.0);
g = (g < 0) ? 0 : (g > 255) ? 255 : g;
b = (int) (color_values[2][k] * 255.0);
b = (b < 0) ? 0 : (b > 255) ? 255 : b;
a = 255;
image.setRGB(i, j, ((a << 24) | (r << 16) | (g << 8) | b));
k++;
}
for (int i=data_width; i<texture_width; i++) {
image.setRGB(i, j, 0);
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
image.setRGB(i, j, 0);
}
}
}
appearance.image = image;
group.addChild(appearance);
return false;
}
else if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || spatial_values[0].length == 1) return false;
for (int j=0; j<len; j++) {
spatial_values[0][j] += range_select[0][j];
}
array = makePointGeometry(spatial_values, color_values);
}
else if (pointMode) {
array = makePointGeometry(spatial_values, color_values);
}
else if (spatial_set == null) {
array = makePointGeometry(spatial_values, color_values);
}
else if (spatialManifoldDimension == 1) {
array = spatial_set.make1DGeometry(color_values);
}
else if (spatialManifoldDimension == 2) {
array = spatial_set.make2DGeometry(color_values);
}
else if (spatialManifoldDimension == 3) {
array = makePointGeometry(spatial_values, color_values);
}
else if (spatialManifoldDimension == 0) {
array = spatial_set.makePointGeometry(color_values);
}
else {
throw new DisplayException("ShadowFunctionOrSetType.doTransform: " +
"bad spatialManifoldDimension");
}
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
if (renderer instanceof DirectManipulationRendererJ2D) {
((DirectManipulationRendererJ2D) renderer).
setSpatialValues(spatial_values);
}
}
}
return false;
}
else {
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"terminal LEGAL");
}
}
else {
boolean post = false;
AVControlJ2D control = null;
VisADSwitch swit = null;
int index = -1;
for (int i=0; i<valueArrayLength; i++) {
float[] values = display_values[i];
if (values != null) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.Animation) ||
real.equals(Display.SelectValue)) {
swit = new VisADSwitch();
index = i;
control = (AVControlJ2D)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
break;
}
}
}
if (control != null) {
group.addChild(swit);
control.addPair(swit, domain_set, renderer);
}
float[] range_value_array = new float[valueArrayLength];
for (int j=0; j<display.getValueArrayLength(); j++) {
range_value_array[j] = Float.NaN;
}
for (int i=0; i<domain_length; i++) {
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i] == range_select[0][i]) {
for (int j=0; j<valueArrayLength; j++) {
if (display_values[j] != null) {
if (display_values[j].length == 1) {
range_value_array[j] = display_values[j][0];
}
else {
range_value_array[j] = display_values[j][i];
}
}
}
if (control != null) {
VisADGroup branch = new VisADGroup();
swit.addChild(branch);
post |= Range.doTransform(branch, ((Field) data).getSample(i),
range_value_array, default_values, renderer);
}
else {
post |= Range.doTransform(group, ((Field) data).getSample(i),
range_value_array, default_values, renderer);
}
}
else {
if (control != null) {
VisADGroup branch = new VisADGroup();
swit.addChild(branch);
branch.addChild(new VisADAppearance());
}
}
}
if (control != null) {
control.init();
}
return post;
}
}
| public boolean doTransform(VisADGroup group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer)
throws VisADException, RemoteException {
if (data.isMissing()) return false;
int LevelOfDifficulty = adaptedShadowType.getLevelOfDifficulty();
if (LevelOfDifficulty == NOTHING_MAPPED) return false;
boolean time_flag = false;
if (renderer instanceof DefaultRendererJ2D) {
if (((DefaultRendererJ2D) renderer).time_flag) {
time_flag = true;
}
else {
if (500 < System.currentTimeMillis() -
((DefaultRendererJ2D) renderer).start_time) {
((DefaultRendererJ2D) renderer).time_flag = true;
time_flag = true;
}
}
}
if (time_flag) {
DataDisplayLink link = ((DefaultRendererJ2D) renderer).link;
if (link.peekTicks()) {
throw new DisplayInterruptException("please wait . . .");
}
Enumeration maps = link.getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.peekTicks(renderer, link)) {
throw new DisplayInterruptException("please wait . . .");
}
}
}
boolean anyContour =
((ShadowFunctionOrSetType) adaptedShadowType).getAnyContour();
boolean anyFlow =
((ShadowFunctionOrSetType) adaptedShadowType).getAnyFlow();
boolean anyShape =
((ShadowFunctionOrSetType) adaptedShadowType).getAnyShape();
if (anyShape) {
throw new UnimplementedException("ShadowFunctionOrSetTypeJ2D.doTransform" +
"Shape not yet supported");
}
int valueArrayLength = display.getValueArrayLength();
int[] valueToScalar = display.getValueToScalar();
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
float[][] display_values = new float[valueArrayLength][];
int[] inherited_values =
((ShadowFunctionOrSetType) adaptedShadowType).getInheritedValues();
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0) {
display_values[i] = new float[1];
display_values[i][0] = value_array[i];
}
}
if (adaptedShadowType.getIsTerminal() && anyContour && !anyFlow) {
boolean any_enabled = false;
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) any_enabled = true;
}
}
if (!any_enabled) return false;
}
Set domain_set = null;
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (this instanceof ShadowFunctionTypeJ2D) {
if (!(data instanceof Field)) {
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"data must be Field");
}
domain_set = ((Field) data).getDomainSet();
dataUnits = ((Function) data).getDomainUnits();
dataCoordinateSystem = ((Function) data).getDomainCoordinateSystem();
}
else if (this instanceof ShadowSetTypeJ2D) {
domain_set = (Set) data;
dataUnits = ((Set) data).getSetUnits();
dataCoordinateSystem = ((Set) data).getCoordinateSystem();
}
else {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform: " +
"must be ShadowFunctionType or ShadowSetType");
}
float[][] domain_values = null;
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
int domain_length = domain_set.getLength();
ShadowRealType[] DomainComponents =
((ShadowFunctionOrSetType) adaptedShadowType).getDomainComponents();
int alpha_index = display.getDisplayScalarIndex(Display.Alpha);
boolean isTextureMap = adaptedShadowType.getIsTextureMap() &&
default_values[alpha_index] > 0.99 &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2));
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
float[] colors = null;
int data_width = 0;
int data_height = 0;
int texture_width = 1;
int texture_height = 1;
if (isTextureMap) {
if (renderer instanceof DirectManipulationRendererJ2D) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform" +
" DirectManipulationRendererJ2D");
}
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
float value2 = 0.0f;
limits = Unit.convertTuple(limits, dataUnits, domain_units);
data_width = X.getLength();
data_height = Y.getLength();
texture_width = data_width;
texture_height = data_height;
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform" +
" domain dimension != 2");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
ScalarMap map = (ScalarMap) maps.nextElement();
limits[i] = map.scaleValues(limits[i]);
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform" +
" isTextureMap with bad tuple");
}
tuple_index[i] = real.getTupleIndex();
if (maps.hasMoreElements()) {
throw new DisplayException("ShadowFunctionOrSetTypeJ2D.doTransform" +
" isTextureMap with multiple");
}
}
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
coordinates = new float[12];
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
coordinates[3 + tuple_index[0]] = limits[0][1];
coordinates[3 + tuple_index[1]] = limits[1][0];
coordinates[3 + tuple_index[2]] = value2;
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
coordinates[9 + tuple_index[0]] = limits[0][0];
coordinates[9 + tuple_index[1]] = limits[1][1];
coordinates[9 + tuple_index[2]] = value2;
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
texCoords[0] = 0.0f;
texCoords[1] = 1.0f - ratioh;
texCoords[2] = ratiow;
texCoords[3] = 1.0f - ratioh;
texCoords[4] = ratiow;
texCoords[5] = 1.0f;
texCoords[6] = 0.0f;
texCoords[7] = 1.0f;
normals = new float[12];
float n0 = ((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+1]-coordinates[0+1])) -
((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+2]-coordinates[0+2]));
float n1 = ((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+2]-coordinates[0+2])) -
((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+0]-coordinates[0+0]));
float n2 = ((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+0]-coordinates[0+0])) -
((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+1]-coordinates[0+1]));
float nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
normals[0] = n0;
normals[1] = n1;
normals[2] = n2;
normals[3] = n0;
normals[4] = n1;
normals[5] = n2;
normals[6] = n0;
normals[7] = n1;
normals[8] = n2;
normals[9] = n0;
normals[10] = n1;
normals[11] = n2;
colors = new float[12];
for (int i=0; i<12; i++) colors[i] = 0.5f;
}
else {
domain_values = domain_set.getSamples(false);
domain_values = Unit.convertTuple(domain_values, dataUnits, domain_units);
mapValues(display_values, domain_values, DomainComponents);
ShadowRealTupleType domain_reference = Domain.getReference();
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
RealTupleType ref = (RealTupleType) domain_reference.getType();
float[][] reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_values);
ShadowRealType[] DomainReferenceComponents =
((ShadowFunctionOrSetType) adaptedShadowType).
getDomainReferenceComponents();
mapValues(display_values, reference_values, DomainReferenceComponents);
reference_values = null;
}
domain_values = null;
}
if (this instanceof ShadowFunctionTypeJ2D) {
double[][] range_values = ((Field) data).getValues();
if (range_values != null) {
ShadowRealType[] RangeComponents =
((ShadowFunctionOrSetType) adaptedShadowType).getRangeComponents();
mapValues(display_values, range_values, RangeComponents);
int[] refToComponent = adaptedShadowType.getRefToComponent();
ShadowRealTupleType[] componentWithRef =
adaptedShadowType.getComponentWithRef();
int[] componentIndex = adaptedShadowType.getComponentIndex();
if (refToComponent != null) {
for (int i=0; i<refToComponent.length; i++) {
int n = componentWithRef[i].getDimension();
int start = refToComponent[i];
double[][] values = new double[n][];
for (int j=0; j<n; j++) values[j] = range_values[j + start];
ShadowRealTupleType component_reference =
componentWithRef[i].getReference();
RealTupleType ref = (RealTupleType) component_reference.getType();
Unit[] range_units;
CoordinateSystem[] range_coord_sys;
if (i == 0 && componentWithRef[i].equals(Range)) {
range_units = ((Field) data).getDefaultRangeUnits();
range_coord_sys = ((Field) data).getRangeCoordinateSystem();
}
else {
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
range_units = new Unit[n];
for (int j=0; j<n; j++) range_units[j] = dummy_units[j + start];
range_coord_sys =
((Field) data).getRangeCoordinateSystem(componentIndex[i]);
}
double[][] reference_values = null;
if (range_coord_sys.length == 1) {
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[0], range_units, null, values);
}
else {
reference_values = new double[n][domain_length];
double[][] temp = new double[n][1];
for (int j=0; j<domain_length; j++) {
for (int k=0; k<n; k++) temp[k][0] = values[k][j];
temp =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[j], range_units, null, temp);
for (int k=0; k<n; k++) reference_values[k][j] = temp[k][0];
}
}
mapValues(display_values, reference_values,
getComponents(componentWithRef[i], false));
reference_values = null;
values = null;
}
}
range_values = null;
}
}
float[][] range_select =
assembleSelect(display_values, domain_length, valueArrayLength,
valueToScalar, display);
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
if (adaptedShadowType.getIsTerminal()) {
if (!((ShadowFunctionOrSetType) adaptedShadowType).getFlat()) {
throw new DisplayException("terminal but not Flat");
}
GraphicsModeControl mode = display.getGraphicsModeControl();
boolean pointMode = mode.getPointMode();
float[][] flow1_values = new float[3][];
float[][] flow2_values = new float[3][];
float[] flowScale = new float[2];
assembleFlow(flow1_values, flow2_values, flowScale,
display_values, valueArrayLength, valueToScalar,
display, default_values, range_select);
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
float[][] spatial_values = new float[3][];
int[] spatialDimensions = new int[2];
Set spatial_set =
assembleSpatial(spatial_values, display_values, valueArrayLength,
valueToScalar, display, default_values,
inherited_values, domain_set,
((ShadowRealTupleType) Domain.adaptedShadowType).getAllSpatial(),
anyContour, spatialDimensions, range_select,
flow1_values, flow2_values, flowScale);
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
int spatialDomainDimension = spatialDimensions[0];
int spatialManifoldDimension = spatialDimensions[1];
int spatial_length = Math.min(domain_length, spatial_values[0].length);
float[][] color_values =
assembleColor(display_values, valueArrayLength, valueToScalar,
display, default_values, range_select);
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
int color_length = Math.min(domain_length, color_values[0].length);
int alpha_length = color_values[3].length;
VisADAppearance appearance;
float constant_alpha = Float.NaN;
float[] constant_color = null;
if (alpha_length == 1) {
if (color_values[3][0] != color_values[3][0]) {
return false;
}
if (color_values[3][0] > 0.999999f) {
constant_alpha = 0.0f;
float[][] c = new float[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
else {
constant_alpha = 1.0f - color_values[3][0];
}
float[][] c = new float[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
if (color_length == 1) {
if (color_values[0][0] != color_values[0][0] ||
color_values[1][0] != color_values[1][0] ||
color_values[2][0] != color_values[2][0]) {
return false;
}
constant_color = new float[] {color_values[0][0], color_values[1][0],
color_values[2][0]};
color_values = null;
}
if (range_select[0] != null && range_select[0].length == 1 &&
range_select[0][0] != range_select[0][0]) {
return false;
}
if (LevelOfDifficulty == SIMPLE_FIELD) {
VisADGeometryArray array;
boolean anyFlowCreated = false;
if (anyFlow) {
array = makeFlow(flow1_values, flowScale[0], spatial_values,
color_values, range_select);
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
anyFlowCreated = true;
}
array = makeFlow(flow2_values, flowScale[1], spatial_values,
color_values, range_select);
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
anyFlowCreated = true;
}
}
boolean anyContourCreated = false;
if (anyContour) {
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
array = null;
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) {
if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || display_values[i].length == 1) break;
for (int j=0; j<len; j++) {
display_values[i][j] += range_select[0][j];
}
}
if (spatialManifoldDimension == 3) {
if (fvalues[0] == fvalues[0]) {
array = spatial_set.makeIsoSurface(fvalues[0],
display_values[i], color_values);
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
}
}
anyContourCreated = true;
}
else if (spatialManifoldDimension == 2) {
VisADGeometryArray[] arrays =
spatial_set.makeIsoLines(fvalues[1], fvalues[2], fvalues[3],
fvalues[4], display_values[i], color_values);
if (arrays != null && arrays.length != 0 && arrays[0] != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, arrays[0]);
group.addChild(appearance);
if (bvalues[1] && arrays[2] != null) {
array = arrays[2];
arrays = null;
}
else if ((!bvalues[1]) && arrays[1] != null) {
array = arrays[1];
arrays = null;
}
else {
array = null;
}
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
}
}
anyContourCreated = true;
}
}
}
}
}
if (!anyContourCreated && !anyFlowCreated) {
if (isTextureMap) {
if (color_values == null) {
color_values = new float[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = constant_color[0];
color_values[1][i] = constant_color[1];
color_values[2][i] = constant_color[2];
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
for (int i=0; i<len; i++) {
if (range_select[0][i] != range_select[0][i]) {
color_values[0][i] = 0.0f;
color_values[1][i] = 0.0f;
color_values[2][i] = 0.0f;
}
}
}
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
qarray.colors = colors;
appearance = makeAppearance(mode, constant_alpha,
constant_color, qarray);
BufferedImage image = null;
int[] rgbArray = new int[texture_width * texture_height];
if (color_values.length > 3) {
int k = 0;
int r, g, b, a;
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_ARGB);
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (int) (color_values[0][k] * 255.0);
r = (r < 0) ? 0 : (r > 255) ? 255 : r;
g = (int) (color_values[1][k] * 255.0);
g = (g < 0) ? 0 : (g > 255) ? 255 : g;
b = (int) (color_values[2][k] * 255.0);
b = (b < 0) ? 0 : (b > 255) ? 255 : b;
a = (int) (color_values[3][k] * 255.0);
a = (a < 0) ? 0 : (a > 255) ? 255 : a;
image.setRGB(i, j, ((a << 24) | (r << 16) | (g << 8) | b));
k++;
}
for (int i=data_width; i<texture_width; i++) {
image.setRGB(i, j, 0);
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
image.setRGB(i, j, 0);
}
}
}
else {
int k = 0;
int r, g, b, a;
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_ARGB);
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (int) (color_values[0][k] * 255.0);
r = (r < 0) ? 0 : (r > 255) ? 255 : r;
g = (int) (color_values[1][k] * 255.0);
g = (g < 0) ? 0 : (g > 255) ? 255 : g;
b = (int) (color_values[2][k] * 255.0);
b = (b < 0) ? 0 : (b > 255) ? 255 : b;
a = 255;
image.setRGB(i, j, ((a << 24) | (r << 16) | (g << 8) | b));
k++;
}
for (int i=data_width; i<texture_width; i++) {
image.setRGB(i, j, 0);
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
image.setRGB(i, j, 0);
}
}
}
appearance.image = image;
group.addChild(appearance);
return false;
}
else if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || spatial_values[0].length == 1) return false;
for (int j=0; j<len; j++) {
spatial_values[0][j] += range_select[0][j];
}
array = makePointGeometry(spatial_values, color_values);
}
else if (pointMode) {
array = makePointGeometry(spatial_values, color_values);
}
else if (spatial_set == null) {
array = makePointGeometry(spatial_values, color_values);
}
else if (spatialManifoldDimension == 1) {
array = spatial_set.make1DGeometry(color_values);
}
else if (spatialManifoldDimension == 2) {
array = spatial_set.make2DGeometry(color_values);
}
else if (spatialManifoldDimension == 3) {
array = makePointGeometry(spatial_values, color_values);
}
else if (spatialManifoldDimension == 0) {
array = spatial_set.makePointGeometry(color_values);
}
else {
throw new DisplayException("ShadowFunctionOrSetType.doTransform: " +
"bad spatialManifoldDimension");
}
if (array != null) {
appearance = makeAppearance(mode, constant_alpha,
constant_color, array);
group.addChild(appearance);
if (renderer instanceof DirectManipulationRendererJ2D) {
((DirectManipulationRendererJ2D) renderer).
setSpatialValues(spatial_values);
}
}
}
return false;
}
else {
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"terminal LEGAL");
}
}
else {
boolean post = false;
AVControlJ2D control = null;
VisADSwitch swit = null;
int index = -1;
for (int i=0; i<valueArrayLength; i++) {
float[] values = display_values[i];
if (values != null) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.Animation) ||
real.equals(Display.SelectValue)) {
swit = new VisADSwitch();
index = i;
control = (AVControlJ2D)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
break;
}
}
}
if (control != null) {
group.addChild(swit);
control.addPair(swit, domain_set, renderer);
}
float[] range_value_array = new float[valueArrayLength];
for (int j=0; j<display.getValueArrayLength(); j++) {
range_value_array[j] = Float.NaN;
}
for (int i=0; i<domain_length; i++) {
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i] == range_select[0][i]) {
for (int j=0; j<valueArrayLength; j++) {
if (display_values[j] != null) {
if (display_values[j].length == 1) {
range_value_array[j] = display_values[j][0];
}
else {
range_value_array[j] = display_values[j][i];
}
}
}
if (control != null) {
VisADGroup branch = new VisADGroup();
swit.addChild(branch);
post |= Range.doTransform(branch, ((Field) data).getSample(i),
range_value_array, default_values, renderer);
}
else {
post |= Range.doTransform(group, ((Field) data).getSample(i),
range_value_array, default_values, renderer);
}
}
else {
if (control != null) {
VisADGroup branch = new VisADGroup();
swit.addChild(branch);
branch.addChild(new VisADAppearance());
}
}
}
if (control != null) {
control.init();
}
return post;
}
}
|
public void entityDamage(EntityDamageEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
boolean isFatal = false;
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String cause = event.getCause().name();
String determination;
dPlayer player = null;
dNPC npc = null;
if (entity.isNPC()) {
npc = new dNPC(entity.getNPC());
context.put("entity", npc);
entityType = "npc";
}
else if (entity.isPlayer()) {
player = new dPlayer(entity.getPlayer());
context.put("entity", player);
}
else {
context.put("entity", entity);
}
context.put("damage", new Element(event.getDamage()));
context.put("cause", new Element(event.getCause().name()));
if (entity instanceof LivingEntity) {
if (event.getDamage() >= ((LivingEntity) entity).getHealth()) {
isFatal = true;
}
}
List<String> events = new ArrayList<String>();
events.add("entity damaged");
events.add("entity damaged by " + cause);
events.add(entityType + " damaged");
events.add(entityType + " damaged by " + cause);
if (isFatal) {
events.add("entity killed");
events.add("entity killed by " + cause);
events.add(entityType + " killed");
events.add(entityType + " killed by " + cause);
}
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
dPlayer subPlayer = null;
dNPC subNPC = null;
dEntity damager = new dEntity(subEvent.getDamager());
String damagerType = damager.getEntityType().name();
if (damager.isNPC()) {
subNPC = new dNPC(damager.getNPC());
context.put("damager", subNPC);
damagerType = "npc";
if (npc == null) npc = subNPC;
}
else if (damager.isPlayer()) {
subPlayer = new dPlayer(damager.getPlayer());
context.put("damager", subPlayer);
if (player == null) player = subPlayer;
}
else {
context.put("damager", damager);
if (damager instanceof Projectile) {
if (((Projectile) damager.getBukkitEntity()).getShooter() != null) {
dEntity shooter = new dEntity(((Projectile) damager.getBukkitEntity()).getShooter());
if (shooter.isNPC()) {
context.put("shooter", new dNPC(shooter.getNPC()));
}
else if (shooter.isPlayer()) {
context.put("shooter", new dPlayer(shooter.getPlayer()));
}
else {
context.put("shooter", shooter);
}
}
}
}
events.add("entity damaged by entity");
events.add("entity damaged by " + damagerType);
events.add(entityType + " damaged by entity");
events.add(entityType + " damaged by " + damagerType);
List<String> subEvents = new ArrayList<String>();
subEvents.add("entity damages entity");
subEvents.add("entity damages " + entityType);
subEvents.add(damagerType + " damages entity");
subEvents.add(damagerType + " damages " + entityType);
if (isFatal) {
events.add("entity killed by entity");
events.add("entity killed by " + damagerType);
events.add(entityType + " killed by entity");
events.add(entityType + " killed by " + damagerType);
subEvents.add("entity kills entity");
subEvents.add("entity kills " + entityType);
subEvents.add(damagerType + " kills entity");
subEvents.add(damagerType + " kills " + entityType);
}
determination = doEvents(subEvents, subNPC, (subPlayer != null?subPlayer.getPlayerEntity():null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
determination = doEvents(events, npc,
(player != null && player.isOnline() ? player.getPlayerEntity() : null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
| public void entityDamage(EntityDamageEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
boolean isFatal = false;
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String cause = event.getCause().name();
String determination;
dPlayer player = null;
dNPC npc = null;
if (entity.isNPC()) {
npc = new dNPC(entity.getNPC());
context.put("entity", npc);
entityType = "npc";
}
else if (entity.isPlayer()) {
player = new dPlayer(entity.getPlayer());
context.put("entity", player);
}
else {
context.put("entity", entity);
}
context.put("damage", new Element(event.getDamage()));
context.put("cause", new Element(event.getCause().name()));
if (entity instanceof LivingEntity) {
if (event.getDamage() >= ((LivingEntity) entity).getHealth()) {
isFatal = true;
}
}
List<String> events = new ArrayList<String>();
events.add("entity damaged");
events.add("entity damaged by " + cause);
events.add(entityType + " damaged");
events.add(entityType + " damaged by " + cause);
if (isFatal) {
events.add("entity killed");
events.add("entity killed by " + cause);
events.add(entityType + " killed");
events.add(entityType + " killed by " + cause);
}
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
dPlayer subPlayer = null;
dNPC subNPC = null;
dEntity damager = new dEntity(subEvent.getDamager());
String damagerType = damager.getEntityType().name();
if (damager.isNPC()) {
subNPC = new dNPC(damager.getNPC());
context.put("damager", subNPC);
damagerType = "npc";
if (npc == null) npc = subNPC;
}
else if (damager.isPlayer()) {
subPlayer = new dPlayer(damager.getPlayer());
context.put("damager", subPlayer);
if (player == null) player = subPlayer;
}
else {
context.put("damager", damager);
if (damager.getBukkitEntity() instanceof Projectile) {
if (((Projectile) damager.getBukkitEntity()).getShooter() != null) {
dEntity shooter = new dEntity(((Projectile) damager.getBukkitEntity()).getShooter());
if (shooter.isNPC()) {
context.put("shooter", new dNPC(shooter.getNPC()));
}
else if (shooter.isPlayer()) {
context.put("shooter", new dPlayer(shooter.getPlayer()));
}
else {
context.put("shooter", shooter);
}
}
}
}
events.add("entity damaged by entity");
events.add("entity damaged by " + damagerType);
events.add(entityType + " damaged by entity");
events.add(entityType + " damaged by " + damagerType);
List<String> subEvents = new ArrayList<String>();
subEvents.add("entity damages entity");
subEvents.add("entity damages " + entityType);
subEvents.add(damagerType + " damages entity");
subEvents.add(damagerType + " damages " + entityType);
if (isFatal) {
events.add("entity killed by entity");
events.add("entity killed by " + damagerType);
events.add(entityType + " killed by entity");
events.add(entityType + " killed by " + damagerType);
subEvents.add("entity kills entity");
subEvents.add("entity kills " + entityType);
subEvents.add(damagerType + " kills entity");
subEvents.add(damagerType + " kills " + entityType);
}
determination = doEvents(subEvents, subNPC, (subPlayer != null?subPlayer.getPlayerEntity():null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
determination = doEvents(events, npc,
(player != null && player.isOnline() ? player.getPlayerEntity() : null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
|
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession();
Object sequence = session.getAttribute("seq");
if (sequence == null) {
String sequenceInCookie = HttpUtils.getCookie(httpRequest, "seq");
if (sequenceInCookie == null) {
httpResponse.sendRedirect("/pilot/login/login.html");
return;
}
Integer userSequence = Integer.valueOf(sequenceInCookie);
User user = userDao.getUserBySequence(userSequence);
System.out.println("user: " + user);
session.setAttribute("user", user);
}
chain.doFilter(request, response);
}
| public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession();
User user = (User) session.getAttribute("user");
if (user == null) {
String sequenceInCookie = HttpUtils.getCookie(httpRequest, "seq");
if (sequenceInCookie == null) {
httpResponse.sendRedirect("/pilot/login/login.html");
return;
}
Integer userSequence = Integer.valueOf(sequenceInCookie);
user = userDao.getUserBySequence(userSequence);
session.setAttribute("user", user);
}
chain.doFilter(request, response);
}
|
public synchronized Class<?> loadClass(String name) throws ClassNotFoundException {
logger.logp(Level.FINER, getClass().getName(), "loadClass", "loading class for ["+name+"]");
String _name = name.replace('-', '_');
Class<?> c = findLoadedClass(_name);
if (c != null) {
logger.logp(Level.FINER, getClass().getName(), "loadClass", "class already loaded for ["+_name+"]");
return c;
}
try {
c = getParent().loadClass(_name);
} catch (ClassNotFoundException e) {
}
if (c == null) {
String fileName = name.replace('.', '/').replace('~', '.');
fileName += ".js";
if (fileName.charAt(0) != '/') {
fileName = '/'+fileName;
}
logger.logp(Level.FINER, getClass().getName(), "loadClass", "Resolved filename for ["+name+"] ["+fileName+"]");
InputStream is = null;
try {
String resource = resourceLoader.readResource(fileName);
String className = name.replace('-', '_').replace('~', '_');
String _fileName = fileName.replace('-', '_').replace('~', '_');
if (resource != null) {
ClassCompiler classCompiler = new ClassCompiler(new CompilerEnvirons());
Object[] classBytes = classCompiler.compileToClassFiles(resource, _fileName, 1, className);
c = defineClass(className, (byte[])classBytes[1], 0, ((byte[])classBytes[1]).length);
resolveClass(c);
} else {
throw new ClassNotFoundException(className);
}
} catch (IOException e) {
logger.logp(Level.SEVERE, getClass().getName(), "loadJS", "IOException while loading class for ["+name+"]", e);
throw new ClassNotFoundException(name);
} finally {
if (is != null) {
try {is.close();}catch (IOException e) {}
}
}
}
return c;
}
| public synchronized Class<?> loadClass(String name) throws ClassNotFoundException {
logger.logp(Level.FINER, getClass().getName(), "loadClass", "loading class for ["+name+"]");
String _name = name.replace('-', '_');
Class<?> c = findLoadedClass(_name);
if (c != null) {
logger.logp(Level.FINER, getClass().getName(), "loadClass", "class already loaded for ["+_name+"]");
return c;
}
try {
c = getParent().loadClass(_name);
} catch (ClassNotFoundException e) {
}
if (c == null) {
String fileName = name.replace('.', '/').replace('~', '.');
fileName += ".js";
if (fileName.charAt(0) != '/') {
fileName = '/'+fileName;
}
logger.logp(Level.FINER, getClass().getName(), "loadClass", "Resolved filename for ["+name+"] ["+fileName+"]");
InputStream is = null;
try {
String resource = resourceLoader.readResource(fileName);
String className = name.replace('-', '_').replace('~', '_');
String _fileName = fileName.replace('-', '_').replace('~', '_');
if (resource != null) {
ClassCompiler classCompiler = new ClassCompiler(new CompilerEnvirons());
Object[] classBytes = classCompiler.compileToClassFiles(resource, _fileName, 1, className);
c = defineClass(className, (byte[])classBytes[1], 0, ((byte[])classBytes[1]).length);
resolveClass(c);
} else {
throw new ClassNotFoundException(className);
}
} catch (Throwable e) {
logger.logp(Level.SEVERE, getClass().getName(), "loadJS", "Exception while loading class for ["+name+"]", e);
throw new ClassNotFoundException(name);
} finally {
if (is != null) {
try {is.close();}catch (IOException e) {}
}
}
}
return c;
}
|
public static final void initAndRun(String[] args) {
try {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT);
String callingClassName = Thread.currentThread().getStackTrace()[2].getClassName();
Class<AbstractTool> callingClass = (Class<AbstractTool>) Class.forName(callingClassName);
AbstractTool tool = context.getBean(callingClass);
tool.run(args);
context.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
| public static final void initAndRun(String[] args) {
AbstractApplicationContext context = null;
try {
context = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT);
String callingClassName = Thread.currentThread().getStackTrace()[2].getClassName();
Class<AbstractTool> callingClass = (Class<AbstractTool>) Class.forName(callingClassName);
AbstractTool tool = context.getBean(callingClass);
tool.run(args);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (context != null)
context.close();
}
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String LOG_TAG = "TestIterations";
long targetIterationCount = 0L, targetIterationTime = 0L, previousIterationCount = 0L, previousIterationTime = 0L;
String algorithName = "PBEWITHSHA1AND128BITAES-CBC-BC";
String passphrase = "thisisatest";
long goalTime = 500L;
int iterationStep = 100;
int currentIterationCount = 0;
long previousIterationElapsedTime = 0L;
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[16];
random.nextBytes(salt);
while(true) {
currentIterationCount += iterationStep;
long startTime = SystemClock.elapsedRealtime();
PBEKeySpec keyspec = new PBEKeySpec(passphrase.toCharArray(), salt, currentIterationCount);
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithName);
SecretKey sk = skf.generateSecret(keyspec);
long finishTime = SystemClock.elapsedRealtime();
if (finishTime-startTime > goalTime) {
Log.d(LOG_TAG, "Current iteration count of " + currentIterationCount + " exceeds the goalTime of: " + goalTime + "ms by " + (finishTime-startTime) + "ms");
Log.d(LOG_TAG, "The previous iteration count was: " + (currentIterationCount - iterationStep) + " and took: " + previousIterationElapsedTime + "ms that is under the goalTime of " + goalTime + " by " + (goalTime-previousIterationElapsedTime) + "ms");
targetIterationCount = currentIterationCount;
targetIterationTime = finishTime-startTime;
previousIterationCount = currentIterationCount - iterationStep;
previousIterationTime = previousIterationElapsedTime;
break;
} else {
Log.d(LOG_TAG, "Current iteration count of " + currentIterationCount + " took " + (finishTime-startTime) + "ms and has " + (goalTime-(finishTime-startTime)) + "ms more to reach the goalTime of: " + goalTime + "ms");
previousIterationElapsedTime = finishTime-startTime;
}
}
} catch (NoSuchAlgorithmException e) {
Log.e(LOG_TAG, "NoSuchAlgorithmException: " + e.toString());
} catch (InvalidKeySpecException e) {
Log.e(LOG_TAG, "InvalidKeySpecException: " + e.toString());
}
((TextView) findViewById(R.id.resultsText)).setText("The below results are using the algorithm: " + algorithName
+ " with passphrase: " + passphrase + System.getProperty("line.separator") +
+ System.getProperty("line.separator") + "Target Iteration Count: " + targetIterationCount
+ System.getProperty("line.separator") + "Target Iteration Duration: " + targetIterationTime + "ms"
+ System.getProperty("line.separator") + System.getProperty("line.separator")
+ "Prior Iteration Count: " + previousIterationCount + System.getProperty("line.separator")
+ "Prior Iteration Duration: " + previousIterationTime + "ms");
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String LOG_TAG = "TestIterations";
long targetIterationCount = 0L, targetIterationTime = 0L, previousIterationCount = 0L, previousIterationTime = 0L;
String algorithName = "PBEWITHSHA1AND128BITAES-CBC-BC";
String passphrase = "thisisatest";
long goalTime = 500L;
int iterationStep = 100;
int currentIterationCount = 0;
long previousIterationElapsedTime = 0L;
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[16];
random.nextBytes(salt);
while(true) {
currentIterationCount += iterationStep;
long startTime = SystemClock.elapsedRealtime();
PBEKeySpec keyspec = new PBEKeySpec(passphrase.toCharArray(), salt, currentIterationCount);
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithName);
SecretKey sk = skf.generateSecret(keyspec);
long finishTime = SystemClock.elapsedRealtime();
if (finishTime-startTime > goalTime) {
Log.d(LOG_TAG, "Current iteration count of " + currentIterationCount + " exceeds the goalTime of: " + goalTime + "ms by " + (finishTime-startTime) + "ms");
Log.d(LOG_TAG, "The previous iteration count was: " + (currentIterationCount - iterationStep) + " and took: " + previousIterationElapsedTime + "ms that is under the goalTime of " + goalTime + " by " + (goalTime-previousIterationElapsedTime) + "ms");
targetIterationCount = currentIterationCount;
targetIterationTime = finishTime-startTime;
previousIterationCount = currentIterationCount - iterationStep;
previousIterationTime = previousIterationElapsedTime;
break;
} else {
Log.d(LOG_TAG, "Current iteration count of " + currentIterationCount + " took " + (finishTime-startTime) + "ms and has " + (goalTime-(finishTime-startTime)) + "ms more to reach the goalTime of: " + goalTime + "ms");
previousIterationElapsedTime = finishTime-startTime;
}
}
} catch (NoSuchAlgorithmException e) {
Log.e(LOG_TAG, "NoSuchAlgorithmException: " + e.toString());
} catch (InvalidKeySpecException e) {
Log.e(LOG_TAG, "InvalidKeySpecException: " + e.toString());
}
((TextView) findViewById(R.id.resultsText)).setText("The below results are using the algorithm: " + algorithName
+ " with passphrase: " + passphrase + System.getProperty("line.separator")
+ System.getProperty("line.separator") + "Target Iteration Count: " + targetIterationCount
+ System.getProperty("line.separator") + "Target Iteration Duration: " + targetIterationTime + "ms"
+ System.getProperty("line.separator") + System.getProperty("line.separator")
+ "Prior Iteration Count: " + previousIterationCount + System.getProperty("line.separator")
+ "Prior Iteration Duration: " + previousIterationTime + "ms");
}
|
protected boolean yieldRule(InternalJob job) {
Thread current = Thread.currentThread();
Assert.isLegal(job.getState() == Job.RUNNING, "Cannot yield job that is not running");
Assert.isLegal(current == job.getThread(), "Cannot yield from outside job's thread");
boolean interrupted = false;
InternalJob unblocked;
ThreadJob threadJob;
synchronized (implicitJobs) {
synchronized (lock) {
unblocked = job.previous();
if (unblocked == null) {
unblocked = implicitJobs.findBlockedJob(job);
}
if (unblocked == null)
return false;
changeState(job, InternalJob.YIELDING);
threadJob = implicitJobs.getThreadJob(current);
if (threadJob != null && threadJob != job) {
changeState(threadJob, InternalJob.YIELDING);
}
job.setThread(null);
if ((job.getRule() != null) && !(job instanceof ThreadJob)) {
getLockManager().removeLockThread(current, job.getRule());
}
}
}
if (unblocked instanceof ThreadJob) {
synchronized (unblocked.jobStateLock) {
while (((ThreadJob) unblocked).isWaiting) {
try {
unblocked.jobStateLock.wait();
} catch (InterruptedException e) {
interrupted = true;
}
}
}
} else {
synchronized (unblocked.jobStateLock) {
while (unblocked.internalGetState() == Job.WAITING) {
try {
unblocked.jobStateLock.wait();
} catch (InterruptedException e) {
interrupted = true;
}
}
}
}
InternalJob waitingFor = unblocked;
while (true) {
if (threadJob != null) {
synchronized (implicitJobs) {
synchronized (lock) {
waitingFor = findBlockingJob(threadJob);
if (waitingFor == null) {
changeState(job, Job.RUNNING);
implicitJobs.resumeJob(threadJob);
if (threadJob != job) {
changeState(threadJob, Job.RUNNING);
}
break;
}
}
}
} else {
synchronized (lock) {
waitingFor = findBlockingJob(job);
if (waitingFor == null) {
changeState(job, Job.RUNNING);
job.setThread(current);
break;
}
}
}
synchronized (waitingFor.jobStateLock) {
try {
waitingFor.jobStateLock.wait();
} catch (InterruptedException e) {
interrupted = true;
}
}
}
if ((job.getRule() != null) && !(job instanceof ThreadJob)) {
getLockManager().addLockThread(Thread.currentThread(), job.getRule());
}
if (interrupted)
Thread.currentThread().interrupt();
return true;
}
| protected boolean yieldRule(InternalJob job) {
Thread current = Thread.currentThread();
Assert.isLegal(job.getState() == Job.RUNNING, "Cannot yield job that is not running");
Assert.isLegal(current == job.getThread(), "Cannot yield from outside job's thread");
boolean interrupted = false;
InternalJob unblocked;
ThreadJob threadJob;
synchronized (implicitJobs) {
synchronized (lock) {
unblocked = job.previous();
if (unblocked == null) {
unblocked = implicitJobs.findBlockedJob(job);
}
if (unblocked == null)
return false;
changeState(job, InternalJob.YIELDING);
threadJob = implicitJobs.getThreadJob(current);
if (threadJob != null && threadJob != job) {
changeState(threadJob, InternalJob.YIELDING);
}
job.setThread(null);
if ((job.getRule() != null) && !(job instanceof ThreadJob)) {
getLockManager().removeLockThread(current, job.getRule());
}
}
}
if (unblocked instanceof ThreadJob) {
synchronized (unblocked.jobStateLock) {
while (((ThreadJob) unblocked).isWaiting) {
try {
unblocked.jobStateLock.wait(5000);
} catch (InterruptedException e) {
interrupted = true;
}
}
}
} else {
synchronized (unblocked.jobStateLock) {
while (unblocked.internalGetState() == Job.WAITING) {
try {
unblocked.jobStateLock.wait(5000);
} catch (InterruptedException e) {
interrupted = true;
}
}
}
}
InternalJob waitingFor = unblocked;
while (true) {
if (threadJob != null) {
synchronized (implicitJobs) {
synchronized (lock) {
waitingFor = findBlockingJob(threadJob);
if (waitingFor == null) {
changeState(job, Job.RUNNING);
implicitJobs.resumeJob(threadJob);
if (threadJob != job) {
changeState(threadJob, Job.RUNNING);
}
break;
}
}
}
} else {
synchronized (lock) {
waitingFor = findBlockingJob(job);
if (waitingFor == null) {
changeState(job, Job.RUNNING);
job.setThread(current);
break;
}
}
}
synchronized (waitingFor.jobStateLock) {
try {
waitingFor.jobStateLock.wait();
} catch (InterruptedException e) {
interrupted = true;
}
}
}
if ((job.getRule() != null) && !(job instanceof ThreadJob)) {
getLockManager().addLockThread(Thread.currentThread(), job.getRule());
}
if (interrupted)
Thread.currentThread().interrupt();
return true;
}
|
public Collection<File> generateCode( ADag dag ) throws CodeGeneratorException{
DagInfo ndi = dag.dagInfo;
Vector vSubInfo = dag.vJobSubInfos;
if ( mInitializeGridStart ){
mConcreteWorkflow = dag;
mGridStartFactory.initialize( mBag, dag );
mInitializeGridStart = false;
}
CodeGenerator storkGenerator = CodeGeneratorFactory.loadInstance( mBag, "Stork" );
String className = this.getClass().getName();
String dagFileName = getDAGFilename( dag, ".dag" );
mDone = false;
File dagFile = null;
Collection<File> result = new ArrayList(1);
if (ndi.dagJobs.isEmpty()) {
concreteDagEmpty( dagFileName, dag );
return result ;
} else {
dagFile = initializeDagFileWriter( dagFileName, ndi );
result.add( dagFile );
printDagString( this.getCategoryDAGManKnobs( mProps ) );
}
if( mProps.symlinkCommonLog() ){
String dir = mProps.getSubmitLogsDirectory();
File directory = null;
if( dir != null ){
directory = new File( dir );
if( !directory.exists() && !directory.mkdirs() ){
directory = null;
}
}
mLogger.log( "Condor logs directory to be used is " + directory,
LogManager.DEBUG_MESSAGE_LEVEL );
try{
File f = File.createTempFile( dag.dagInfo.nameOfADag + "-" +
dag.dagInfo.index,".log",
directory );
mTempLogFile=f.getAbsolutePath();
} catch (IOException ioe) {
mLogger.log( "Error while creating an empty log file in " +
"the local temp directory " + ioe.getMessage(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
mLogger.logEventStart( LoggingKeys.EVENT_PEGASUS_CODE_GENERATION,
LoggingKeys.DAX_ID,
dag.getAbstractWorkflowName(),
LogManager.DEBUG_MESSAGE_LEVEL);
Graph workflow = Adapter.convert( dag );
SUBDAXGenerator subdaxGen = new SUBDAXGenerator();
subdaxGen.initialize( mBag, dag, workflow, mDagWriter );
for( Iterator it = workflow.iterator(); it.hasNext(); ){
GraphNode node = ( GraphNode )it.next();
Job job = (Job)node.getContent();
if( !job.condorVariables.containsKey( Condor.PRIORITY_KEY ) &&
this.mAssignDefaultJobPriorities ){
int priority = getJobPriority( job, node.getDepth() );
job.condorVariables.construct( Condor.PRIORITY_KEY,
new Integer(priority).toString() );
StringBuffer sb = new StringBuffer();
sb.append( "Applying priority of " ).append( priority ).
append( " to " ).append( job.getID() );
mLogger.log( sb.toString(), LogManager.DEBUG_MESSAGE_LEVEL );
}
if ( job.getSiteHandle().equals( "stork" ) ) {
StringBuffer dagString = new StringBuffer();
dagString.append( "DATA " ).append( job.getName() ).append( " " );
dagString.append( job.getName() ).append( ".stork" );
printDagString( dagString.toString() );
storkGenerator.generateCode( dag, job );
}
else if( job instanceof DAGJob ){
DAGJob djob = ( DAGJob )job;
StringBuffer sb = new StringBuffer();
sb.append( Dagman.SUBDAG_EXTERNAL_KEY ).append( " " ).append( job.getName() ).
append( " " ).append( djob.getDAGFile() );
String dagDir = djob.getDirectory();
if( dagDir != null){
sb.append( " " ).append( Dagman.DIRECTORY_EXTERNAL_KEY ).
append( " " ).append( dagDir );
}
if( !job.dagmanVariables.containsKey( Dagman.CATEGORY_KEY ) ){
job.dagmanVariables.construct( Dagman.CATEGORY_KEY, DEFAULT_SUBDAG_CATEGORY_KEY );
}
printDagString( sb.toString() );
printDagString( job.dagmanVariables.toString( job.getName()) );
}
else{
if( job.typeRecursive() ){
Job daxJob = job;
job = subdaxGen.generateCode( job );
daxJob.setArguments( job.getArguments() );
}
if( job != null ){
generateCode( dag, job );
}
printDagString( job.dagmanVariables.toString( job.getName()) );
}
mLogger.log("Written Submit file : " +
getFileBaseName(job), LogManager.DEBUG_MESSAGE_LEVEL);
}
mLogger.logEventCompletion( LogManager.DEBUG_MESSAGE_LEVEL );
this.writeDagFileTail( ndi );
mLogger.log("Written Dag File : " + dagFileName.toString(),
LogManager.DEBUG_MESSAGE_LEVEL);
if( mProps.symlinkCommonLog() ){
this.generateLogFileSymlink( this.getCondorLogInTmpDirectory(),
this.getCondorLogInSubmitDirectory( dag ) );
}
mLogger.log( "Writing out the DOT file ", LogManager.DEBUG_MESSAGE_LEVEL );
this.writeDOTFile( getDAGFilename( dag, ".dot"), dag );
this.writeOutNotifications( dag );
this.writeOutDAXReplicaStore( dag );
this.writeOutStampedeEvents( dag );
this.writeOutWorkflowMetrics(dag);
this.writeOutBraindump( dag );
mDone = true;
return result;
}
| public Collection<File> generateCode( ADag dag ) throws CodeGeneratorException{
DagInfo ndi = dag.dagInfo;
Vector vSubInfo = dag.vJobSubInfos;
if ( mInitializeGridStart ){
mConcreteWorkflow = dag;
mGridStartFactory.initialize( mBag, dag );
mInitializeGridStart = false;
}
CodeGenerator storkGenerator = CodeGeneratorFactory.loadInstance( mBag, "Stork" );
String className = this.getClass().getName();
String dagFileName = getDAGFilename( dag, ".dag" );
mDone = false;
File dagFile = null;
Collection<File> result = new ArrayList(1);
if (ndi.dagJobs.isEmpty()) {
concreteDagEmpty( dagFileName, dag );
return result ;
} else {
dagFile = initializeDagFileWriter( dagFileName, ndi );
result.add( dagFile );
printDagString( this.getCategoryDAGManKnobs( mProps ) );
}
if( mProps.symlinkCommonLog() ){
String dir = mProps.getSubmitLogsDirectory();
File directory = null;
if( dir != null ){
directory = new File( dir );
if( !directory.exists() && !directory.mkdirs() ){
directory = null;
}
}
mLogger.log( "Condor logs directory to be used is " + directory,
LogManager.DEBUG_MESSAGE_LEVEL );
try{
File f = File.createTempFile( dag.dagInfo.nameOfADag + "-" +
dag.dagInfo.index,".log",
directory );
mTempLogFile=f.getAbsolutePath();
} catch (IOException ioe) {
mLogger.log( "Error while creating an empty log file in " +
"the local temp directory " + ioe.getMessage(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
mLogger.logEventStart( LoggingKeys.EVENT_PEGASUS_CODE_GENERATION,
LoggingKeys.DAX_ID,
dag.getAbstractWorkflowName(),
LogManager.DEBUG_MESSAGE_LEVEL);
Graph workflow = Adapter.convert( dag );
SUBDAXGenerator subdaxGen = new SUBDAXGenerator();
subdaxGen.initialize( mBag, dag, workflow, mDagWriter );
for( Iterator it = workflow.iterator(); it.hasNext(); ){
GraphNode node = ( GraphNode )it.next();
Job job = (Job)node.getContent();
if( !job.condorVariables.containsKey( Condor.PRIORITY_KEY ) &&
this.mAssignDefaultJobPriorities ){
int priority = getJobPriority( job, node.getDepth() );
job.condorVariables.construct( Condor.PRIORITY_KEY,
new Integer(priority).toString() );
StringBuffer sb = new StringBuffer();
sb.append( "Applying priority of " ).append( priority ).
append( " to " ).append( job.getID() );
mLogger.log( sb.toString(), LogManager.DEBUG_MESSAGE_LEVEL );
}
if ( job.getSiteHandle().equals( "stork" ) ) {
StringBuffer dagString = new StringBuffer();
dagString.append( "DATA " ).append( job.getName() ).append( " " );
dagString.append( job.getName() ).append( ".stork" );
printDagString( dagString.toString() );
storkGenerator.generateCode( dag, job );
}
else if( job instanceof DAGJob ){
DAGJob djob = ( DAGJob )job;
StringBuffer sb = new StringBuffer();
sb.append( Dagman.SUBDAG_EXTERNAL_KEY ).append( " " ).append( job.getName() ).
append( " " ).append( djob.getDAGFile() );
String dagDir = djob.getDirectory();
if( dagDir != null){
sb.append( " " ).append( Dagman.DIRECTORY_EXTERNAL_KEY ).
append( " " ).append( dagDir );
}
if( !job.dagmanVariables.containsKey( Dagman.CATEGORY_KEY ) ){
job.dagmanVariables.construct( Dagman.CATEGORY_KEY, DEFAULT_SUBDAG_CATEGORY_KEY );
}
printDagString( sb.toString() );
printDagString( job.dagmanVariables.toString( job.getName()) );
}
else{
if( job.typeRecursive() ){
Job daxJob = job;
job = subdaxGen.generateCode( job );
daxJob.setRemoteExecutable( job.getRemoteExecutable() );
daxJob.setArguments( job.getArguments() );
}
if( job != null ){
generateCode( dag, job );
}
printDagString( job.dagmanVariables.toString( job.getName()) );
}
mLogger.log("Written Submit file : " +
getFileBaseName(job), LogManager.DEBUG_MESSAGE_LEVEL);
}
mLogger.logEventCompletion( LogManager.DEBUG_MESSAGE_LEVEL );
this.writeDagFileTail( ndi );
mLogger.log("Written Dag File : " + dagFileName.toString(),
LogManager.DEBUG_MESSAGE_LEVEL);
if( mProps.symlinkCommonLog() ){
this.generateLogFileSymlink( this.getCondorLogInTmpDirectory(),
this.getCondorLogInSubmitDirectory( dag ) );
}
mLogger.log( "Writing out the DOT file ", LogManager.DEBUG_MESSAGE_LEVEL );
this.writeDOTFile( getDAGFilename( dag, ".dot"), dag );
this.writeOutNotifications( dag );
this.writeOutDAXReplicaStore( dag );
this.writeOutStampedeEvents( dag );
this.writeOutWorkflowMetrics(dag);
this.writeOutBraindump( dag );
mDone = true;
return result;
}
|
protected void handleReplay(WaybackRequest wbRequest,
HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws IOException, ServletException, WaybackException {
checkInterstitialRedirect(httpRequest,wbRequest);
String requestURL = wbRequest.getRequestUrl();
if (getSelfRedirectCanonicalizer() != null) {
try {
requestURL = getSelfRedirectCanonicalizer().urlStringToKey(requestURL);
} catch (IOException io) {
}
}
long requestMS = Timestamp.parseBefore(wbRequest.getReplayTimestamp()).getDate().getTime();
PerformanceLogger p = new PerformanceLogger("replay");
if (this.isTimestampSearch()) {
if (wbRequest.isAnyEmbeddedContext() || wbRequest.isIdentityContext()) {
wbRequest.setTimestampSearchKey(true);
}
}
SearchResults results = queryIndex(wbRequest);
p.queried();
if(!(results instanceof CaptureSearchResults)) {
throw new ResourceNotAvailableException("Bad results...");
}
CaptureSearchResults captureResults =
(CaptureSearchResults) results;
CaptureSearchResult closest = null;
closest =
getReplay().getClosest(wbRequest, captureResults);
CaptureSearchResult originalClosest = closest;
int counter = 0;
Set<String> skipFiles = null;
while (true) {
Resource httpHeadersResource = null;
Resource payloadResource = null;
boolean isRevisit = false;
try {
counter++;
if (closest == null) {
throw new ResourceNotAvailableException("Self-Redirect: No Closest Match Found");
}
closest.setClosest(true);
checkAnchorWindow(wbRequest,closest);
if (closest.isDuplicateDigest()) {
isRevisit = true;
if ((closest.getDuplicatePayloadFile() != null) &&
(skipFiles != null) && skipFiles.contains(closest.getDuplicatePayloadFile())) {
counter--;
throw new ResourceNotAvailableException("Revisit: Skipping already failed " + closest.getDuplicatePayloadFile());
} else if ((closest.getDuplicatePayloadFile() == null) && wbRequest.isTimestampSearchKey()) {
wbRequest.setTimestampSearchKey(false);
results = queryIndex(wbRequest);
captureResults = (CaptureSearchResults)results;
closest = getReplay().getClosest(wbRequest, captureResults);
originalClosest = closest;
continue;
}
if (EMPTY_VALUE.equals(closest.getFile())) {
closest.setFile(closest.getDuplicatePayloadFile());
closest.setOffset(closest.getDuplicatePayloadOffset());
httpHeadersResource = getResource(closest, skipFiles);
if (!closest.getCaptureTimestamp().equals(closest.getDuplicateDigestStoredTimestamp())) {
throwRedirect(wbRequest, httpResponse, captureResults, closest.getDuplicateDigestStoredTimestamp(), closest.getOriginalUrl());
}
payloadResource = httpHeadersResource;
} else {
httpHeadersResource = getResource(closest, skipFiles);
payloadResource = retrievePayloadForIdenticalContentRevisit(httpHeadersResource, captureResults, closest, skipFiles);
if (httpHeadersResource.getRecordLength() <= 0) {
httpHeadersResource.close();
httpHeadersResource = payloadResource;
}
}
} else {
httpHeadersResource = getResource(closest, skipFiles);
payloadResource = httpHeadersResource;
}
if (isSelfRedirect(httpHeadersResource, closest, wbRequest, requestURL)) {
LOGGER.info("Self-Redirect: Skipping " + closest.getCaptureTimestamp() + "/" + closest.getOriginalUrl());
closest = findNextClosest(closest, captureResults, requestMS);
continue;
}
if (!closest.isHttpSuccess() && (wbRequest.isAnyEmbeddedContext() || wbRequest.isBestLatestReplayRequest())) {
CaptureSearchResult nextClosest = closest;
while ((nextClosest = findNextClosest(nextClosest, captureResults, requestMS)) != null) {
if (nextClosest.isHttpRedirect()) {
closest = nextClosest;
} else if (nextClosest.isHttpSuccess()) {
closest = nextClosest;
break;
}
}
}
if (!closest.getCaptureTimestamp().equals(wbRequest.getReplayTimestamp())) {
throwRedirect(wbRequest, httpResponse, captureResults, closest.getCaptureTimestamp(), closest.getOriginalUrl());
}
p.retrieved();
ReplayRenderer renderer =
getReplay().getRenderer(wbRequest, closest, httpHeadersResource, payloadResource);
if (this.isEnableWarcFileHeader() && (warcFileHeader != null)) {
if (isRevisit && (closest.getDuplicatePayloadFile() != null)) {
httpResponse.addHeader(warcFileHeader, closest.getDuplicatePayloadFile());
} else {
httpResponse.addHeader(warcFileHeader, closest.getFile());
}
}
if (this.isEnableMemento()) {
MementoUtils.addMementoHeaders(httpResponse, captureResults, closest, wbRequest);
}
renderer.renderResource(httpRequest, httpResponse, wbRequest,
closest, httpHeadersResource, payloadResource, getUriConverter(), captureResults);
p.rendered();
p.write(wbRequest.getReplayTimestamp() + " " +
wbRequest.getRequestUrl());
break;
} catch (SpecificCaptureReplayException scre) {
CaptureSearchResult nextClosest = null;
if (counter > maxRedirectAttempts) {
LOGGER.info("LOADFAIL: Timeout: Too many retries, limited to " + maxRedirectAttempts);
} else if ((closest != null) && !wbRequest.isIdentityContext()) {
nextClosest = findNextClosest(closest, captureResults, requestMS);
}
String msg = null;
if (closest != null) {
msg = scre.getMessage() + " /" + closest.getCaptureTimestamp() + "/" + closest.getOriginalUrl();
} else {
msg = scre.getMessage() + " /" + wbRequest.getReplayTimestamp() + "/" + wbRequest.getRequestUrl();
}
if (nextClosest != null) {
if (isRevisit) {
if (scre.getDetails() != null) {
if (skipFiles == null) {
skipFiles = new HashSet<String>();
}
skipFiles.add(scre.getDetails());
}
}
if (msg.startsWith("Self-Redirect")) {
LOGGER.info("(" + counter + ")LOADFAIL-> " + msg + " -> " + nextClosest.getCaptureTimestamp());
} else {
LOGGER.warning("(" + counter + ")LOADFAIL-> " + msg + " -> " + nextClosest.getCaptureTimestamp());
}
closest = nextClosest;
} else if (wbRequest.isTimestampSearchKey()) {
wbRequest.setTimestampSearchKey(false);
results = queryIndex(wbRequest);
captureResults = (CaptureSearchResults)results;
closest = getReplay().getClosest(wbRequest, captureResults);
originalClosest = closest;
continue;
} else {
LOGGER.warning("(" + counter + ")LOADFAIL: " + msg);
scre.setCaptureContext(captureResults, closest);
throw scre;
}
} finally {
closeResources(payloadResource, httpHeadersResource);
}
}
}
| protected void handleReplay(WaybackRequest wbRequest,
HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws IOException, ServletException, WaybackException {
checkInterstitialRedirect(httpRequest,wbRequest);
String requestURL = wbRequest.getRequestUrl();
if (getSelfRedirectCanonicalizer() != null) {
try {
requestURL = getSelfRedirectCanonicalizer().urlStringToKey(requestURL);
} catch (IOException io) {
}
}
long requestMS = Timestamp.parseBefore(wbRequest.getReplayTimestamp()).getDate().getTime();
PerformanceLogger p = new PerformanceLogger("replay");
if (this.isTimestampSearch()) {
if (wbRequest.isAnyEmbeddedContext() || wbRequest.isIdentityContext()) {
wbRequest.setTimestampSearchKey(true);
}
}
SearchResults results = queryIndex(wbRequest);
p.queried();
if(!(results instanceof CaptureSearchResults)) {
throw new ResourceNotAvailableException("Bad results...");
}
CaptureSearchResults captureResults =
(CaptureSearchResults) results;
CaptureSearchResult closest = null;
closest =
getReplay().getClosest(wbRequest, captureResults);
CaptureSearchResult originalClosest = closest;
int counter = 0;
Set<String> skipFiles = null;
while (true) {
Resource httpHeadersResource = null;
Resource payloadResource = null;
boolean isRevisit = false;
try {
counter++;
if (closest == null) {
throw new ResourceNotAvailableException("Self-Redirect: No Closest Match Found");
}
closest.setClosest(true);
checkAnchorWindow(wbRequest,closest);
if (closest.isDuplicateDigest()) {
isRevisit = true;
if ((closest.getDuplicatePayloadFile() != null) &&
(skipFiles != null) && skipFiles.contains(closest.getDuplicatePayloadFile())) {
counter--;
throw new ResourceNotAvailableException("Revisit: Skipping already failed " + closest.getDuplicatePayloadFile());
} else if ((closest.getDuplicatePayloadFile() == null) && wbRequest.isTimestampSearchKey()) {
wbRequest.setTimestampSearchKey(false);
results = queryIndex(wbRequest);
captureResults = (CaptureSearchResults)results;
closest = getReplay().getClosest(wbRequest, captureResults);
originalClosest = closest;
continue;
}
if (EMPTY_VALUE.equals(closest.getFile())) {
closest.setFile(closest.getDuplicatePayloadFile());
closest.setOffset(closest.getDuplicatePayloadOffset());
httpHeadersResource = getResource(closest, skipFiles);
if (!closest.getCaptureTimestamp().equals(closest.getDuplicateDigestStoredTimestamp())) {
throwRedirect(wbRequest, httpResponse, captureResults, closest.getDuplicateDigestStoredTimestamp(), closest.getOriginalUrl());
}
payloadResource = httpHeadersResource;
} else {
httpHeadersResource = getResource(closest, skipFiles);
payloadResource = retrievePayloadForIdenticalContentRevisit(httpHeadersResource, captureResults, closest, skipFiles);
if (httpHeadersResource.getRecordLength() <= 0) {
httpHeadersResource.close();
httpHeadersResource = payloadResource;
}
}
} else {
httpHeadersResource = getResource(closest, skipFiles);
payloadResource = httpHeadersResource;
}
if (isSelfRedirect(httpHeadersResource, closest, wbRequest, requestURL)) {
LOGGER.info("Self-Redirect: Skipping " + closest.getCaptureTimestamp() + "/" + closest.getOriginalUrl());
closest = findNextClosest(closest, captureResults, requestMS);
continue;
}
if ((wbRequest.isAnyEmbeddedContext() && closest.isHttpError()) ||
(wbRequest.isBestLatestReplayRequest() && !closest.isHttpSuccess())) {
CaptureSearchResult nextClosest = closest;
while ((nextClosest = findNextClosest(nextClosest, captureResults, requestMS)) != null) {
if (nextClosest.isHttpRedirect()) {
closest = nextClosest;
} else if (nextClosest.isHttpSuccess()) {
closest = nextClosest;
break;
}
}
}
if (!closest.getCaptureTimestamp().equals(wbRequest.getReplayTimestamp())) {
throwRedirect(wbRequest, httpResponse, captureResults, closest.getCaptureTimestamp(), closest.getOriginalUrl());
}
p.retrieved();
ReplayRenderer renderer =
getReplay().getRenderer(wbRequest, closest, httpHeadersResource, payloadResource);
if (this.isEnableWarcFileHeader() && (warcFileHeader != null)) {
if (isRevisit && (closest.getDuplicatePayloadFile() != null)) {
httpResponse.addHeader(warcFileHeader, closest.getDuplicatePayloadFile());
} else {
httpResponse.addHeader(warcFileHeader, closest.getFile());
}
}
if (this.isEnableMemento()) {
MementoUtils.addMementoHeaders(httpResponse, captureResults, closest, wbRequest);
}
renderer.renderResource(httpRequest, httpResponse, wbRequest,
closest, httpHeadersResource, payloadResource, getUriConverter(), captureResults);
p.rendered();
p.write(wbRequest.getReplayTimestamp() + " " +
wbRequest.getRequestUrl());
break;
} catch (SpecificCaptureReplayException scre) {
CaptureSearchResult nextClosest = null;
if (counter > maxRedirectAttempts) {
LOGGER.info("LOADFAIL: Timeout: Too many retries, limited to " + maxRedirectAttempts);
} else if ((closest != null) && !wbRequest.isIdentityContext()) {
nextClosest = findNextClosest(closest, captureResults, requestMS);
}
String msg = null;
if (closest != null) {
msg = scre.getMessage() + " /" + closest.getCaptureTimestamp() + "/" + closest.getOriginalUrl();
} else {
msg = scre.getMessage() + " /" + wbRequest.getReplayTimestamp() + "/" + wbRequest.getRequestUrl();
}
if (nextClosest != null) {
if (isRevisit) {
if (scre.getDetails() != null) {
if (skipFiles == null) {
skipFiles = new HashSet<String>();
}
skipFiles.add(scre.getDetails());
}
}
if (msg.startsWith("Self-Redirect")) {
LOGGER.info("(" + counter + ")LOADFAIL-> " + msg + " -> " + nextClosest.getCaptureTimestamp());
} else {
LOGGER.warning("(" + counter + ")LOADFAIL-> " + msg + " -> " + nextClosest.getCaptureTimestamp());
}
closest = nextClosest;
} else if (wbRequest.isTimestampSearchKey()) {
wbRequest.setTimestampSearchKey(false);
results = queryIndex(wbRequest);
captureResults = (CaptureSearchResults)results;
closest = getReplay().getClosest(wbRequest, captureResults);
originalClosest = closest;
continue;
} else {
LOGGER.warning("(" + counter + ")LOADFAIL: " + msg);
scre.setCaptureContext(captureResults, closest);
throw scre;
}
} finally {
closeResources(payloadResource, httpHeadersResource);
}
}
}
|
public static Option[] configuration() throws Exception {
Option[] baseOptions = Helper.getDefaultOptions();
if (DEBUG) {
baseOptions = combine(baseOptions, Helper.activateDebugging(DEBUG_PORT));
}
return combine(
baseOptions,
Helper.loadKarafStandardFeatures("config", "ssh", "management", "wrapper", "obr"),
Helper.setLogLevel(LOG_LEVEL),
mavenBundle(maven().groupId("org.apache.aries").artifactId("org.apache.aries.util")
.versionAsInProject()),
mavenBundle(maven().groupId("org.apache.aries.proxy").artifactId("org.apache.aries.proxy")
.versionAsInProject()),
mavenBundle(maven().groupId("org.apache.aries.blueprint").artifactId("org.apache.aries.blueprint")
.versionAsInProject()),
scanFeatures(maven().groupId("org.openengsb").artifactId("openengsb").type("xml").classifier("features")
.versionAsInProject(), "openengsb-core"), workingDirectory(getWorkingDirectory()),
vmOption("-Dorg.osgi.framework.system.packages.extra=sun.reflect"),
vmOption("-Dorg.osgi.service.http.port=8090"), waitForFrameworkStartup(),
mavenBundle(maven().groupId("org.openengsb.wrapped").artifactId("net.sourceforge.htmlunit-all")
.versionAsInProject()), felix());
}
| public static Option[] configuration() throws Exception {
Option[] baseOptions = Helper.getDefaultOptions();
if (DEBUG) {
baseOptions = combine(baseOptions, Helper.activateDebugging(DEBUG_PORT));
}
return combine(
baseOptions,
Helper.loadKarafStandardFeatures("config", "ssh", "management", "wrapper", "obr"),
Helper.setLogLevel(LOG_LEVEL),
mavenBundle(maven().groupId("org.apache.aries").artifactId("org.apache.aries.util")
.versionAsInProject()),
mavenBundle(maven().groupId("org.apache.aries.proxy").artifactId("org.apache.aries.proxy")
.versionAsInProject()),
mavenBundle(maven().groupId("org.apache.aries.blueprint").artifactId("org.apache.aries.blueprint")
.versionAsInProject()),
scanFeatures(maven().groupId("org.openengsb").artifactId("openengsb").type("xml").classifier("features")
.versionAsInProject(), "openengsb-ui-admin"), workingDirectory(getWorkingDirectory()),
vmOption("-Dorg.osgi.framework.system.packages.extra=sun.reflect"),
vmOption("-Dorg.osgi.service.http.port=8090"), waitForFrameworkStartup(),
mavenBundle(maven().groupId("org.openengsb.wrapped").artifactId("net.sourceforge.htmlunit-all")
.versionAsInProject()), felix());
}
|
public void setUp() throws JDOMException, IOException {
final String tikaConfigFilename = "target/classes/config.xml";
final String log4jPropertiesFilename = "target/classes/log4j/log4j.properties";
testFilesBaseDir = new File("src/test/resources/test-documents");
tc = new TikaConfig(tikaConfigFilename);
TikaLogger.setLoggerConfigFile(log4jPropertiesFilename);
}
| public void setUp() throws JDOMException, IOException {
final String tikaConfigFilename = "target/classes/tika-config.xml";
final String log4jPropertiesFilename = "target/classes/log4j/log4j.properties";
testFilesBaseDir = new File("src/test/resources/test-documents");
tc = new TikaConfig(tikaConfigFilename);
TikaLogger.setLoggerConfigFile(log4jPropertiesFilename);
}
|
public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
final String method = request.getMethod();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
try {
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
} catch(IllegalArgumentException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, e);
}
if(applicationId == null && applicationName == null) {
javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI();
final String host = sipRequestUri.getHost();
final int port = sipRequestUri.getPort();
final String transport = JainSipUtils.findTransport(request);
final boolean isAnotherDomain = sipApplicationDispatcher.isExternal(host, port, transport);
if(isAnotherDomain) {
if(logger.isDebugEnabled()) {
logger.debug("No application found to handle this request " + request + " with the following popped route header " + poppedRouteHeader + " so forwarding statelessly to the outside since it is not targeted at the container");
}
try {
sipProvider.sendRequest(request);
} catch (SipException e) {
throw new DispatcherException("cannot proxy statelessly outside of the container the following request " + request, e);
}
return;
} else {
if(Request.ACK.equals(method)) {
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
} else {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request);
}
}
}
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request);
}
}
final SipManager sipManager = (SipManager)sipContext.getManager();
final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
}
if(sipApplicationSession == null) {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ", it may already have been invalidated or timed out");
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
", it may already have been invalidated or timed out");
}
}
}
if(StaticServiceHolder.sipStandardService.isHttpFollowsSip()) {
String jvmRoute = StaticServiceHolder.sipStandardService.getJvmRoute();
if(jvmRoute == null) {
sipApplicationSession.setJvmRoute(jvmRoute);
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ", it may already have been invalidated or timed out");
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session to this subsequent request " + request +
", it may already have been invalidated or timed out");
}
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSession(sipSession);
if(request.getMethod().equals(Request.ACK)) {
sipSession.setRequestsPending(sipSession.getRequestsPending() - 1);
} else if(request.getMethod().equals(Request.INVITE)){
if(logger.isDebugEnabled()) {
logger.debug("INVITE requests pending " + sipSession.getRequestsPending());
}
if(StaticServiceHolder.sipStandardService.isDialogPendingRequestChecking() &&
sipSession.getProxy() == null && sipSession.getRequestsPending() > 0) {
try {
sipServletRequest.createResponse(491).send();
return;
} catch (IOException e) {
logger.error("Problem sending 491 response");
}
}
sipSession.setRequestsPending(sipSession.getRequestsPending() + 1);
}
final SubsequentDispatchTask dispatchTask = new SubsequentDispatchTask(sipServletRequest, sipProvider);
sipContext.enterSipApp(sipApplicationSession, sipSession);
if(sipSession.getProxy() == null) {
boolean isValid = sipSession.validateCSeq(sipServletRequest);
if(!isValid) {
sipContext.exitSipApp(sipApplicationSession, sipSession);
return;
}
}
if(sipApplicationDispatcher.isBypassRequestExecutor() || ConcurrencyControlMode.Transaction.equals((sipContext.getConcurrencyControlMode()))) {
dispatchTask.dispatchAndHandleExceptions();
} else {
if(logger.isDebugEnabled()) {
logger.debug("We are just before executor with sipAppSession=" + sipApplicationSession + " and sipSession=" + sipSession + " for " + sipServletMessage);
}
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
if(logger.isDebugEnabled()) {
logger.debug("We are just after executor with sipAppSession=" + sipApplicationSession + " and sipSession=" + sipSession + " for " + sipServletMessage);
}
}
}
| public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
final String method = request.getMethod();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
try {
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
} catch(IllegalArgumentException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, e);
}
if(applicationId == null && applicationName == null) {
javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI();
final String host = sipRequestUri.getHost();
final int port = sipRequestUri.getPort();
final String transport = JainSipUtils.findTransport(request);
final boolean isAnotherDomain = sipApplicationDispatcher.isExternal(host, port, transport);
if(isAnotherDomain) {
if(logger.isDebugEnabled()) {
logger.debug("No application found to handle this request " + request + " with the following popped route header " + poppedRouteHeader + " so forwarding statelessly to the outside since it is not targeted at the container");
}
try {
sipProvider.sendRequest(request);
} catch (SipException e) {
throw new DispatcherException("cannot proxy statelessly outside of the container the following request " + request, e);
}
return;
} else {
if(Request.ACK.equals(method)) {
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
} else {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request);
}
}
}
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request);
}
}
final SipManager sipManager = (SipManager)sipContext.getManager();
final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
}
if(sipApplicationSession == null) {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.CALL_OR_TRANSACTION_DOES_NOT_EXIST, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ", it may already have been invalidated or timed out");
} else {
throw new DispatcherException(Response.CALL_OR_TRANSACTION_DOES_NOT_EXIST, "Cannot find the corresponding sip application session to this subsequent request " + request +
", it may already have been invalidated or timed out");
}
}
}
if(StaticServiceHolder.sipStandardService.isHttpFollowsSip()) {
String jvmRoute = StaticServiceHolder.sipStandardService.getJvmRoute();
if(jvmRoute == null) {
sipApplicationSession.setJvmRoute(jvmRoute);
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.CALL_OR_TRANSACTION_DOES_NOT_EXIST, "Cannot find the corresponding sip session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ", it may already have been invalidated or timed out");
} else {
throw new DispatcherException(Response.CALL_OR_TRANSACTION_DOES_NOT_EXIST, "Cannot find the corresponding sip session to this subsequent request " + request +
", it may already have been invalidated or timed out");
}
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSession(sipSession);
if(request.getMethod().equals(Request.ACK)) {
sipSession.setRequestsPending(sipSession.getRequestsPending() - 1);
} else if(request.getMethod().equals(Request.INVITE)){
if(logger.isDebugEnabled()) {
logger.debug("INVITE requests pending " + sipSession.getRequestsPending());
}
if(StaticServiceHolder.sipStandardService.isDialogPendingRequestChecking() &&
sipSession.getProxy() == null && sipSession.getRequestsPending() > 0) {
try {
sipServletRequest.createResponse(491).send();
return;
} catch (IOException e) {
logger.error("Problem sending 491 response");
}
}
sipSession.setRequestsPending(sipSession.getRequestsPending() + 1);
}
final SubsequentDispatchTask dispatchTask = new SubsequentDispatchTask(sipServletRequest, sipProvider);
sipContext.enterSipApp(sipApplicationSession, sipSession);
if(sipSession.getProxy() == null) {
boolean isValid = sipSession.validateCSeq(sipServletRequest);
if(!isValid) {
sipContext.exitSipApp(sipApplicationSession, sipSession);
return;
}
}
if(sipApplicationDispatcher.isBypassRequestExecutor() || ConcurrencyControlMode.Transaction.equals((sipContext.getConcurrencyControlMode()))) {
dispatchTask.dispatchAndHandleExceptions();
} else {
if(logger.isDebugEnabled()) {
logger.debug("We are just before executor with sipAppSession=" + sipApplicationSession + " and sipSession=" + sipSession + " for " + sipServletMessage);
}
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
if(logger.isDebugEnabled()) {
logger.debug("We are just after executor with sipAppSession=" + sipApplicationSession + " and sipSession=" + sipSession + " for " + sipServletMessage);
}
}
}
|
public Point2D query(final int idx) {
int index = idx +1;
double percent = (double) index /(double) elementCount;
double angle = Math.toRadians((percent *360) -90 + startAngle);
double radius = this.radius;
if (radius <= 0) {
double c = elementCount * size;
radius = c/(2 * Math.PI);
}
double x,y;
double xRadius = radius;
double yRadius = radius * ratio;
x = xRadius * Math.cos(angle) + origin.getX();
y = yRadius * Math.sin(angle) + origin.getY();
return new Point2D.Double(x,y);
}
| public Point2D query(final int idx) {
int index = idx +1;
double percent = (double) index /(double) (elementCount +1);
double angle = Math.toRadians((percent *360) -90 + startAngle);
double radius = this.radius;
if (radius <= 0) {
double c = (elementCount+1) * size;
radius = c/(2 * Math.PI);
}
double x,y;
double xRadius = radius;
double yRadius = radius * ratio;
x = xRadius * Math.cos(angle) + origin.getX();
y = yRadius * Math.sin(angle) + origin.getY();
return new Point2D.Double(x,y);
}
|
public static void wrapMain(String name, String[] args, final int minHeapSizeMegs) {
if(args.length > 0 && args[0].equals(NO_REEXEC)) {
args[0] = "";
return;
}
Thread t = Thread.currentThread();
azzert("main".equals(t.getName()));
StackTraceElement[] stack = t.getStackTrace();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName();
boolean needsReExecing = false;
int newHeapSizeMegs = (int) ((Runtime.getRuntime().maxMemory()/1024)/1024);
if(newHeapSizeMegs < minHeapSizeMegs) {
newHeapSizeMegs = minHeapSizeMegs;
needsReExecing = true;
}
File jar = Utils.getJarFile();
String jvm = "java";
if(System.getProperty("os.name").startsWith("Windows")) {
if(name == null) {
if(jar == null) {
name = mainClass;
} else {
name = jar.getName();
if(name.toLowerCase().endsWith(".jar")) {
name = name.substring(0, name.length() - ".jar".length());
}
}
}
if(!name.toLowerCase().endsWith(".exe")) {
name = name + ".exe";
}
File jre = new File(System.getProperty("java.home"));
File java = new File(jre + "\\bin", "java.exe");
File launcherDir = new File(jre + "\\temp-launcher");
launcherDir.mkdir();
if(launcherDir.isDirectory()) {
File newLauncher = new File(launcherDir, name);
if(newLauncher.exists()) {
jvm = "\"" + newLauncher.getPath() + "\"";
} else {
try {
Utils.copyFile(java, newLauncher);
jvm = "\"" + newLauncher.getPath() + "\"";
needsReExecing = true;
} catch (IOException e) {
l.log(Level.WARNING, "Couldn't copy java.exe", e);
}
}
}
}
String classpath = System.getProperty("java.class.path");
ArrayList<String> jvmArgs = new ArrayList<String>();
jvmArgs.add(jvm);
jvmArgs.add("-Xmx" + newHeapSizeMegs + "m");
jvmArgs.add("-classpath");
jvmArgs.add(classpath);
jvmArgs.add(mainClass);
jvmArgs.add(NO_REEXEC);
jvmArgs.addAll(Arrays.asList(args));
try {
l.info("Rexecing with " + jvmArgs);
ProcessBuilder pb = new ProcessBuilder(jvmArgs);
pb.redirectErrorStream(true);
final Process p = pb.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
p.destroy();
};
});
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
byte[] buff = new byte[1024];
int read;
while((read = in.read(buff)) >= 0 ) {
System.out.write(buff, 0, read);
}
System.exit(0);
} catch(IOException e) {
l.log(Level.WARNING, "", e);
}
}
| public static void wrapMain(String name, String[] args, final int minHeapSizeMegs) {
if(args.length > 0 && args[0].equals(NO_REEXEC)) {
args[0] = "";
return;
}
Thread t = Thread.currentThread();
azzert("main".equals(t.getName()));
StackTraceElement[] stack = t.getStackTrace();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName();
boolean needsReExecing = false;
int newHeapSizeMegs = (int) ((Runtime.getRuntime().maxMemory()/1024)/1024);
if(newHeapSizeMegs < minHeapSizeMegs) {
newHeapSizeMegs = minHeapSizeMegs;
needsReExecing = true;
}
File jar = Utils.getJarFile();
String jvm = "java";
if(System.getProperty("os.name").startsWith("Windows")) {
if(name == null) {
if(jar == null) {
name = mainClass;
} else {
name = jar.getName();
if(name.toLowerCase().endsWith(".jar")) {
name = name.substring(0, name.length() - ".jar".length());
}
}
}
if(!name.toLowerCase().endsWith(".exe")) {
name = name + ".exe";
}
File jre = new File(System.getProperty("java.home"));
File java = new File(jre + "\\bin", "java.exe");
File launcherDir = new File(jre + "\\temp-launcher");
launcherDir.mkdir();
if(launcherDir.isDirectory()) {
File newLauncher = new File(launcherDir, name);
if(newLauncher.exists()) {
jvm = "\"" + newLauncher.getPath() + "\"";
} else {
try {
Utils.copyFile(java, newLauncher);
jvm = "\"" + newLauncher.getPath() + "\"";
needsReExecing = true;
} catch (IOException e) {
l.log(Level.WARNING, "Couldn't copy java.exe", e);
}
}
}
}
if(!needsReExecing) {
return;
}
String classpath = System.getProperty("java.class.path");
ArrayList<String> jvmArgs = new ArrayList<String>();
jvmArgs.add(jvm);
jvmArgs.add("-Xmx" + newHeapSizeMegs + "m");
jvmArgs.add("-classpath");
jvmArgs.add(classpath);
jvmArgs.add(mainClass);
jvmArgs.add(NO_REEXEC);
jvmArgs.addAll(Arrays.asList(args));
try {
l.info("Re-execing with " + jvmArgs);
ProcessBuilder pb = new ProcessBuilder(jvmArgs);
pb.redirectErrorStream(true);
final Process p = pb.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
p.destroy();
};
});
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
byte[] buff = new byte[1024];
int read;
while((read = in.read(buff)) >= 0 ) {
System.out.write(buff, 0, read);
}
System.exit(0);
} catch(IOException e) {
l.log(Level.WARNING, "", e);
}
}
|
public @Nonnull List<RuleError> validate() {
List<RuleError> ret = Lists.newLinkedList();
if (type == null) {
ret.add(new RuleError("type", "Missing or invalid type."));
}
if (owner == null) {
ret.add(new RuleError("owner", "Missing rule owner."));
}
if (StringUtils.isBlank(pattern)) {
ret.add(new RuleError("pattern", "Pattern cannot be empty."));
} else if (pattern.contains("/")) {
ret.add(new RuleError("pattern", "Pattern cannot contain slashes (/)."));
}
else if ((type == RuleType.EXT_EQ) &&
pattern.contains(".")) {
ret.add(new RuleError("pattern", "Extensions cannot contain periods."));
}
if (StringUtils.isBlank(dest)) {
ret.add(new RuleError("dest", "Destination directory cannot be empty."));
} else if (! dest.startsWith("/")) {
ret.add(new RuleError("dest", "Destination directory must start with a slash (/)."));
}
return ret;
}
| public @Nonnull List<RuleError> validate() {
List<RuleError> ret = Lists.newLinkedList();
if (type == null) {
ret.add(new RuleError("type", "Missing or invalid type."));
}
if (owner == null) {
ret.add(new RuleError("owner", "Missing owner."));
}
if (StringUtils.isBlank(pattern)) {
ret.add(new RuleError("pattern", "Can't be empty."));
} else if (pattern.contains("/")) {
ret.add(new RuleError("pattern", "Can't contain slashes (/)."));
}
else if ((type == RuleType.EXT_EQ) &&
pattern.contains(".")) {
ret.add(new RuleError("pattern", "Can't contain periods."));
}
if (StringUtils.isBlank(dest)) {
ret.add(new RuleError("dest", "Can't be empty."));
} else if (! dest.startsWith("/")) {
ret.add(new RuleError("dest", "Must start with a slash (/)."));
}
return ret;
}
|
public static void main(String[] args) {
System.out.println("Progetto di Ingegneria del Software\n");
System.out.println("Autore: Giovanni Dini");
System.out.println("Matricola: 232274");
System.out.println("Email: [email protected]\n");
System.out.println("Operazioni disponibili:");
System.out.println("- Inserire l'URL da cui cominciare l'analisi \n- Digitare \"file\" se ");
System.out.print("si desidera leggere la workload dal file apposito (workload.csv)");
System.out.println("- Digitare \"restart\" se si desidera riprendere una vecchia sessione :");
System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):\n\n");
Scanner user_input = new Scanner(System.in);
String first_url;
first_url = user_input.next();
while ("help".equals(first_url)) {
System.out.print("\n\n*----------*\n\nCosa è e a cosa serve questo software?");
System.out.print("\n\nQuesto software genera un sistema di crawler che girano per la rete, ");
System.out.print("raccogliendo indirizzi email e salvandoli per un successivo utilizzo.");
System.out.print("\n\n*----------*\n\nCome si utilizza?");
System.out.print("\n\nIl funzionamento è molto semplice: è sufficiente inserire un URL ");
System.out.print("(nel formato http://www.sito.com) e il programma lo analizzerà, raccogliendo ");
System.out.print("automaticamente gli indirizzi dei link che troverà e analizzando successivamente ");
System.out.print("anche quelli. Tutti gli indirizzi email trovati durante l'analisi sono salvati per ");
System.out.print("un successivo utilizzo. ");
System.out.print("\n\n*----------*\n\nQuale è l'utilità pratica di questo software?");
System.out.print("\n\nIn questa versione il software si limita a raccogliere indirizzi email ");
System.out.print("(si ricorda che lo spam non è una pratica legale), ma con poche e semplici ");
System.out.print("modifiche è possibile fargli raccogliere e analizzare praticamente tutto ciò che ");
System.out.print("può essere contenuto in una pagina web. Vista la natura di questo software ");
System.out.print("(realizzato per un progetto d'esame), è da considerarsi un puro esercizio, ma che ");
System.out.print("con poche modifiche può avere scopi decisamente più utili.");
System.out.print("\n\n*----------*\n\nQuali comode funzionalità offre questo programma?");
System.out.print("\n\n-Gli URL da visitare possono essere passati anche tramite file (workload.csv).");
System.out.print("\n-Gli URL già visitati sono salvati in un file di testo e riletti ogni volta che ");
System.out.print("il programma viene avviato, per evitare di ripetere lavoro già fatto in precedenza.");
System.out.print("\n-Stessa cosa viene fatta per gli indirizzi email.");
System.out.print("\n-I parametri di configurazione del programma sono contenuti in un semplice file di ");
System.out.print("testo e comprendono il numero massimo di thread crawlers che operano in contemporanea ");
System.out.print("e la profondità dell'analisi (espressa nel numero massimo di URL da analizzare.");
System.out.print("\n\n*----------*\n\nIl programma è coperto da copyright?");
System.out.print("\n\nLa licenza con cui viene fornito questo software è la Attribution-NonCommercial-ShareAlike ");
System.out.print("3.0 Unported (CC BY-NC-SA 3.0). E' possibile modificare questo software e ridistribuirlo ");
System.out.print("solo riportandone l'autore originale (Giovanni Dini). Non è possibile derivarne prodotti ");
System.out.print("commerciali. Ogni derivazione dovrà essere distribuita sotto la stessa licenza.\n");
System.out.println("\nInserire l'URL da cui cominciare l'analisi, oppure digitare \"file\" se ");
System.out.println("si desidera leggere la workload dal file apposito ");
System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):\n\n");
first_url = user_input.next();
}
ArrayList workload = new ArrayList();
ArrayList visited = new ArrayList();
ArrayList emails = new ArrayList();
ArrayList param = new ArrayList();
if ("exit".equals(first_url)){
return;
}
if ("file".equals(first_url)) {
File workloadFile = new File ("workload.csv");
if(!workloadFile.exists()) {
try {
workloadFile.createNewFile();
System.out.println("\n\nIl file non esisteva. Aggiungere manualmente il primo URL da analizzare: ");
first_url = user_input.next();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Devo leggere il file.");
Organizer.fileWorkload(workloadFile, workload);
first_url = (String) workload.get(0);
System.out.println("Devo analizzare questo: "+first_url);
}
if ("restart".equals(first_url)) {
File lastWorkload = new File ("nextWorkload.csv");
if(!lastWorkload.exists()) {
System.out.println("\n\nIl file non esisteva. Aggiungere manualmente il primo URL da analizzare: ");
first_url = user_input.next();
}
System.out.println("Riprendo il lavoro dall'ultima sessione.");
Organizer.fileWorkload(lastWorkload, workload);
}
File emailsFile = new File("emails.csv");
File visitedFile = new File ("visited.csv");
if(!emailsFile.exists()) {
try {
emailsFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(!visitedFile.exists()) {
try {
visitedFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
Organizer.fileEmails(emailsFile, emails);
Organizer.fileVisited(visitedFile, visited);
workload.add(first_url);
int numCrawlers;
int maxURLS;
File paramFile = new File ("preferences.cfg");
if(!paramFile.exists()) {
System.out.println("Il file di configurazione non esiste. Saranno utilizzati i parametri di default: ");
System.out.println("Numero di crawlers in contemporanea: 5.\nProfondità dell'analisi: 30 URLs.");
numCrawlers = 5;
maxURLS = 30;
} else {
Organizer.fileParam(paramFile, param);
numCrawlers = (Integer) param.get(0);
maxURLS = (Integer) param.get(1);
System.out.println("\nTrovato file di configurazione. Il programma avrà questi parametri: ");
System.out.println("-Numero di crawlers in contemporanea: "+numCrawlers);
System.out.println("-Profondità dell'analisi: "+maxURLS+" URLS\n");
}
Runnable manager = new Manager(workload, visited, emails, numCrawlers, maxURLS);
Thread m = new Thread(manager);
m.start();
m.setName("Manager");
try {
m.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Runnable organizer = new Organizer(visited, emails);
Thread o = new Thread(organizer);
o.start();
o.setName("Organizer");
try {
o.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("L'analisi è stata completata. ");
System.out.println("Ci sono ancora "+workload.size()+" URL nella workload.");
System.out.println("Vuoi che siano scritti in un file in modo da poter proseguire l'analisi successivamente? si/no");
String answer = user_input.next();
if ("si".equals(answer)){
File finalWorkload = new File("nextWorkload.csv");
Organizer.finalWorkload(finalWorkload, workload);
}
| public static void main(String[] args) {
System.out.println("Progetto di Ingegneria del Software\n");
System.out.println("Autore: Giovanni Dini");
System.out.println("Matricola: 232274");
System.out.println("Email: [email protected]\n");
System.out.println("Operazioni disponibili:");
System.out.println("- Inserire l'URL da cui cominciare l'analisi \n- Digitare \"file\" se ");
System.out.print("si desidera leggere la workload dal file apposito (workload.csv)");
System.out.println("- Digitare \"restart\" se si desidera riprendere una vecchia sessione :");
System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):");
Scanner user_input = new Scanner(System.in);
String first_url;
first_url = user_input.next();
while ("help".equals(first_url)) {
System.out.print("\n\n*----------*\n\nCosa è e a cosa serve questo software?");
System.out.print("\n\nQuesto software genera un sistema di crawler che girano per la rete, ");
System.out.print("raccogliendo indirizzi email e salvandoli per un successivo utilizzo.");
System.out.print("\n\n*----------*\n\nCome si utilizza?");
System.out.print("\n\nIl funzionamento è molto semplice: è sufficiente inserire un URL ");
System.out.print("(nel formato http://www.sito.com) e il programma lo analizzerà, raccogliendo ");
System.out.print("automaticamente gli indirizzi dei link che troverà e analizzando successivamente ");
System.out.print("anche quelli. Tutti gli indirizzi email trovati durante l'analisi sono salvati per ");
System.out.print("un successivo utilizzo. ");
System.out.print("\n\n*----------*\n\nQuale è l'utilità pratica di questo software?");
System.out.print("\n\nIn questa versione il software si limita a raccogliere indirizzi email ");
System.out.print("(si ricorda che lo spam non è una pratica legale), ma con poche e semplici ");
System.out.print("modifiche è possibile fargli raccogliere e analizzare praticamente tutto ciò che ");
System.out.print("può essere contenuto in una pagina web. Vista la natura di questo software ");
System.out.print("(realizzato per un progetto d'esame), è da considerarsi un puro esercizio, ma che ");
System.out.print("con poche modifiche può avere scopi decisamente più utili.");
System.out.print("\n\n*----------*\n\nQuali comode funzionalità offre questo programma?");
System.out.print("\n\n-Gli URL da visitare possono essere passati anche tramite file (workload.csv).");
System.out.print("\n-Gli URL già visitati sono salvati in un file di testo e riletti ogni volta che ");
System.out.print("il programma viene avviato, per evitare di ripetere lavoro già fatto in precedenza.");
System.out.print("\n-Stessa cosa viene fatta per gli indirizzi email.");
System.out.print("\n-I parametri di configurazione del programma sono contenuti in un semplice file di ");
System.out.print("testo e comprendono il numero massimo di thread crawlers che operano in contemporanea ");
System.out.print("e la profondità dell'analisi (espressa nel numero massimo di URL da analizzare.");
System.out.print("\n\n*----------*\n\nIl programma è coperto da copyright?");
System.out.print("\n\nLa licenza con cui viene fornito questo software è la Attribution-NonCommercial-ShareAlike ");
System.out.print("3.0 Unported (CC BY-NC-SA 3.0). E' possibile modificare questo software e ridistribuirlo ");
System.out.print("solo riportandone l'autore originale (Giovanni Dini). Non è possibile derivarne prodotti ");
System.out.print("commerciali. Ogni derivazione dovrà essere distribuita sotto la stessa licenza.\n");
System.out.println("\nInserire l'URL da cui cominciare l'analisi, oppure digitare \"file\" se ");
System.out.println("si desidera leggere la workload dal file apposito ");
System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):");
first_url = user_input.next();
}
ArrayList workload = new ArrayList();
ArrayList visited = new ArrayList();
ArrayList emails = new ArrayList();
ArrayList param = new ArrayList();
if ("exit".equals(first_url)){
return;
}
if ("file".equals(first_url)) {
File workloadFile = new File ("workload.csv");
if(!workloadFile.exists()) {
try {
workloadFile.createNewFile();
System.out.println("\n\nIl file non esisteva. Aggiungere manualmente il primo URL da analizzare: ");
first_url = user_input.next();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Devo leggere il file.");
Organizer.fileWorkload(workloadFile, workload);
first_url = (String) workload.get(0);
System.out.println("Devo analizzare questo: "+first_url);
}
if ("restart".equals(first_url)) {
File lastWorkload = new File ("nextWorkload.csv");
if(!lastWorkload.exists()) {
System.out.println("\nIl file nextWorkload.csv non esiste. Aggiungere manualmente il primo URL da analizzare:");
first_url = user_input.next();
} else {
System.out.println("Riprendo il lavoro dall'ultima sessione.");
Organizer.fileWorkload(lastWorkload, workload);
first_url = (String) workload.get(0);
System.out.println("Devo analizzare questo: "+first_url);
}
}
File emailsFile = new File("emails.csv");
File visitedFile = new File ("visited.csv");
if(!emailsFile.exists()) {
try {
emailsFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(!visitedFile.exists()) {
try {
visitedFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
Organizer.fileEmails(emailsFile, emails);
Organizer.fileVisited(visitedFile, visited);
workload.add(first_url);
int numCrawlers;
int maxURLS;
File paramFile = new File ("preferences.cfg");
if(!paramFile.exists()) {
System.out.println("Il file di configurazione non esiste. Saranno utilizzati i parametri di default: ");
System.out.println("Numero di crawlers in contemporanea: 5.\nProfondità dell'analisi: 30 URLs.");
numCrawlers = 5;
maxURLS = 30;
} else {
Organizer.fileParam(paramFile, param);
numCrawlers = (Integer) param.get(0);
maxURLS = (Integer) param.get(1);
System.out.println("\nTrovato file di configurazione. Il programma avrà questi parametri: ");
System.out.println("-Numero di crawlers in contemporanea: "+numCrawlers);
System.out.println("-Profondità dell'analisi: "+maxURLS+" URLS\n");
}
Runnable manager = new Manager(workload, visited, emails, numCrawlers, maxURLS);
Thread m = new Thread(manager);
m.start();
m.setName("Manager");
try {
m.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Runnable organizer = new Organizer(visited, emails);
Thread o = new Thread(organizer);
o.start();
o.setName("Organizer");
try {
o.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("L'analisi è stata completata. ");
System.out.println("Ci sono ancora "+workload.size()+" URL nella workload.");
System.out.println("Vuoi che siano scritti in un file in modo da poter proseguire l'analisi successivamente? si/no");
String answer = user_input.next();
if ("si".equals(answer)){
File finalWorkload = new File("nextWorkload.csv");
Organizer.finalWorkload(finalWorkload, workload);
}
|
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionErrors errors = new ActionErrors();
CommonUtil util = new CommonUtil();
ActionForward forward = null;
HttpSession session = request.getSession();
LoginForm loginForm =
(LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT);
String userEmail = util.checkUserLogin(session);
if ((loginForm == null) && (userEmail == null))
{
log
.debug("||||Failure|No Session or User Object Forwarding to the Login Page||");
return mapping.findForward(ForwardConstants.LOGIN_PAGE);
}
util.clearSessionData(session);
session.setAttribute(DisplayConstants.CURRENT_TABLE_ID,
DisplayConstants.HOME_ID);
if (userEmail != null)
{
boolean loggedIn = true;
loginForm = new LoginForm();
String username = userEmail;
loginForm.setLoginId(username);
LabViewerAuthorizationHelper authHelper = new LabViewerAuthorizationHelper();
Set<SuiteRole> userRoles = null;
try
{
userRoles = authHelper.getUserRoles(username);
if (!(userRoles.contains(SuiteRole.SYSTEM_ADMINISTRATOR) ||
userRoles.contains(SuiteRole.USER_ADMINISTRATOR) ||
userRoles.contains(SuiteRole.LAB_DATA_USER)))
{
log.error("User authenticated but not authorized");
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(
DisplayConstants.ERROR_ID,
"User does not have permissions for this application"));
saveErrors(request, errors);
loggedIn = false;
forward = mapping.findForward(ForwardConstants.LOGIN_FAILURE);
}
}
catch (SuiteAuthorizationAccessException e)
{
log.error("User authenticated but not authorized");
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(
DisplayConstants.ERROR_ID,
"User does not have permissions for this application"));
saveErrors(request, errors);
loggedIn = false;
forward = mapping.findForward(ForwardConstants.LOGIN_FAILURE);
}
if (loggedIn)
{
loginForm.setGridProxy("test");
util.getProperties(session);
session.setAttribute(DisplayConstants.LOGIN_OBJECT, loginForm);
session.setAttribute(DisplayConstants.CURRENT_TABLE_ID,
DisplayConstants.HOME_ID);
session.setAttribute(DisplayConstants.USER_ROLES, userRoles);
if (session.getAttribute("HOT_LINK") == "true")
{
LabActivitiesSearchForm labFm =
(LabActivitiesSearchForm) session
.getAttribute("CURRENT_FORM");
session.setAttribute("CURRENT_FORM", labFm);
return (mapping
.findForward(ForwardConstants.LOGIN_SUCCESS_HOTLINK));
}
forward = mapping.findForward(ForwardConstants.LOGIN_SUCCESS);
}
}
return forward;
}
| public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionErrors errors = new ActionErrors();
CommonUtil util = new CommonUtil();
ActionForward forward = null;
HttpSession session = request.getSession();
LoginForm loginForm =
(LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT);
String userEmail = util.checkUserLogin(session);
if ((loginForm == null) && (userEmail == null))
{
log
.debug("||||Failure|No Session or User Object Forwarding to the Login Page||");
return mapping.findForward(ForwardConstants.LOGIN_PAGE);
}
util.clearSessionData(session);
session.setAttribute(DisplayConstants.CURRENT_TABLE_ID,
DisplayConstants.HOME_ID);
if (userEmail != null)
{
boolean loggedIn = true;
loginForm = new LoginForm();
String username = userEmail;
loginForm.setLoginId(username);
LabViewerAuthorizationHelper authHelper = new LabViewerAuthorizationHelper();
Set<SuiteRole> userRoles = null;
try
{
userRoles = authHelper.getUserRoles(username);
if (!(userRoles.contains(SuiteRole.SYSTEM_ADMINISTRATOR) ||
userRoles.contains(SuiteRole.USER_ADMINISTRATOR) ||
userRoles.contains(SuiteRole.LAB_DATA_USER)))
{
log.error("User not authorized for LabViewer");
loggedIn = false;
forward = mapping.findForward(ForwardConstants.LOGIN_FAILURE);
}
}
catch (SuiteAuthorizationAccessException e)
{
log.error("Error authorizing user for LabViewer: ", e);
loggedIn = false;
forward = mapping.findForward(ForwardConstants.LOGIN_FAILURE);
}
if (loggedIn)
{
loginForm.setGridProxy("test");
util.getProperties(session);
session.setAttribute(DisplayConstants.LOGIN_OBJECT, loginForm);
session.setAttribute(DisplayConstants.CURRENT_TABLE_ID,
DisplayConstants.HOME_ID);
session.setAttribute(DisplayConstants.USER_ROLES, userRoles);
if (session.getAttribute("HOT_LINK") == "true")
{
LabActivitiesSearchForm labFm =
(LabActivitiesSearchForm) session
.getAttribute("CURRENT_FORM");
session.setAttribute("CURRENT_FORM", labFm);
return (mapping
.findForward(ForwardConstants.LOGIN_SUCCESS_HOTLINK));
}
forward = mapping.findForward(ForwardConstants.LOGIN_SUCCESS);
}
}
return forward;
}
|
private void testRuleLists(AtlasStyler as, boolean sEnabled, String sTitle,
Filter sFilter, boolean uEnabled, String uTitle, Filter uFilter,
boolean gEnabled, String gTitle, Filter gFilter, boolean tEnabled,
String tTitle, Filter tFilter) throws IOException,
FileNotFoundException {
double sMin = rand.nextDouble();
double sMax = rand.nextDouble();
double gMin = rand.nextDouble();
double gMax = rand.nextDouble();
double uMin = rand.nextDouble();
double uMax = rand.nextDouble();
double tMin = rand.nextDouble();
double tMax = rand.nextDouble();
as.reset();
assertEquals(0, as.getRuleLists().size());
{
SingleRuleList<?> singleRulesList = as
.getRlf()
.createSingleRulesList(
AtlasStyler.getRuleTitleFor(as.getStyledFeatures()),
true);
singleRulesList.setMinScaleDenominator(sMin);
singleRulesList.setMaxScaleDenominator(sMax);
UniqueValuesRuleList uniqueRulesList = as.getRlf()
.createUniqueValuesRulesList(true);
assertEquals(-1, uniqueRulesList.getAllOthersRuleIdx());
uniqueRulesList.addDefaultRule();
uniqueRulesList.setMinScaleDenominator(uMin);
uniqueRulesList.setMaxScaleDenominator(uMax);
assertEquals(0, uniqueRulesList.getAllOthersRuleIdx());
GraduatedColorRuleList gradColorsRulesList = as.getRlf()
.createGraduatedColorRuleList(true);
TreeSet<Double> classLimits = new TreeSet<Double>();
classLimits.add(1.);
classLimits.add(2.);
gradColorsRulesList.setClassLimits(classLimits);
gradColorsRulesList.setMinScaleDenominator(gMin);
gradColorsRulesList.setMaxScaleDenominator(gMax);
TextRuleList textRulesList = as.getRlf().createTextRulesList(true);
textRulesList.setMinScaleDenominator(tMin);
textRulesList.setMaxScaleDenominator(tMax);
singleRulesList.setEnabled(sEnabled);
uniqueRulesList.setEnabled(uEnabled);
gradColorsRulesList.setEnabled(gEnabled);
textRulesList.setEnabled(tEnabled);
singleRulesList.setTitle(sTitle);
uniqueRulesList.setTitle(uTitle);
gradColorsRulesList.setTitle(gTitle);
textRulesList.setTitle(tTitle);
singleRulesList.setRlFilter(sFilter);
uniqueRulesList.setRlFilter(uFilter);
gradColorsRulesList.setRlFilter(gFilter);
textRulesList.setRlFilter(tFilter);
as.addRulesList(singleRulesList);
as.addRulesList(uniqueRulesList);
as.addRulesList(gradColorsRulesList);
as.addRulesList(textRulesList);
assertEquals(4, as.getRuleLists().size());
}
File tf = File.createTempFile("junit", ".sld");
boolean saveStyleToSld = StylingUtil.saveStyleToSld(as.getStyle(), tf);
assertTrue(saveStyleToSld);
StylingUtil.validates(as.getStyle());
as = new AtlasStyler(TestDatasetsVector.polygonSnow.getFeatureSource());
Style[] importStyle = StylingUtil.loadSLD(tf);
as.importStyle(importStyle[0]);
SingleRuleList singleRulesList = (SingleRuleList) as.getRuleLists()
.get(0);
UniqueValuesRuleList uniqueRulesList = (UniqueValuesRuleList) as
.getRuleLists().get(1);
GraduatedColorRuleList gradColorsRulesList = (GraduatedColorRuleList) as
.getRuleLists().get(2);
TextRuleList textRulesList = (TextRuleList) as.getRuleLists().get(3);
assertEquals(sEnabled, singleRulesList.isEnabled());
assertEquals(tEnabled, textRulesList.isEnabled());
assertEquals(gEnabled, gradColorsRulesList.isEnabled());
assertEquals(uEnabled, uniqueRulesList.isEnabled());
assertEquals(sTitle, singleRulesList.getTitle());
assertEquals(tTitle, textRulesList.getTitle());
assertEquals(uTitle, uniqueRulesList.getTitle());
assertEquals(gTitle, gradColorsRulesList.getTitle());
assertEquals(sFilter, singleRulesList.getRlFilter());
assertEquals(gFilter, gradColorsRulesList.getRlFilter());
assertEquals(uFilter, uniqueRulesList.getRlFilter());
assertEquals(tFilter, textRulesList.getRlFilter());
assertEquals(sMin, singleRulesList.getMinScaleDenominator(), 0.00001);
assertEquals(sMax, singleRulesList.getMaxScaleDenominator(), 0.00001);
assertEquals(gMin, gradColorsRulesList.getMinScaleDenominator(),
0.00001);
assertEquals(gMax, gradColorsRulesList.getMaxScaleDenominator(),
0.00001);
assertEquals(uMin, uniqueRulesList.getMinScaleDenominator(), 0.00001);
assertEquals(uMax, uniqueRulesList.getMaxScaleDenominator(), 0.00001);
assertEquals(tMin, textRulesList.getMinScaleDenominator(), 0.00001);
assertEquals(tMax, textRulesList.getMaxScaleDenominator(), 0.00001);
}
| private void testRuleLists(AtlasStyler as, boolean sEnabled, String sTitle,
Filter sFilter, boolean uEnabled, String uTitle, Filter uFilter,
boolean gEnabled, String gTitle, Filter gFilter, boolean tEnabled,
String tTitle, Filter tFilter) throws IOException,
FileNotFoundException {
double sMin = 5000;
double sMax = 10000;
double gMin = 10000;
double gMax = 15000;
double uMin = 16000;
double uMax = 16000 + 5000;
double tMin = 0;
double tMax = 33333333.;
as.reset();
assertEquals(0, as.getRuleLists().size());
{
SingleRuleList<?> singleRulesList = as
.getRlf()
.createSingleRulesList(
AtlasStyler.getRuleTitleFor(as.getStyledFeatures()),
true);
singleRulesList.setMinScaleDenominator(sMin);
singleRulesList.setMaxScaleDenominator(sMax);
UniqueValuesRuleList uniqueRulesList = as.getRlf()
.createUniqueValuesRulesList(true);
assertEquals(-1, uniqueRulesList.getAllOthersRuleIdx());
uniqueRulesList.addDefaultRule();
uniqueRulesList.setMinScaleDenominator(uMin);
uniqueRulesList.setMaxScaleDenominator(uMax);
assertEquals(0, uniqueRulesList.getAllOthersRuleIdx());
GraduatedColorRuleList gradColorsRulesList = as.getRlf()
.createGraduatedColorRuleList(true);
TreeSet<Double> classLimits = new TreeSet<Double>();
classLimits.add(1.);
classLimits.add(2.);
gradColorsRulesList.setClassLimits(classLimits);
gradColorsRulesList.setMinScaleDenominator(gMin);
gradColorsRulesList.setMaxScaleDenominator(gMax);
TextRuleList textRulesList = as.getRlf().createTextRulesList(true);
textRulesList.setMinScaleDenominator(tMin);
textRulesList.setMaxScaleDenominator(tMax);
singleRulesList.setEnabled(sEnabled);
uniqueRulesList.setEnabled(uEnabled);
gradColorsRulesList.setEnabled(gEnabled);
textRulesList.setEnabled(tEnabled);
singleRulesList.setTitle(sTitle);
uniqueRulesList.setTitle(uTitle);
gradColorsRulesList.setTitle(gTitle);
textRulesList.setTitle(tTitle);
singleRulesList.setRlFilter(sFilter);
uniqueRulesList.setRlFilter(uFilter);
gradColorsRulesList.setRlFilter(gFilter);
textRulesList.setRlFilter(tFilter);
as.addRulesList(singleRulesList);
as.addRulesList(uniqueRulesList);
as.addRulesList(gradColorsRulesList);
as.addRulesList(textRulesList);
assertEquals(4, as.getRuleLists().size());
}
File tf = File.createTempFile("junit", ".sld");
boolean saveStyleToSld = StylingUtil.saveStyleToSld(as.getStyle(), tf);
assertTrue(saveStyleToSld);
StylingUtil.validates(as.getStyle());
as = new AtlasStyler(TestDatasetsVector.polygonSnow.getFeatureSource());
Style[] importStyle = StylingUtil.loadSLD(tf);
as.importStyle(importStyle[0]);
SingleRuleList singleRulesList = (SingleRuleList) as.getRuleLists()
.get(0);
UniqueValuesRuleList uniqueRulesList = (UniqueValuesRuleList) as
.getRuleLists().get(1);
GraduatedColorRuleList gradColorsRulesList = (GraduatedColorRuleList) as
.getRuleLists().get(2);
TextRuleList textRulesList = (TextRuleList) as.getRuleLists().get(3);
assertEquals(sEnabled, singleRulesList.isEnabled());
assertEquals(tEnabled, textRulesList.isEnabled());
assertEquals(gEnabled, gradColorsRulesList.isEnabled());
assertEquals(uEnabled, uniqueRulesList.isEnabled());
assertEquals(sTitle, singleRulesList.getTitle());
assertEquals(tTitle, textRulesList.getTitle());
assertEquals(uTitle, uniqueRulesList.getTitle());
assertEquals(gTitle, gradColorsRulesList.getTitle());
assertEquals(sFilter, singleRulesList.getRlFilter());
assertEquals(gFilter, gradColorsRulesList.getRlFilter());
assertEquals(uFilter, uniqueRulesList.getRlFilter());
assertEquals(tFilter, textRulesList.getRlFilter());
assertEquals(sMin, singleRulesList.getMinScaleDenominator(), 0.00001);
assertEquals(sMax, singleRulesList.getMaxScaleDenominator(), 0.00001);
assertEquals(gMin, gradColorsRulesList.getMinScaleDenominator(),
0.00001);
assertEquals(gMax, gradColorsRulesList.getMaxScaleDenominator(),
0.00001);
assertEquals(uMin, uniqueRulesList.getMinScaleDenominator(), 0.00001);
assertEquals(uMax, uniqueRulesList.getMaxScaleDenominator(), 0.00001);
assertEquals(tMin, textRulesList.getMinScaleDenominator(), 0.00001);
assertEquals(tMax, textRulesList.getMaxScaleDenominator(), 0.00001);
}
|
private void internalRenderText(
final int xPos,
final int yPos,
final String text,
final float size,
final boolean useAlphaTexture,
final float alpha) {
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
int originalWidth = getStringWidthInternal(text, 1.0f);
int sizedWidth = getStringWidthInternal(text, size);
int x = xPos - (sizedWidth - originalWidth) / 2;
int activeTextureIdx = -1;
for (int i = 0; i < text.length(); i++) {
Result result = colorValueParser.isColor(text, i);
while (result.isColor()) {
Color color = result.getColor();
GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), alpha);
i = result.getNextIndex();
if (i >= text.length()) {
break;
}
result = colorValueParser.isColor(text, i);
}
char currentc = text.charAt(i);
char nextc = FontHelper.getNextCharacter(text, i);
CharacterInfo charInfoC = font.getChar((char) currentc);
int kerning = 0;
float characterWidth = 0;
if (charInfoC != null) {
int texId = charInfoC.getPage();
if (activeTextureIdx != texId) {
activeTextureIdx = texId;
textures[activeTextureIdx].bind();
}
kerning = LwjglRenderFont.getKerning(charInfoC, nextc);
characterWidth = (float) (charInfoC.getXadvance() * size + kerning);
GL11.glLoadIdentity();
GL11.glTranslatef(x, yPos, 0.0f);
GL11.glTranslatef(0.0f, getHeight() / 2, 0.0f);
GL11.glScalef(size, size, 1.0f);
GL11.glTranslatef(0.0f, -getHeight() / 2, 0.0f);
boolean characterDone = false;
if (isSelection()) {
if (i >= selectionStart && i < selectionEnd) {
GL11.glPushAttrib(GL11.GL_CURRENT_BIT);
disableBlend();
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(selectionBackgroundR, selectionBackgroundG, selectionBackgroundB, selectionBackgroundA);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2i(0, 0);
GL11.glVertex2i((int) characterWidth, 0);
GL11.glVertex2i((int) characterWidth, 0 + getHeight());
GL11.glVertex2i(0, 0 + getHeight());
GL11.glEnd();
GL11.glEnable(GL11.GL_TEXTURE_2D);
enableBlend();
GL11.glColor4f(selectionR, selectionG, selectionB, selectionA);
GL11.glCallList(displayListMap.get(currentc));
Tools.checkGLError("glCallList");
GL11.glPopAttrib();
characterDone = true;
}
}
if (!characterDone) {
GL11.glCallList(displayListMap.get(currentc));
Tools.checkGLError("glCallList");
}
x += characterWidth;
}
}
GL11.glPopMatrix();
}
| private void internalRenderText(
final int xPos,
final int yPos,
final String text,
final float size,
final boolean useAlphaTexture,
final float alpha) {
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
int originalWidth = getStringWidthInternal(text, 1.0f);
int sizedWidth = getStringWidthInternal(text, size);
int x = xPos - (sizedWidth - originalWidth) / 2;
int activeTextureIdx = -1;
for (int i = 0; i < text.length(); i++) {
Result result = colorValueParser.isColor(text, i);
while (result.isColor()) {
Color color = result.getColor();
GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), alpha);
i = result.getNextIndex();
if (i >= text.length()) {
break;
}
result = colorValueParser.isColor(text, i);
}
if (i >= text.length()) {
break;
}
char currentc = text.charAt(i);
char nextc = FontHelper.getNextCharacter(text, i);
CharacterInfo charInfoC = font.getChar((char) currentc);
int kerning = 0;
float characterWidth = 0;
if (charInfoC != null) {
int texId = charInfoC.getPage();
if (activeTextureIdx != texId) {
activeTextureIdx = texId;
textures[activeTextureIdx].bind();
}
kerning = LwjglRenderFont.getKerning(charInfoC, nextc);
characterWidth = (float) (charInfoC.getXadvance() * size + kerning);
GL11.glLoadIdentity();
GL11.glTranslatef(x, yPos, 0.0f);
GL11.glTranslatef(0.0f, getHeight() / 2, 0.0f);
GL11.glScalef(size, size, 1.0f);
GL11.glTranslatef(0.0f, -getHeight() / 2, 0.0f);
boolean characterDone = false;
if (isSelection()) {
if (i >= selectionStart && i < selectionEnd) {
GL11.glPushAttrib(GL11.GL_CURRENT_BIT);
disableBlend();
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(selectionBackgroundR, selectionBackgroundG, selectionBackgroundB, selectionBackgroundA);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2i(0, 0);
GL11.glVertex2i((int) characterWidth, 0);
GL11.glVertex2i((int) characterWidth, 0 + getHeight());
GL11.glVertex2i(0, 0 + getHeight());
GL11.glEnd();
GL11.glEnable(GL11.GL_TEXTURE_2D);
enableBlend();
GL11.glColor4f(selectionR, selectionG, selectionB, selectionA);
GL11.glCallList(displayListMap.get(currentc));
Tools.checkGLError("glCallList");
GL11.glPopAttrib();
characterDone = true;
}
}
if (!characterDone) {
GL11.glCallList(displayListMap.get(currentc));
Tools.checkGLError("glCallList");
}
x += characterWidth;
}
}
GL11.glPopMatrix();
}
|
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object command, Exception exception) {
logger.error(ExceptionUtils.getStackTrace(exception));
if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
response.setHeader("AJAX_ERROR", "true");
try {
response.sendError(508);
}
catch (Exception e) {
logger.warn("Error setting error code to 508");
}
}
return super.resolveException(request, response, command, exception);
}
| public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object command, Exception exception) {
String stackTrace = ExceptionUtils.getStackTrace(exception);
logger.error(stackTrace);
request.setAttribute("exceptionStackTrace", stackTrace);
if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
response.setHeader("AJAX_ERROR", "true");
try {
response.sendError(508);
}
catch (Exception e) {
logger.warn("Error setting error code to 508");
}
}
return super.resolveException(request, response, command, exception);
}
|
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.text_table_daily_attendance, null);
TextView numberTextView = (TextView) convertView.findViewById(R.id.number_text);
TextView nameTextView = (TextView) convertView.findViewById(R.id.name_text);
TextView checkInTextView = (TextView) convertView.findViewById(R.id.check_in_text);
TextView checkOutTextView = (TextView) convertView.findViewById(R.id.check_out_text);
convertView.setBackgroundColor(position % 2 == 0 ? Color.WHITE : Color.parseColor("#cbe7f3"));
numberTextView.setText(values.get(position).getNumber());
nameTextView.setText(values.get(position).getName());
checkInTextView.setText(values.get(position).getCheckIn());
checkOutTextView.setText(values.get(position).getCheckOut());
return convertView;
}
| public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.text_table_daily_attendance, null);
TextView numberTextView = (TextView) convertView.findViewById(R.id.number_text);
TextView nameTextView = (TextView) convertView.findViewById(R.id.name_text);
TextView checkInTextView = (TextView) convertView.findViewById(R.id.check_in_text);
TextView checkOutTextView = (TextView) convertView.findViewById(R.id.check_out_text);
convertView.setBackgroundColor(position % 2 == 0 ? Color.WHITE : Color.parseColor("#cfe9d0"));
numberTextView.setText(values.get(position).getNumber());
nameTextView.setText(values.get(position).getName());
checkInTextView.setText(values.get(position).getCheckIn());
checkOutTextView.setText(values.get(position).getCheckOut());
return convertView;
}
|
public String horizontalPrint() {
StringBuilder result = new StringBuilder();
List<Button> buttons = getButtons();
result.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
result.append("<td width=\"100\"> </td>");
if (buttons.size() > 0) {
result.append("<td>");
result.append(buttons.get(0).print());
result.append("</td>");
}
for (int i = 1; i < buttons.size(); i++) {
result.append("<td> </td>");
result.append("<td>");
result.append(buttons.get(i).print());
result.append("</td>");
}
result.append("<td width=\"100\"> </td>");
result.append("</tr></table>");
return result.toString();
}
| public String horizontalPrint() {
StringBuilder result = new StringBuilder();
List<Button> buttons = getButtons();
result.append("<div class=\"buttonPane\">");
result.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
result.append("<td width=\"100\"> </td>");
if (buttons.size() > 0) {
result.append("<td>");
result.append(buttons.get(0).print());
result.append("</td>");
}
for (int i = 1; i < buttons.size(); i++) {
result.append("<td> </td>");
result.append("<td>");
result.append(buttons.get(i).print());
result.append("</td>");
}
result.append("<td width=\"100\"> </td>");
result.append("</tr></table>");
result.append("</div>");
return result.toString();
}
|
public static void setUpOnce() {
CAL_INSTANCE.set(1971, 1, 1);
final String date = "1971-01-01";
birthDate = MConverter.longToByteBuffer(CAL_INSTANCE.getTimeInMillis()).array();
sessionBean = new MSessionBean();
sessionBean.setId(USER_ID + "_SESSION");
sessionBean.setUser(USER_ID);
sessionBean.setIp(IP);
sessionBean.setCurrentApplications("");
sessionBean.setP2P(false);
userBean = new MUserBean();
userBean.setId(USER_ID);
userBean.setBirthday(date);
userBean.setSocialNetworkID(NAME);
userBean.setBuddyList(BUDDY_LST_ID);
userBean.setEmail(EMAIL);
userBean.setFirstName(FIRST_NAME);
userBean.setGender(GENDER);
userBean.setHometown(HOMETOWN);
userBean.setLastName(LAST_NAME);
userBean.setLink(LINK);
userBean.setName(LOGIN);
userBean.setSession(SESSION_ID);
userBean.setInteractionList(INTERACTION_LST_ID);
userBean.setLastConnection(CAL_INSTANCE.getTimeInMillis());
userBean.setReputation(REPUTATION_ID);
userBean.setSubscribtionList(SUBSCRIPTION_LST_ID);
try {
name = MConverter.stringToByteBuffer(NAME).array();
firstName = MConverter.stringToByteBuffer(FIRST_NAME).array();
lastName = MConverter.stringToByteBuffer(LAST_NAME).array();
} catch (final InternalBackEndException ex) {
fail(ex.getMessage());
}
interactionBean = new MInteractionBean();
CAL_INSTANCE.set(2011, 1, 1);
interactionBean.setStart(CAL_INSTANCE.getTimeInMillis());
CAL_INSTANCE.set(2011, 1, 3);
interactionBean.setEnd(CAL_INSTANCE.getTimeInMillis());
interactionBean.setId(INTERACTION_ID);
interactionBean.setApplication(APPLICATION_ID);
interactionBean.setProducer(PRODUCER_ID);
interactionBean.setConsumer(CONSUMER_ID);
interactionBean.setSnooze(0);
interactionBean.setComplexInteraction(INTERACTION_LST_ID);
authenticationBean.setLogin(LOGIN);
authenticationBean.setPassword(getRandomPwd());
authenticationBean.setUser(USER_ID);
}
| public static void setUpOnce() {
CAL_INSTANCE.set(1971, 1, 1);
final String date = "1971-01-01";
birthDate = MConverter.longToByteBuffer(CAL_INSTANCE.getTimeInMillis()).array();
sessionBean = new MSessionBean();
sessionBean.setId(USER_ID + "_SESSION");
sessionBean.setUser(USER_ID);
sessionBean.setIp(IP);
sessionBean.setCurrentApplications("");
sessionBean.setP2P(false);
userBean = new MUserBean();
userBean.setId(USER_ID);
userBean.setBirthday(date);
userBean.setSocialNetworkID(NAME);
userBean.setBuddyList(BUDDY_LST_ID);
userBean.setEmail(EMAIL);
userBean.setFirstName(FIRST_NAME);
userBean.setGender(GENDER);
userBean.setHometown(HOMETOWN);
userBean.setLastName(LAST_NAME);
userBean.setLink(LINK);
userBean.setName(LOGIN);
userBean.setSession(SESSION_ID);
userBean.setInteractionList(INTERACTION_LST_ID);
userBean.setLastConnection(CAL_INSTANCE.getTimeInMillis());
userBean.setReputation(REPUTATION_ID);
userBean.setSubscribtionList(SUBSCRIPTION_LST_ID);
try {
name = MConverter.stringToByteBuffer(NAME).array();
firstName = MConverter.stringToByteBuffer(FIRST_NAME).array();
lastName = MConverter.stringToByteBuffer(LAST_NAME).array();
} catch (final InternalBackEndException ex) {
fail(ex.getMessage());
}
interactionBean = new MInteractionBean();
CAL_INSTANCE.set(2011, 1, 1);
interactionBean.setStart(CAL_INSTANCE.getTimeInMillis());
CAL_INSTANCE.set(2011, 1, 3);
interactionBean.setEnd(CAL_INSTANCE.getTimeInMillis());
interactionBean.setId(INTERACTION_ID);
interactionBean.setApplication(APPLICATION_ID);
interactionBean.setProducer(PRODUCER_ID);
interactionBean.setConsumer(CONSUMER_ID);
interactionBean.setSnooze(0);
interactionBean.setComplexInteraction(INTERACTION_LST_ID);
authenticationBean = new MAuthenticationBean();
authenticationBean.setLogin(LOGIN);
authenticationBean.setPassword(getRandomPwd());
authenticationBean.setUser(USER_ID);
}
|
private OperatorFilter getDimensionFilter( Map<String, List<?>> dims, List<String> headers )
throws OWSException {
LinkedList<Operator> ops = new LinkedList<Operator>();
Dimension<?> time = getMetadata().getDimensions().get( "time" );
if ( time != null ) {
final ValueReference property = new ValueReference( time.getPropertyName() );
List<?> vals = dims.get( "time" );
if ( vals == null ) {
vals = time.getDefaultValue();
if ( vals == null ) {
throw new OWSException( "The TIME parameter was missing.", "MissingDimensionValue", "time" );
}
String defVal = formatDimensionValueList( vals, true );
headers.add( "99 Default value used: time=" + defVal + " ISO8601" );
}
Operator[] os = new Operator[vals.size()];
int i = 0;
for ( Object o : vals ) {
if ( !time.getNearestValue() && !time.isValid( o ) ) {
String msg = "The value " + ( o instanceof Date ? formatDateTime( (Date) o ) : o.toString() )
+ " for dimension TIME was invalid.";
throw new OWSException( msg, "InvalidDimensionValue", "time" );
}
Date theVal = null;
if ( o instanceof DimensionInterval<?, ?, ?> ) {
DimensionInterval<?, ?, ?> iv = (DimensionInterval<?, ?, ?>) o;
final String min = formatDateTime( (Date) iv.min );
final String max = formatDateTime( (Date) iv.max );
os[i++] = new PropertyIsBetween( property, new Literal<PrimitiveValue>( min ),
new Literal<PrimitiveValue>( max ), false, null );
} else if ( o.toString().equalsIgnoreCase( "current" ) ) {
if ( !time.getCurrent() ) {
String msg = "The value 'current' for TIME was invalid.";
throw new OWSException( msg, "InvalidDimensionValue", "time" );
}
theVal = new Date( currentTimeMillis() );
} else if ( o instanceof Date ) {
theVal = (Date) o;
} else if ( o instanceof TimeInstant ) {
theVal = ( (TimeInstant) o ).getDate();
} else {
throw new RuntimeException( "Unexpected dimension value class: " + o.getClass() );
}
if ( theVal != null ) {
if ( time.getNearestValue() ) {
Object nearest = time.getNearestValue( theVal );
if ( !nearest.equals( theVal ) ) {
theVal = (Date) nearest;
headers.add( "99 Nearest value used: time=" + formatDateTime( theVal ) + " "
+ time.getUnits() );
}
}
Literal<PrimitiveValue> lit = new Literal<PrimitiveValue>( formatDateTime( theVal ) );
os[i++] = new PropertyIsEqualTo( property, lit, null, null );
}
}
if ( os.length > 1 ) {
if ( !time.getMultipleValues() ) {
String msg = "Multiple values are not allowed for TIME.";
throw new OWSException( msg, "InvalidDimensionValue", "time" );
}
try {
ops.add( new Or( os ) );
} catch ( Throwable e ) {
}
} else {
ops.add( os[0] );
}
}
for ( String name : getMetadata().getDimensions().keySet() ) {
if ( name.equals( "time" ) ) {
continue;
}
Dimension<?> dim = getMetadata().getDimensions().get( name );
final ValueReference property = new ValueReference( dim.getPropertyName() );
List<?> vals = dims.get( name );
if ( vals == null ) {
vals = dim.getDefaultValue();
if ( vals == null ) {
throw new OWSException( "The dimension value for " + name + " was missing.",
"MissingDimensionValue", name );
}
String units = dim.getUnits();
if ( name.equals( "elevation" ) ) {
headers.add( "99 Default value used: elevation=" + formatDimensionValueList( vals, false ) + " "
+ ( units == null ? "m" : units ) );
} else if ( name.equals( "time" ) ) {
headers.add( "99 Default value used: time=" + formatDimensionValueList( vals, true ) + " "
+ ( units == null ? "ISO8601" : units ) );
} else {
headers.add( "99 Default value used: DIM_" + name + "=" + formatDimensionValueList( vals, false )
+ " " + units );
}
}
Operator[] os = new Operator[vals.size()];
int i = 0;
for ( Object o : vals ) {
if ( !dim.getNearestValue() && !dim.isValid( o ) ) {
throw new OWSException( "The value " + o.toString() + " was not valid for dimension " + name + ".",
"InvalidDimensionValue", name );
}
if ( o instanceof DimensionInterval<?, ?, ?> ) {
DimensionInterval<?, ?, ?> iv = (DimensionInterval<?, ?, ?>) o;
final String min;
if ( iv.min instanceof Date ) {
min = formatDateTime( (Date) iv.min );
} else {
min = ( (Number) iv.min ).toString();
}
final String max;
if ( iv.max instanceof Date ) {
max = formatDateTime( (Date) iv.max );
} else if ( iv.max instanceof String ) {
max = formatDateTime( new Date() );
} else {
max = ( (Number) iv.max ).toString();
}
os[i++] = new PropertyIsBetween( property, new Literal<PrimitiveValue>( min ),
new Literal<PrimitiveValue>( max ), false, null );
} else {
if ( dim.getNearestValue() ) {
Object nearest = dim.getNearestValue( o );
if ( !nearest.equals( o ) ) {
o = nearest;
if ( "elevation".equals( name ) ) {
headers.add( "99 Nearest value used: elevation=" + o + " " + dim.getUnits() );
} else {
headers.add( "99 Nearest value used: DIM_" + name + "=" + o + " " + dim.getUnits() );
}
}
}
os[i++] = new PropertyIsEqualTo( new ValueReference( dim.getPropertyName() ),
new Literal<PrimitiveValue>( o.toString() ), false, null );
}
}
if ( os.length > 1 ) {
if ( !dim.getMultipleValues() ) {
throw new OWSException( "Multiple values are not allowed for ELEVATION.", "InvalidDimensionValue",
"elevation" );
}
ops.add( new Or( os ) );
} else {
ops.add( os[0] );
}
}
if ( ops.isEmpty() ) {
return null;
}
if ( ops.size() > 1 ) {
return new OperatorFilter( new And( ops.toArray( new Operator[ops.size()] ) ) );
}
return new OperatorFilter( ops.get( 0 ) );
}
| private OperatorFilter getDimensionFilter( Map<String, List<?>> dims, List<String> headers )
throws OWSException {
LinkedList<Operator> ops = new LinkedList<Operator>();
Dimension<?> time = getMetadata().getDimensions().get( "time" );
if ( time != null ) {
final ValueReference property = new ValueReference( time.getPropertyName() );
List<?> vals = dims.get( "time" );
if ( vals == null ) {
vals = time.getDefaultValue();
if ( vals == null ) {
throw new OWSException( "The TIME parameter was missing.", "MissingDimensionValue", "time" );
}
String defVal = formatDimensionValueList( vals, true );
headers.add( "99 Default value used: time=" + defVal + " ISO8601" );
}
Operator[] os = new Operator[vals.size()];
int i = 0;
for ( Object o : vals ) {
if ( !time.getNearestValue() && !time.isValid( o ) ) {
String msg = "The value " + ( o instanceof Date ? formatDateTime( (Date) o ) : o.toString() )
+ " for dimension TIME was invalid.";
throw new OWSException( msg, "InvalidDimensionValue", "time" );
}
Date theVal = null;
if ( o instanceof DimensionInterval<?, ?, ?> ) {
DimensionInterval<?, ?, ?> iv = (DimensionInterval<?, ?, ?>) o;
final String min = formatDateTime( (Date) iv.min );
final String max = formatDateTime( (Date) iv.max );
os[i++] = new PropertyIsBetween( property, new Literal<PrimitiveValue>( min ),
new Literal<PrimitiveValue>( max ), true, null );
} else if ( o.toString().equalsIgnoreCase( "current" ) ) {
if ( !time.getCurrent() ) {
String msg = "The value 'current' for TIME was invalid.";
throw new OWSException( msg, "InvalidDimensionValue", "time" );
}
theVal = new Date( currentTimeMillis() );
} else if ( o instanceof Date ) {
theVal = (Date) o;
} else if ( o instanceof TimeInstant ) {
theVal = ( (TimeInstant) o ).getDate();
} else {
throw new RuntimeException( "Unexpected dimension value class: " + o.getClass() );
}
if ( theVal != null ) {
if ( time.getNearestValue() ) {
Object nearest = time.getNearestValue( theVal );
if ( !nearest.equals( theVal ) ) {
theVal = (Date) nearest;
headers.add( "99 Nearest value used: time=" + formatDateTime( theVal ) + " "
+ time.getUnits() );
}
}
Literal<PrimitiveValue> lit = new Literal<PrimitiveValue>( formatDateTime( theVal ) );
os[i++] = new PropertyIsEqualTo( property, lit, null, null );
}
}
if ( os.length > 1 ) {
if ( !time.getMultipleValues() ) {
String msg = "Multiple values are not allowed for TIME.";
throw new OWSException( msg, "InvalidDimensionValue", "time" );
}
try {
ops.add( new Or( os ) );
} catch ( Throwable e ) {
}
} else {
ops.add( os[0] );
}
}
for ( String name : getMetadata().getDimensions().keySet() ) {
if ( name.equals( "time" ) ) {
continue;
}
Dimension<?> dim = getMetadata().getDimensions().get( name );
final ValueReference property = new ValueReference( dim.getPropertyName() );
List<?> vals = dims.get( name );
if ( vals == null ) {
vals = dim.getDefaultValue();
if ( vals == null ) {
throw new OWSException( "The dimension value for " + name + " was missing.",
"MissingDimensionValue", name );
}
String units = dim.getUnits();
if ( name.equals( "elevation" ) ) {
headers.add( "99 Default value used: elevation=" + formatDimensionValueList( vals, false ) + " "
+ ( units == null ? "m" : units ) );
} else if ( name.equals( "time" ) ) {
headers.add( "99 Default value used: time=" + formatDimensionValueList( vals, true ) + " "
+ ( units == null ? "ISO8601" : units ) );
} else {
headers.add( "99 Default value used: DIM_" + name + "=" + formatDimensionValueList( vals, false )
+ " " + units );
}
}
Operator[] os = new Operator[vals.size()];
int i = 0;
for ( Object o : vals ) {
if ( !dim.getNearestValue() && !dim.isValid( o ) ) {
throw new OWSException( "The value " + o.toString() + " was not valid for dimension " + name + ".",
"InvalidDimensionValue", name );
}
if ( o instanceof DimensionInterval<?, ?, ?> ) {
DimensionInterval<?, ?, ?> iv = (DimensionInterval<?, ?, ?>) o;
final String min;
if ( iv.min instanceof Date ) {
min = formatDateTime( (Date) iv.min );
} else {
min = ( (Number) iv.min ).toString();
}
final String max;
if ( iv.max instanceof Date ) {
max = formatDateTime( (Date) iv.max );
} else if ( iv.max instanceof String ) {
max = formatDateTime( new Date() );
} else {
max = ( (Number) iv.max ).toString();
}
os[i++] = new PropertyIsBetween( property, new Literal<PrimitiveValue>( min ),
new Literal<PrimitiveValue>( max ), true, null );
} else {
if ( dim.getNearestValue() ) {
Object nearest = dim.getNearestValue( o );
if ( !nearest.equals( o ) ) {
o = nearest;
if ( "elevation".equals( name ) ) {
headers.add( "99 Nearest value used: elevation=" + o + " " + dim.getUnits() );
} else {
headers.add( "99 Nearest value used: DIM_" + name + "=" + o + " " + dim.getUnits() );
}
}
}
os[i++] = new PropertyIsEqualTo( new ValueReference( dim.getPropertyName() ),
new Literal<PrimitiveValue>( o.toString() ), null, null );
}
}
if ( os.length > 1 ) {
if ( !dim.getMultipleValues() ) {
throw new OWSException( "Multiple values are not allowed for ELEVATION.", "InvalidDimensionValue",
"elevation" );
}
ops.add( new Or( os ) );
} else {
ops.add( os[0] );
}
}
if ( ops.isEmpty() ) {
return null;
}
if ( ops.size() > 1 ) {
return new OperatorFilter( new And( ops.toArray( new Operator[ops.size()] ) ) );
}
return new OperatorFilter( ops.get( 0 ) );
}
|
public void onEnable() {
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvents(this.FPListener, this);
FactionsPlusJail.server = getServer();
FactionsVersion = (this.getServer().getPluginManager().getPlugin("Factions").getDescription().getVersion());
if(FactionsVersion.startsWith("1.6")) {
isOnePointSix = true;
} else {
isOnePointSix = false;
}
log.info("[FactionsPlus] Factions version " + FactionsVersion + " - " + isOnePointSix.toString());
try {
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator).exists()) {
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator);
new File("plugins" + File.separator + "FactionsPlus" + File.separator).mkdir();
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").createNewFile();
log.info("[FactionsPlus] Created file: plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt");
}
} catch (Exception e) {
e.printStackTrace();
}
if(!FactionsPlus.configFile.exists()) {
try {
FactionsPlus.configFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
wconfig = YamlConfiguration.loadConfiguration(configFile);
configFile.delete();
configFile.createNewFile();
config = YamlConfiguration.loadConfiguration(configFile);
if(wconfig.isSet("disableUpdateCheck")) {
config.set("disableUpdateCheck", wconfig.getBoolean("disableUpdateCheck"));
} else config.set("disableUpdateCheck", false);
if(wconfig.isSet("unDisguiseIfInOwnTerritory")) {
config.set("unDisguiseIfInOwnTerritory", wconfig.getBoolean("unDisguiseIfInOwnTerritory"));
} else config.set("unDisguiseIfInOwnTerritory", Boolean.valueOf(false));
if(wconfig.isSet("unDisguiseIfInEnemyTerritory")) {
config.set("unDisguiseIfInEnemyTerritory", wconfig.getBoolean("unDisguiseIfInEnemyTerritory"));
} else config.set("unDisguiseIfInEnemyTerritory", Boolean.valueOf(false));
if(wconfig.isSet("leadersCanSetWarps")) {
config.set("leadersCanSetWarps", wconfig.getBoolean("leadersCanSetWarps"));
} else config.set("leadersCanSetWarps", true);
if(wconfig.isSet("officersCanSetWarps")) {
config.set("officersCanSetWarps", wconfig.getBoolean("officersCanSetWarps"));
} else config.set("officersCanSetWarps", true);
if(wconfig.isSet("membersCanSetWarps")) {
config.set("membersCanSetWarps", wconfig.getBoolean("membersCanSetWarps"));
} else config.set("membersCanSetWarps", false);
if(wconfig.isSet("warpSetting")) {
config.set("warpSetting", wconfig.getInt("warpSetting"));
} else config.set("warpSetting", Integer.valueOf(1));
if(wconfig.isSet("maxWarps")) {
config.set("maxWarps", wconfig.getInt("maxWarps"));
} else config.set("maxWarps", Integer.valueOf(5));
if(wconfig.isSet("mustBeInOwnTerritoryToCreate")) {
config.set("mustBeInOwnTerritoryToCreate", wconfig.getBoolean("mustBeInOwnTerritoryToCreate"));
} else config.set("mustBeInOwnTerritoryToCreate", true);
if(wconfig.isSet("warpTeleportAllowedFromEnemyTerritory")){
config.set("homesTeleportAllowedFromEnemyTerritory", wconfig.getBoolean("homesTeleportAllowedFromEnemyTerritory"));
} else config.set("homesTeleportAllowedFromEnemyTerritory", true);
if(wconfig.isSet("warpTeleportAllowedFromDifferentWorld")){
config.set("warpTeleportAllowedFromDifferentWorld", wconfig.getBoolean("warpTeleportAllowedFromDifferentWorld"));
} else config.set("warpTeleportAllowedFromDifferentWorld", true);
if(wconfig.isSet("warpTeleportAllowedEnemyDistance")) {
config.set("warpTeleportAllowedEnemyDistance", wconfig.getInt("warpTeleportAllowedEnemyDistance"));
} else config.set("warpTeleportAllowedEnemyDistance", Integer.valueOf(35));
if(wconfig.isSet("warpTeleportIgnoreEnemiesIfInOwnTerritory")){
config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", wconfig.getBoolean("warpTeleportIgnoreEnemiesIfInOwnTerritory"));
} else config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", true);
if(wconfig.isSet("smokeEffectOnWarp")) {
config.set("smokeEffectOnWarp", wconfig.getBoolean("smokeEffectOnWarp"));
} else config.set("smokeEffectOnWarp", true);
if(wconfig.isSet("powerBoostIfPeaceful")) {
config.set("powerBoostIfPeaceful", wconfig.getInt("powerBoostIfPeaceful"));
} else config.set("powerBoostIfPeaceful", Integer.valueOf(0));
if(wconfig.isSet("leadersCanSetJails")) {
config.set("leadersCanSetJails", wconfig.getBoolean("leadersCanSetJails"));
} else config.set("leadersCanSetJails", true);
if(wconfig.isSet("officersCanSetJails")) {
config.set("officersCanSetJails", wconfig.getBoolean("officersCanSetJails"));
} else config.set("officersCanSetJails", true);
if(wconfig.isSet("leadersCanSetRules")) {
config.set("leadersCanSetRules", wconfig.getBoolean("leadersCanSetRules"));
} else config.set("leadersCanSetRules", true);
if(wconfig.isSet("officersCanSetRules")) {
config.set("officersCanSetRules", wconfig.getBoolean("officersCanSetRules"));
} else config.set("officersCanSetRules", true);
if(wconfig.isSet("maxRulesPerFaction")) {
config.set("maxRulesPerFaction", wconfig.getInt("maxRulesPerFaction"));
} else config.set("maxRulesPerFaction", Integer.valueOf(12));
if(wconfig.isSet("membersCanSetJails")) {
config.set("membersCanSetJails", wconfig.getBoolean("membersCanSetJails"));
} else config.set("membersCanSetJails", false);
if(wconfig.isSet("leadersCanJail")) {
config.set("leadersCanJail", wconfig.getBoolean("leadersCanJail"));
} else config.set("leadersCanJail", true);
if(wconfig.isSet("officersCanJail")) {
config.set("officersCanJail", wconfig.getBoolean("officersCanJail"));
} else config.set("officersCanJail", true);
if(wconfig.isSet("leadersCanAnnounce")) {
config.set("leadersCanAnnounce", wconfig.getBoolean("leadersCanAnnounce"));
} else config.set("leadersCanAnnounce", true);
if(wconfig.isSet("officersCanAnnounce")) {
config.set("officersCanAnnounce", wconfig.getBoolean("officersCanAnnounce"));
} else config.set("officersCanAnnounce", true);
if(wconfig.isSet("showLastAnnounceOnLogin")) {
config.set("showLastAnnounceOnLogin", wconfig.getBoolean("showLastAnnounceOnLogin"));
} else config.set("showLastAnnounceOnLogin", true);
if(wconfig.isSet("showLastAnnounceOnLandEnter")) {
config.set("showLastAnnounceOnLandEnter", wconfig.getBoolean("showLastAnnounceOnLandEnter"));
} else config.set("showLastAnnounceOnLandEnter", true);
if(wconfig.isSet("leadersCanFactionBan")) {
config.set("leadersCanFactionBan", wconfig.getBoolean("leadersCanFactionBan"));
} else config.set("leadersCanFactionBan", true);
if(wconfig.isSet("officersCanFactionBan")) {
config.set("officersCanFactionBan", wconfig.getBoolean("officersCanFactionBan"));
} else config.set("officersCanFactionBan", true);
if(wconfig.isSet("leaderCanNotBeBanned")) {
config.set("leaderCanNotBeBanned", wconfig.getBoolean("leaderCanNotBeBanned"));
} else config.set("leaderCanNotBeBanned", true);
if(wconfig.isSet("leadersCanToggleState")) {
config.set("leadersCanToggleState", wconfig.getBoolean("leadersCanToggleState"));
} else config.set("leadersCanToggleState", false);
if(wconfig.isSet("officersCanToggleState")) {
config.set("officersCanToggleState", wconfig.getBoolean("officersCanToggleState"));
} else config.set("officersCanToggleState", false);
if(wconfig.isSet("membersCanToggleState")) {
config.set("membersCanToggleState", wconfig.getBoolean("membersCanToggleState"));
} else config.set("membersCanToggleState", false);
if(wconfig.isSet("extraPowerLossIfDeathByOther")) {
config.set("extraPowerLossIfDeathByOther", wconfig.getDouble("extraPowerLossIfDeathByOther"));
} else config.set("extraPowerLossIfDeathByOther", Double.valueOf(0));
if(wconfig.isSet("extraPowerWhenKillPlayer")) {
config.set("extraPowerWhenKillPlayer", wconfig.getDouble("extraPowerWhenKillPlayer"));
} else config.set("extraPowerWhenKillPlayer", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathBySuicide")) {
config.set("extraPowerLossIfDeathBySuicide", wconfig.getDouble("extraPowerLossIfDeathBySuicide"));
} else config.set("extraPowerLossIfDeathBySuicide", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByPVP")) {
config.set("extraPowerLossIfDeathByPVP", wconfig.getDouble("extraPowerLossIfDeathByPVP"));
} else config.set("extraPowerLossIfDeathByPVP", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByMob")) {
config.set("extraPowerLossIfDeathByMob", wconfig.getDouble("extraPowerLossIfDeathByMob"));
} else config.set("extraPowerLossIfDeathByMob", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByCactus")) {
config.set("extraPowerLossIfDeathByCactus", wconfig.getDouble("extraPowerLossIfDeathByCactus"));
} else config.set("extraPowerLossIfDeathByCactus", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByTNT")) {
config.set("extraPowerLossIfDeathByTNT", wconfig.getDouble("extraPowerLossIfDeathByTNT"));
} else config.set("extraPowerLossIfDeathByTNT", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByFire")) {
config.set("extraPowerLossIfDeathByFire", wconfig.getDouble("extraPowerLossIfDeathByFire"));
} else config.set("extraPowerLossIfDeathByFire", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByPotion")) {
config.set("extraPowerLossIfDeathByPotion", wconfig.getDouble("extraPowerLossIfDeathByPotion"));
} else config.set("extraPowerLossIfDeathByPotion", Double.valueOf(0));
if(wconfig.isSet("enablePermissionGroups")) {
config.set("enablePermissionGroups", wconfig.getBoolean("enablePermissionGroups"));
} else config.set("enablePermissionGroups", Boolean.valueOf(false));
if(wconfig.isSet("economy_enable")) {
config.set("economy_enable", wconfig.getBoolean("economy_enable"));
} else config.set("economy_enable", Boolean.valueOf(false));
if(wconfig.isSet("economy_costToWarp")) {
config.set("economy_costToWarp", wconfig.getInt("economy_costToWarp"));
} else config.set("economy_costToWarp", Integer.valueOf(0));
if(wconfig.isSet("economy_costToCreateWarp")) {
config.set("economy_costToCreateWarp", wconfig.getInt("economy_costToCreateWarp"));
} else config.set("economy_costToCreateWarp", Integer.valueOf(0));
if(wconfig.isSet("economy_costToDeleteWarp")) {
config.set("economy_costToDeleteWarp", wconfig.getInt("economy_costToDeleteWarp"));
} else config.set("economy_costToDeleteWarp", Integer.valueOf(0));
if(wconfig.isSet("economy_costToAnnounce")) {
config.set("economy_costToAnnounce", wconfig.getInt("economy_costToAnnounce"));
} else config.set("economy_costToAnnounce", Integer.valueOf(0));
if(wconfig.isSet("economy_costToJail")) {
config.set("economy_costToJail", wconfig.getInt("economy_costToJail"));
} else config.set("economy_costToJail", Integer.valueOf(0));
if(wconfig.isSet("economy_costToSetJail")) {
config.set("economy_costToSetJail", wconfig.getInt("economy_costToSetJail"));
} else config.set("economy_costToSetJail", Integer.valueOf(0));
if(wconfig.isSet("economy_costToUnJail")) {
config.set("economy_costToUnJail", wconfig.getInt("economy_costToUnJail"));
} else config.set("economy_costToUnJail", Integer.valueOf(0));
if(wconfig.isSet("economy_costToToggleUpPeaceful")) {
config.set("economy_costToToggleUpPeaceful", wconfig.getInt("economy_costToToggleUpPeaceful"));
} else config.set("economy_costToToggleUpPeaceful", Integer.valueOf(0));
if(wconfig.isSet("economy_costToToggleDownPeaceful")) {
config.set("economy_costToToggleDownPeaceful", wconfig.getInt("economy_costToToggleDownPeaceful"));
} else config.set("economy_costToToggleDownPeaceful", Integer.valueOf(0));
if(wconfig.isSet("useLWCIntegrationFix")) {
config.set("useLWCIntegrationFix", wconfig.getBoolean("useLWCIntegrationFix"));
} else config.set("useLWCIntegrationFix", false);
config.set("DoNotChangeMe", Integer.valueOf(8));
config.save(configFile);
saveConfig();
} catch(Exception e) {
e.printStackTrace();
log.info("[FactionsPlus] An error occured while managing the configuration file (-18)");
getPluginLoader().disablePlugin(this);
}
if (!templatesFile.exists()) {
FactionsPlusTemplates.createTemplatesFile();
}
templates = YamlConfiguration.loadConfiguration(templatesFile);
config = YamlConfiguration.loadConfiguration(configFile);
FactionsPlusCommandManager.setup();
FactionsPlusHelpModifier.modify();
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) {
permission = permissionProvider.getProvider();
}
if(config.getBoolean("economy_enable")) {
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
}
if(getServer().getPluginManager().isPluginEnabled("DisguiseCraft")) {
pm.registerEvents(this.DCListener, this);
log.info("[FactionsPlus] Hooked into DisguiseCraft!");
isDisguiseCraftEnabled = true;
}
if(getServer().getPluginManager().isPluginEnabled("MobDisguise")) {
pm.registerEvents(this.MDListener, this);
log.info("[FactionsPlus] Hooked into MobDisguise!");
isMobDisguiseEnabled = true;
}
if(getServer().getPluginManager().isPluginEnabled("WorldEdit")) {
worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit");
log.info("[FactionsPlus] Hooked into WorldEdit!");
isWorldEditEnabled = true;
}
if(getServer().getPluginManager().isPluginEnabled("WorldGuard")) {
worldGuardPlugin = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard");
log.info("[FactionsPlus] Hooked into WorldGuard!");
isWorldGuardEnabled = true;
}
if(config.getBoolean("useLWCIntegrationFix") == true) {
if(getServer().getPluginManager().isPluginEnabled("LWC")) {
pm.registerEvents(this.LWCListener, this);
log.info("[FactionsPlus] Hooked into LWC!");
LWCFunctions.integrateLWC((LWCPlugin)getServer().getPluginManager().getPlugin("LWC"));
isLWCEnabled = true;
}
else {
log.info("[FactionsPlus] No LWC Found but Integration Option Is Enabled!");
}
}
FactionsPlus.config = YamlConfiguration.loadConfiguration(FactionsPlus.configFile);
version = getDescription().getVersion();
FactionsPlusUpdate.checkUpdates();
log.info("[FactionsPlus] Ready.");
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
log.info("[FactionsPlus] Waah! Couldn't metrics-up! :'(");
}
}
| public void onEnable() {
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvents(this.FPListener, this);
FactionsPlusJail.server = getServer();
FactionsVersion = (this.getServer().getPluginManager().getPlugin("Factions").getDescription().getVersion());
if(FactionsVersion.startsWith("1.6")) {
isOnePointSix = true;
} else {
isOnePointSix = false;
}
log.info("[FactionsPlus] Factions version " + FactionsVersion + " - " + isOnePointSix.toString());
try {
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator).exists()) {
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator);
new File("plugins" + File.separator + "FactionsPlus" + File.separator).mkdir();
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).mkdir();
log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator);
}
if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").exists()) {
new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").createNewFile();
log.info("[FactionsPlus] Created file: plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt");
}
} catch (Exception e) {
e.printStackTrace();
}
if(!FactionsPlus.configFile.exists()) {
try {
FactionsPlus.configFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
wconfig = YamlConfiguration.loadConfiguration(configFile);
configFile.delete();
configFile.createNewFile();
config = YamlConfiguration.loadConfiguration(configFile);
if(wconfig.isSet("disableUpdateCheck")) {
config.set("disableUpdateCheck", wconfig.getBoolean("disableUpdateCheck"));
} else config.set("disableUpdateCheck", false);
if(wconfig.isSet("unDisguiseIfInOwnTerritory")) {
config.set("unDisguiseIfInOwnTerritory", wconfig.getBoolean("unDisguiseIfInOwnTerritory"));
} else config.set("unDisguiseIfInOwnTerritory", Boolean.valueOf(false));
if(wconfig.isSet("unDisguiseIfInEnemyTerritory")) {
config.set("unDisguiseIfInEnemyTerritory", wconfig.getBoolean("unDisguiseIfInEnemyTerritory"));
} else config.set("unDisguiseIfInEnemyTerritory", Boolean.valueOf(false));
if(wconfig.isSet("leadersCanSetWarps")) {
config.set("leadersCanSetWarps", wconfig.getBoolean("leadersCanSetWarps"));
} else config.set("leadersCanSetWarps", true);
if(wconfig.isSet("officersCanSetWarps")) {
config.set("officersCanSetWarps", wconfig.getBoolean("officersCanSetWarps"));
} else config.set("officersCanSetWarps", true);
if(wconfig.isSet("membersCanSetWarps")) {
config.set("membersCanSetWarps", wconfig.getBoolean("membersCanSetWarps"));
} else config.set("membersCanSetWarps", false);
if(wconfig.isSet("warpSetting")) {
config.set("warpSetting", wconfig.getInt("warpSetting"));
} else config.set("warpSetting", Integer.valueOf(1));
if(wconfig.isSet("maxWarps")) {
config.set("maxWarps", wconfig.getInt("maxWarps"));
} else config.set("maxWarps", Integer.valueOf(5));
if(wconfig.isSet("mustBeInOwnTerritoryToCreate")) {
config.set("mustBeInOwnTerritoryToCreate", wconfig.getBoolean("mustBeInOwnTerritoryToCreate"));
} else config.set("mustBeInOwnTerritoryToCreate", true);
if(wconfig.isSet("warpTeleportAllowedFromEnemyTerritory")){
config.set("warpTeleportAllowedFromEnemyTerritory", wconfig.getBoolean("warpTeleportAllowedFromEnemyTerritory"));
} else config.set("warpTeleportAllowedFromEnemyTerritory", true);
if(wconfig.isSet("warpTeleportAllowedFromDifferentWorld")){
config.set("warpTeleportAllowedFromDifferentWorld", wconfig.getBoolean("warpTeleportAllowedFromDifferentWorld"));
} else config.set("warpTeleportAllowedFromDifferentWorld", true);
if(wconfig.isSet("warpTeleportAllowedEnemyDistance")) {
config.set("warpTeleportAllowedEnemyDistance", wconfig.getInt("warpTeleportAllowedEnemyDistance"));
} else config.set("warpTeleportAllowedEnemyDistance", Integer.valueOf(35));
if(wconfig.isSet("warpTeleportIgnoreEnemiesIfInOwnTerritory")){
config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", wconfig.getBoolean("warpTeleportIgnoreEnemiesIfInOwnTerritory"));
} else config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", true);
if(wconfig.isSet("smokeEffectOnWarp")) {
config.set("smokeEffectOnWarp", wconfig.getBoolean("smokeEffectOnWarp"));
} else config.set("smokeEffectOnWarp", true);
if(wconfig.isSet("powerBoostIfPeaceful")) {
config.set("powerBoostIfPeaceful", wconfig.getInt("powerBoostIfPeaceful"));
} else config.set("powerBoostIfPeaceful", Integer.valueOf(0));
if(wconfig.isSet("leadersCanSetJails")) {
config.set("leadersCanSetJails", wconfig.getBoolean("leadersCanSetJails"));
} else config.set("leadersCanSetJails", true);
if(wconfig.isSet("officersCanSetJails")) {
config.set("officersCanSetJails", wconfig.getBoolean("officersCanSetJails"));
} else config.set("officersCanSetJails", true);
if(wconfig.isSet("leadersCanSetRules")) {
config.set("leadersCanSetRules", wconfig.getBoolean("leadersCanSetRules"));
} else config.set("leadersCanSetRules", true);
if(wconfig.isSet("officersCanSetRules")) {
config.set("officersCanSetRules", wconfig.getBoolean("officersCanSetRules"));
} else config.set("officersCanSetRules", true);
if(wconfig.isSet("maxRulesPerFaction")) {
config.set("maxRulesPerFaction", wconfig.getInt("maxRulesPerFaction"));
} else config.set("maxRulesPerFaction", Integer.valueOf(12));
if(wconfig.isSet("membersCanSetJails")) {
config.set("membersCanSetJails", wconfig.getBoolean("membersCanSetJails"));
} else config.set("membersCanSetJails", false);
if(wconfig.isSet("leadersCanJail")) {
config.set("leadersCanJail", wconfig.getBoolean("leadersCanJail"));
} else config.set("leadersCanJail", true);
if(wconfig.isSet("officersCanJail")) {
config.set("officersCanJail", wconfig.getBoolean("officersCanJail"));
} else config.set("officersCanJail", true);
if(wconfig.isSet("leadersCanAnnounce")) {
config.set("leadersCanAnnounce", wconfig.getBoolean("leadersCanAnnounce"));
} else config.set("leadersCanAnnounce", true);
if(wconfig.isSet("officersCanAnnounce")) {
config.set("officersCanAnnounce", wconfig.getBoolean("officersCanAnnounce"));
} else config.set("officersCanAnnounce", true);
if(wconfig.isSet("showLastAnnounceOnLogin")) {
config.set("showLastAnnounceOnLogin", wconfig.getBoolean("showLastAnnounceOnLogin"));
} else config.set("showLastAnnounceOnLogin", true);
if(wconfig.isSet("showLastAnnounceOnLandEnter")) {
config.set("showLastAnnounceOnLandEnter", wconfig.getBoolean("showLastAnnounceOnLandEnter"));
} else config.set("showLastAnnounceOnLandEnter", true);
if(wconfig.isSet("leadersCanFactionBan")) {
config.set("leadersCanFactionBan", wconfig.getBoolean("leadersCanFactionBan"));
} else config.set("leadersCanFactionBan", true);
if(wconfig.isSet("officersCanFactionBan")) {
config.set("officersCanFactionBan", wconfig.getBoolean("officersCanFactionBan"));
} else config.set("officersCanFactionBan", true);
if(wconfig.isSet("leaderCanNotBeBanned")) {
config.set("leaderCanNotBeBanned", wconfig.getBoolean("leaderCanNotBeBanned"));
} else config.set("leaderCanNotBeBanned", true);
if(wconfig.isSet("leadersCanToggleState")) {
config.set("leadersCanToggleState", wconfig.getBoolean("leadersCanToggleState"));
} else config.set("leadersCanToggleState", false);
if(wconfig.isSet("officersCanToggleState")) {
config.set("officersCanToggleState", wconfig.getBoolean("officersCanToggleState"));
} else config.set("officersCanToggleState", false);
if(wconfig.isSet("membersCanToggleState")) {
config.set("membersCanToggleState", wconfig.getBoolean("membersCanToggleState"));
} else config.set("membersCanToggleState", false);
if(wconfig.isSet("extraPowerLossIfDeathByOther")) {
config.set("extraPowerLossIfDeathByOther", wconfig.getDouble("extraPowerLossIfDeathByOther"));
} else config.set("extraPowerLossIfDeathByOther", Double.valueOf(0));
if(wconfig.isSet("extraPowerWhenKillPlayer")) {
config.set("extraPowerWhenKillPlayer", wconfig.getDouble("extraPowerWhenKillPlayer"));
} else config.set("extraPowerWhenKillPlayer", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathBySuicide")) {
config.set("extraPowerLossIfDeathBySuicide", wconfig.getDouble("extraPowerLossIfDeathBySuicide"));
} else config.set("extraPowerLossIfDeathBySuicide", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByPVP")) {
config.set("extraPowerLossIfDeathByPVP", wconfig.getDouble("extraPowerLossIfDeathByPVP"));
} else config.set("extraPowerLossIfDeathByPVP", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByMob")) {
config.set("extraPowerLossIfDeathByMob", wconfig.getDouble("extraPowerLossIfDeathByMob"));
} else config.set("extraPowerLossIfDeathByMob", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByCactus")) {
config.set("extraPowerLossIfDeathByCactus", wconfig.getDouble("extraPowerLossIfDeathByCactus"));
} else config.set("extraPowerLossIfDeathByCactus", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByTNT")) {
config.set("extraPowerLossIfDeathByTNT", wconfig.getDouble("extraPowerLossIfDeathByTNT"));
} else config.set("extraPowerLossIfDeathByTNT", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByFire")) {
config.set("extraPowerLossIfDeathByFire", wconfig.getDouble("extraPowerLossIfDeathByFire"));
} else config.set("extraPowerLossIfDeathByFire", Double.valueOf(0));
if(wconfig.isSet("extraPowerLossIfDeathByPotion")) {
config.set("extraPowerLossIfDeathByPotion", wconfig.getDouble("extraPowerLossIfDeathByPotion"));
} else config.set("extraPowerLossIfDeathByPotion", Double.valueOf(0));
if(wconfig.isSet("enablePermissionGroups")) {
config.set("enablePermissionGroups", wconfig.getBoolean("enablePermissionGroups"));
} else config.set("enablePermissionGroups", Boolean.valueOf(false));
if(wconfig.isSet("economy_enable")) {
config.set("economy_enable", wconfig.getBoolean("economy_enable"));
} else config.set("economy_enable", Boolean.valueOf(false));
if(wconfig.isSet("economy_costToWarp")) {
config.set("economy_costToWarp", wconfig.getInt("economy_costToWarp"));
} else config.set("economy_costToWarp", Integer.valueOf(0));
if(wconfig.isSet("economy_costToCreateWarp")) {
config.set("economy_costToCreateWarp", wconfig.getInt("economy_costToCreateWarp"));
} else config.set("economy_costToCreateWarp", Integer.valueOf(0));
if(wconfig.isSet("economy_costToDeleteWarp")) {
config.set("economy_costToDeleteWarp", wconfig.getInt("economy_costToDeleteWarp"));
} else config.set("economy_costToDeleteWarp", Integer.valueOf(0));
if(wconfig.isSet("economy_costToAnnounce")) {
config.set("economy_costToAnnounce", wconfig.getInt("economy_costToAnnounce"));
} else config.set("economy_costToAnnounce", Integer.valueOf(0));
if(wconfig.isSet("economy_costToJail")) {
config.set("economy_costToJail", wconfig.getInt("economy_costToJail"));
} else config.set("economy_costToJail", Integer.valueOf(0));
if(wconfig.isSet("economy_costToSetJail")) {
config.set("economy_costToSetJail", wconfig.getInt("economy_costToSetJail"));
} else config.set("economy_costToSetJail", Integer.valueOf(0));
if(wconfig.isSet("economy_costToUnJail")) {
config.set("economy_costToUnJail", wconfig.getInt("economy_costToUnJail"));
} else config.set("economy_costToUnJail", Integer.valueOf(0));
if(wconfig.isSet("economy_costToToggleUpPeaceful")) {
config.set("economy_costToToggleUpPeaceful", wconfig.getInt("economy_costToToggleUpPeaceful"));
} else config.set("economy_costToToggleUpPeaceful", Integer.valueOf(0));
if(wconfig.isSet("economy_costToToggleDownPeaceful")) {
config.set("economy_costToToggleDownPeaceful", wconfig.getInt("economy_costToToggleDownPeaceful"));
} else config.set("economy_costToToggleDownPeaceful", Integer.valueOf(0));
if(wconfig.isSet("useLWCIntegrationFix")) {
config.set("useLWCIntegrationFix", wconfig.getBoolean("useLWCIntegrationFix"));
} else config.set("useLWCIntegrationFix", false);
config.set("DoNotChangeMe", Integer.valueOf(8));
config.save(configFile);
saveConfig();
} catch(Exception e) {
e.printStackTrace();
log.info("[FactionsPlus] An error occured while managing the configuration file (-18)");
getPluginLoader().disablePlugin(this);
}
if (!templatesFile.exists()) {
FactionsPlusTemplates.createTemplatesFile();
}
templates = YamlConfiguration.loadConfiguration(templatesFile);
config = YamlConfiguration.loadConfiguration(configFile);
FactionsPlusCommandManager.setup();
FactionsPlusHelpModifier.modify();
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) {
permission = permissionProvider.getProvider();
}
if(config.getBoolean("economy_enable")) {
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
}
if(getServer().getPluginManager().isPluginEnabled("DisguiseCraft")) {
pm.registerEvents(this.DCListener, this);
log.info("[FactionsPlus] Hooked into DisguiseCraft!");
isDisguiseCraftEnabled = true;
}
if(getServer().getPluginManager().isPluginEnabled("MobDisguise")) {
pm.registerEvents(this.MDListener, this);
log.info("[FactionsPlus] Hooked into MobDisguise!");
isMobDisguiseEnabled = true;
}
if(getServer().getPluginManager().isPluginEnabled("WorldEdit")) {
worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit");
log.info("[FactionsPlus] Hooked into WorldEdit!");
isWorldEditEnabled = true;
}
if(getServer().getPluginManager().isPluginEnabled("WorldGuard")) {
worldGuardPlugin = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard");
log.info("[FactionsPlus] Hooked into WorldGuard!");
isWorldGuardEnabled = true;
}
if(config.getBoolean("useLWCIntegrationFix") == true) {
if(getServer().getPluginManager().isPluginEnabled("LWC")) {
pm.registerEvents(this.LWCListener, this);
log.info("[FactionsPlus] Hooked into LWC!");
LWCFunctions.integrateLWC((LWCPlugin)getServer().getPluginManager().getPlugin("LWC"));
isLWCEnabled = true;
}
else {
log.info("[FactionsPlus] No LWC Found but Integration Option Is Enabled!");
}
}
FactionsPlus.config = YamlConfiguration.loadConfiguration(FactionsPlus.configFile);
version = getDescription().getVersion();
FactionsPlusUpdate.checkUpdates();
log.info("[FactionsPlus] Ready.");
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
log.info("[FactionsPlus] Waah! Couldn't metrics-up! :'(");
}
}
|
protected boolean activateMachine()
{
if(_inventory[0] == null || !(_inventory[0].getItem() instanceof ItemSafariNet) || _inventory[0].getTagCompound() == null || ItemSafariNet.isSingleUse(_inventory[0]))
{
setWorkDone(0);
return false;
}
if(getWorkDone() < getWorkMax())
{
if(_tank.getLiquid() != null && _tank.getLiquid().amount >= 10)
{
_tank.getLiquid().amount -= 10;
setWorkDone(getWorkDone() + 1);
return true;
}
else
{
return false;
}
}
else
{
Entity spawnedEntity = null;
try
{
spawnedEntity = EntityList.createEntityByName((String)EntityList.classToStringMapping.get(Class.forName(_inventory[0].getTagCompound().getString("_class"))), worldObj);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
return false;
}
if(!(spawnedEntity instanceof EntityLiving))
{
return false;
}
EntityLiving spawnedLiving = (EntityLiving)spawnedEntity;
spawnedLiving.initCreature();
if(_spawnExact)
{
NBTTagCompound tag = (NBTTagCompound)_inventory[0].getTagCompound().copy();
tag.removeTag("Equipment");
spawnedLiving.readEntityFromNBT(tag);
}
double x = xCoord + (worldObj.rand.nextDouble() - worldObj.rand.nextDouble()) * _spawnRange;
double y = yCoord + worldObj.rand.nextInt(3) - 1;
double z = zCoord + (worldObj.rand.nextDouble() - worldObj.rand.nextDouble()) * _spawnRange;
spawnedLiving.setLocationAndAngles(x, y, z, worldObj.rand.nextFloat() * 360.0F, 0.0F);
if(!this.worldObj.checkIfAABBIsClear(spawnedLiving.boundingBox) ||
!this.worldObj.getCollidingBoundingBoxes(spawnedLiving, spawnedLiving.boundingBox).isEmpty() ||
(this.worldObj.isAnyLiquid(spawnedLiving.boundingBox) && !(spawnedLiving instanceof EntityWaterMob)) ||
(!this.worldObj.isAnyLiquid(spawnedLiving.boundingBox) && spawnedLiving instanceof EntityWaterMob))
{
return false;
}
worldObj.spawnEntityInWorld(spawnedLiving);
worldObj.playAuxSFX(2004, this.xCoord, this.yCoord, this.zCoord, 0);
spawnedLiving.spawnExplosionParticle();
setWorkDone(0);
return true;
}
}
| protected boolean activateMachine()
{
if(_inventory[0] == null || !(_inventory[0].getItem() instanceof ItemSafariNet) || _inventory[0].getTagCompound() == null || ItemSafariNet.isSingleUse(_inventory[0]))
{
setWorkDone(0);
return false;
}
if(getWorkDone() < getWorkMax())
{
if(_tank.getLiquid() != null && _tank.getLiquid().amount >= 10)
{
_tank.getLiquid().amount -= 10;
setWorkDone(getWorkDone() + 1);
return true;
}
else
{
return false;
}
}
else
{
Entity spawnedEntity = EntityList.createEntityByName(_inventory[0].getTagCompound().getString("id"), worldObj);
if(!(spawnedEntity instanceof EntityLiving))
{
return false;
}
EntityLiving spawnedLiving = (EntityLiving)spawnedEntity;
spawnedLiving.initCreature();
if(_spawnExact)
{
NBTTagCompound tag = (NBTTagCompound)_inventory[0].getTagCompound().copy();
tag.removeTag("Equipment");
spawnedLiving.readEntityFromNBT(tag);
}
double x = xCoord + (worldObj.rand.nextDouble() - worldObj.rand.nextDouble()) * _spawnRange;
double y = yCoord + worldObj.rand.nextInt(3) - 1;
double z = zCoord + (worldObj.rand.nextDouble() - worldObj.rand.nextDouble()) * _spawnRange;
spawnedLiving.setLocationAndAngles(x, y, z, worldObj.rand.nextFloat() * 360.0F, 0.0F);
if(!this.worldObj.checkIfAABBIsClear(spawnedLiving.boundingBox) ||
!this.worldObj.getCollidingBoundingBoxes(spawnedLiving, spawnedLiving.boundingBox).isEmpty() ||
(this.worldObj.isAnyLiquid(spawnedLiving.boundingBox) && !(spawnedLiving instanceof EntityWaterMob)) ||
(!this.worldObj.isAnyLiquid(spawnedLiving.boundingBox) && spawnedLiving instanceof EntityWaterMob))
{
return false;
}
worldObj.spawnEntityInWorld(spawnedLiving);
worldObj.playAuxSFX(2004, this.xCoord, this.yCoord, this.zCoord, 0);
spawnedLiving.spawnExplosionParticle();
setWorkDone(0);
return true;
}
}
|
public void returnsFriendsInOrder() {
final Restaurant a = restaurant("a");
final Restaurant b = restaurant("b");
final Restaurant c = restaurant("c");
final UserAccount A = user("A");
final UserAccount B1 = user("B1");
final UserAccount B2 = user("B2");
final UserAccount C1 = user("C1");
Assert.assertNotNull("user has node", node(A));
A.knows(B1);
A.knows(B2);
B1.knows(C1);
C1.rate(a, 1, "");
C1.rate(b, 3, "");
C1.rate(c, 5, "");
final Node node = node(A);
final Collection<RatedRestaurant> topNRatedRestaurants = new TopRatedRestaurantFinder().getTopNRatedRestaurants(A, 5);
Collection<Restaurant> result = new ArrayList<Restaurant>();
for (RatedRestaurant ratedRestaurant : topNRatedRestaurants) {
result.add(ratedRestaurant.getRestaurant());
}
final Restaurant b2 = em.find(Restaurant.class, 2L);
Assert.assertNotNull(b2);
Assert.assertEquals(asList(b, c, a), result);
}
| public void returnsFriendsInOrder() {
final Restaurant a = restaurant("a");
final Restaurant b = restaurant("b");
final Restaurant c = restaurant("c");
final UserAccount A = user("A");
final UserAccount B1 = user("B1");
final UserAccount B2 = user("B2");
final UserAccount C1 = user("C1");
Assert.assertNotNull("user has node", node(A));
A.knows(B1);
A.knows(B2);
B1.knows(C1);
C1.rate(a, 1, "");
C1.rate(b, 5, "");
C1.rate(c, 3, "");
final Node node = node(A);
final Collection<RatedRestaurant> topNRatedRestaurants = new TopRatedRestaurantFinder().getTopNRatedRestaurants(A, 5);
Collection<Restaurant> result = new ArrayList<Restaurant>();
for (RatedRestaurant ratedRestaurant : topNRatedRestaurants) {
result.add(ratedRestaurant.getRestaurant());
}
final Restaurant b2 = em.find(Restaurant.class, 2L);
Assert.assertNotNull(b2);
Assert.assertEquals(asList(b,c, a), result);
}
|
public void transformSelectedNodes(TransformerImpl transformer)
throws TransformerException
{
final XPathContext xctxt = transformer.getXPathContext();
final int sourceNode = xctxt.getCurrentNode();
DTMIterator sourceNodes = m_selectExpression.asIterator(xctxt, sourceNode);
VariableStack vars = xctxt.getVarStack();
int nParams = getParamElemCount();
int thisframe = vars.getStackFrame();
try
{
final Vector keys = (m_sortElems == null)
? null
: transformer.processSortKeys(this, sourceNode);
if (null != keys)
sourceNodes = sortNodes(xctxt, keys, sourceNodes);
if (TransformerImpl.S_DEBUG)
{
transformer.getTraceManager().fireSelectedEvent(sourceNode, this,
"select", new XPath(m_selectExpression),
new org.apache.xpath.objects.XNodeSet(sourceNodes));
}
final ResultTreeHandler rth = transformer.getResultTreeHandler();
ContentHandler chandler = rth.getContentHandler();
final StylesheetRoot sroot = transformer.getStylesheet();
final TemplateList tl = sroot.getTemplateListComposed();
final boolean quiet = transformer.getQuietConflictWarnings();
DTM dtm = xctxt.getDTM(sourceNode);
int argsFrame = -1;
if(nParams > 0)
{
argsFrame = vars.link(nParams);
vars.setStackFrame(thisframe);
for (int i = 0; i < nParams; i++)
{
ElemWithParam ewp = m_paramElems[i];
XObject obj = ewp.getValue(transformer, sourceNode);
vars.setLocalVariable(i, obj, argsFrame);
}
vars.setStackFrame(argsFrame);
}
xctxt.pushCurrentNode(DTM.NULL);
int[] currentNodes = xctxt.getCurrentNodeStack();
int currentNodePos = xctxt.getCurrentNodeFirstFree() - 1;
xctxt.pushCurrentExpressionNode(DTM.NULL);
int[] currentExpressionNodes = xctxt.getCurrentExpressionNodeStack();
int currentExpressionNodePos = xctxt.getCurrentExpressionNodesFirstFree() - 1;
xctxt.pushSAXLocatorNull();
xctxt.pushContextNodeList(sourceNodes);
transformer.pushElemTemplateElement(null);
int child;
while (DTM.NULL != (child = sourceNodes.nextNode()))
{
currentNodes[currentNodePos] = child;
currentExpressionNodes[currentExpressionNodePos] = child;
if(xctxt.getDTM(child) != dtm)
{
dtm = xctxt.getDTM(child);
}
final int exNodeType = dtm.getExpandedTypeID(child);
final int nodeType = (exNodeType >> ExpandedNameTable.ROTAMOUNT_TYPE);
final QName mode = transformer.getMode();
ElemTemplate template = tl.getTemplateFast(xctxt, child, exNodeType, mode,
-1, quiet, dtm);
if (null == template)
{
switch (nodeType)
{
case DTM.DOCUMENT_FRAGMENT_NODE :
case DTM.ELEMENT_NODE :
template = sroot.getDefaultRule();
break;
case DTM.ATTRIBUTE_NODE :
case DTM.CDATA_SECTION_NODE :
case DTM.TEXT_NODE :
transformer.pushPairCurrentMatched(sroot.getDefaultTextRule(), child);
transformer.setCurrentElement(sroot.getDefaultTextRule());
dtm.dispatchCharactersEvents(child, rth, false);
transformer.popCurrentMatched();
continue;
case DTM.DOCUMENT_NODE :
template = sroot.getDefaultRootRule();
break;
default :
continue;
}
}
transformer.pushPairCurrentMatched(template, child);
if(template.m_frameSize > 0)
{
vars.link(template.m_frameSize);
if( template.m_inArgsSize > 0)
{
int paramIndex = 0;
for (ElemTemplateElement elem = template.getFirstChildElem();
null != elem; elem = elem.getNextSiblingElem())
{
if(Constants.ELEMNAME_PARAMVARIABLE == elem.getXSLToken())
{
ElemParam ep = (ElemParam)elem;
int i;
for (i = 0; i < nParams; i++)
{
ElemWithParam ewp = m_paramElems[i];
if(ewp.m_qnameID == ep.m_qnameID)
{
XObject obj = vars.getLocalVariable(i, argsFrame);
vars.setLocalVariable(paramIndex, obj);
break;
}
}
if(i == nParams)
vars.setLocalVariable(paramIndex, null);
}
else
break;
paramIndex++;
}
}
}
if (TransformerImpl.S_DEBUG)
transformer.getTraceManager().fireTraceEvent(template);
for (ElemTemplateElement t = template.m_firstChild;
t != null; t = t.m_nextSibling)
{
xctxt.setSAXLocator(t);
transformer.setCurrentElement(t);
t.execute(transformer);
}
if (TransformerImpl.S_DEBUG)
transformer.getTraceManager().fireTraceEndEvent(this);
if(template.m_frameSize > 0)
vars.unlink();
transformer.popCurrentMatched();
}
}
catch (SAXException se)
{
transformer.getErrorListener().fatalError(new TransformerException(se));
}
finally
{
if (TransformerImpl.S_DEBUG)
transformer.getTraceManager().fireSelectedEndEvent(sourceNode, this,
"select", new XPath(m_selectExpression),
new org.apache.xpath.objects.XNodeSet(sourceNodes));
if(nParams > 0)
vars.unlink(thisframe);
xctxt.popSAXLocator();
xctxt.popContextNodeList();
transformer.popElemTemplateElement();
xctxt.popCurrentExpressionNode();
xctxt.popCurrentNode();
sourceNodes.detach();
}
}
| public void transformSelectedNodes(TransformerImpl transformer)
throws TransformerException
{
final XPathContext xctxt = transformer.getXPathContext();
final int sourceNode = xctxt.getCurrentNode();
DTMIterator sourceNodes = m_selectExpression.asIterator(xctxt, sourceNode);
VariableStack vars = xctxt.getVarStack();
int nParams = getParamElemCount();
int thisframe = vars.getStackFrame();
try
{
final Vector keys = (m_sortElems == null)
? null
: transformer.processSortKeys(this, sourceNode);
if (null != keys)
sourceNodes = sortNodes(xctxt, keys, sourceNodes);
if (TransformerImpl.S_DEBUG)
{
transformer.getTraceManager().fireSelectedEvent(sourceNode, this,
"select", new XPath(m_selectExpression),
new org.apache.xpath.objects.XNodeSet(sourceNodes));
}
final ResultTreeHandler rth = transformer.getResultTreeHandler();
ContentHandler chandler = rth.getContentHandler();
final StylesheetRoot sroot = transformer.getStylesheet();
final TemplateList tl = sroot.getTemplateListComposed();
final boolean quiet = transformer.getQuietConflictWarnings();
DTM dtm = xctxt.getDTM(sourceNode);
int argsFrame = -1;
if(nParams > 0)
{
argsFrame = vars.link(nParams);
vars.setStackFrame(thisframe);
for (int i = 0; i < nParams; i++)
{
ElemWithParam ewp = m_paramElems[i];
XObject obj = ewp.getValue(transformer, sourceNode);
vars.setLocalVariable(i, obj, argsFrame);
}
vars.setStackFrame(argsFrame);
}
xctxt.pushCurrentNode(DTM.NULL);
int[] currentNodes = xctxt.getCurrentNodeStack();
int currentNodePos = xctxt.getCurrentNodeFirstFree() - 1;
xctxt.pushCurrentExpressionNode(DTM.NULL);
int[] currentExpressionNodes = xctxt.getCurrentExpressionNodeStack();
int currentExpressionNodePos = xctxt.getCurrentExpressionNodesFirstFree() - 1;
xctxt.pushSAXLocatorNull();
xctxt.pushContextNodeList(sourceNodes);
transformer.pushElemTemplateElement(null);
int child;
while (DTM.NULL != (child = sourceNodes.nextNode()))
{
currentNodes[currentNodePos] = child;
currentExpressionNodes[currentExpressionNodePos] = child;
if(xctxt.getDTM(child) != dtm)
{
dtm = xctxt.getDTM(child);
}
final int exNodeType = dtm.getExpandedTypeID(child);
final int nodeType = (exNodeType >> ExpandedNameTable.ROTAMOUNT_TYPE);
final QName mode = transformer.getMode();
ElemTemplate template = tl.getTemplateFast(xctxt, child, exNodeType, mode,
-1, quiet, dtm);
if (null == template)
{
switch (nodeType)
{
case DTM.DOCUMENT_FRAGMENT_NODE :
case DTM.ELEMENT_NODE :
template = sroot.getDefaultRule();
break;
case DTM.ATTRIBUTE_NODE :
case DTM.CDATA_SECTION_NODE :
case DTM.TEXT_NODE :
transformer.pushPairCurrentMatched(sroot.getDefaultTextRule(), child);
transformer.setCurrentElement(sroot.getDefaultTextRule());
dtm.dispatchCharactersEvents(child, rth, false);
transformer.popCurrentMatched();
continue;
case DTM.DOCUMENT_NODE :
template = sroot.getDefaultRootRule();
break;
default :
continue;
}
}
transformer.pushPairCurrentMatched(template, child);
int currentFrameBottom;
if(template.m_frameSize > 0)
{
xctxt.pushRTFContext();
currentFrameBottom = vars.getStackFrame();
vars.link(template.m_frameSize);
if( template.m_inArgsSize > 0)
{
int paramIndex = 0;
for (ElemTemplateElement elem = template.getFirstChildElem();
null != elem; elem = elem.getNextSiblingElem())
{
if(Constants.ELEMNAME_PARAMVARIABLE == elem.getXSLToken())
{
ElemParam ep = (ElemParam)elem;
int i;
for (i = 0; i < nParams; i++)
{
ElemWithParam ewp = m_paramElems[i];
if(ewp.m_qnameID == ep.m_qnameID)
{
XObject obj = vars.getLocalVariable(i, argsFrame);
vars.setLocalVariable(paramIndex, obj);
break;
}
}
if(i == nParams)
vars.setLocalVariable(paramIndex, null);
}
else
break;
paramIndex++;
}
}
}
else
currentFrameBottom = 0;
if (TransformerImpl.S_DEBUG)
transformer.getTraceManager().fireTraceEvent(template);
for (ElemTemplateElement t = template.m_firstChild;
t != null; t = t.m_nextSibling)
{
xctxt.setSAXLocator(t);
transformer.setCurrentElement(t);
t.execute(transformer);
}
if (TransformerImpl.S_DEBUG)
transformer.getTraceManager().fireTraceEndEvent(template);
if(template.m_frameSize > 0)
{
vars.unlink(currentFrameBottom);
xctxt.popRTFContext();
}
transformer.popCurrentMatched();
}
}
catch (SAXException se)
{
transformer.getErrorListener().fatalError(new TransformerException(se));
}
finally
{
if (TransformerImpl.S_DEBUG)
transformer.getTraceManager().fireSelectedEndEvent(sourceNode, this,
"select", new XPath(m_selectExpression),
new org.apache.xpath.objects.XNodeSet(sourceNodes));
if(nParams > 0)
vars.unlink(thisframe);
xctxt.popSAXLocator();
xctxt.popContextNodeList();
transformer.popElemTemplateElement();
xctxt.popCurrentExpressionNode();
xctxt.popCurrentNode();
sourceNodes.detach();
}
}
|
public void update(GameContainer gc, int delta) {
Input input = gc.getInput();
if(input.isKeyPressed(Input.KEY_DOWN)){
y++;
if(y > HEIGHT-1){
y = 0;
}
}
if(input.isKeyPressed(Input.KEY_UP)){
y--;
if(y < 0){
y = HEIGHT;
}
}
if(input.isKeyPressed(Input.KEY_RIGHT)){
x++;
if(x > WIDTH-1){
x = 0;
}
}
if(input.isKeyPressed(Input.KEY_LEFT)){
x--;
if(x < 0){
x = WIDTH;
}
}
if(input.isKeyPressed(Input.KEY_SPACE)){
lock.lock();
switch(state){
case UnitPlacement :
if(queue[0] == null){
queue[0] = new Location(x,y);
condition.signalAll();
}
break;
case UnitSwitching :
case GamePhase :
if(queue[0] == null){
queue[0] = new Location(x,y);
}
else if(queue[1] == null){
queue[1] = new Location(x,y);
condition.signalAll();
}
else{
condition.signalAll();
}
}
lock.unlock();
}
if(input.isKeyPressed(Input.KEY_Q)){
endInitPhase = true;
}
}
| public void update(GameContainer gc, int delta) {
Input input = gc.getInput();
if(input.isKeyPressed(Input.KEY_DOWN)){
y++;
if(y > HEIGHT-1){
y = 0;
}
}
if(input.isKeyPressed(Input.KEY_UP)){
y--;
if(y < 0){
y = HEIGHT-1;
}
}
if(input.isKeyPressed(Input.KEY_RIGHT)){
x++;
if(x > WIDTH-1){
x = 0;
}
}
if(input.isKeyPressed(Input.KEY_LEFT)){
x--;
if(x < 0){
x = WIDTH-1;
}
}
if(input.isKeyPressed(Input.KEY_SPACE)){
lock.lock();
switch(state){
case UnitPlacement :
if(queue[0] == null){
queue[0] = new Location(x,y);
condition.signalAll();
}
break;
case UnitSwitching :
case GamePhase :
if(queue[0] == null){
queue[0] = new Location(x,y);
}
else if(queue[1] == null){
queue[1] = new Location(x,y);
condition.signalAll();
}
else{
condition.signalAll();
}
}
lock.unlock();
}
if(input.isKeyPressed(Input.KEY_Q)){
endInitPhase = true;
}
}
|
protected short[] decodeSamples(Processor processor, int vagAddr, int size) {
Memory mem = Processor.memory;
short[] samples = new short[size / 16 * 28];
int numSamples = 0;
int headerCheck = mem.read32(vagAddr);
if ((headerCheck & 0x00FFFFFF) == 0x00474156) {
vagAddr += 0x30;
}
int[] unpackedSamples = new int[28];
int hist1 = 0;
int hist2 = 0;
final double[][] VAG_f = {
{ 0.0 , 0.0 },
{ 60.0 / 64.0, 0.0 },
{ 115.0 / 64.0, -52.0 / 64.0 },
{ 98.0 / 64.0, -55.0 / 64.0 },
{ 122.0 / 64.0, -60.0 / 64.0 }
};
for (int i = 0; i <= (size - 16); ) {
int n = mem.read8(vagAddr + i);
i++;
int predict_nr = n >> 4;
int shift_factor = n & 0x0F;
int flag = mem.read8(vagAddr + i);
i++;
if (flag == 0x07) {
break;
}
for (int j = 0; j < 28; j += 2) {
int d = mem.read8(vagAddr + i);
i++;
int s = (short) ((d & 0x0F) << 12);
unpackedSamples[j] = s >> shift_factor;
s = (short) ((d & 0xF0) << 8);
unpackedSamples[j + 1] = s >> shift_factor;
}
for (int j = 0; j < 28; j++) {
int sample = (int) (unpackedSamples[j] + hist1 * VAG_f[predict_nr][0] + hist2 * VAG_f[predict_nr][1]);
hist2 = hist1;
hist1 = sample;
if (sample < -32768) {
samples[numSamples] = -32768;
} else if (sample > 0x7FFF) {
samples[numSamples] = 0x7FFF;
} else {
samples[numSamples] = (short) sample;
}
numSamples++;
}
}
if (samples.length != numSamples) {
short[] resizedSamples = new short[numSamples];
for (int i = 0; i < numSamples; i++) {
resizedSamples[i] = samples[i];
}
samples = resizedSamples;
}
return samples;
}
| protected short[] decodeSamples(Processor processor, int vagAddr, int size) {
Memory mem = Processor.memory;
short[] samples = new short[size / 16 * 28];
int numSamples = 0;
int headerCheck = mem.read32(vagAddr);
if ((headerCheck & 0x00FFFFFF) == 0x00474156) {
vagAddr += 0x30;
}
int[] unpackedSamples = new int[28];
int hist1 = 0;
int hist2 = 0;
final double[][] VAG_f = {
{ 0.0 , 0.0 },
{ 60.0 / 64.0, 0.0 },
{ 115.0 / 64.0, -52.0 / 64.0 },
{ 98.0 / 64.0, -55.0 / 64.0 },
{ 122.0 / 64.0, -60.0 / 64.0 }
};
for (int i = 0; i <= (size - 16); ) {
int n = mem.read8(vagAddr + i);
i++;
int predict_nr = n >> 4;
if (predict_nr >= VAG_f.length) {
Modules.log.warn("sceSasCore.decodeSamples: Unknown value for predict_nr: " + predict_nr);
predict_nr = 0;
}
int shift_factor = n & 0x0F;
int flag = mem.read8(vagAddr + i);
i++;
if (flag == 0x07) {
break;
}
for (int j = 0; j < 28; j += 2) {
int d = mem.read8(vagAddr + i);
i++;
int s = (short) ((d & 0x0F) << 12);
unpackedSamples[j] = s >> shift_factor;
s = (short) ((d & 0xF0) << 8);
unpackedSamples[j + 1] = s >> shift_factor;
}
for (int j = 0; j < 28; j++) {
int sample = (int) (unpackedSamples[j] + hist1 * VAG_f[predict_nr][0] + hist2 * VAG_f[predict_nr][1]);
hist2 = hist1;
hist1 = sample;
if (sample < -32768) {
samples[numSamples] = -32768;
} else if (sample > 0x7FFF) {
samples[numSamples] = 0x7FFF;
} else {
samples[numSamples] = (short) sample;
}
numSamples++;
}
}
if (samples.length != numSamples) {
short[] resizedSamples = new short[numSamples];
for (int i = 0; i < numSamples; i++) {
resizedSamples[i] = samples[i];
}
samples = resizedSamples;
}
return samples;
}
|
private void putValues() {
put(SiteTokens.HOME, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.homeSpace);
}
});
put(SiteTokens.WAVEINBOX, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.userSpace);
}
});
put(SiteTokens.SIGNIN, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
signIn.get().showSignInDialog();
}
});
put(SiteTokens.REGISTER, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
register.get().doRegister();
}
});
put(SiteTokens.NEWGROUP, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
newGroup.get().doNewGroup();
}
});
put(SiteTokens.ABOUTKUNE, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
aboutKuneDialog.get().showCentered();
}
});
put(SiteTokens.TRANSLATE, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
if (session.getInitData().isTranslatorEnabled()) {
translator.get().show();
}
}
});
put(SiteTokens.SUBTITLES, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
subProvider.get().show(token);
}
});
}
| private void putValues() {
put(SiteTokens.HOME, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.homeSpace);
}
});
put(SiteTokens.WAVEINBOX, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.userSpace);
}
});
put(SiteTokens.SIGNIN, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
signIn.get().showSignInDialog();
}
});
put(SiteTokens.REGISTER, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
register.get().doRegister();
}
});
put(SiteTokens.NEWGROUP, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
newGroup.get().doNewGroup();
}
});
put(SiteTokens.ABOUTKUNE, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
aboutKuneDialog.get().showCentered();
}
});
put(SiteTokens.TRANSLATE, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
if (session.isLogged() && session.getInitData().isTranslatorEnabled()) {
translator.get().show();
}
}
});
put(SiteTokens.SUBTITLES, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
subProvider.get().show(token);
}
});
}
|
protected Cursor queryLocal(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder, long directoryId) {
if (VERBOSE_LOGGING) {
Log.v(TAG, "query: " + uri);
}
if (mActiveDb.get() == null) {
mActiveDb.set(mContactsHelper.getReadableDatabase());
}
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String groupBy = null;
String limit = getLimit(uri);
boolean snippetDeferred = false;
String addressBookIndexerCountExpression = null;
final int match = sUriMatcher.match(uri);
switch (match) {
case SYNCSTATE:
case PROFILE_SYNCSTATE:
return mDbHelper.get().getSyncState().query(mActiveDb.get(), projection, selection,
selectionArgs, sortOrder);
case CONTACTS: {
setTablesAndProjectionMapForContacts(qb, uri, projection);
appendLocalDirectorySelectionIfNeeded(qb, directoryId);
break;
}
case CONTACTS_ID: {
long contactId = ContentUris.parseId(uri);
setTablesAndProjectionMapForContacts(qb, uri, projection);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(Contacts._ID + "=?");
break;
}
case CONTACTS_LOOKUP:
case CONTACTS_LOOKUP_ID: {
List<String> pathSegments = uri.getPathSegments();
int segmentCount = pathSegments.size();
if (segmentCount < 3) {
throw new IllegalArgumentException(mDbHelper.get().exceptionMessage(
"Missing a lookup key", uri));
}
String lookupKey = pathSegments.get(2);
if (segmentCount == 4) {
long contactId = Long.parseLong(pathSegments.get(3));
SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
setTablesAndProjectionMapForContacts(lookupQb, uri, projection);
Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri,
projection, selection, selectionArgs, sortOrder, groupBy, limit,
Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey);
if (c != null) {
return c;
}
}
setTablesAndProjectionMapForContacts(qb, uri, projection);
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey)));
qb.appendWhere(Contacts._ID + "=?");
break;
}
case CONTACTS_LOOKUP_DATA:
case CONTACTS_LOOKUP_ID_DATA:
case CONTACTS_LOOKUP_PHOTO:
case CONTACTS_LOOKUP_ID_PHOTO: {
List<String> pathSegments = uri.getPathSegments();
int segmentCount = pathSegments.size();
if (segmentCount < 4) {
throw new IllegalArgumentException(mDbHelper.get().exceptionMessage(
"Missing a lookup key", uri));
}
String lookupKey = pathSegments.get(2);
if (segmentCount == 5) {
long contactId = Long.parseLong(pathSegments.get(3));
SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
setTablesAndProjectionMapForData(lookupQb, uri, projection, false);
if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) {
qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
}
lookupQb.appendWhere(" AND ");
Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri,
projection, selection, selectionArgs, sortOrder, groupBy, limit,
Data.CONTACT_ID, contactId, Data.LOOKUP_KEY, lookupKey);
if (c != null) {
return c;
}
}
setTablesAndProjectionMapForData(qb, uri, projection, false);
long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey);
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(contactId));
if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) {
qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
}
qb.appendWhere(" AND " + Data.CONTACT_ID + "=?");
break;
}
case CONTACTS_ID_STREAM_ITEMS: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForStreamItems(qb);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(StreamItems.CONTACT_ID + "=?");
break;
}
case CONTACTS_LOOKUP_STREAM_ITEMS:
case CONTACTS_LOOKUP_ID_STREAM_ITEMS: {
List<String> pathSegments = uri.getPathSegments();
int segmentCount = pathSegments.size();
if (segmentCount < 4) {
throw new IllegalArgumentException(mDbHelper.get().exceptionMessage(
"Missing a lookup key", uri));
}
String lookupKey = pathSegments.get(2);
if (segmentCount == 5) {
long contactId = Long.parseLong(pathSegments.get(3));
SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
setTablesAndProjectionMapForStreamItems(lookupQb);
Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri,
projection, selection, selectionArgs, sortOrder, groupBy, limit,
StreamItems.CONTACT_ID, contactId,
StreamItems.CONTACT_LOOKUP_KEY, lookupKey);
if (c != null) {
return c;
}
}
setTablesAndProjectionMapForStreamItems(qb);
long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(RawContacts.CONTACT_ID + "=?");
break;
}
case CONTACTS_AS_VCARD: {
final String lookupKey = Uri.encode(uri.getPathSegments().get(2));
long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey);
qb.setTables(Views.CONTACTS);
qb.setProjectionMap(sContactsVCardProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(contactId));
qb.appendWhere(Contacts._ID + "=?");
break;
}
case CONTACTS_AS_MULTI_VCARD: {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateString = dateFormat.format(new Date()).toString();
return mActiveDb.get().rawQuery(
"SELECT" +
" 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," +
" NULL AS " + OpenableColumns.SIZE,
new String[] { currentDateString });
}
case CONTACTS_FILTER: {
String filterParam = "";
boolean deferredSnipRequested = deferredSnippetingRequested(uri);
if (uri.getPathSegments().size() > 2) {
filterParam = uri.getLastPathSegment();
}
setTablesAndProjectionMapForContactsWithSnippet(
qb, uri, projection, filterParam, directoryId,
deferredSnipRequested);
snippetDeferred = isSingleWordQuery(filterParam) &&
deferredSnipRequested && snippetNeeded(projection);
break;
}
case CONTACTS_STREQUENT_FILTER:
case CONTACTS_STREQUENT: {
final boolean phoneOnly = readBooleanQueryParameter(
uri, ContactsContract.STREQUENT_PHONE_ONLY, false);
if (match == CONTACTS_STREQUENT_FILTER && uri.getPathSegments().size() > 3) {
String filterParam = uri.getLastPathSegment();
StringBuilder sb = new StringBuilder();
sb.append(Contacts._ID + " IN ");
appendContactFilterAsNestedQuery(sb, filterParam);
selection = DbQueryUtils.concatenateClauses(selection, sb.toString());
}
String[] subProjection = null;
if (projection != null) {
subProjection = appendProjectionArg(projection, TIMES_USED_SORT_COLUMN);
}
setTablesAndProjectionMapForContacts(qb, uri, projection, false);
qb.setProjectionMap(phoneOnly ?
sStrequentPhoneOnlyStarredProjectionMap
: sStrequentStarredProjectionMap);
if (phoneOnly) {
qb.appendWhere(DbQueryUtils.concatenateClauses(
selection, Contacts.HAS_PHONE_NUMBER + "=1"));
}
qb.setStrict(true);
final String starredQuery = qb.buildQuery(subProjection,
Contacts.STARRED + "=1", Contacts._ID, null, null, null);
qb = new SQLiteQueryBuilder();
qb.setStrict(true);
final String frequentQuery;
if (phoneOnly) {
final StringBuilder tableBuilder = new StringBuilder();
tableBuilder.append(Tables.DATA_USAGE_STAT
+ " INNER JOIN " + Views.DATA + " " + Tables.DATA
+ " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "="
+ DataColumns.CONCRETE_ID + " AND "
+ DataUsageStatColumns.CONCRETE_USAGE_TYPE + "="
+ DataUsageStatColumns.USAGE_TYPE_INT_CALL + ")");
appendContactPresenceJoin(tableBuilder, projection, RawContacts.CONTACT_ID);
appendContactStatusUpdateJoin(tableBuilder, projection,
ContactsColumns.LAST_STATUS_UPDATE_ID);
qb.setTables(tableBuilder.toString());
qb.setProjectionMap(sStrequentPhoneOnlyFrequentProjectionMap);
qb.appendWhere(DbQueryUtils.concatenateClauses(
selection,
Contacts.STARRED + "=0 OR " + Contacts.STARRED + " IS NULL",
MimetypesColumns.MIMETYPE + " IN ("
+ "'" + Phone.CONTENT_ITEM_TYPE + "', "
+ "'" + SipAddress.CONTENT_ITEM_TYPE + "')"));
frequentQuery = qb.buildQuery(subProjection, null, null, null, null, null);
} else {
setTablesAndProjectionMapForContacts(qb, uri, projection, true);
qb.setProjectionMap(sStrequentFrequentProjectionMap);
qb.appendWhere(DbQueryUtils.concatenateClauses(
selection,
"(" + Contacts.STARRED + " =0 OR " + Contacts.STARRED + " IS NULL)"));
frequentQuery = qb.buildQuery(subProjection,
null, Contacts._ID, null, null, null);
}
final String unionQuery =
qb.buildUnionQuery(new String[] {starredQuery, frequentQuery},
STREQUENT_ORDER_BY, STREQUENT_LIMIT);
String[] doubledSelectionArgs = null;
if (selectionArgs != null) {
final int length = selectionArgs.length;
doubledSelectionArgs = new String[length * 2];
System.arraycopy(selectionArgs, 0, doubledSelectionArgs, 0, length);
System.arraycopy(selectionArgs, 0, doubledSelectionArgs, length, length);
}
Cursor cursor = mActiveDb.get().rawQuery(unionQuery, doubledSelectionArgs);
if (cursor != null) {
cursor.setNotificationUri(getContext().getContentResolver(),
ContactsContract.AUTHORITY_URI);
}
return cursor;
}
case CONTACTS_FREQUENT: {
setTablesAndProjectionMapForContacts(qb, uri, projection, true);
qb.setProjectionMap(sStrequentFrequentProjectionMap);
groupBy = Contacts._ID;
if (!TextUtils.isEmpty(sortOrder)) {
sortOrder = FREQUENT_ORDER_BY + ", " + sortOrder;
} else {
sortOrder = FREQUENT_ORDER_BY;
}
break;
}
case CONTACTS_GROUP: {
setTablesAndProjectionMapForContacts(qb, uri, projection);
if (uri.getPathSegments().size() > 2) {
qb.appendWhere(CONTACTS_IN_GROUP_SELECT);
String groupMimeTypeId = String.valueOf(
mDbHelper.get().getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE));
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
selectionArgs = insertSelectionArg(selectionArgs, groupMimeTypeId);
}
break;
}
case PROFILE: {
setTablesAndProjectionMapForContacts(qb, uri, projection);
break;
}
case PROFILE_ENTITIES: {
setTablesAndProjectionMapForEntities(qb, uri, projection);
break;
}
case PROFILE_AS_VCARD: {
qb.setTables(Views.CONTACTS);
qb.setProjectionMap(sContactsVCardProjectionMap);
break;
}
case CONTACTS_ID_DATA: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?");
break;
}
case CONTACTS_ID_PHOTO: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?");
qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
break;
}
case CONTACTS_ID_ENTITIES: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForEntities(qb, uri, projection);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?");
break;
}
case CONTACTS_LOOKUP_ENTITIES:
case CONTACTS_LOOKUP_ID_ENTITIES: {
List<String> pathSegments = uri.getPathSegments();
int segmentCount = pathSegments.size();
if (segmentCount < 4) {
throw new IllegalArgumentException(mDbHelper.get().exceptionMessage(
"Missing a lookup key", uri));
}
String lookupKey = pathSegments.get(2);
if (segmentCount == 5) {
long contactId = Long.parseLong(pathSegments.get(3));
SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
setTablesAndProjectionMapForEntities(lookupQb, uri, projection);
lookupQb.appendWhere(" AND ");
Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri,
projection, selection, selectionArgs, sortOrder, groupBy, limit,
Contacts.Entity.CONTACT_ID, contactId,
Contacts.Entity.LOOKUP_KEY, lookupKey);
if (c != null) {
return c;
}
}
setTablesAndProjectionMapForEntities(qb, uri, projection);
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey)));
qb.appendWhere(" AND " + Contacts.Entity.CONTACT_ID + "=?");
break;
}
case STREAM_ITEMS: {
setTablesAndProjectionMapForStreamItems(qb);
break;
}
case STREAM_ITEMS_ID: {
setTablesAndProjectionMapForStreamItems(qb);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(StreamItems._ID + "=?");
break;
}
case STREAM_ITEMS_LIMIT: {
MatrixCursor cursor = new MatrixCursor(new String[]{StreamItems.MAX_ITEMS}, 1);
cursor.addRow(new Object[]{MAX_STREAM_ITEMS_PER_RAW_CONTACT});
return cursor;
}
case STREAM_ITEMS_PHOTOS: {
setTablesAndProjectionMapForStreamItemPhotos(qb);
break;
}
case STREAM_ITEMS_ID_PHOTOS: {
setTablesAndProjectionMapForStreamItemPhotos(qb);
String streamItemId = uri.getPathSegments().get(1);
selectionArgs = insertSelectionArg(selectionArgs, streamItemId);
qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?");
break;
}
case STREAM_ITEMS_ID_PHOTOS_ID: {
setTablesAndProjectionMapForStreamItemPhotos(qb);
String streamItemId = uri.getPathSegments().get(1);
String streamItemPhotoId = uri.getPathSegments().get(3);
selectionArgs = insertSelectionArg(selectionArgs, streamItemPhotoId);
selectionArgs = insertSelectionArg(selectionArgs, streamItemId);
qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=? AND " +
StreamItemPhotosColumns.CONCRETE_ID + "=?");
break;
}
case PHOTO_DIMENSIONS: {
MatrixCursor cursor = new MatrixCursor(
new String[]{DisplayPhoto.DISPLAY_MAX_DIM, DisplayPhoto.THUMBNAIL_MAX_DIM},
1);
cursor.addRow(new Object[]{mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim});
return cursor;
}
case PHONES: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + "=" +
mDbHelper.get().getMimeTypeIdForPhone());
groupBy = RawContacts.CONTACT_ID + ", " + Data.DATA1;
addressBookIndexerCountExpression = "DISTINCT "
+ RawContacts.CONTACT_ID + "||','||" + Data.DATA1;
break;
}
case PHONES_ID: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForPhone());
qb.appendWhere(" AND " + Data._ID + "=?");
break;
}
case PHONES_FILTER: {
String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE);
Integer typeInt = sDataUsageTypeMap.get(typeParam);
if (typeInt == null) {
typeInt = DataUsageStatColumns.USAGE_TYPE_INT_CALL;
}
setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForPhone());
if (uri.getPathSegments().size() > 2) {
String filterParam = uri.getLastPathSegment();
StringBuilder sb = new StringBuilder();
sb.append(" AND (");
boolean hasCondition = false;
boolean orNeeded = false;
final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery(
filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING);
if (ftsMatchQuery.length() > 0) {
sb.append(Data.RAW_CONTACT_ID + " IN " +
"(SELECT " + RawContactsColumns.CONCRETE_ID +
" FROM " + Tables.SEARCH_INDEX +
" JOIN " + Tables.RAW_CONTACTS +
" ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID
+ "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" +
" WHERE " + SearchIndexColumns.NAME + " MATCH '");
sb.append(ftsMatchQuery);
sb.append("')");
orNeeded = true;
hasCondition = true;
}
String number = PhoneNumberUtils.normalizeNumber(filterParam);
if (!TextUtils.isEmpty(number)) {
if (orNeeded) {
sb.append(" OR ");
}
sb.append(Data._ID +
" IN (SELECT DISTINCT " + PhoneLookupColumns.DATA_ID
+ " FROM " + Tables.PHONE_LOOKUP
+ " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '");
sb.append(number);
sb.append("%')");
hasCondition = true;
}
if (!hasCondition) {
sb.append("0");
}
sb.append(")");
qb.appendWhere(sb);
}
groupBy = "(CASE WHEN " + PhoneColumns.NORMALIZED_NUMBER
+ " IS NOT NULL THEN " + PhoneColumns.NORMALIZED_NUMBER
+ " ELSE " + Phone.NUMBER + " END), " + RawContacts.CONTACT_ID;
if (sortOrder == null) {
final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri);
if (!TextUtils.isEmpty(accountPromotionSortOrder)) {
sortOrder = accountPromotionSortOrder + ", " + PHONE_FILTER_SORT_ORDER;
} else {
sortOrder = PHONE_FILTER_SORT_ORDER;
}
}
break;
}
case EMAILS: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForEmail());
break;
}
case EMAILS_ID: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForEmail()
+ " AND " + Data._ID + "=?");
break;
}
case EMAILS_LOOKUP: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForEmail());
if (uri.getPathSegments().size() > 2) {
String email = uri.getLastPathSegment();
String address = mDbHelper.get().extractAddressFromEmailAddress(email);
selectionArgs = insertSelectionArg(selectionArgs, address);
qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)");
}
break;
}
case EMAILS_FILTER: {
String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE);
Integer typeInt = sDataUsageTypeMap.get(typeParam);
if (typeInt == null) {
typeInt = DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT;
}
setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt);
String filterParam = null;
if (uri.getPathSegments().size() > 3) {
filterParam = uri.getLastPathSegment();
if (TextUtils.isEmpty(filterParam)) {
filterParam = null;
}
}
if (filterParam == null) {
qb.appendWhere(" AND 0");
} else {
StringBuilder sb = new StringBuilder();
sb.append(" AND " + Data._ID + " IN (");
sb.append(
"SELECT " + Data._ID +
" FROM " + Tables.DATA +
" WHERE " + DataColumns.MIMETYPE_ID + "=");
sb.append(mDbHelper.get().getMimeTypeIdForEmail());
sb.append(" AND " + Data.DATA1 + " LIKE ");
DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%');
if (!filterParam.contains("@")) {
sb.append(
" UNION SELECT " + Data._ID +
" FROM " + Tables.DATA +
" WHERE +" + DataColumns.MIMETYPE_ID + "=");
sb.append(mDbHelper.get().getMimeTypeIdForEmail());
sb.append(" AND " + Data.RAW_CONTACT_ID + " IN " +
"(SELECT " + RawContactsColumns.CONCRETE_ID +
" FROM " + Tables.SEARCH_INDEX +
" JOIN " + Tables.RAW_CONTACTS +
" ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID
+ "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" +
" WHERE " + SearchIndexColumns.NAME + " MATCH '");
final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery(
filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING);
sb.append(ftsMatchQuery);
sb.append("')");
}
sb.append(")");
qb.appendWhere(sb);
}
groupBy = Email.DATA + "," + RawContacts.CONTACT_ID;
if (sortOrder == null) {
final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri);
if (!TextUtils.isEmpty(accountPromotionSortOrder)) {
sortOrder = accountPromotionSortOrder + ", " + EMAIL_FILTER_SORT_ORDER;
} else {
sortOrder = EMAIL_FILTER_SORT_ORDER;
}
}
break;
}
case POSTALS: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForStructuredPostal());
break;
}
case POSTALS_ID: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForStructuredPostal());
qb.appendWhere(" AND " + Data._ID + "=?");
break;
}
case RAW_CONTACTS:
case PROFILE_RAW_CONTACTS: {
setTablesAndProjectionMapForRawContacts(qb, uri);
break;
}
case RAW_CONTACTS_ID:
case PROFILE_RAW_CONTACTS_ID: {
long rawContactId = ContentUris.parseId(uri);
setTablesAndProjectionMapForRawContacts(qb, uri);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(" AND " + RawContacts._ID + "=?");
break;
}
case RAW_CONTACTS_DATA:
case PROFILE_RAW_CONTACTS_ID_DATA: {
int segment = match == RAW_CONTACTS_DATA ? 1 : 2;
long rawContactId = Long.parseLong(uri.getPathSegments().get(segment));
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?");
break;
}
case RAW_CONTACTS_ID_STREAM_ITEMS: {
long rawContactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForStreamItems(qb);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=?");
break;
}
case RAW_CONTACTS_ID_STREAM_ITEMS_ID: {
long rawContactId = Long.parseLong(uri.getPathSegments().get(1));
long streamItemId = Long.parseLong(uri.getPathSegments().get(3));
setTablesAndProjectionMapForStreamItems(qb);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(streamItemId));
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=? AND " +
StreamItems._ID + "=?");
break;
}
case PROFILE_RAW_CONTACTS_ID_ENTITIES: {
long rawContactId = Long.parseLong(uri.getPathSegments().get(2));
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
setTablesAndProjectionMapForRawEntities(qb, uri);
qb.appendWhere(" AND " + RawContacts._ID + "=?");
break;
}
case DATA:
case PROFILE_DATA: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
break;
}
case DATA_ID:
case PROFILE_DATA_ID: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(" AND " + Data._ID + "=?");
break;
}
case PROFILE_PHOTO: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
break;
}
case PHONE_LOOKUP: {
selection = null;
selectionArgs = null;
if (uri.getBooleanQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, false)) {
if (TextUtils.isEmpty(sortOrder)) {
sortOrder = Contacts.DISPLAY_NAME + " ASC";
}
String sipAddress = uri.getPathSegments().size() > 1
? Uri.decode(uri.getLastPathSegment()) : "";
setTablesAndProjectionMapForData(qb, uri, null, false, true);
StringBuilder sb = new StringBuilder();
selectionArgs = mDbHelper.get().buildSipContactQuery(sb, sipAddress);
selection = sb.toString();
} else {
if (TextUtils.isEmpty(sortOrder)) {
sortOrder = " length(lookup.normalized_number) DESC";
}
String number = uri.getPathSegments().size() > 1
? uri.getLastPathSegment() : "";
String numberE164 = PhoneNumberUtils.formatNumberToE164(number,
mDbHelper.get().getCurrentCountryIso());
String normalizedNumber =
PhoneNumberUtils.normalizeNumber(number);
mDbHelper.get().buildPhoneLookupAndContactQuery(
qb, normalizedNumber, numberE164);
qb.setProjectionMap(sPhoneLookupProjectionMap);
}
break;
}
case GROUPS: {
qb.setTables(Views.GROUPS);
qb.setProjectionMap(sGroupsProjectionMap);
appendAccountFromParameter(qb, uri);
break;
}
case GROUPS_ID: {
qb.setTables(Views.GROUPS);
qb.setProjectionMap(sGroupsProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(Groups._ID + "=?");
break;
}
case GROUPS_SUMMARY: {
final boolean returnGroupCountPerAccount =
readBooleanQueryParameter(uri, Groups.PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT,
false);
String tables = Views.GROUPS + " AS " + Tables.GROUPS;
if (hasColumn(projection, Groups.SUMMARY_COUNT)) {
tables = tables + Joins.GROUP_MEMBER_COUNT;
}
qb.setTables(tables);
qb.setProjectionMap(returnGroupCountPerAccount ?
sGroupsSummaryProjectionMapWithGroupCountPerAccount
: sGroupsSummaryProjectionMap);
appendAccountFromParameter(qb, uri);
groupBy = GroupsColumns.CONCRETE_ID;
break;
}
case AGGREGATION_EXCEPTIONS: {
qb.setTables(Tables.AGGREGATION_EXCEPTIONS);
qb.setProjectionMap(sAggregationExceptionsProjectionMap);
break;
}
case AGGREGATION_SUGGESTIONS: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
String filter = null;
if (uri.getPathSegments().size() > 3) {
filter = uri.getPathSegments().get(3);
}
final int maxSuggestions;
if (limit != null) {
maxSuggestions = Integer.parseInt(limit);
} else {
maxSuggestions = DEFAULT_MAX_SUGGESTIONS;
}
ArrayList<AggregationSuggestionParameter> parameters = null;
List<String> query = uri.getQueryParameters("query");
if (query != null && !query.isEmpty()) {
parameters = new ArrayList<AggregationSuggestionParameter>(query.size());
for (String parameter : query) {
int offset = parameter.indexOf(':');
parameters.add(offset == -1
? new AggregationSuggestionParameter(
AggregationSuggestions.PARAMETER_MATCH_NAME,
parameter)
: new AggregationSuggestionParameter(
parameter.substring(0, offset),
parameter.substring(offset + 1)));
}
}
setTablesAndProjectionMapForContacts(qb, uri, projection);
return mAggregator.get().queryAggregationSuggestions(qb, projection, contactId,
maxSuggestions, filter, parameters);
}
case SETTINGS: {
qb.setTables(Tables.SETTINGS);
qb.setProjectionMap(sSettingsProjectionMap);
appendAccountFromParameter(qb, uri);
final String groupMembershipMimetypeId = Long.toString(mDbHelper.get()
.getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE));
if (projection != null && projection.length != 0 &&
mDbHelper.get().isInProjection(projection, Settings.UNGROUPED_COUNT)) {
selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId);
}
if (projection != null && projection.length != 0 &&
mDbHelper.get().isInProjection(
projection, Settings.UNGROUPED_WITH_PHONES)) {
selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId);
}
break;
}
case STATUS_UPDATES:
case PROFILE_STATUS_UPDATES: {
setTableAndProjectionMapForStatusUpdates(qb, projection);
break;
}
case STATUS_UPDATES_ID: {
setTableAndProjectionMapForStatusUpdates(qb, projection);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(DataColumns.CONCRETE_ID + "=?");
break;
}
case SEARCH_SUGGESTIONS: {
return mGlobalSearchSupport.handleSearchSuggestionsQuery(
mActiveDb.get(), uri, projection, limit);
}
case SEARCH_SHORTCUT: {
String lookupKey = uri.getLastPathSegment();
String filter = getQueryParameter(
uri, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
return mGlobalSearchSupport.handleSearchShortcutRefresh(
mActiveDb.get(), projection, lookupKey, filter);
}
case RAW_CONTACT_ENTITIES:
case PROFILE_RAW_CONTACT_ENTITIES: {
setTablesAndProjectionMapForRawEntities(qb, uri);
break;
}
case RAW_CONTACT_ENTITY_ID: {
long rawContactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForRawEntities(qb, uri);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(" AND " + RawContacts._ID + "=?");
break;
}
case PROVIDER_STATUS: {
return queryProviderStatus(uri, projection);
}
case DIRECTORIES : {
qb.setTables(Tables.DIRECTORIES);
qb.setProjectionMap(sDirectoryProjectionMap);
break;
}
case DIRECTORIES_ID : {
long id = ContentUris.parseId(uri);
qb.setTables(Tables.DIRECTORIES);
qb.setProjectionMap(sDirectoryProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(id));
qb.appendWhere(Directory._ID + "=?");
break;
}
case COMPLETE_NAME: {
return completeName(uri, projection);
}
default:
return mLegacyApiSupport.query(uri, projection, selection, selectionArgs,
sortOrder, limit);
}
qb.setStrict(true);
Cursor cursor =
query(mActiveDb.get(), qb, projection, selection, selectionArgs, sortOrder, groupBy,
limit);
if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) {
cursor = bundleLetterCountExtras(cursor, mActiveDb.get(), qb, selection,
selectionArgs, sortOrder, addressBookIndexerCountExpression);
}
if (snippetDeferred) {
cursor = addDeferredSnippetingExtra(cursor);
}
return cursor;
}
| protected Cursor queryLocal(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder, long directoryId) {
if (VERBOSE_LOGGING) {
Log.v(TAG, "query: " + uri);
}
if (mActiveDb.get() == null) {
mActiveDb.set(mContactsHelper.getReadableDatabase());
}
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String groupBy = null;
String limit = getLimit(uri);
boolean snippetDeferred = false;
String addressBookIndexerCountExpression = null;
final int match = sUriMatcher.match(uri);
switch (match) {
case SYNCSTATE:
case PROFILE_SYNCSTATE:
return mDbHelper.get().getSyncState().query(mActiveDb.get(), projection, selection,
selectionArgs, sortOrder);
case CONTACTS: {
setTablesAndProjectionMapForContacts(qb, uri, projection);
appendLocalDirectorySelectionIfNeeded(qb, directoryId);
break;
}
case CONTACTS_ID: {
long contactId = ContentUris.parseId(uri);
setTablesAndProjectionMapForContacts(qb, uri, projection);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(Contacts._ID + "=?");
break;
}
case CONTACTS_LOOKUP:
case CONTACTS_LOOKUP_ID: {
List<String> pathSegments = uri.getPathSegments();
int segmentCount = pathSegments.size();
if (segmentCount < 3) {
throw new IllegalArgumentException(mDbHelper.get().exceptionMessage(
"Missing a lookup key", uri));
}
String lookupKey = pathSegments.get(2);
if (segmentCount == 4) {
long contactId = Long.parseLong(pathSegments.get(3));
SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
setTablesAndProjectionMapForContacts(lookupQb, uri, projection);
Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri,
projection, selection, selectionArgs, sortOrder, groupBy, limit,
Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey);
if (c != null) {
return c;
}
}
setTablesAndProjectionMapForContacts(qb, uri, projection);
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey)));
qb.appendWhere(Contacts._ID + "=?");
break;
}
case CONTACTS_LOOKUP_DATA:
case CONTACTS_LOOKUP_ID_DATA:
case CONTACTS_LOOKUP_PHOTO:
case CONTACTS_LOOKUP_ID_PHOTO: {
List<String> pathSegments = uri.getPathSegments();
int segmentCount = pathSegments.size();
if (segmentCount < 4) {
throw new IllegalArgumentException(mDbHelper.get().exceptionMessage(
"Missing a lookup key", uri));
}
String lookupKey = pathSegments.get(2);
if (segmentCount == 5) {
long contactId = Long.parseLong(pathSegments.get(3));
SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
setTablesAndProjectionMapForData(lookupQb, uri, projection, false);
if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) {
qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
}
lookupQb.appendWhere(" AND ");
Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri,
projection, selection, selectionArgs, sortOrder, groupBy, limit,
Data.CONTACT_ID, contactId, Data.LOOKUP_KEY, lookupKey);
if (c != null) {
return c;
}
}
setTablesAndProjectionMapForData(qb, uri, projection, false);
long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey);
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(contactId));
if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) {
qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
}
qb.appendWhere(" AND " + Data.CONTACT_ID + "=?");
break;
}
case CONTACTS_ID_STREAM_ITEMS: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForStreamItems(qb);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(StreamItems.CONTACT_ID + "=?");
break;
}
case CONTACTS_LOOKUP_STREAM_ITEMS:
case CONTACTS_LOOKUP_ID_STREAM_ITEMS: {
List<String> pathSegments = uri.getPathSegments();
int segmentCount = pathSegments.size();
if (segmentCount < 4) {
throw new IllegalArgumentException(mDbHelper.get().exceptionMessage(
"Missing a lookup key", uri));
}
String lookupKey = pathSegments.get(2);
if (segmentCount == 5) {
long contactId = Long.parseLong(pathSegments.get(3));
SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
setTablesAndProjectionMapForStreamItems(lookupQb);
Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri,
projection, selection, selectionArgs, sortOrder, groupBy, limit,
StreamItems.CONTACT_ID, contactId,
StreamItems.CONTACT_LOOKUP_KEY, lookupKey);
if (c != null) {
return c;
}
}
setTablesAndProjectionMapForStreamItems(qb);
long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(RawContacts.CONTACT_ID + "=?");
break;
}
case CONTACTS_AS_VCARD: {
final String lookupKey = Uri.encode(uri.getPathSegments().get(2));
long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey);
qb.setTables(Views.CONTACTS);
qb.setProjectionMap(sContactsVCardProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(contactId));
qb.appendWhere(Contacts._ID + "=?");
break;
}
case CONTACTS_AS_MULTI_VCARD: {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateString = dateFormat.format(new Date()).toString();
return mActiveDb.get().rawQuery(
"SELECT" +
" 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," +
" NULL AS " + OpenableColumns.SIZE,
new String[] { currentDateString });
}
case CONTACTS_FILTER: {
String filterParam = "";
boolean deferredSnipRequested = deferredSnippetingRequested(uri);
if (uri.getPathSegments().size() > 2) {
filterParam = uri.getLastPathSegment();
}
setTablesAndProjectionMapForContactsWithSnippet(
qb, uri, projection, filterParam, directoryId,
deferredSnipRequested);
snippetDeferred = isSingleWordQuery(filterParam) &&
deferredSnipRequested && snippetNeeded(projection);
break;
}
case CONTACTS_STREQUENT_FILTER:
case CONTACTS_STREQUENT: {
final boolean phoneOnly = readBooleanQueryParameter(
uri, ContactsContract.STREQUENT_PHONE_ONLY, false);
if (match == CONTACTS_STREQUENT_FILTER && uri.getPathSegments().size() > 3) {
String filterParam = uri.getLastPathSegment();
StringBuilder sb = new StringBuilder();
sb.append(Contacts._ID + " IN ");
appendContactFilterAsNestedQuery(sb, filterParam);
selection = DbQueryUtils.concatenateClauses(selection, sb.toString());
}
String[] subProjection = null;
if (projection != null) {
subProjection = appendProjectionArg(projection, TIMES_USED_SORT_COLUMN);
}
setTablesAndProjectionMapForContacts(qb, uri, projection, false);
qb.setProjectionMap(phoneOnly ?
sStrequentPhoneOnlyStarredProjectionMap
: sStrequentStarredProjectionMap);
if (phoneOnly) {
qb.appendWhere(DbQueryUtils.concatenateClauses(
selection, Contacts.HAS_PHONE_NUMBER + "=1"));
}
qb.setStrict(true);
final String starredQuery = qb.buildQuery(subProjection,
Contacts.STARRED + "=1", Contacts._ID, null, null, null);
qb = new SQLiteQueryBuilder();
qb.setStrict(true);
final String frequentQuery;
if (phoneOnly) {
final StringBuilder tableBuilder = new StringBuilder();
tableBuilder.append(Tables.DATA_USAGE_STAT
+ " INNER JOIN " + Views.DATA + " " + Tables.DATA
+ " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "="
+ DataColumns.CONCRETE_ID + " AND "
+ DataUsageStatColumns.CONCRETE_USAGE_TYPE + "="
+ DataUsageStatColumns.USAGE_TYPE_INT_CALL + ")");
appendContactPresenceJoin(tableBuilder, projection, RawContacts.CONTACT_ID);
appendContactStatusUpdateJoin(tableBuilder, projection,
ContactsColumns.LAST_STATUS_UPDATE_ID);
qb.setTables(tableBuilder.toString());
qb.setProjectionMap(sStrequentPhoneOnlyFrequentProjectionMap);
qb.appendWhere(DbQueryUtils.concatenateClauses(
selection,
Contacts.STARRED + "=0 OR " + Contacts.STARRED + " IS NULL",
MimetypesColumns.MIMETYPE + " IN ("
+ "'" + Phone.CONTENT_ITEM_TYPE + "', "
+ "'" + SipAddress.CONTENT_ITEM_TYPE + "')"));
frequentQuery = qb.buildQuery(subProjection, null, null, null, null, null);
} else {
setTablesAndProjectionMapForContacts(qb, uri, projection, true);
qb.setProjectionMap(sStrequentFrequentProjectionMap);
qb.appendWhere(DbQueryUtils.concatenateClauses(
selection,
"(" + Contacts.STARRED + " =0 OR " + Contacts.STARRED + " IS NULL)"));
frequentQuery = qb.buildQuery(subProjection,
null, Contacts._ID, null, null, null);
}
final String unionQuery =
qb.buildUnionQuery(new String[] {starredQuery, frequentQuery},
STREQUENT_ORDER_BY, STREQUENT_LIMIT);
String[] doubledSelectionArgs = null;
if (selectionArgs != null) {
final int length = selectionArgs.length;
doubledSelectionArgs = new String[length * 2];
System.arraycopy(selectionArgs, 0, doubledSelectionArgs, 0, length);
System.arraycopy(selectionArgs, 0, doubledSelectionArgs, length, length);
}
Cursor cursor = mActiveDb.get().rawQuery(unionQuery, doubledSelectionArgs);
if (cursor != null) {
cursor.setNotificationUri(getContext().getContentResolver(),
ContactsContract.AUTHORITY_URI);
}
return cursor;
}
case CONTACTS_FREQUENT: {
setTablesAndProjectionMapForContacts(qb, uri, projection, true);
qb.setProjectionMap(sStrequentFrequentProjectionMap);
groupBy = Contacts._ID;
if (!TextUtils.isEmpty(sortOrder)) {
sortOrder = FREQUENT_ORDER_BY + ", " + sortOrder;
} else {
sortOrder = FREQUENT_ORDER_BY;
}
break;
}
case CONTACTS_GROUP: {
setTablesAndProjectionMapForContacts(qb, uri, projection);
if (uri.getPathSegments().size() > 2) {
qb.appendWhere(CONTACTS_IN_GROUP_SELECT);
String groupMimeTypeId = String.valueOf(
mDbHelper.get().getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE));
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
selectionArgs = insertSelectionArg(selectionArgs, groupMimeTypeId);
}
break;
}
case PROFILE: {
setTablesAndProjectionMapForContacts(qb, uri, projection);
break;
}
case PROFILE_ENTITIES: {
setTablesAndProjectionMapForEntities(qb, uri, projection);
break;
}
case PROFILE_AS_VCARD: {
qb.setTables(Views.CONTACTS);
qb.setProjectionMap(sContactsVCardProjectionMap);
break;
}
case CONTACTS_ID_DATA: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?");
break;
}
case CONTACTS_ID_PHOTO: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?");
qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
break;
}
case CONTACTS_ID_ENTITIES: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForEntities(qb, uri, projection);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?");
break;
}
case CONTACTS_LOOKUP_ENTITIES:
case CONTACTS_LOOKUP_ID_ENTITIES: {
List<String> pathSegments = uri.getPathSegments();
int segmentCount = pathSegments.size();
if (segmentCount < 4) {
throw new IllegalArgumentException(mDbHelper.get().exceptionMessage(
"Missing a lookup key", uri));
}
String lookupKey = pathSegments.get(2);
if (segmentCount == 5) {
long contactId = Long.parseLong(pathSegments.get(3));
SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
setTablesAndProjectionMapForEntities(lookupQb, uri, projection);
lookupQb.appendWhere(" AND ");
Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri,
projection, selection, selectionArgs, sortOrder, groupBy, limit,
Contacts.Entity.CONTACT_ID, contactId,
Contacts.Entity.LOOKUP_KEY, lookupKey);
if (c != null) {
return c;
}
}
setTablesAndProjectionMapForEntities(qb, uri, projection);
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey)));
qb.appendWhere(" AND " + Contacts.Entity.CONTACT_ID + "=?");
break;
}
case STREAM_ITEMS: {
setTablesAndProjectionMapForStreamItems(qb);
break;
}
case STREAM_ITEMS_ID: {
setTablesAndProjectionMapForStreamItems(qb);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(StreamItems._ID + "=?");
break;
}
case STREAM_ITEMS_LIMIT: {
MatrixCursor cursor = new MatrixCursor(new String[]{StreamItems.MAX_ITEMS}, 1);
cursor.addRow(new Object[]{MAX_STREAM_ITEMS_PER_RAW_CONTACT});
return cursor;
}
case STREAM_ITEMS_PHOTOS: {
setTablesAndProjectionMapForStreamItemPhotos(qb);
break;
}
case STREAM_ITEMS_ID_PHOTOS: {
setTablesAndProjectionMapForStreamItemPhotos(qb);
String streamItemId = uri.getPathSegments().get(1);
selectionArgs = insertSelectionArg(selectionArgs, streamItemId);
qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?");
break;
}
case STREAM_ITEMS_ID_PHOTOS_ID: {
setTablesAndProjectionMapForStreamItemPhotos(qb);
String streamItemId = uri.getPathSegments().get(1);
String streamItemPhotoId = uri.getPathSegments().get(3);
selectionArgs = insertSelectionArg(selectionArgs, streamItemPhotoId);
selectionArgs = insertSelectionArg(selectionArgs, streamItemId);
qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=? AND " +
StreamItemPhotosColumns.CONCRETE_ID + "=?");
break;
}
case PHOTO_DIMENSIONS: {
MatrixCursor cursor = new MatrixCursor(
new String[]{DisplayPhoto.DISPLAY_MAX_DIM, DisplayPhoto.THUMBNAIL_MAX_DIM},
1);
cursor.addRow(new Object[]{mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim});
return cursor;
}
case PHONES: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + "=" +
mDbHelper.get().getMimeTypeIdForPhone());
groupBy = RawContacts.CONTACT_ID + ", " + Data.DATA1;
addressBookIndexerCountExpression = "DISTINCT "
+ RawContacts.CONTACT_ID + "||','||" + Data.DATA1;
break;
}
case PHONES_ID: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForPhone());
qb.appendWhere(" AND " + Data._ID + "=?");
break;
}
case PHONES_FILTER: {
String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE);
Integer typeInt = sDataUsageTypeMap.get(typeParam);
if (typeInt == null) {
typeInt = DataUsageStatColumns.USAGE_TYPE_INT_CALL;
}
setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForPhone());
if (uri.getPathSegments().size() > 2) {
String filterParam = uri.getLastPathSegment();
StringBuilder sb = new StringBuilder();
sb.append(" AND (");
boolean hasCondition = false;
boolean orNeeded = false;
final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery(
filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING);
if (ftsMatchQuery.length() > 0) {
sb.append(Data.RAW_CONTACT_ID + " IN " +
"(SELECT " + RawContactsColumns.CONCRETE_ID +
" FROM " + Tables.SEARCH_INDEX +
" JOIN " + Tables.RAW_CONTACTS +
" ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID
+ "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" +
" WHERE " + SearchIndexColumns.NAME + " MATCH '");
sb.append(ftsMatchQuery);
sb.append("')");
orNeeded = true;
hasCondition = true;
}
String number = PhoneNumberUtils.normalizeNumber(filterParam);
if (!TextUtils.isEmpty(number)) {
if (orNeeded) {
sb.append(" OR ");
}
sb.append(Data._ID +
" IN (SELECT DISTINCT " + PhoneLookupColumns.DATA_ID
+ " FROM " + Tables.PHONE_LOOKUP
+ " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '");
sb.append(number);
sb.append("%')");
hasCondition = true;
}
if (!hasCondition) {
sb.append("0");
}
sb.append(")");
qb.appendWhere(sb);
}
groupBy = "(CASE WHEN " + PhoneColumns.NORMALIZED_NUMBER
+ " IS NOT NULL THEN " + PhoneColumns.NORMALIZED_NUMBER
+ " ELSE " + Phone.NUMBER + " END), " + RawContacts.CONTACT_ID;
if (sortOrder == null) {
final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri);
if (!TextUtils.isEmpty(accountPromotionSortOrder)) {
sortOrder = accountPromotionSortOrder + ", " + PHONE_FILTER_SORT_ORDER;
} else {
sortOrder = PHONE_FILTER_SORT_ORDER;
}
}
break;
}
case EMAILS: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForEmail());
break;
}
case EMAILS_ID: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForEmail()
+ " AND " + Data._ID + "=?");
break;
}
case EMAILS_LOOKUP: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForEmail());
if (uri.getPathSegments().size() > 2) {
String email = uri.getLastPathSegment();
String address = mDbHelper.get().extractAddressFromEmailAddress(email);
selectionArgs = insertSelectionArg(selectionArgs, address);
qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)");
}
if (sortOrder == null) {
sortOrder = "(" + RawContacts.CONTACT_ID + " IN " +
Tables.DEFAULT_DIRECTORY + ") DESC";
}
break;
}
case EMAILS_FILTER: {
String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE);
Integer typeInt = sDataUsageTypeMap.get(typeParam);
if (typeInt == null) {
typeInt = DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT;
}
setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt);
String filterParam = null;
if (uri.getPathSegments().size() > 3) {
filterParam = uri.getLastPathSegment();
if (TextUtils.isEmpty(filterParam)) {
filterParam = null;
}
}
if (filterParam == null) {
qb.appendWhere(" AND 0");
} else {
StringBuilder sb = new StringBuilder();
sb.append(" AND " + Data._ID + " IN (");
sb.append(
"SELECT " + Data._ID +
" FROM " + Tables.DATA +
" WHERE " + DataColumns.MIMETYPE_ID + "=");
sb.append(mDbHelper.get().getMimeTypeIdForEmail());
sb.append(" AND " + Data.DATA1 + " LIKE ");
DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%');
if (!filterParam.contains("@")) {
sb.append(
" UNION SELECT " + Data._ID +
" FROM " + Tables.DATA +
" WHERE +" + DataColumns.MIMETYPE_ID + "=");
sb.append(mDbHelper.get().getMimeTypeIdForEmail());
sb.append(" AND " + Data.RAW_CONTACT_ID + " IN " +
"(SELECT " + RawContactsColumns.CONCRETE_ID +
" FROM " + Tables.SEARCH_INDEX +
" JOIN " + Tables.RAW_CONTACTS +
" ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID
+ "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" +
" WHERE " + SearchIndexColumns.NAME + " MATCH '");
final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery(
filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING);
sb.append(ftsMatchQuery);
sb.append("')");
}
sb.append(")");
qb.appendWhere(sb);
}
groupBy = Email.DATA + "," + RawContacts.CONTACT_ID;
if (sortOrder == null) {
final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri);
if (!TextUtils.isEmpty(accountPromotionSortOrder)) {
sortOrder = accountPromotionSortOrder + ", " + EMAIL_FILTER_SORT_ORDER;
} else {
sortOrder = EMAIL_FILTER_SORT_ORDER;
}
}
break;
}
case POSTALS: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForStructuredPostal());
break;
}
case POSTALS_ID: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = "
+ mDbHelper.get().getMimeTypeIdForStructuredPostal());
qb.appendWhere(" AND " + Data._ID + "=?");
break;
}
case RAW_CONTACTS:
case PROFILE_RAW_CONTACTS: {
setTablesAndProjectionMapForRawContacts(qb, uri);
break;
}
case RAW_CONTACTS_ID:
case PROFILE_RAW_CONTACTS_ID: {
long rawContactId = ContentUris.parseId(uri);
setTablesAndProjectionMapForRawContacts(qb, uri);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(" AND " + RawContacts._ID + "=?");
break;
}
case RAW_CONTACTS_DATA:
case PROFILE_RAW_CONTACTS_ID_DATA: {
int segment = match == RAW_CONTACTS_DATA ? 1 : 2;
long rawContactId = Long.parseLong(uri.getPathSegments().get(segment));
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?");
break;
}
case RAW_CONTACTS_ID_STREAM_ITEMS: {
long rawContactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForStreamItems(qb);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=?");
break;
}
case RAW_CONTACTS_ID_STREAM_ITEMS_ID: {
long rawContactId = Long.parseLong(uri.getPathSegments().get(1));
long streamItemId = Long.parseLong(uri.getPathSegments().get(3));
setTablesAndProjectionMapForStreamItems(qb);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(streamItemId));
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=? AND " +
StreamItems._ID + "=?");
break;
}
case PROFILE_RAW_CONTACTS_ID_ENTITIES: {
long rawContactId = Long.parseLong(uri.getPathSegments().get(2));
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
setTablesAndProjectionMapForRawEntities(qb, uri);
qb.appendWhere(" AND " + RawContacts._ID + "=?");
break;
}
case DATA:
case PROFILE_DATA: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
break;
}
case DATA_ID:
case PROFILE_DATA_ID: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(" AND " + Data._ID + "=?");
break;
}
case PROFILE_PHOTO: {
setTablesAndProjectionMapForData(qb, uri, projection, false);
qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
break;
}
case PHONE_LOOKUP: {
selection = null;
selectionArgs = null;
if (uri.getBooleanQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, false)) {
if (TextUtils.isEmpty(sortOrder)) {
sortOrder = Contacts.DISPLAY_NAME + " ASC";
}
String sipAddress = uri.getPathSegments().size() > 1
? Uri.decode(uri.getLastPathSegment()) : "";
setTablesAndProjectionMapForData(qb, uri, null, false, true);
StringBuilder sb = new StringBuilder();
selectionArgs = mDbHelper.get().buildSipContactQuery(sb, sipAddress);
selection = sb.toString();
} else {
if (TextUtils.isEmpty(sortOrder)) {
sortOrder = " length(lookup.normalized_number) DESC";
}
String number = uri.getPathSegments().size() > 1
? uri.getLastPathSegment() : "";
String numberE164 = PhoneNumberUtils.formatNumberToE164(number,
mDbHelper.get().getCurrentCountryIso());
String normalizedNumber =
PhoneNumberUtils.normalizeNumber(number);
mDbHelper.get().buildPhoneLookupAndContactQuery(
qb, normalizedNumber, numberE164);
qb.setProjectionMap(sPhoneLookupProjectionMap);
}
break;
}
case GROUPS: {
qb.setTables(Views.GROUPS);
qb.setProjectionMap(sGroupsProjectionMap);
appendAccountFromParameter(qb, uri);
break;
}
case GROUPS_ID: {
qb.setTables(Views.GROUPS);
qb.setProjectionMap(sGroupsProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(Groups._ID + "=?");
break;
}
case GROUPS_SUMMARY: {
final boolean returnGroupCountPerAccount =
readBooleanQueryParameter(uri, Groups.PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT,
false);
String tables = Views.GROUPS + " AS " + Tables.GROUPS;
if (hasColumn(projection, Groups.SUMMARY_COUNT)) {
tables = tables + Joins.GROUP_MEMBER_COUNT;
}
qb.setTables(tables);
qb.setProjectionMap(returnGroupCountPerAccount ?
sGroupsSummaryProjectionMapWithGroupCountPerAccount
: sGroupsSummaryProjectionMap);
appendAccountFromParameter(qb, uri);
groupBy = GroupsColumns.CONCRETE_ID;
break;
}
case AGGREGATION_EXCEPTIONS: {
qb.setTables(Tables.AGGREGATION_EXCEPTIONS);
qb.setProjectionMap(sAggregationExceptionsProjectionMap);
break;
}
case AGGREGATION_SUGGESTIONS: {
long contactId = Long.parseLong(uri.getPathSegments().get(1));
String filter = null;
if (uri.getPathSegments().size() > 3) {
filter = uri.getPathSegments().get(3);
}
final int maxSuggestions;
if (limit != null) {
maxSuggestions = Integer.parseInt(limit);
} else {
maxSuggestions = DEFAULT_MAX_SUGGESTIONS;
}
ArrayList<AggregationSuggestionParameter> parameters = null;
List<String> query = uri.getQueryParameters("query");
if (query != null && !query.isEmpty()) {
parameters = new ArrayList<AggregationSuggestionParameter>(query.size());
for (String parameter : query) {
int offset = parameter.indexOf(':');
parameters.add(offset == -1
? new AggregationSuggestionParameter(
AggregationSuggestions.PARAMETER_MATCH_NAME,
parameter)
: new AggregationSuggestionParameter(
parameter.substring(0, offset),
parameter.substring(offset + 1)));
}
}
setTablesAndProjectionMapForContacts(qb, uri, projection);
return mAggregator.get().queryAggregationSuggestions(qb, projection, contactId,
maxSuggestions, filter, parameters);
}
case SETTINGS: {
qb.setTables(Tables.SETTINGS);
qb.setProjectionMap(sSettingsProjectionMap);
appendAccountFromParameter(qb, uri);
final String groupMembershipMimetypeId = Long.toString(mDbHelper.get()
.getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE));
if (projection != null && projection.length != 0 &&
mDbHelper.get().isInProjection(projection, Settings.UNGROUPED_COUNT)) {
selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId);
}
if (projection != null && projection.length != 0 &&
mDbHelper.get().isInProjection(
projection, Settings.UNGROUPED_WITH_PHONES)) {
selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId);
}
break;
}
case STATUS_UPDATES:
case PROFILE_STATUS_UPDATES: {
setTableAndProjectionMapForStatusUpdates(qb, projection);
break;
}
case STATUS_UPDATES_ID: {
setTableAndProjectionMapForStatusUpdates(qb, projection);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(DataColumns.CONCRETE_ID + "=?");
break;
}
case SEARCH_SUGGESTIONS: {
return mGlobalSearchSupport.handleSearchSuggestionsQuery(
mActiveDb.get(), uri, projection, limit);
}
case SEARCH_SHORTCUT: {
String lookupKey = uri.getLastPathSegment();
String filter = getQueryParameter(
uri, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
return mGlobalSearchSupport.handleSearchShortcutRefresh(
mActiveDb.get(), projection, lookupKey, filter);
}
case RAW_CONTACT_ENTITIES:
case PROFILE_RAW_CONTACT_ENTITIES: {
setTablesAndProjectionMapForRawEntities(qb, uri);
break;
}
case RAW_CONTACT_ENTITY_ID: {
long rawContactId = Long.parseLong(uri.getPathSegments().get(1));
setTablesAndProjectionMapForRawEntities(qb, uri);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
qb.appendWhere(" AND " + RawContacts._ID + "=?");
break;
}
case PROVIDER_STATUS: {
return queryProviderStatus(uri, projection);
}
case DIRECTORIES : {
qb.setTables(Tables.DIRECTORIES);
qb.setProjectionMap(sDirectoryProjectionMap);
break;
}
case DIRECTORIES_ID : {
long id = ContentUris.parseId(uri);
qb.setTables(Tables.DIRECTORIES);
qb.setProjectionMap(sDirectoryProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(id));
qb.appendWhere(Directory._ID + "=?");
break;
}
case COMPLETE_NAME: {
return completeName(uri, projection);
}
default:
return mLegacyApiSupport.query(uri, projection, selection, selectionArgs,
sortOrder, limit);
}
qb.setStrict(true);
Cursor cursor =
query(mActiveDb.get(), qb, projection, selection, selectionArgs, sortOrder, groupBy,
limit);
if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) {
cursor = bundleLetterCountExtras(cursor, mActiveDb.get(), qb, selection,
selectionArgs, sortOrder, addressBookIndexerCountExpression);
}
if (snippetDeferred) {
cursor = addDeferredSnippetingExtra(cursor);
}
return cursor;
}
|
public Object getFacet(String name, HttpServletRequest request, Object targetObject, Class targetObjectClass) {
logger.debug("Trying to get facet " + name + " for target object " + targetObject + ", targetObjectClass " + targetObjectClass + "...");
String username = getUsername(request);
List<String> roles;
if (username==null) {
roles = fallbackRoles;
logger.debug("Username not supplied, using fallback roles : " + fallbackRoles);
} else {
roles = userManager.getRoles(username);
if (roles==null || roles.size()==0) {
logger.debug("No roles returned for user '" + username + "', using fallback roles : " + fallbackRoles);
roles = fallbackRoles;
}
logger.debug("Using roles $roles found for user " + username);
}
if (!roles.contains(ROLE_ALL)) {
roles = new ArrayList<String>(roles);
roles.add(ROLE_ALL);
}
if (targetObject==null && targetObjectClass==null) {
logger.debug("No object or class provided, defaulting to Object.class");
targetObjectClass = Object.class;
}
if (targetObjectClass==null && targetObject!=null) {
targetObjectClass = targetObject.getClass();
}
for (String role : roles) {
logger.debug("Trying role : " + role);
Object facet = jFacets.getFacet(name, role, targetObject, targetObjectClass);
if (facet!=null) {
request.setAttribute(name, facet);
logger.debug("Facet found and bound to request with name '" + name + "', returning " + facet);
return facet;
}
}
logger.debug("Facet not found for name: " + name + ", roles: " + roles + ", targetObject: " + targetObject + ", targetObjectClass: " + targetObjectClass + ", returning null");
return null;
}
| public Object getFacet(String name, HttpServletRequest request, Object targetObject, Class targetObjectClass) {
logger.debug("Trying to get facet " + name + " for target object " + targetObject + ", targetObjectClass " + targetObjectClass + "...");
String username = getUsername(request);
List<String> roles;
if (username==null) {
roles = fallbackRoles;
logger.debug("Username not supplied, using fallback roles : " + fallbackRoles);
} else {
roles = userManager.getRoles(username);
if (roles==null || roles.size()==0) {
logger.debug("No roles returned for user '" + username + "', using fallback roles : " + fallbackRoles);
roles = fallbackRoles;
}
logger.debug("Using roles " + roles + " for user " + username);
}
if (!roles.contains(ROLE_ALL)) {
roles = new ArrayList<String>(roles);
roles.add(ROLE_ALL);
}
if (targetObject==null && targetObjectClass==null) {
logger.debug("No object or class provided, defaulting to Object.class");
targetObjectClass = Object.class;
}
if (targetObjectClass==null && targetObject!=null) {
targetObjectClass = targetObject.getClass();
}
for (String role : roles) {
logger.debug("Trying role : " + role);
Object facet = jFacets.getFacet(name, role, targetObject, targetObjectClass);
if (facet!=null) {
request.setAttribute(name, facet);
logger.debug("Facet found and bound to request with name '" + name + "', returning " + facet);
return facet;
}
}
logger.debug("Facet not found for name: " + name + ", roles: " + roles + ", targetObject: " + targetObject + ", targetObjectClass: " + targetObjectClass + ", returning null");
return null;
}
|
public boolean onCommand(final CommandSender sender, final Command cmd,
final String commandLabel, final String[] args) {
if (args.length < 1) {
sender.sendMessage("�e�l|-- PVP Arena --|");
sender.sendMessage("�e�o--By slipcor--");
sender.sendMessage("�7�oDo �e/pa help �7�ofor help.");
return true;
}
if (args.length > 1 && sender.hasPermission("pvparena.admin")
&& args[0].equalsIgnoreCase("ALL")) {
final String [] newArgs = StringParser.shiftArrayBy(args, 1);
for (Arena arena : ArenaManager.getArenas()) {
try {
Bukkit.getServer().dispatchCommand(
sender,
"pa " + arena.getName() + " "
+ StringParser.joinArray(newArgs, " "));
} catch (Exception e) {
getLogger().warning("arena null!");
}
}
return true;
}
final AbstractGlobalCommand pacmd = AbstractGlobalCommand.getByName(args[0]);
ArenaPlayer player = ArenaPlayer.parsePlayer(sender.getName());
if (pacmd != null
&& !((player.getArena() != null) && (pacmd
.getName().contains("PAI_ArenaList")))) {
player.getArena().getDebugger().i("committing: " + pacmd.getName(), sender);
pacmd.commit(sender, StringParser.shiftArrayBy(args, 1));
return true;
}
if (args[0].equalsIgnoreCase("-s")
|| args[0].equalsIgnoreCase("stats")) {
final PAI_Stats scmd = new PAI_Stats();
DEBUG.i("committing: " + scmd.getName(), sender);
scmd.commit(null, sender, StringParser.shiftArrayBy(args, 1));
return true;
} else if (args.length > 1 &&
(args[1].equalsIgnoreCase("-s")
|| args[1].equalsIgnoreCase("stats"))) {
final PAI_Stats scmd = new PAI_Stats();
DEBUG.i("committing: " + scmd.getName(), sender);
scmd.commit(ArenaManager.getArenaByName(args[0]), sender, StringParser.shiftArrayBy(args, 2));
return true;
} else if (args[0].equalsIgnoreCase("!rl")
|| args[0].toLowerCase().contains("reload")) {
final PAA_Reload scmd = new PAA_Reload();
DEBUG.i("committing: " + scmd.getName(), sender);
this.reloadConfig();
final String[] emptyArray = new String[0];
for (Arena a : ArenaManager.getArenas()) {
scmd.commit(a, sender, emptyArray);
}
ArenaManager.load_arenas();
return true;
}
Arena tempArena = ArenaManager.getArenaByName(args[0]);
final String name = args[0];
String[] newArgs = args;
if (tempArena == null) {
if (sender instanceof Player
&& ArenaPlayer.parsePlayer(sender.getName()).getArena() != null) {
tempArena = ArenaPlayer.parsePlayer(sender.getName()).getArena();
} else if (PAA_Edit.activeEdits.containsKey(sender.getName())) {
tempArena = PAA_Edit.activeEdits.get(sender.getName());
} else if (ArenaManager.count() == 1) {
tempArena = ArenaManager.getFirst();
} else if (ArenaManager.count() < 1) {
Arena.pmsg(sender, Language.parse(MSG.ERROR_NO_ARENAS));
return true;
}
} else {
if (args != null && args.length > 1) {
newArgs = StringParser.shiftArrayBy(args, 1);
}
}
if (tempArena == null) {
Arena.pmsg(sender, Language.parse(MSG.ERROR_ARENA_NOTFOUND, name));
return true;
}
AbstractArenaCommand paacmd = AbstractArenaCommand.getByName(newArgs[0]);
if (paacmd == null && (PACheck.handleCommand(tempArena, sender, newArgs))) {
return true;
}
if (paacmd == null
&& tempArena.getArenaConfig().getBoolean(CFG.CMDS_DEFAULTJOIN)) {
paacmd = new PAG_Join();
if (newArgs.length > 1) {
newArgs = StringParser.shiftArrayBy(newArgs, 1);
}
tempArena.getDebugger().i("committing: " + paacmd.getName(), sender);
paacmd.commit(tempArena, sender, newArgs);
return true;
}
if (paacmd != null) {
tempArena.getDebugger().i("committing: " + paacmd.getName(), sender);
paacmd.commit(tempArena, sender, StringParser.shiftArrayBy(newArgs, 1));
return true;
}
tempArena.getDebugger().i("cmd null", sender);
return false;
}
| public boolean onCommand(final CommandSender sender, final Command cmd,
final String commandLabel, final String[] args) {
if (args.length < 1) {
sender.sendMessage("�e�l|-- PVP Arena --|");
sender.sendMessage("�e�o--By slipcor--");
sender.sendMessage("�7�oDo �e/pa help �7�ofor help.");
return true;
}
if (args.length > 1 && sender.hasPermission("pvparena.admin")
&& args[0].equalsIgnoreCase("ALL")) {
final String [] newArgs = StringParser.shiftArrayBy(args, 1);
for (Arena arena : ArenaManager.getArenas()) {
try {
Bukkit.getServer().dispatchCommand(
sender,
"pa " + arena.getName() + " "
+ StringParser.joinArray(newArgs, " "));
} catch (Exception e) {
getLogger().warning("arena null!");
}
}
return true;
}
final AbstractGlobalCommand pacmd = AbstractGlobalCommand.getByName(args[0]);
ArenaPlayer player = ArenaPlayer.parsePlayer(sender.getName());
if (pacmd != null
&& !((player.getArena() != null) && (pacmd
.getName().contains("PAI_ArenaList")))) {
DEBUG.i("committing: " + pacmd.getName(), sender);
pacmd.commit(sender, StringParser.shiftArrayBy(args, 1));
return true;
}
if (args[0].equalsIgnoreCase("-s")
|| args[0].equalsIgnoreCase("stats")) {
final PAI_Stats scmd = new PAI_Stats();
DEBUG.i("committing: " + scmd.getName(), sender);
scmd.commit(null, sender, StringParser.shiftArrayBy(args, 1));
return true;
} else if (args.length > 1 &&
(args[1].equalsIgnoreCase("-s")
|| args[1].equalsIgnoreCase("stats"))) {
final PAI_Stats scmd = new PAI_Stats();
DEBUG.i("committing: " + scmd.getName(), sender);
scmd.commit(ArenaManager.getArenaByName(args[0]), sender, StringParser.shiftArrayBy(args, 2));
return true;
} else if (args[0].equalsIgnoreCase("!rl")
|| args[0].toLowerCase().contains("reload")) {
final PAA_Reload scmd = new PAA_Reload();
DEBUG.i("committing: " + scmd.getName(), sender);
this.reloadConfig();
final String[] emptyArray = new String[0];
for (Arena a : ArenaManager.getArenas()) {
scmd.commit(a, sender, emptyArray);
}
ArenaManager.load_arenas();
return true;
}
Arena tempArena = ArenaManager.getArenaByName(args[0]);
final String name = args[0];
String[] newArgs = args;
if (tempArena == null) {
if (sender instanceof Player
&& ArenaPlayer.parsePlayer(sender.getName()).getArena() != null) {
tempArena = ArenaPlayer.parsePlayer(sender.getName()).getArena();
} else if (PAA_Edit.activeEdits.containsKey(sender.getName())) {
tempArena = PAA_Edit.activeEdits.get(sender.getName());
} else if (ArenaManager.count() == 1) {
tempArena = ArenaManager.getFirst();
} else if (ArenaManager.count() < 1) {
Arena.pmsg(sender, Language.parse(MSG.ERROR_NO_ARENAS));
return true;
}
} else {
if (args != null && args.length > 1) {
newArgs = StringParser.shiftArrayBy(args, 1);
}
}
if (tempArena == null) {
Arena.pmsg(sender, Language.parse(MSG.ERROR_ARENA_NOTFOUND, name));
return true;
}
AbstractArenaCommand paacmd = AbstractArenaCommand.getByName(newArgs[0]);
if (paacmd == null && (PACheck.handleCommand(tempArena, sender, newArgs))) {
return true;
}
if (paacmd == null
&& tempArena.getArenaConfig().getBoolean(CFG.CMDS_DEFAULTJOIN)) {
paacmd = new PAG_Join();
if (newArgs.length > 1) {
newArgs = StringParser.shiftArrayBy(newArgs, 1);
}
tempArena.getDebugger().i("committing: " + paacmd.getName(), sender);
paacmd.commit(tempArena, sender, newArgs);
return true;
}
if (paacmd != null) {
tempArena.getDebugger().i("committing: " + paacmd.getName(), sender);
paacmd.commit(tempArena, sender, StringParser.shiftArrayBy(newArgs, 1));
return true;
}
tempArena.getDebugger().i("cmd null", sender);
return false;
}
|
public View newView(Context context, Cursor cursor, ViewGroup list) {
TextView view = new TextView(context);
view.setTextAppearance(context, R.style.HistoryFont);
Long millis = cursor.getLong(cursor.getColumnIndex("dateStart"));
Date startDate = new Date(millis);
int distanceRan = cursor.getInt(cursor.getColumnIndex(MMRDbAdapter.KEY_RUN_DISTANCE_RAN));
int routeDistance = cursor.getInt(cursor.getColumnIndex(MMRDbAdapter.KEY_ROUTE_DISTANCE));
view.setText(
new SimpleDateFormat("yyyy-mm-dd").format(startDate) +
" Distance: " +
distanceRan +
" / " + routeDistance);
return view;
}
| public View newView(Context context, Cursor cursor, ViewGroup list) {
TextView view = new TextView(context);
view.setTextAppearance(context, R.style.HistoryFont);
Long millis = cursor.getLong(cursor.getColumnIndex("dateStart"));
Date startDate = new Date(millis);
int distanceRan = cursor.getInt(cursor.getColumnIndex(MMRDbAdapter.KEY_RUN_DISTANCE_RAN));
int routeDistance = cursor.getInt(cursor.getColumnIndex(MMRDbAdapter.KEY_ROUTE_DISTANCE));
view.setText(
new SimpleDateFormat("yyyy-MM-dd").format(startDate) +
" Distance: " +
distanceRan +
" / " + routeDistance);
return view;
}
|
public synchronized Map<String, Domain> getDomains() throws LibvirtException {
Map<String, Domain> domains = new HashMap<String, Domain>();
Connect hypervisorConnection = makeConnection();
LogRecord info = new LogRecord(Level.INFO, "Getting hypervisor domains");
LOGGER.log(info);
if (hypervisorConnection != null) {
for (String c : hypervisorConnection.listDefinedDomains()) {
if (c != null && !c.equals("")) {
Domain domain = null;
try {
domain = hypervisorConnection.domainLookupByName(c);
domains.put(domain.getName(), domain);
} catch (Exception e) {
LogRecord rec = new LogRecord(Level.INFO, "Error retreiving information for domain with name: {0}");
rec.setParameters(new Object[]{c});
rec.setThrown(e);
LOGGER.log(rec);
}
}
}
for (int c : hypervisorConnection.listDomains()) {
Domain domain = null;
try {
domain = hypervisorConnection.domainLookupByID(c);
domains.put(domain.getName(), domain);
} catch (Exception e) {
LogRecord rec = new LogRecord(Level.INFO, "Error retreiving information for domain with id: {0}");
rec.setParameters(new Object[]{c});
rec.setThrown(e);
LOGGER.log(rec);
}
}
LogRecord rec = new LogRecord(Level.INFO, "Closing hypervisor connection");
LOGGER.log(rec);
hypervisorConnection.close();
hypervisorConnection = null;
} else {
LogRecord rec = new LogRecord(Level.SEVERE, "Cannot connect to datacenter {0} as {1}/******");
rec.setParameters(new Object[]{hypervisorHost, username});
LOGGER.log(rec);
}
return domains;
}
| public synchronized Map<String, Domain> getDomains() throws LibvirtException {
Map<String, Domain> domains = new HashMap<String, Domain>();
Connect hypervisorConnection = makeConnection();
LogRecord info = new LogRecord(Level.INFO, "Getting hypervisor domains");
LOGGER.log(info);
if (hypervisorConnection != null) {
for (String c : hypervisorConnection.listDefinedDomains()) {
if (c != null && !c.equals("")) {
Domain domain = null;
try {
domain = hypervisorConnection.domainLookupByName(c);
domains.put(domain.getName(), domain);
} catch (Exception e) {
LogRecord rec = new LogRecord(Level.INFO, "Error retreiving information for domain with name: {0}");
rec.setParameters(new Object[]{c});
rec.setThrown(e);
LOGGER.log(rec);
}
}
}
for (int c : hypervisorConnection.listDomains()) {
Domain domain = null;
try {
domain = hypervisorConnection.domainLookupByID(c);
domains.put(domain.getName(), domain);
} catch (Exception e) {
LogRecord rec = new LogRecord(Level.INFO, "Error retreiving information for domain with id: {0}");
rec.setParameters(new Object[]{c});
rec.setThrown(e);
LOGGER.log(rec);
}
}
LogRecord rec = new LogRecord(Level.INFO, "Closing hypervisor connection");
LOGGER.log(rec);
hypervisorConnection.close();
} else {
LogRecord rec = new LogRecord(Level.SEVERE, "Cannot connect to datacenter {0} as {1}/******");
rec.setParameters(new Object[]{hypervisorHost, username});
LOGGER.log(rec);
}
return domains;
}
|
public void execute(RequestHandler handler,
FtpRequestImpl request,
FtpWriter out) throws IOException, FtpException {
boolean bSuccess = false;
IFtpConfig fconfig = handler.getConfig();
IConnectionManager conManager = fconfig.getConnectionManager();
IFtpStatistics stat = (IFtpStatistics)fconfig.getFtpStatistics();
try {
request.resetState();
String userName = request.getArgument();
if(userName == null) {
out.send(501, "USER", null);
return;
}
BaseUser user = (BaseUser)request.getUser();
if(request.isLoggedIn()) {
if( userName.equals(user.getName()) ) {
out.send(230, "USER", null);
bSuccess = true;
}
else {
out.send(530, "USER.invalid", null);
}
return;
}
boolean bAnonymous = userName.equals("anonymous");
if( bAnonymous && (!conManager.isAnonymousLoginEnabled()) ) {
out.send(530, "USER.anonymous", null);
return;
}
int currAnonLogin = stat.getCurrentAnonymousLoginNumber();
int maxAnonLogin = conManager.getMaxAnonymousLogins();
if( bAnonymous && (currAnonLogin >= maxAnonLogin) ) {
out.send(421, "USER.anonymous", null);
return;
}
int currLogin = stat.getCurrentLoginNumber();
int maxLogin = conManager.getMaxLogins();
if(currLogin >= maxLogin) {
out.send(421, "USER.login", null);
return;
}
User configUser = handler.getConfig().getUserManager().getUserByName(userName);
if(configUser != null){
int maxUserLoginNumber = configUser.getMaxLoginNumber();
if(maxUserLoginNumber > 0){
int currUserLogin = stat.getCurrentUserLoginNumber(configUser);
if(currUserLogin >= maxUserLoginNumber){
out.send(421, "USER.login", null);
return;
}
}
int maxUserLoginPerIP = configUser.getMaxLoginPerIP();
if(maxUserLoginPerIP > 0){
int currUserLoginPerIP = stat.getCurrentUserLoginNumber(configUser, request.getRemoteAddress());
if(currUserLoginPerIP >= maxUserLoginPerIP){
out.send(421, "USER.login", null);
return;
}
}
}
bSuccess = true;
user.setName(userName);
if(bAnonymous) {
out.send(331, "USER.anonymous", userName);
}
else {
out.send(331, "USER", userName);
}
}
finally {
if(!bSuccess) {
conManager.closeConnection(handler);
}
}
}
| public void execute(RequestHandler handler,
FtpRequestImpl request,
FtpWriter out) throws IOException, FtpException {
boolean bSuccess = false;
IFtpConfig fconfig = handler.getConfig();
IConnectionManager conManager = fconfig.getConnectionManager();
IFtpStatistics stat = (IFtpStatistics)fconfig.getFtpStatistics();
try {
request.resetState();
String userName = request.getArgument();
if(userName == null) {
out.send(501, "USER", null);
return;
}
BaseUser user = (BaseUser)request.getUser();
if(request.isLoggedIn()) {
if( userName.equals(user.getName()) ) {
out.send(230, "USER", null);
bSuccess = true;
}
else {
out.send(530, "USER.invalid", null);
}
return;
}
boolean bAnonymous = userName.equals("anonymous");
if( bAnonymous && (!conManager.isAnonymousLoginEnabled()) ) {
out.send(530, "USER.anonymous", null);
return;
}
int currAnonLogin = stat.getCurrentAnonymousLoginNumber();
int maxAnonLogin = conManager.getMaxAnonymousLogins();
if( bAnonymous && (currAnonLogin >= maxAnonLogin) ) {
out.send(421, "USER.anonymous", null);
return;
}
int currLogin = stat.getCurrentLoginNumber();
int maxLogin = conManager.getMaxLogins();
if(currLogin >= maxLogin) {
out.send(421, "USER.login", null);
return;
}
User configUser = handler.getConfig().getUserManager().getUserByName(userName);
if(configUser != null){
int maxUserLoginNumber = configUser.getMaxLoginNumber();
if(maxUserLoginNumber > 0){
int currUserLogin = stat.getCurrentUserLoginNumber(configUser);
if(currUserLogin >= maxUserLoginNumber){
out.send(421, "USER.login", null);
return;
}
}
int maxUserLoginPerIP = configUser.getMaxLoginPerIP();
if(maxUserLoginPerIP > 0){
int currUserLoginPerIP = stat.getCurrentUserLoginNumber(configUser, request.getRemoteAddress());
if(currUserLoginPerIP >= maxUserLoginPerIP){
out.send(421, "USER.login", null);
return;
}
}
}
bSuccess = true;
request.setUserArgument(userName);
if(bAnonymous) {
out.send(331, "USER.anonymous", userName);
}
else {
out.send(331, "USER", userName);
}
}
finally {
if(!bSuccess) {
conManager.closeConnection(handler);
}
}
}
|
public void run() {
MulticastThreadSuper value = null;
long time1 = System.nanoTime();
Map<MulticastData, MulticastThreadSuper> v = null;
boolean memoryWarnedForLog = false;
if (!memoryWarned && Runtime.getRuntime().freeMemory() < Runtime.getRuntime().totalMemory()*0.1) {
logger
.warning("Your memory is about to expire.(<10% remaining)\n"
+ "Please be careful, save your files and "
+ "try to free memory with closing of sender/reciever or tabs.\n\n" +
"Free Memory: " + Runtime.getRuntime().freeMemory()/(1024*1024) + "\n" +
"Total Allocated Memory: " + Runtime.getRuntime().totalMemory()/(1024*1024) + "\n" +
"Maximum Memory for JVM: " + Runtime.getRuntime().maxMemory()/(1024*1024) );
memoryWarnedForLog = true;
this.memoryWarned = true;
}
for (int i = 0; i < 2; i++) {
switch (i) {
case 0:
v = mc_sender_l3;
break;
case 1:
v = mc_receiver_l3;
break;
}
for (Entry<MulticastData, MulticastThreadSuper> m : v.entrySet()) {
value = m.getValue();
if (value.getMultiCastData().isActive()) {
value.update();
}
}
}
if (viewController != null) {
if (viewController.isInitFinished()) {
viewController.viewUpdate();
}
}
if (!memoryWarnedForLog && ((System.nanoTime() - time1) / 1000000) > 200) {
logger.log(Level.INFO, "Updatetime is rather long: "
+ ((System.nanoTime() - time1) / 1000000)
+ " ms !!!!!!!!!!!!");
if (((System.nanoTime() - time1) / 1000000) > 300)
if (viewController != null)
logger
.log(
Level.WARNING,
"Updating the user interface takes very long. Consider the help for more information.");
}
}
| public void run() {
MulticastThreadSuper value = null;
long time1 = System.nanoTime();
Map<MulticastData, MulticastThreadSuper> v = null;
boolean memoryWarnedForLog = false;
Runtime rt= Runtime.getRuntime();
if (!memoryWarned && rt.freeMemory()+ (rt.maxMemory()-rt.totalMemory())
< rt.maxMemory()*0.1) {
logger
.warning("Your memory is about to expire.(<10% remaining)\n"
+ "Please be careful, save your files and "
+ "try to free memory with closing of sender/reciever or tabs.\n\n" +
"Free Memory: " + rt.freeMemory()/(1024*1024) + "\n" +
"Total Allocated Memory: " + rt.totalMemory()/(1024*1024) + "\n" +
"Maximum Memory for JVM: " + rt.maxMemory()/(1024*1024) );
memoryWarnedForLog = true;
this.memoryWarned = true;
}
for (int i = 0; i < 2; i++) {
switch (i) {
case 0:
v = mc_sender_l3;
break;
case 1:
v = mc_receiver_l3;
break;
}
for (Entry<MulticastData, MulticastThreadSuper> m : v.entrySet()) {
value = m.getValue();
if (value.getMultiCastData().isActive()) {
value.update();
}
}
}
if (viewController != null) {
if (viewController.isInitFinished()) {
viewController.viewUpdate();
}
}
if (!memoryWarnedForLog && ((System.nanoTime() - time1) / 1000000) > 200) {
logger.log(Level.INFO, "Updatetime is rather long: "
+ ((System.nanoTime() - time1) / 1000000)
+ " ms !!!!!!!!!!!!");
if (((System.nanoTime() - time1) / 1000000) > 300)
if (viewController != null)
logger
.log(
Level.WARNING,
"Updating the user interface takes very long. Consider the help for more information.");
}
}
|
public NavigationDetails getNavigationDetails(DocumentReference calConfigDocRef,
IEvent event, EventSearchQuery query) {
LOGGER.debug("getNavigationDetails for '" + event + "'");
Date eventDate = event.getEventDate();
if (eventDate != null) {
ICalendar cal = new Calendar(calConfigDocRef, false);
cal.setStartDate(eventDate);
int offset = 0;
int nb = 10;
int eventIndex, start = 0;
List<IEvent> events;
boolean hasMore, notFound;
do {
if (query == null) {
events = getEventMgr().getEventsInternal(cal, start, nb);
} else {
events = getEventMgr().searchEvents(cal, query).getEventList(start, nb);
}
hasMore = events.size() == nb;
eventIndex = events.indexOf(event);
notFound = eventIndex < 0;
offset = start + eventIndex;
start = start + nb;
nb = nb * 2;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getNavigationDetails: events '" + events + "'");
LOGGER.debug("getNavigationDetails: index for event '" + eventIndex);
}
} while (notFound && hasMore);
if (!notFound) {
NavigationDetails navDetail = new NavigationDetails(cal.getStartDate(), offset);
LOGGER.debug("getNavigationDetails: found '" + navDetail + "'");
return navDetail;
} else {
LOGGER.debug("getNavigationDetails: not found");
}
} else {
LOGGER.error("getNavigationDetails: eventDate is null for '" + event + "'");
}
return null;
}
| public NavigationDetails getNavigationDetails(DocumentReference calConfigDocRef,
IEvent event, EventSearchQuery query) {
LOGGER.debug("getNavigationDetails for '" + event + "'");
Date eventDate = event.getEventDate();
if (eventDate != null) {
ICalendar cal = new Calendar(calConfigDocRef, false);
cal.setStartDate(eventDate);
int offset = 0;
int nb = 10;
int eventIndex, start = 0;
List<IEvent> events;
boolean hasMore, notFound;
do {
if (query == null) {
events = getEventMgr().getEventsInternal(cal, start, nb);
} else {
events = getEventMgr().searchEvents(cal, query).getEventList(start, nb);
}
hasMore = events.size() == nb;
eventIndex = events.indexOf(event);
notFound = eventIndex < 0;
offset = start + eventIndex;
start = start + nb;
nb = nb * 2;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getNavigationDetails: events '" + events + "'");
LOGGER.debug("getNavigationDetails: index for event '" + eventIndex);
}
} while (notFound && hasMore);
if (!notFound) {
NavigationDetails navDetail = new NavigationDetails(cal.getStartDate(), offset);
LOGGER.debug("getNavigationDetails: found '" + navDetail + "'");
return navDetail;
} else {
LOGGER.warn("getNavigationDetails: not found");
}
} else {
LOGGER.error("getNavigationDetails: eventDate is null for '" + event + "'");
}
return null;
}
|
public List<Goal> goals(Job job) {
List<Goal> superGoals = super.goals(job);
ArrayList<Goal> goals = new ArrayList<Goal>(superGoals.size()+10);
for (Goal g : superGoals) {
if (g == Desugarer(job)) {
goals.add(ExpressionFlattenerForAtExpr(job));
goals.add(VarsBoxer(job));
}
if (g == CodeGenerated(job)) {
goals.add(JavaCodeGenStart(job));
goals.add(StaticInitializer(job));
goals.add(AsyncInitializer(job));
goals.add(ClosureRemoved(job));
goals.add(RailInLoopOptimizer(job));
goals.add(CastsRemoved(job));
goals.add(JavaCaster(job));
goals.add(InlineHelped(job));
}
goals.add(g);
}
return goals;
}
| public List<Goal> goals(Job job) {
List<Goal> superGoals = super.goals(job);
ArrayList<Goal> goals = new ArrayList<Goal>(superGoals.size()+10);
for (Goal g : superGoals) {
if (g == Desugarer(job)) {
goals.add(ExpressionFlattenerForAtExpr(job));
goals.add(VarsBoxer(job));
}
if (g == CodeGenerated(job)) {
goals.add(JavaCodeGenStart(job));
goals.add(ClosuresToStaticMethods(job));
goals.add(StaticInitializer(job));
goals.add(AsyncInitializer(job));
goals.add(RailInLoopOptimizer(job));
goals.add(CastsRemoved(job));
goals.add(JavaCaster(job));
goals.add(InlineHelped(job));
}
goals.add(g);
}
return goals;
}
|
public void onSecond(TimeSecondEvent event) {
for (Player p : waterBreathers) {
if (p.getLocation().getBlock().isLiquid()) {
p.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 40, potionMultiplier));
}
}
}
| public void onSecond(TimeSecondEvent event) {
for (Player p : waterBreathers) {
if (p.getLocation().getBlock().isLiquid()) {
p.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 40, potionMultiplier), true);
}
}
}
|
private List<String> processOptions(String[] args) {
JSLintFlags jslintFlags = new JSLintFlags();
Flags flags = new Flags();
JCommander jc = new JCommander(new Object[] { flags , jslintFlags });
jc.setProgramName("jslint4java");
try {
jc.parse(args);
} catch (ParameterException e) {
usage(jc);
}
if (flags.help) {
usage(jc);
}
if (flags.encoding != null) {
encoding = flags.encoding;
}
if (flags.jslint != null) {
setJSLint(flags.jslint);
}
setResultFormatter(flags.report);
for (ParameterDescription pd : jc.getParameters()) {
Field field = pd.getField();
if (!field.getDeclaringClass().isAssignableFrom(JSLintFlags.class)) {
continue;
}
try {
Option o = getOption(field.getName());
Object val = field.get(jslintFlags);
if (val == null) {
continue;
}
Class<?> type = field.getType();
if (type.isAssignableFrom(Boolean.class)) {
lint.addOption(o);
}
else if (type.isAssignableFrom(String.class)) {
lint.addOption(o, (String) val);
} else {
die("unknown type \"" + type + "\" (for " + field.getName() + ")");
}
} catch (IllegalArgumentException e) {
die(e.getMessage());
} catch (IllegalAccessException e) {
die(e.getMessage());
}
}
if (flags.files.isEmpty()) {
usage(jc);
return null;
} else {
return flags.files;
}
}
| private List<String> processOptions(String[] args) {
JSLintFlags jslintFlags = new JSLintFlags();
Flags flags = new Flags();
JCommander jc = new JCommander(new Object[] { flags , jslintFlags });
jc.setProgramName("jslint4java");
try {
jc.parse(args);
} catch (ParameterException e) {
info(e.getMessage());
usage(jc);
}
if (flags.help) {
usage(jc);
}
if (flags.encoding != null) {
encoding = flags.encoding;
}
if (flags.jslint != null) {
setJSLint(flags.jslint);
}
setResultFormatter(flags.report);
for (ParameterDescription pd : jc.getParameters()) {
Field field = pd.getField();
if (!field.getDeclaringClass().isAssignableFrom(JSLintFlags.class)) {
continue;
}
try {
Option o = getOption(field.getName());
Object val = field.get(jslintFlags);
if (val == null) {
continue;
}
Class<?> type = field.getType();
if (type.isAssignableFrom(Boolean.class)) {
lint.addOption(o);
}
else if (type.isAssignableFrom(String.class)) {
lint.addOption(o, (String) val);
} else {
die("unknown type \"" + type + "\" (for " + field.getName() + ")");
}
} catch (IllegalArgumentException e) {
die(e.getMessage());
} catch (IllegalAccessException e) {
die(e.getMessage());
}
}
if (flags.files.isEmpty()) {
usage(jc);
return null;
} else {
return flags.files;
}
}
|
public void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(this.port), 0);
server.createContext("/hello_world", new HelloWorldHandler());
server.setExecutor(null);
server.start();
}
| public void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(this.port), 0);
server.createContext("/hello", new HelloWorldHandler());
server.setExecutor(null);
server.start();
}
|
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 5) {
android.accounts.Account[] accounts = AccountManager.get(mContext)
.getAccountsByType(AccountManagerTypes.TYPE_EXCHANGE);
for (android.accounts.Account account: accounts) {
AccountManager.get(mContext).removeAccount(account, null, null);
}
resetMessageTable(db, oldVersion, newVersion);
resetAttachmentTable(db, oldVersion, newVersion);
resetMailboxTable(db, oldVersion, newVersion);
resetHostAuthTable(db, oldVersion, newVersion);
resetAccountTable(db, oldVersion, newVersion);
return;
}
if (oldVersion == 5) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from v5 to v6", e);
}
oldVersion = 6;
}
if (oldVersion == 6) {
db.execSQL("drop trigger mailbox_delete;");
db.execSQL(TRIGGER_MAILBOX_DELETE);
oldVersion = 7;
}
if (oldVersion == 7) {
try {
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + AccountColumns.SECURITY_FLAGS + " integer" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 7 to 8 " + e);
}
oldVersion = 8;
}
if (oldVersion == 8) {
try {
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + AccountColumns.SECURITY_SYNC_KEY + " text" + ";");
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + AccountColumns.SIGNATURE + " text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 8 to 9 " + e);
}
oldVersion = 9;
}
if (oldVersion == 9) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + MessageColumns.MEETING_INFO + " text" + ";");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + MessageColumns.MEETING_INFO + " text" + ";");
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + MessageColumns.MEETING_INFO + " text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 9 to 10 " + e);
}
oldVersion = 10;
}
if (oldVersion == 10) {
try {
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + AttachmentColumns.CONTENT + " text" + ";");
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + AttachmentColumns.FLAGS + " integer" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 10 to 11 " + e);
}
oldVersion = 11;
}
if (oldVersion == 11) {
try {
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + AttachmentColumns.CONTENT_BYTES + " blob" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 11 to 12 " + e);
}
oldVersion = 12;
}
if (oldVersion == 12) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.MESSAGE_COUNT
+" integer not null default 0" + ";");
recalculateMessageCount(db);
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 12 to 13 " + e);
}
oldVersion = 13;
}
if (oldVersion == 13) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + Message.SNIPPET
+" text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 13 to 14 " + e);
}
oldVersion = 14;
}
if (oldVersion == 14) {
try {
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + Message.SNIPPET +" text" + ";");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + Message.SNIPPET +" text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 14 to 15 " + e);
}
oldVersion = 15;
}
if (oldVersion == 15) {
try {
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + Attachment.ACCOUNT_KEY +" integer" + ";");
db.execSQL("update " + Attachment.TABLE_NAME + " set " +
Attachment.ACCOUNT_KEY + "= (SELECT " + Message.TABLE_NAME + "." +
Message.ACCOUNT_KEY + " from " + Message.TABLE_NAME + " where " +
Message.TABLE_NAME + "." + Message.RECORD_ID + " = " +
Attachment.TABLE_NAME + "." + Attachment.MESSAGE_KEY + ")");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 15 to 16 " + e);
}
oldVersion = 16;
}
if (oldVersion == 16) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.PARENT_KEY + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 16 to 17 " + e);
}
oldVersion = 17;
}
if (oldVersion == 17) {
upgradeFromVersion17ToVersion18(db);
oldVersion = 18;
}
if (oldVersion == 18) {
try {
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + Account.POLICY_KEY + " integer;");
db.execSQL("drop trigger account_delete;");
db.execSQL(TRIGGER_ACCOUNT_DELETE);
createPolicyTable(db);
convertPolicyFlagsToPolicyTable(db);
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 18 to 19 " + e);
}
oldVersion = 19;
}
if (oldVersion == 19) {
try {
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING +
" integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.DONT_ALLOW_CAMERA + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.DONT_ALLOW_HTML + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE +
" integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_HTML_TRUNCATION_SIZE +
" integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.PASSWORD_RECOVERY_ENABLED +
" integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " + e);
}
oldVersion = 20;
}
if (oldVersion == 20) {
oldVersion = 21;
}
if (oldVersion == 21) {
upgradeFromVersion21ToVersion22(db, mContext);
oldVersion = 22;
}
if (oldVersion == 22) {
upgradeFromVersion22ToVersion23(db);
oldVersion = 23;
}
if (oldVersion == 23) {
upgradeFromVersion23ToVersion24(db);
oldVersion = 24;
}
if (oldVersion == 24) {
upgradeFromVersion24ToVersion25(db);
oldVersion = 25;
}
if (oldVersion == 25) {
upgradeFromVersion25ToVersion26(db);
oldVersion = 26;
}
if (oldVersion == 26) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + Message.PROTOCOL_SEARCH_INFO + " text;");
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 26 to 27 " + e);
}
oldVersion = 27;
}
if (oldVersion == 27) {
oldVersion = 28;
}
if (oldVersion == 28) {
try {
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + Policy.PROTOCOL_POLICIES_ENFORCED + " text;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + Policy.PROTOCOL_POLICIES_UNSUPPORTED + " text;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 28 to 29 " + e);
}
oldVersion = 29;
}
if (oldVersion == 29) {
upgradeFromVersion29ToVersion30(db);
oldVersion = 30;
}
if (oldVersion == 30) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.UI_SYNC_STATUS + " integer;");
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.UI_LAST_SYNC_RESULT + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 30 to 31 " + e);
}
oldVersion = 31;
}
if (oldVersion == 31) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY + " integer;");
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT + " integer;");
db.execSQL("update Mailbox set " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY +
"=0 where " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY + " IS NULL");
db.execSQL("update Mailbox set " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT +
"=0 where " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT + " IS NULL");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 31 to 32 " + e);
}
oldVersion = 32;
}
if (oldVersion == 32) {
try {
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + Attachment.UI_STATE + " integer;");
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + Attachment.UI_DESTINATION + " integer;");
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + Attachment.UI_DOWNLOADED_SIZE + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 32 to 33 " + e);
}
oldVersion = 33;
}
if (oldVersion == 33) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + MailboxColumns.TOTAL_COUNT + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 33 to 34 " + e);
}
oldVersion = 34;
}
if (oldVersion == 34) {
oldVersion = 35;
}
if (oldVersion == 35 || oldVersion == 36) {
oldVersion = 37;
}
if (oldVersion == 37) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + MessageColumns.THREAD_TOPIC + " text;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 37 to 38 " + e);
}
oldVersion = 38;
}
if (oldVersion == 38) {
try {
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + MessageColumns.THREAD_TOPIC + " text;");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + MessageColumns.THREAD_TOPIC + " text;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 38 to 39 " + e);
}
oldVersion = 39;
}
}
| public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 5) {
android.accounts.Account[] accounts = AccountManager.get(mContext)
.getAccountsByType(AccountManagerTypes.TYPE_EXCHANGE);
for (android.accounts.Account account: accounts) {
AccountManager.get(mContext).removeAccount(account, null, null);
}
resetMessageTable(db, oldVersion, newVersion);
resetAttachmentTable(db, oldVersion, newVersion);
resetMailboxTable(db, oldVersion, newVersion);
resetHostAuthTable(db, oldVersion, newVersion);
resetAccountTable(db, oldVersion, newVersion);
return;
}
if (oldVersion == 5) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from v5 to v6", e);
}
oldVersion = 6;
}
if (oldVersion == 6) {
db.execSQL("drop trigger mailbox_delete;");
db.execSQL(TRIGGER_MAILBOX_DELETE);
oldVersion = 7;
}
if (oldVersion == 7) {
try {
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + AccountColumns.SECURITY_FLAGS + " integer" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 7 to 8 " + e);
}
oldVersion = 8;
}
if (oldVersion == 8) {
try {
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + AccountColumns.SECURITY_SYNC_KEY + " text" + ";");
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + AccountColumns.SIGNATURE + " text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 8 to 9 " + e);
}
oldVersion = 9;
}
if (oldVersion == 9) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + MessageColumns.MEETING_INFO + " text" + ";");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + MessageColumns.MEETING_INFO + " text" + ";");
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + MessageColumns.MEETING_INFO + " text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 9 to 10 " + e);
}
oldVersion = 10;
}
if (oldVersion == 10) {
try {
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + AttachmentColumns.CONTENT + " text" + ";");
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + AttachmentColumns.FLAGS + " integer" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 10 to 11 " + e);
}
oldVersion = 11;
}
if (oldVersion == 11) {
try {
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + AttachmentColumns.CONTENT_BYTES + " blob" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 11 to 12 " + e);
}
oldVersion = 12;
}
if (oldVersion == 12) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.MESSAGE_COUNT
+" integer not null default 0" + ";");
recalculateMessageCount(db);
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 12 to 13 " + e);
}
oldVersion = 13;
}
if (oldVersion == 13) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + Message.SNIPPET
+" text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 13 to 14 " + e);
}
oldVersion = 14;
}
if (oldVersion == 14) {
try {
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + Message.SNIPPET +" text" + ";");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + Message.SNIPPET +" text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 14 to 15 " + e);
}
oldVersion = 15;
}
if (oldVersion == 15) {
try {
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + Attachment.ACCOUNT_KEY +" integer" + ";");
db.execSQL("update " + Attachment.TABLE_NAME + " set " +
Attachment.ACCOUNT_KEY + "= (SELECT " + Message.TABLE_NAME + "." +
Message.ACCOUNT_KEY + " from " + Message.TABLE_NAME + " where " +
Message.TABLE_NAME + "." + Message.RECORD_ID + " = " +
Attachment.TABLE_NAME + "." + Attachment.MESSAGE_KEY + ")");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 15 to 16 " + e);
}
oldVersion = 16;
}
if (oldVersion == 16) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.PARENT_KEY + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 16 to 17 " + e);
}
oldVersion = 17;
}
if (oldVersion == 17) {
upgradeFromVersion17ToVersion18(db);
oldVersion = 18;
}
if (oldVersion == 18) {
try {
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + Account.POLICY_KEY + " integer;");
db.execSQL("drop trigger account_delete;");
db.execSQL(TRIGGER_ACCOUNT_DELETE);
createPolicyTable(db);
convertPolicyFlagsToPolicyTable(db);
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 18 to 19 " + e);
}
oldVersion = 19;
}
if (oldVersion == 19) {
try {
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING +
" integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.DONT_ALLOW_CAMERA + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.DONT_ALLOW_HTML + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE +
" integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_HTML_TRUNCATION_SIZE +
" integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + PolicyColumns.PASSWORD_RECOVERY_ENABLED +
" integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " + e);
}
oldVersion = 20;
}
if (oldVersion == 20) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.LAST_SEEN_MESSAGE_KEY + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
}
oldVersion = 21;
}
if (oldVersion == 21) {
upgradeFromVersion21ToVersion22(db, mContext);
oldVersion = 22;
}
if (oldVersion == 22) {
upgradeFromVersion22ToVersion23(db);
oldVersion = 23;
}
if (oldVersion == 23) {
upgradeFromVersion23ToVersion24(db);
oldVersion = 24;
}
if (oldVersion == 24) {
upgradeFromVersion24ToVersion25(db);
oldVersion = 25;
}
if (oldVersion == 25) {
upgradeFromVersion25ToVersion26(db);
oldVersion = 26;
}
if (oldVersion == 26) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + Message.PROTOCOL_SEARCH_INFO + " text;");
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 26 to 27 " + e);
}
oldVersion = 27;
}
if (oldVersion == 27) {
try {
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + Account.NOTIFIED_MESSAGE_ID + " integer;");
db.execSQL("alter table " + Account.TABLE_NAME
+ " add column " + Account.NOTIFIED_MESSAGE_COUNT + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 27 to 28 " + e);
}
oldVersion = 28;
}
if (oldVersion == 28) {
try {
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + Policy.PROTOCOL_POLICIES_ENFORCED + " text;");
db.execSQL("alter table " + Policy.TABLE_NAME
+ " add column " + Policy.PROTOCOL_POLICIES_UNSUPPORTED + " text;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 28 to 29 " + e);
}
oldVersion = 29;
}
if (oldVersion == 29) {
upgradeFromVersion29ToVersion30(db);
oldVersion = 30;
}
if (oldVersion == 30) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.UI_SYNC_STATUS + " integer;");
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.UI_LAST_SYNC_RESULT + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 30 to 31 " + e);
}
oldVersion = 31;
}
if (oldVersion == 31) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY + " integer;");
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT + " integer;");
db.execSQL("update Mailbox set " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY +
"=0 where " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY + " IS NULL");
db.execSQL("update Mailbox set " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT +
"=0 where " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT + " IS NULL");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 31 to 32 " + e);
}
oldVersion = 32;
}
if (oldVersion == 32) {
try {
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + Attachment.UI_STATE + " integer;");
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + Attachment.UI_DESTINATION + " integer;");
db.execSQL("alter table " + Attachment.TABLE_NAME
+ " add column " + Attachment.UI_DOWNLOADED_SIZE + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 32 to 33 " + e);
}
oldVersion = 33;
}
if (oldVersion == 33) {
try {
db.execSQL("alter table " + Mailbox.TABLE_NAME
+ " add column " + MailboxColumns.TOTAL_COUNT + " integer;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 33 to 34 " + e);
}
oldVersion = 34;
}
if (oldVersion == 34) {
oldVersion = 35;
}
if (oldVersion == 35 || oldVersion == 36) {
oldVersion = 37;
}
if (oldVersion == 37) {
try {
db.execSQL("alter table " + Message.TABLE_NAME
+ " add column " + MessageColumns.THREAD_TOPIC + " text;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 37 to 38 " + e);
}
oldVersion = 38;
}
if (oldVersion == 38) {
try {
db.execSQL("alter table " + Message.DELETED_TABLE_NAME
+ " add column " + MessageColumns.THREAD_TOPIC + " text;");
db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
+ " add column " + MessageColumns.THREAD_TOPIC + " text;");
} catch (SQLException e) {
Log.w(TAG, "Exception upgrading EmailProvider.db from 38 to 39 " + e);
}
oldVersion = 39;
}
}
|
public Vector getSuperconceptCodes(String scheme, String version, String code) {
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getSuperconceptCodes_Local(String scheme, String version, String code) {
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
LexBIGService lbSvc = new LexBIGServiceImpl();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
java.lang.String[] ids = hierarchies[0].getAssociationIds();
for (int i=0; i<ids.length; i++)
{
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public static String getVocabularyVersionByTag(String codingSchemeName, String ltag)
{
if (codingSchemeName == null) return null;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes();
CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering();
for (int i=0; i<csra.length; i++)
{
CodingSchemeRendering csr = csra[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0)
{
if (ltag == null) return css.getRepresentsVersion();
RenderingDetail rd = csr.getRenderingDetail();
CodingSchemeTagList cstl = rd.getVersionTags();
java.lang.String[] tags = cstl.getTag();
for (int j=0; j<tags.length; j++)
{
String version_tag = (String) tags[j];
if (version_tag.compareToIgnoreCase(ltag) == 0)
{
return css.getRepresentsVersion();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName);
return null;
}
public static Vector<String> getVersionListData(String codingSchemeName) {
Vector<String> v = new Vector();
try {
RemoteServerUtil rsu = new RemoteServerUtil();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes();
if(csrl == null) System.out.println("csrl is NULL");
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i=0; i<csrs.length; i++)
{
CodingSchemeRendering csr = csrs[i];
Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
if (isActive != null && isActive.equals(Boolean.TRUE))
{
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
if (formalname.compareTo(codingSchemeName) == 0)
{
String representsVersion = css.getRepresentsVersion();
v.add(representsVersion);
}
}
}
} catch (Exception ex) {
}
return v;
}
protected static Association processForAnonomousNodes(Association assoc){
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for(int i = 0; i < assoc.getAssociatedConcepts().getAssociatedConceptCount(); i++)
{
if(
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != false &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@") &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@@")
)
{
}
else{
temp.getAssociatedConcepts().addAssociatedConcept(assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
public static NameAndValueList createNameAndValueList(String[] names, String[] values)
{
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.length; i++)
{
NameAndValue nv = new NameAndValue();
nv.setName(names[i]);
if (values != null)
{
nv.setContent(values[i]);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
public static LocalNameList vector2LocalNameList(Vector<String> v)
{
if (v == null) return null;
LocalNameList list = new LocalNameList();
for (int i=0; i<v.size(); i++)
{
String vEntry = (String) v.elementAt(i);
list.addEntry(vEntry);
}
return list;
}
protected static NameAndValueList createNameAndValueList(Vector names, Vector values)
{
if (names == null) return null;
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.size(); i++)
{
String name = (String) names.elementAt(i);
String value = (String) values.elementAt(i);
NameAndValue nv = new NameAndValue();
nv.setName(name);
if (value != null)
{
nv.setContent(value);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
public static ResolvedConceptReferencesIterator restrictToMatchingProperty(
String codingSchemeName,
String version,
Vector property_vec,
Vector source_vec,
Vector qualifier_name_vec,
Vector qualifier_value_vec,
java.lang.String matchText,
java.lang.String matchAlgorithm,
java.lang.String language)
{
LocalNameList propertyList = vector2LocalNameList(property_vec);
CodedNodeSet.PropertyType[] propertyTypes = null;
LocalNameList sourceList = vector2LocalNameList(source_vec);
NameAndValueList qualifierList = createNameAndValueList(qualifier_name_vec, qualifier_value_vec);
return restrictToMatchingProperty(codingSchemeName,
version,
propertyList,
propertyTypes,
sourceList,
qualifierList,
matchText,
matchAlgorithm,
language);
}
public static ResolvedConceptReferencesIterator restrictToMatchingProperty(
String codingSchemeName,
String version,
LocalNameList propertyList,
CodedNodeSet.PropertyType[] propertyTypes,
LocalNameList sourceList,
NameAndValueList qualifierList,
java.lang.String matchText,
java.lang.String matchAlgorithm,
java.lang.String language)
{
CodedNodeSet cns = null;
ResolvedConceptReferencesIterator iterator = null;
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
if (lbSvc == null)
{
System.out.println("lbSvc = null");
return null;
}
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag);
if (cns == null)
{
System.out.println("cns = null");
return null;
}
LocalNameList contextList = null;
try {
cns = cns.restrictToMatchingProperties(propertyList,
propertyTypes,
sourceList,
contextList,
qualifierList,
matchText,
matchAlgorithm,
language
);
} catch (Exception ex) {
return null;
}
LocalNameList restrictToProperties = new LocalNameList();
SortOptionList sortCriteria = null;
try {
boolean resolveConcepts = false;
try {
iterator = cns.resolve(sortCriteria, null, restrictToProperties, null, resolveConcepts);
} catch (Exception e) {
System.out.println("ERROR: cns.resolve throws exceptions.");
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return iterator;
}
private boolean isNull(String s) {
if (s == null) return true;
s = s.trim();
if (s.length() == 0) return true;
if (s.compareTo("") == 0) return true;
if (s.compareToIgnoreCase("null") == 0) return true;
return false;
}
public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code)
{
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null)
{
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(vers);
ConceptReferenceList crefs =
createConceptReferenceList(
new String[] {code}, codingSchemeName);
CodedNodeSet cns = null;
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag);
} catch (Exception e1) {
e1.printStackTrace();
}
cns = cns.restrictToCodes(crefs);
ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, null, false, 1);
if (matches == null)
{
System.out.println("Concep not found.");
return null;
}
if (matches.getResolvedConceptReferenceCount() > 0) {
ResolvedConceptReference ref =
(ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement();
org.LexGrid.concepts.Concept entry = new org.LexGrid.concepts.Concept();
entry.setId(ref.getConceptCode());
entry.setEntityDescription(ref.getEntityDescription());
return entry;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public static ConceptReferenceList createConceptReferenceList(String[] codes, String codingSchemeName)
{
if (codes == null)
{
return null;
}
ConceptReferenceList list = new ConceptReferenceList();
for (int i = 0; i < codes.length; i++)
{
ConceptReference cr = new ConceptReference();
cr.setCodingScheme(codingSchemeName);
cr.setConceptCode(codes[i]);
list.addConceptReference(cr);
}
return list;
}
public Vector getParentCodes(String scheme, String version, String code) {
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version);
if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0)
{
return null;
}
String hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0);
Vector superconcept_vec = getAssociationSources(scheme, version, code, hierarchicalAssoName);
if (superconcept_vec == null) return null;
return superconcept_vec;
}
public ResolvedConceptReferenceList getNext(ResolvedConceptReferencesIterator iterator)
{
return iterator.getNext();
}
public static Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn)
{
return resolveIterator(iterator, maxToReturn, null);
}
public static Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code)
{
Vector v = new Vector();
if (iterator == null)
{
System.out.println("No match.");
return v;
}
try {
int iteration = 0;
while (iterator.hasNext())
{
iteration++;
iterator = iterator.scroll(maxToReturn);
ResolvedConceptReferenceList rcrl = iterator.getNext();
ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference();
for (int i=0; i<rcra.length; i++)
{
ResolvedConceptReference rcr = rcra[i];
org.LexGrid.concepts.Concept ce = new org.LexGrid.concepts.Concept();
ce.setId(rcr.getConceptCode());
ce.setEntityDescription(rcr.getEntityDescription());
if (code == null)
{
v.add(ce);
}
else
{
if (ce.getId().compareTo(code) != 0) v.add(ce);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator(
CodedNodeGraph cng,
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveAssociationDepth,
int maxToReturn) {
CodedNodeSet cns = null;
try {
cns = cng.toNodeList(graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
if (cns == null)
{
System.out.println("cng.toNodeList returns null???");
return null;
}
SortOptionList sortCriteria = null;
LocalNameList propertyNames = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
ResolvedConceptReferencesIterator iterator = null;
try {
iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes);
} catch (Exception e) {
e.printStackTrace();
}
if(iterator == null)
{
System.out.println("cns.resolve returns null???");
}
return iterator;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public Vector getSuperconcepts(String scheme, String version, String code)
{
String hierarchicalAssoName = "hasSubtype";
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version);
if (hierarchicalAssoName_vec != null && hierarchicalAssoName_vec.size() > 0)
{
hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0);
}
return getAssociationSources(scheme, version, code, hierarchicalAssoName);
}
public Vector getAssociationSources(String scheme, String version, String code, String assocName)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList =
createNameAndValueList(
new String[] {assocName}, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = false;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = 1000;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public Vector getSubconcepts(String scheme, String version, String code)
{
String hierarchicalAssoName = "hasSubtype";
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version);
if (hierarchicalAssoName_vec != null && hierarchicalAssoName_vec.size() > 0)
{
hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0);
}
return getAssociationTargets(scheme, version, code, hierarchicalAssoName);
}
public Vector getAssociationTargets(String scheme, String version, String code, String assocName)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList =
createNameAndValueList(
new String[] {assocName}, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = false;
int resolveAssociationDepth = 1;
int maxToReturn = 1000;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public static String preprocessContains(String s)
{
if (s == null) return null;
if (s.length() == 0) return null;
s = s.trim();
List<String> words = toWords(s, "\\s", false, false);
String delim = ".*";
StringBuffer searchPhrase = new StringBuffer();
int k = -1;
searchPhrase.append(delim);
for (int i = 0; i < words.size(); i++) {
String wd = (String) words.get(i);
wd = wd.trim();
if (wd.compareTo("") != 0)
{
searchPhrase.append(wd);
if (words.size() > 1 && i < words.size()-1)
{
searchPhrase.append("\\s");
}
}
}
searchPhrase.append(delim);
String t = searchPhrase.toString();
return t;
}
private boolean isNumber(String s) {
if (s.length() == 0) return false;
for(int i=0; i<s.length(); i++)
{
if(!Character.isDigit(s.charAt(i)))
return false;
}
return true;
}
public Vector<org.LexGrid.concepts.Concept> searchByName(String scheme, String version, String matchText, String matchAlgorithm, int maxToReturn) {
String matchText0 = matchText;
String matchAlgorithm0 = matchAlgorithm;
matchText0 = matchText0.trim();
boolean preprocess = true;
if (matchText == null || matchText.length() == 0)
{
return new Vector();
}
matchText = matchText.trim();
if (matchAlgorithm.compareToIgnoreCase("exactMatch") == 0)
{
if (!isNumber(matchText)) {
if (nonAlphabetic(matchText) || matchText.indexOf(".") != -1 || matchText.indexOf("/") != -1)
{
return searchByName(scheme, version, matchText, "RegExp", maxToReturn);
}
}
if (containsSpecialChars(matchText))
{
return searchByName(scheme, version, matchText, "RegExp", maxToReturn);
}
}
else if (matchAlgorithm.compareToIgnoreCase("startsWith") == 0)
{
}
else if (matchAlgorithm.compareToIgnoreCase("contains") == 0)
{
matchText = replaceSpecialCharsWithBlankChar(matchText);
if (matchText.indexOf(" ") != -1) {
matchText = preprocessContains(matchText);
matchAlgorithm = "RegExp";
preprocess = false;
}
}
if (matchAlgorithm.compareToIgnoreCase("RegExp") == 0 && preprocess)
{
matchText = preprocessRegExp(matchText);
}
LocalNameList propertyList = null;
CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1];
propertyTypes[0] = CodedNodeSet.PropertyType.PRESENTATION;
LocalNameList sourceList = null;
NameAndValueList qualifierList = null;
String language = null;
ResolvedConceptReferencesIterator iterator = restrictToMatchingProperty(
scheme,
version,
propertyList,
propertyTypes,
sourceList,
qualifierList,
matchText,
matchAlgorithm,
language);
if (apply_sort_score)
{
long ms = System.currentTimeMillis();
try {
iterator = sortByScore(matchText0, iterator, maxToReturn, true);
} catch (Exception ex) {
}
System.out.println("Sorting delay ---- Run time (ms): " + (System.currentTimeMillis() - ms));
}
if (iterator != null) {
Vector v = resolveIterator( iterator, maxToReturn);
if (v != null && v.size() > 0)
{
if(!apply_sort_score)
{
SortUtils.quickSort(v);
}
return v;
}
if (matchAlgorithm.compareToIgnoreCase("exactMatch") == 0) {
Concept c = getConceptByCode(scheme, null, null, matchText0);
if (c != null)
{
v = new Vector();
v.add(c);
return v;
}
}
}
if (matchAlgorithm0.compareToIgnoreCase("exactMatch") == 0) {
matchText0 = matchText0.trim();
Concept c = getConceptByCode(scheme, null, null, matchText0);
if (c != null)
{
Vector v = new Vector();
v.add(c);
return v;
}
}
else
{
return searchByName(scheme, version, matchText0, "exactMatch", maxToReturn);
}
return new Vector();
}
public void testSearchByName() {
String scheme = "NCI Thesaurus";
String version = "08.11d";
String matchText = "blood";
String matchAlgorithm = "contains";
int maxToReturn = 1000;
long ms = System.currentTimeMillis();
Vector<org.LexGrid.concepts.Concept> v = searchByName(scheme, version, matchText, matchAlgorithm, maxToReturn);
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
if (v != null)
{
System.out.println("v.size() = " + v.size());
for (int i=0; i<v.size(); i++)
{
int j = i + 1;
Concept ce = (Concept) v.elementAt(i);
System.out.println("(" + j + ")" + " " + ce.getId() + " " + ce.getEntityDescription().getContent());
}
}
}
protected static List<String> toWords(String s, String delimitRegex, boolean removeStopWords, boolean removeDuplicates) {
String[] words = s.split(delimitRegex);
List<String> adjusted = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
String temp = words[i].toLowerCase();
if (removeDuplicates && adjusted.contains(temp))
continue;
if (!removeStopWords || !STOP_WORDS.contains(temp))
adjusted.add(temp);
}
return adjusted;
}
protected static String[] toWords(String s, boolean removeStopWords) {
String[] words = s.split("\\s");
List<String> adjusted = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
if (!removeStopWords || !STOP_WORDS.contains(words[i]))
adjusted.add(words[i].toLowerCase());
}
return adjusted.toArray(new String[adjusted.size()]);
}
public static String preprocessSearchString(String s)
{
if (s == null) return null;
if (s.length() == 0) return null;
StringBuffer searchPhrase = new StringBuffer();
List<String> words = toWords(s, "\\s", true, false);
int k = -1;
for (int i = 0; i < words.size(); i++) {
String wd = (String) words.get(i);
wd = wd.trim();
if (wd.compareTo("") != 0)
{
k++;
if (k > 0)
{
searchPhrase.append(" ");
}
searchPhrase.append(wd);
}
}
String t = searchPhrase.toString();
return t;
}
public static boolean nonAlphabetic(String s)
{
if (s == null) return false;
if (s.length() == 0) return true;
for (int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);
if (Character.isLetter(ch)) return false;
}
return true;
}
private static String escapeSpecialChars(String s, String specChars)
{
String escapeChar = "\\";
StringBuffer regex = new StringBuffer();
for (int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if (specChars.indexOf(c) != -1)
{
regex.append(escapeChar);
}
regex.append(c);
}
return regex.toString();
}
private static String replaceSpecialChars(String s){
String escapedChars = "/";
for (int i=0; i<escapedChars.length(); i++)
{
char c = escapedChars.charAt(i);
s = s.replace(c, '.');
}
return s;
}
public static String preprocessRegExp(String s)
{
s = replaceSpecialChars(s);
s = escapeSpecialChars(s, "(){}\\,-[]");
String prefix = s.toLowerCase();
String[] words = toWords(prefix, false);
StringBuffer regex = new StringBuffer();
regex.append('^');
for (int i = 0; i < words.length; i++) {
boolean lastWord = i == words.length - 1;
String word = words[i];
int word_length = word.length();
if (word_length > 0)
{
regex.append('(');
if (word.charAt(word.length() - 1) == '.') {
regex.append(word.substring(0, word.length()));
regex.append("\\w*");
}
else
{
regex.append(word);
}
regex.append("\\s").append(lastWord ? '*' : '+');
regex.append(')');
}
}
return regex.toString();
}
protected ResolvedConceptReferencesIterator sortByScore(String searchTerm, ResolvedConceptReferencesIterator toSort, int maxToReturn) throws LBException {
List<String> compareWords = toScoreWords(searchTerm);
Map<String, ScoredTerm> scoredResult = new TreeMap<String, ScoredTerm>();
while (toSort.hasNext()) {
ResolvedConceptReferenceList refs = toSort.next(100);
for (int i = 0; i < refs.getResolvedConceptReferenceCount(); i++) {
ResolvedConceptReference ref = refs.getResolvedConceptReference(i);
String code = ref.getConceptCode();
Concept ce = ref.getReferencedEntry();
Presentation[] allTermsForConcept = ce.getPresentation();
for (Presentation p : allTermsForConcept) {
float score = score(p.getText().getContent(), compareWords, p.isIsPreferred(), i);
if (scoredResult.containsKey(code)) {
ScoredTerm scoredTerm = (ScoredTerm) scoredResult.get(code);
if (scoredTerm.score > score)
continue;
}
scoredResult.put(code, new ScoredTerm(ref, score));
}
}
}
return new ScoredIterator(scoredResult.values(), maxToReturn);
}
protected ResolvedConceptReferencesIterator sortByScore(String searchTerm, ResolvedConceptReferencesIterator toSort, int maxToReturn, boolean descriptionOnly) throws LBException {
if (!descriptionOnly) return sortByScore(searchTerm, toSort, maxToReturn);
List<String> compareWords = toScoreWords(searchTerm);
Map<String, ScoredTerm> scoredResult = new TreeMap<String, ScoredTerm>();
while (toSort.hasNext()) {
ResolvedConceptReferenceList refs = toSort.next(100);
for (int i = 0; i < refs.getResolvedConceptReferenceCount(); i++) {
ResolvedConceptReference ref = refs.getResolvedConceptReference(i);
String code = ref.getConceptCode();
String name = ref.getEntityDescription().getContent();
float score = score(name, compareWords, true, i);
scoredResult.put(code, new ScoredTerm(ref, score));
}
}
return new ScoredIterator(scoredResult.values(), maxToReturn);
}
protected float score(String text, List<String> keywords, boolean isPreferred, float searchRank) {
List<String> wordsToCompare = toScoreWords(text);
float totalWords = wordsToCompare.size();
float matchScore = 0;
float position = 0;
for (Iterator<String> words = wordsToCompare.listIterator(); words.hasNext(); position++) {
String word = words.next();
if (keywords.contains(word))
matchScore += ((position / 10) + 1);
}
return
Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2))
* (isPreferred ? 2 : 1);
}
protected List<String> toScoreWords(String s) {
return toWords(s, "[\\s,:+-;]", true, true);
}
private boolean containsSpecialChars(String s){
String escapedChars = "/.|!(){}[]^\"~*?;-_";
for (int i=0; i<escapedChars.length(); i++)
{
char c = escapedChars.charAt(i);
if (s.indexOf(c) != -1) return true;
}
return false;
}
private static String replaceSpecialCharsWithBlankChar(String s){
String escapedChars = "/.|!(){}[]^\"~*?;-_";
for (int i=0; i<escapedChars.length(); i++)
{
char c = escapedChars.charAt(i);
s = s.replace(c, ' ');
}
s = s.trim();
return s;
}
public static void main(String[] args)
{
String url = "http://lexevsapi.nci.nih.gov/lexevsapi42";
if (args.length == 1)
{
url = args[0];
System.out.println(url);
}
SearchUtils test = new SearchUtils(url);
test.testSearchByName();
}
}
| public Vector getSuperconceptCodes(String scheme, String version, String code) {
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getSuperconceptCodes_Local(String scheme, String version, String code) {
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
LexBIGService lbSvc = new LexBIGServiceImpl();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
java.lang.String[] ids = hierarchies[0].getAssociationIds();
for (int i=0; i<ids.length; i++)
{
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public static String getVocabularyVersionByTag(String codingSchemeName, String ltag)
{
if (codingSchemeName == null) return null;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes();
CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering();
for (int i=0; i<csra.length; i++)
{
CodingSchemeRendering csr = csra[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0)
{
if (ltag == null) return css.getRepresentsVersion();
RenderingDetail rd = csr.getRenderingDetail();
CodingSchemeTagList cstl = rd.getVersionTags();
java.lang.String[] tags = cstl.getTag();
for (int j=0; j<tags.length; j++)
{
String version_tag = (String) tags[j];
if (version_tag.compareToIgnoreCase(ltag) == 0)
{
return css.getRepresentsVersion();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName);
return null;
}
public static Vector<String> getVersionListData(String codingSchemeName) {
Vector<String> v = new Vector();
try {
RemoteServerUtil rsu = new RemoteServerUtil();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes();
if(csrl == null) System.out.println("csrl is NULL");
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i=0; i<csrs.length; i++)
{
CodingSchemeRendering csr = csrs[i];
Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
if (isActive != null && isActive.equals(Boolean.TRUE))
{
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
if (formalname.compareTo(codingSchemeName) == 0)
{
String representsVersion = css.getRepresentsVersion();
v.add(representsVersion);
}
}
}
} catch (Exception ex) {
}
return v;
}
protected static Association processForAnonomousNodes(Association assoc){
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for(int i = 0; i < assoc.getAssociatedConcepts().getAssociatedConceptCount(); i++)
{
if(
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != false &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@") &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@@")
)
{
}
else{
temp.getAssociatedConcepts().addAssociatedConcept(assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
public static NameAndValueList createNameAndValueList(String[] names, String[] values)
{
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.length; i++)
{
NameAndValue nv = new NameAndValue();
nv.setName(names[i]);
if (values != null)
{
nv.setContent(values[i]);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
public static LocalNameList vector2LocalNameList(Vector<String> v)
{
if (v == null) return null;
LocalNameList list = new LocalNameList();
for (int i=0; i<v.size(); i++)
{
String vEntry = (String) v.elementAt(i);
list.addEntry(vEntry);
}
return list;
}
protected static NameAndValueList createNameAndValueList(Vector names, Vector values)
{
if (names == null) return null;
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.size(); i++)
{
String name = (String) names.elementAt(i);
String value = (String) values.elementAt(i);
NameAndValue nv = new NameAndValue();
nv.setName(name);
if (value != null)
{
nv.setContent(value);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
public static ResolvedConceptReferencesIterator restrictToMatchingProperty(
String codingSchemeName,
String version,
Vector property_vec,
Vector source_vec,
Vector qualifier_name_vec,
Vector qualifier_value_vec,
java.lang.String matchText,
java.lang.String matchAlgorithm,
java.lang.String language)
{
LocalNameList propertyList = vector2LocalNameList(property_vec);
CodedNodeSet.PropertyType[] propertyTypes = null;
LocalNameList sourceList = vector2LocalNameList(source_vec);
NameAndValueList qualifierList = createNameAndValueList(qualifier_name_vec, qualifier_value_vec);
return restrictToMatchingProperty(codingSchemeName,
version,
propertyList,
propertyTypes,
sourceList,
qualifierList,
matchText,
matchAlgorithm,
language);
}
public static ResolvedConceptReferencesIterator restrictToMatchingProperty(
String codingSchemeName,
String version,
LocalNameList propertyList,
CodedNodeSet.PropertyType[] propertyTypes,
LocalNameList sourceList,
NameAndValueList qualifierList,
java.lang.String matchText,
java.lang.String matchAlgorithm,
java.lang.String language)
{
CodedNodeSet cns = null;
ResolvedConceptReferencesIterator iterator = null;
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
if (lbSvc == null)
{
System.out.println("lbSvc = null");
return null;
}
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag);
if (cns == null)
{
System.out.println("cns = null");
return null;
}
LocalNameList contextList = null;
try {
cns = cns.restrictToMatchingProperties(propertyList,
propertyTypes,
sourceList,
contextList,
qualifierList,
matchText,
matchAlgorithm,
language
);
} catch (Exception ex) {
return null;
}
LocalNameList restrictToProperties = new LocalNameList();
SortOptionList sortCriteria = null;
try {
boolean resolveConcepts = false;
try {
iterator = cns.resolve(sortCriteria, null, restrictToProperties, null, resolveConcepts);
} catch (Exception e) {
System.out.println("ERROR: cns.resolve throws exceptions.");
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return iterator;
}
private boolean isNull(String s) {
if (s == null) return true;
s = s.trim();
if (s.length() == 0) return true;
if (s.compareTo("") == 0) return true;
if (s.compareToIgnoreCase("null") == 0) return true;
return false;
}
public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code)
{
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null)
{
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(vers);
ConceptReferenceList crefs =
createConceptReferenceList(
new String[] {code}, codingSchemeName);
CodedNodeSet cns = null;
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag);
} catch (Exception e1) {
e1.printStackTrace();
}
cns = cns.restrictToCodes(crefs);
ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, null, false, 1);
if (matches == null)
{
System.out.println("Concep not found.");
return null;
}
if (matches.getResolvedConceptReferenceCount() > 0) {
ResolvedConceptReference ref =
(ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement();
org.LexGrid.concepts.Concept entry = new org.LexGrid.concepts.Concept();
entry.setId(ref.getConceptCode());
entry.setEntityDescription(ref.getEntityDescription());
return entry;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public static ConceptReferenceList createConceptReferenceList(String[] codes, String codingSchemeName)
{
if (codes == null)
{
return null;
}
ConceptReferenceList list = new ConceptReferenceList();
for (int i = 0; i < codes.length; i++)
{
ConceptReference cr = new ConceptReference();
cr.setCodingScheme(codingSchemeName);
cr.setConceptCode(codes[i]);
list.addConceptReference(cr);
}
return list;
}
public Vector getParentCodes(String scheme, String version, String code) {
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version);
if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0)
{
return null;
}
String hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0);
Vector superconcept_vec = getAssociationSources(scheme, version, code, hierarchicalAssoName);
if (superconcept_vec == null) return null;
return superconcept_vec;
}
public ResolvedConceptReferenceList getNext(ResolvedConceptReferencesIterator iterator)
{
return iterator.getNext();
}
public static Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn)
{
return resolveIterator(iterator, maxToReturn, null);
}
public static Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code)
{
Vector v = new Vector();
if (iterator == null)
{
System.out.println("No match.");
return v;
}
try {
int iteration = 0;
while (iterator.hasNext())
{
iteration++;
iterator = iterator.scroll(maxToReturn);
ResolvedConceptReferenceList rcrl = iterator.getNext();
ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference();
for (int i=0; i<rcra.length; i++)
{
ResolvedConceptReference rcr = rcra[i];
org.LexGrid.concepts.Concept ce = new org.LexGrid.concepts.Concept();
ce.setId(rcr.getConceptCode());
ce.setEntityDescription(rcr.getEntityDescription());
if (code == null)
{
v.add(ce);
}
else
{
if (ce.getId().compareTo(code) != 0) v.add(ce);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator(
CodedNodeGraph cng,
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveAssociationDepth,
int maxToReturn) {
CodedNodeSet cns = null;
try {
cns = cng.toNodeList(graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
if (cns == null)
{
System.out.println("cng.toNodeList returns null???");
return null;
}
SortOptionList sortCriteria = null;
LocalNameList propertyNames = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
ResolvedConceptReferencesIterator iterator = null;
try {
iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes);
} catch (Exception e) {
e.printStackTrace();
}
if(iterator == null)
{
System.out.println("cns.resolve returns null???");
}
return iterator;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public Vector getSuperconcepts(String scheme, String version, String code)
{
String hierarchicalAssoName = "hasSubtype";
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version);
if (hierarchicalAssoName_vec != null && hierarchicalAssoName_vec.size() > 0)
{
hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0);
}
return getAssociationSources(scheme, version, code, hierarchicalAssoName);
}
public Vector getAssociationSources(String scheme, String version, String code, String assocName)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList =
createNameAndValueList(
new String[] {assocName}, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = false;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = 1000;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public Vector getSubconcepts(String scheme, String version, String code)
{
String hierarchicalAssoName = "hasSubtype";
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version);
if (hierarchicalAssoName_vec != null && hierarchicalAssoName_vec.size() > 0)
{
hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0);
}
return getAssociationTargets(scheme, version, code, hierarchicalAssoName);
}
public Vector getAssociationTargets(String scheme, String version, String code, String assocName)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList =
createNameAndValueList(
new String[] {assocName}, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = false;
int resolveAssociationDepth = 1;
int maxToReturn = 1000;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public static String preprocessContains(String s)
{
if (s == null) return null;
if (s.length() == 0) return null;
s = s.trim();
List<String> words = toWords(s, "\\s", false, false);
String delim = ".*";
StringBuffer searchPhrase = new StringBuffer();
int k = -1;
searchPhrase.append(delim);
for (int i = 0; i < words.size(); i++) {
String wd = (String) words.get(i);
wd = wd.trim();
if (wd.compareTo("") != 0)
{
searchPhrase.append(wd);
if (words.size() > 1 && i < words.size()-1)
{
searchPhrase.append("\\s");
}
}
}
searchPhrase.append(delim);
String t = searchPhrase.toString();
return t;
}
private boolean isNumber(String s) {
if (s.length() == 0) return false;
for(int i=0; i<s.length(); i++)
{
if(!Character.isDigit(s.charAt(i)))
return false;
}
return true;
}
public Vector<org.LexGrid.concepts.Concept> searchByName(String scheme, String version, String matchText, String matchAlgorithm, int maxToReturn) {
String matchText0 = matchText;
String matchAlgorithm0 = matchAlgorithm;
matchText0 = matchText0.trim();
boolean preprocess = true;
if (matchText == null || matchText.length() == 0)
{
return new Vector();
}
matchText = matchText.trim();
if (matchAlgorithm.compareToIgnoreCase("exactMatch") == 0)
{
if (!isNumber(matchText)) {
if (nonAlphabetic(matchText) || matchText.indexOf(".") != -1 || matchText.indexOf("/") != -1)
{
return searchByName(scheme, version, matchText, "RegExp", maxToReturn);
}
}
if (containsSpecialChars(matchText))
{
return searchByName(scheme, version, matchText, "RegExp", maxToReturn);
}
}
else if (matchAlgorithm.compareToIgnoreCase("startsWith") == 0)
{
}
else if (matchAlgorithm.compareToIgnoreCase("contains") == 0)
{
matchText = replaceSpecialCharsWithBlankChar(matchText);
if (matchText.indexOf(" ") != -1) {
matchText = preprocessContains(matchText);
matchAlgorithm = "RegExp";
preprocess = false;
}
}
if (matchAlgorithm.compareToIgnoreCase("RegExp") == 0 && preprocess)
{
matchText = preprocessRegExp(matchText);
}
LocalNameList propertyList = null;
CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1];
propertyTypes[0] = CodedNodeSet.PropertyType.PRESENTATION;
LocalNameList sourceList = null;
NameAndValueList qualifierList = null;
String language = null;
ResolvedConceptReferencesIterator iterator = restrictToMatchingProperty(
scheme,
version,
propertyList,
propertyTypes,
sourceList,
qualifierList,
matchText,
matchAlgorithm,
language);
if (iterator == null) return null;
if (apply_sort_score)
{
long ms = System.currentTimeMillis();
try {
iterator = sortByScore(matchText0, iterator, maxToReturn, true);
} catch (Exception ex) {
}
System.out.println("Sorting delay ---- Run time (ms): " + (System.currentTimeMillis() - ms));
}
if (iterator != null) {
Vector v = resolveIterator( iterator, maxToReturn);
if (v != null && v.size() > 0)
{
if(!apply_sort_score)
{
SortUtils.quickSort(v);
}
return v;
}
if (matchAlgorithm.compareToIgnoreCase("exactMatch") == 0) {
Concept c = getConceptByCode(scheme, null, null, matchText0);
if (c != null)
{
v = new Vector();
v.add(c);
return v;
}
}
}
if (matchAlgorithm0.compareToIgnoreCase("exactMatch") == 0) {
matchText0 = matchText0.trim();
Concept c = getConceptByCode(scheme, null, null, matchText0);
if (c != null)
{
Vector v = new Vector();
v.add(c);
return v;
}
}
else
{
return searchByName(scheme, version, matchText0, "exactMatch", maxToReturn);
}
return new Vector();
}
public void testSearchByName() {
String scheme = "NCI Thesaurus";
String version = "08.11d";
String matchText = "blood";
String matchAlgorithm = "contains";
int maxToReturn = 1000;
long ms = System.currentTimeMillis();
Vector<org.LexGrid.concepts.Concept> v = searchByName(scheme, version, matchText, matchAlgorithm, maxToReturn);
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
if (v != null)
{
System.out.println("v.size() = " + v.size());
for (int i=0; i<v.size(); i++)
{
int j = i + 1;
Concept ce = (Concept) v.elementAt(i);
System.out.println("(" + j + ")" + " " + ce.getId() + " " + ce.getEntityDescription().getContent());
}
}
}
protected static List<String> toWords(String s, String delimitRegex, boolean removeStopWords, boolean removeDuplicates) {
String[] words = s.split(delimitRegex);
List<String> adjusted = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
String temp = words[i].toLowerCase();
if (removeDuplicates && adjusted.contains(temp))
continue;
if (!removeStopWords || !STOP_WORDS.contains(temp))
adjusted.add(temp);
}
return adjusted;
}
protected static String[] toWords(String s, boolean removeStopWords) {
String[] words = s.split("\\s");
List<String> adjusted = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
if (!removeStopWords || !STOP_WORDS.contains(words[i]))
adjusted.add(words[i].toLowerCase());
}
return adjusted.toArray(new String[adjusted.size()]);
}
public static String preprocessSearchString(String s)
{
if (s == null) return null;
if (s.length() == 0) return null;
StringBuffer searchPhrase = new StringBuffer();
List<String> words = toWords(s, "\\s", true, false);
int k = -1;
for (int i = 0; i < words.size(); i++) {
String wd = (String) words.get(i);
wd = wd.trim();
if (wd.compareTo("") != 0)
{
k++;
if (k > 0)
{
searchPhrase.append(" ");
}
searchPhrase.append(wd);
}
}
String t = searchPhrase.toString();
return t;
}
public static boolean nonAlphabetic(String s)
{
if (s == null) return false;
if (s.length() == 0) return true;
for (int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);
if (Character.isLetter(ch)) return false;
}
return true;
}
private static String escapeSpecialChars(String s, String specChars)
{
String escapeChar = "\\";
StringBuffer regex = new StringBuffer();
for (int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if (specChars.indexOf(c) != -1)
{
regex.append(escapeChar);
}
regex.append(c);
}
return regex.toString();
}
private static String replaceSpecialChars(String s){
String escapedChars = "/";
for (int i=0; i<escapedChars.length(); i++)
{
char c = escapedChars.charAt(i);
s = s.replace(c, '.');
}
return s;
}
public static String preprocessRegExp(String s)
{
s = replaceSpecialChars(s);
s = escapeSpecialChars(s, "(){}\\,-[]");
String prefix = s.toLowerCase();
String[] words = toWords(prefix, false);
StringBuffer regex = new StringBuffer();
regex.append('^');
for (int i = 0; i < words.length; i++) {
boolean lastWord = i == words.length - 1;
String word = words[i];
int word_length = word.length();
if (word_length > 0)
{
regex.append('(');
if (word.charAt(word.length() - 1) == '.') {
regex.append(word.substring(0, word.length()));
regex.append("\\w*");
}
else
{
regex.append(word);
}
regex.append("\\s").append(lastWord ? '*' : '+');
regex.append(')');
}
}
return regex.toString();
}
protected ResolvedConceptReferencesIterator sortByScore(String searchTerm, ResolvedConceptReferencesIterator toSort, int maxToReturn) throws LBException {
List<String> compareWords = toScoreWords(searchTerm);
Map<String, ScoredTerm> scoredResult = new TreeMap<String, ScoredTerm>();
while (toSort.hasNext()) {
ResolvedConceptReferenceList refs = toSort.next(100);
for (int i = 0; i < refs.getResolvedConceptReferenceCount(); i++) {
ResolvedConceptReference ref = refs.getResolvedConceptReference(i);
String code = ref.getConceptCode();
Concept ce = ref.getReferencedEntry();
Presentation[] allTermsForConcept = ce.getPresentation();
for (Presentation p : allTermsForConcept) {
float score = score(p.getText().getContent(), compareWords, p.isIsPreferred(), i);
if (scoredResult.containsKey(code)) {
ScoredTerm scoredTerm = (ScoredTerm) scoredResult.get(code);
if (scoredTerm.score > score)
continue;
}
scoredResult.put(code, new ScoredTerm(ref, score));
}
}
}
return new ScoredIterator(scoredResult.values(), maxToReturn);
}
protected ResolvedConceptReferencesIterator sortByScore(String searchTerm, ResolvedConceptReferencesIterator toSort, int maxToReturn, boolean descriptionOnly) throws LBException {
if (!descriptionOnly) return sortByScore(searchTerm, toSort, maxToReturn);
List<String> compareWords = toScoreWords(searchTerm);
Map<String, ScoredTerm> scoredResult = new TreeMap<String, ScoredTerm>();
while (toSort.hasNext()) {
ResolvedConceptReferenceList refs = toSort.next(100);
for (int i = 0; i < refs.getResolvedConceptReferenceCount(); i++) {
ResolvedConceptReference ref = refs.getResolvedConceptReference(i);
String code = ref.getConceptCode();
String name = ref.getEntityDescription().getContent();
float score = score(name, compareWords, true, i);
scoredResult.put(code, new ScoredTerm(ref, score));
}
}
return new ScoredIterator(scoredResult.values(), maxToReturn);
}
protected float score(String text, List<String> keywords, boolean isPreferred, float searchRank) {
List<String> wordsToCompare = toScoreWords(text);
float totalWords = wordsToCompare.size();
float matchScore = 0;
float position = 0;
for (Iterator<String> words = wordsToCompare.listIterator(); words.hasNext(); position++) {
String word = words.next();
if (keywords.contains(word))
matchScore += ((position / 10) + 1);
}
return
Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2))
* (isPreferred ? 2 : 1);
}
protected List<String> toScoreWords(String s) {
return toWords(s, "[\\s,:+-;]", true, true);
}
private boolean containsSpecialChars(String s){
String escapedChars = "/.|!(){}[]^\"~*?;-_";
for (int i=0; i<escapedChars.length(); i++)
{
char c = escapedChars.charAt(i);
if (s.indexOf(c) != -1) return true;
}
return false;
}
private static String replaceSpecialCharsWithBlankChar(String s){
String escapedChars = "/.|!(){}[]^\"~*?;-_";
for (int i=0; i<escapedChars.length(); i++)
{
char c = escapedChars.charAt(i);
s = s.replace(c, ' ');
}
s = s.trim();
return s;
}
public static void main(String[] args)
{
String url = "http://lexevsapi.nci.nih.gov/lexevsapi42";
if (args.length == 1)
{
url = args[0];
System.out.println(url);
}
SearchUtils test = new SearchUtils(url);
test.testSearchByName();
}
}
|
public void handlePingInRegister(ArrayList<SIPNode> ping) {
for (SIPNode pingNode : ping) {
if(nodes.size() < 1) {
nodes.add(pingNode);
if(logger.isLoggable(Level.FINEST)) {
logger.finest("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
return ;
}
SIPNode nodePresent = null;
Iterator<SIPNode> nodesIterator = nodes.iterator();
while (nodesIterator.hasNext() && nodePresent == null) {
SIPNode node = (SIPNode) nodesIterator.next();
if (node.equals(pingNode)) {
nodePresent = node;
}
}
if(nodePresent != null) {
nodePresent.updateTimerStamp();
} else {
nodes.add(pingNode);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
}
}
}
| public void handlePingInRegister(ArrayList<SIPNode> ping) {
for (SIPNode pingNode : ping) {
if(nodes.size() < 1) {
nodes.add(pingNode);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
return ;
}
SIPNode nodePresent = null;
Iterator<SIPNode> nodesIterator = nodes.iterator();
while (nodesIterator.hasNext() && nodePresent == null) {
SIPNode node = (SIPNode) nodesIterator.next();
if (node.equals(pingNode)) {
nodePresent = node;
}
}
if(nodePresent != null) {
nodePresent.updateTimerStamp();
} else {
nodes.add(pingNode);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
}
}
}
|
public org.w3c.dom.Document getCustomConfiguration() {
Configuration customConfig = config.getChild("custom-config");
if (customConfig != null) {
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation();
org.w3c.dom.DocumentType doctype = null;
doc = impl.createDocument(customConfig.getNamespace(), customConfig.getName(), doctype);
Configuration[] children = customConfig.getChildren();
if (children.length > 0) {
Element rootElement = doc.getDocumentElement();
for (int i = 0; i < children.length; i++) {
log.error("DEBUG: child: " + children[i].getName());
rootElement.appendChild(createElement(children[i], doc));
}
}
} catch(Exception e) {
log.error(e.getMessage(), e);
}
return doc;
} else {
log.warn("No custom configuration: " + getUniversalName());
}
return null;
}
| public org.w3c.dom.Document getCustomConfiguration() {
Configuration customConfig = config.getChild("custom-config");
if (customConfig != null) {
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation();
org.w3c.dom.DocumentType doctype = null;
doc = impl.createDocument(customConfig.getNamespace(), customConfig.getName(), doctype);
Configuration[] children = customConfig.getChildren();
if (children.length > 0) {
Element rootElement = doc.getDocumentElement();
for (int i = 0; i < children.length; i++) {
rootElement.appendChild(createElement(children[i], doc));
}
}
} catch(Exception e) {
log.error(e.getMessage(), e);
}
return doc;
} else {
log.warn("No custom configuration: " + getUniversalName());
}
return null;
}
|
GlobalContext(final Footlights footlights)
{
super("global");
register("initialize", new Initializer());
register("load_plugin", new PluginLoader(footlights));
register("reset", new AjaxHandler() {
@Override
public JavaScript service(Request request)
{
while(footlights.plugins().size() > 0)
footlights.unloadPlugin(
footlights.plugins().iterator().next());
return new JavaScript().append("window.location.reload()");
}
});
register("cajole", new AjaxHandler()
{
@Override public JavaScript service(Request request) throws Throwable
{
JavaScript code = new JavaScript();
code.append(
"var sandbox = sandboxes.getOrCreate('sandbox', rootContext, 0, 0, 200, 200);");
code.append("sandbox.load('sandbox.js')");
return code;
}
});
}
| GlobalContext(final Footlights footlights)
{
super("global");
register("initialize", new Initializer());
register("load_plugin", new PluginLoader(footlights));
register("reset", new AjaxHandler() {
@Override
public JavaScript service(Request request)
{
while(footlights.plugins().size() > 0)
footlights.unloadPlugin(
footlights.plugins().iterator().next());
return new JavaScript().append("window.location.reload()");
}
});
register("cajole", new AjaxHandler()
{
@Override public JavaScript service(Request request) throws Throwable
{
JavaScript code = new JavaScript();
code.append(
"var sandbox = sandboxes.getOrCreate('sandbox', rootContext, rootContext.log, 0, 0, 200, 200);");
code.append("sandbox.load('sandbox.js')");
return code;
}
});
}
|
public SingleInstanceWorkloadStrategy(
TalendESBJob esbJob,
String jobName,
String[] arguments,
ESBEndpointRegistry endpointRegistry,
ExecutorService executorService) {
job = esbJob;
name = jobName;
registry = endpointRegistry;
execService = executorService;
}
| public SingleInstanceWorkloadStrategy(
TalendESBJob esbJob,
String jobName,
String[] arguments,
ESBEndpointRegistry endpointRegistry,
ExecutorService executorService) {
job = esbJob;
name = jobName;
args = arguments;
registry = endpointRegistry;
execService = executorService;
}
|
private Set<DeployDetails> buildDeployDetailsFromFileSet(Map.Entry<String, FileSet> fileSetEntry,
String targetRepository, File rootDir, Map<String, String> propertyMap) throws IOException,
NoSuchAlgorithmException {
Set<DeployDetails> result = Sets.newHashSet();
String targetPath = fileSetEntry.getKey();
Iterator<FileResource> iterator = fileSetEntry.getValue().iterator();
while (iterator.hasNext()) {
FileResource fileResource = iterator.next();
File file = fileResource.getFile();
String relativePath = file.getAbsolutePath();
if (StringUtils.startsWith(relativePath, rootDir.getAbsolutePath())) {
relativePath = StringUtils.removeStart(file.getAbsolutePath(), rootDir.getAbsolutePath());
} else {
File fileBaseDir = fileResource.getBaseDir();
if (fileBaseDir != null) {
relativePath = StringUtils.removeStart(file.getAbsolutePath(), fileBaseDir.getAbsolutePath());
}
}
relativePath = FilenameUtils.separatorsToUnix(relativePath);
relativePath = StringUtils.removeStart(relativePath, "/");
String path = PublishedItemsHelper.calculateTargetPath(relativePath, targetPath, file.getName());
path = StringUtils.replace(path, "//", "/");
Map<String, String> checksums = FileChecksumCalculator.calculateChecksums(file, "SHA1", "MD5");
DeployDetails.Builder deployDetails = new DeployDetails.Builder().file(file).md5(checksums.get("MD5"))
.sha1(checksums.get("SHA1")).targetRepository(targetRepository).artifactPath(path);
addCommonProperties(deployDetails);
deployDetails.addProperties(propertyMap);
result.add(deployDetails.build());
}
return result;
}
| private Set<DeployDetails> buildDeployDetailsFromFileSet(Map.Entry<String, FileSet> fileSetEntry,
String targetRepository, File rootDir, Map<String, String> propertyMap) throws IOException,
NoSuchAlgorithmException {
Set<DeployDetails> result = Sets.newHashSet();
String targetPath = fileSetEntry.getKey();
Iterator<FileResource> iterator = fileSetEntry.getValue().iterator();
while (iterator.hasNext()) {
FileResource fileResource = iterator.next();
File file = fileResource.getFile();
String relativePath = file.getAbsolutePath();
if (StringUtils.startsWith(relativePath, rootDir.getAbsolutePath())) {
relativePath = StringUtils.removeStart(file.getAbsolutePath(), rootDir.getAbsolutePath());
} else {
File fileBaseDir = fileResource.getBaseDir();
if (fileBaseDir != null) {
relativePath = StringUtils.removeStart(file.getAbsolutePath(), fileBaseDir.getAbsolutePath());
}
}
relativePath = FilenameUtils.separatorsToUnix(relativePath);
relativePath = StringUtils.removeStart(relativePath, "/");
String path = PublishedItemsHelper.calculateTargetPath(targetPath, file, relativePath);
path = StringUtils.replace(path, "//", "/");
Map<String, String> checksums = FileChecksumCalculator.calculateChecksums(file, "SHA1", "MD5");
DeployDetails.Builder deployDetails = new DeployDetails.Builder().file(file).md5(checksums.get("MD5"))
.sha1(checksums.get("SHA1")).targetRepository(targetRepository).artifactPath(path);
addCommonProperties(deployDetails);
deployDetails.addProperties(propertyMap);
result.add(deployDetails.build());
}
return result;
}
|
private Object _invoke(String serviceName, String methodName, Type returnType, Object... arguments) throws Throwable
{
StringWriter stringWriter = new StringWriter();
String invocationBody = protocol.writeRequest(methodName, arguments);
RpcInvocation invocation = new RpcInvocation(serviceUrl, invocationBody)
.withHeader("Accept", protocol.getAcceptType())
.withContentType(protocol.getContentType());
final RpcRequestContext requestContext = new RpcRequestContext(invoker, invocation, serviceName,
methodName, invocationBody);
if (eventHandler != null)
eventHandler.preInvoke(requestContext);
RpcInvocationResponse response = null;
Object result = null;
long startTimeMillis = System.currentTimeMillis();
try
{
response = invoker.invoke(invocation);
}
catch (Exception e)
{
long timeSpentMillis = System.currentTimeMillis() - startTimeMillis;
firePostInvokeError(requestContext, response, timeSpentMillis, e);
throw new RpcTransportException(format("Exception while communicating with server [endpoint=%s,timeSpentMillis=%d,invoker=%s]",
getEndPointDescription(serviceName, methodName), timeSpentMillis, invoker), e);
}
long timeSpentMillis = System.currentTimeMillis() - startTimeMillis;
if (response.getStatusCode() != 200)
{
final RpcTransportException rpcTransportException = new RpcTransportException(format("Unexpected server HTTP status code [endpoint=%s,httpStatusLine='%s',timeSpentMillis=%d,invoker=%s]",
getEndPointDescription(serviceName, methodName), formatStatusLine(response), timeSpentMillis, invoker), response.getStatusCode());
firePostInvokeError(requestContext, response, timeSpentMillis, rpcTransportException);
throw rpcTransportException;
}
final String responseBody = response.getBody();
if (responseBody == null || responseBody.trim().equals(""))
{
final RpcTransportException rpcTransportException = new RpcTransportException(format("Empty HTTP response [endpoint=%s,httpStatusLine='%s',timeSpentMillis=%d,invoker=%s]",
getEndPointDescription(serviceName, methodName), formatStatusLine(response), timeSpentMillis, invoker), response.getStatusCode());
firePostInvokeError(requestContext, response, timeSpentMillis, rpcTransportException);
throw rpcTransportException;
}
try
{
result = protocol.readResponse(returnType, responseBody);
if (eventHandler != null)
eventHandler.postInvoke(requestContext, new RpcResponseContext(result, response, timeSpentMillis));
}
catch (Exception e)
{
throw e;
}
return result;
}
| private Object _invoke(String serviceName, String methodName, Type returnType, Object... arguments) throws Throwable
{
StringWriter stringWriter = new StringWriter();
String invocationBody = protocol.writeRequest(methodName, arguments);
RpcInvocation invocation = new RpcInvocation(serviceUrl, invocationBody)
.withHeader("Accept", protocol.getAcceptType())
.withContentType(protocol.getContentType());
final RpcRequestContext requestContext = new RpcRequestContext(invoker, invocation, serviceName,
methodName, invocationBody);
if (eventHandler != null)
eventHandler.preInvoke(requestContext);
RpcInvocationResponse response = null;
Object result = null;
long startTimeMillis = System.currentTimeMillis();
try
{
response = invoker.invoke(invocation);
}
catch (Exception e)
{
long timeSpentMillis = System.currentTimeMillis() - startTimeMillis;
firePostInvokeError(requestContext, response, timeSpentMillis, e);
throw new RpcTransportException(format("Exception while communicating with server [endpoint=%s,timeSpentMillis=%d,invoker=%s]",
getEndPointDescription(serviceName, methodName), timeSpentMillis, invoker), e);
}
long timeSpentMillis = System.currentTimeMillis() - startTimeMillis;
if (response.getStatusCode() != 200)
{
final RpcTransportException rpcTransportException = new RpcTransportException(format("Unexpected server HTTP status code [endpoint=%s,httpStatusLine='%s',timeSpentMillis=%d,invoker=%s]",
getEndPointDescription(serviceName, methodName), formatStatusLine(response), timeSpentMillis, invoker), response.getStatusCode());
firePostInvokeError(requestContext, response, timeSpentMillis, rpcTransportException);
throw rpcTransportException;
}
final String responseBody = response.getBody();
if (responseBody == null || responseBody.trim().equals(""))
{
final RpcTransportException rpcTransportException = new RpcTransportException(format("Empty HTTP response [endpoint=%s,httpStatusLine='%s',timeSpentMillis=%d,invoker=%s]",
getEndPointDescription(serviceName, methodName), formatStatusLine(response), timeSpentMillis, invoker), response.getStatusCode());
firePostInvokeError(requestContext, response, timeSpentMillis, rpcTransportException);
throw rpcTransportException;
}
result = protocol.readResponse(returnType, responseBody);
if (eventHandler != null)
eventHandler.postInvoke(requestContext, new RpcResponseContext(result, response, timeSpentMillis));
return result;
}
|
public void execute() throws Throwable
{
StringBuilder response = this._http.fetchUrl( this.getGenerator()._baseUrl );
this.trace( this.getGenerator()._baseUrl );
if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK )
{
String errorMessage = "Url GET ERROR - Received an empty/failed response";
throw new IOException (errorMessage);
}
for( int i = 0; i < this._burstSize; i++ )
{
String url = this.getGenerator()._baseUrl + "/" + (i+1);
response = this._http.fetchUrl( url );
this.trace( url );
if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK )
{
String errorMessage = "Url GET ERROR - Received an empty response";
throw new IOException (errorMessage);
}
}
this.setFailed( false );
}
| public void execute() throws Throwable
{
StringBuilder response = this._http.fetchUrl( this.getGenerator()._baseUrl );
this.trace( this.getGenerator()._baseUrl );
if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK )
{
String errorMessage = "Url GET ERROR - Received an empty/failed response";
throw new IOException (errorMessage);
}
for( int i = 0; i < this._burstSize; i++ )
{
String url = this.getGenerator()._baseUrl + "/" + (i+1);
response = this._http.fetchUrl( url );
this.trace( url );
if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK )
{
String errorMessage = "Url GET ERROR - Received an empty/failed response";
throw new IOException (errorMessage);
}
}
this.setFailed( false );
}
|
ChainSelectionDialog(JFrame owner) {
super(owner, true);
modelLeft = new DefaultComboBoxModel<>();
final JComboBox<File> comboLeft = new JComboBox<>(modelLeft);
final JPanel panelChainsLeft = new JPanel();
panelChainsLeft.setLayout(new BoxLayout(panelChainsLeft,
BoxLayout.Y_AXIS));
panelChainsLeft.setBorder(BorderFactory
.createTitledBorder("Available chains:"));
final JPanel panelLeft = new JPanel();
panelLeft.setLayout(new BorderLayout());
panelLeft.add(comboLeft, BorderLayout.NORTH);
panelLeft.add(new JScrollPane(panelChainsLeft), BorderLayout.CENTER);
modelRight = new DefaultComboBoxModel<>();
final JComboBox<File> comboRight = new JComboBox<>(modelRight);
final JPanel panelChainsRight = new JPanel();
panelChainsRight.setLayout(new BoxLayout(panelChainsRight,
BoxLayout.Y_AXIS));
panelChainsRight.setBorder(BorderFactory
.createTitledBorder("Available chains:"));
JPanel panelRight = new JPanel();
panelRight.setLayout(new BorderLayout());
panelRight.add(comboRight, BorderLayout.NORTH);
panelRight.add(new JScrollPane(panelChainsRight), BorderLayout.CENTER);
JPanel panelBoth = new JPanel();
panelBoth.setLayout(new GridLayout(1, 2));
panelBoth.add(panelLeft);
panelBoth.add(panelRight);
JButton buttonOk = new JButton("OK");
JButton buttonCancel = new JButton("Cancel");
JPanel panelButtons = new JPanel();
panelButtons.add(buttonOk);
panelButtons.add(buttonCancel);
setLayout(new BorderLayout());
add(panelBoth, BorderLayout.CENTER);
add(panelButtons, BorderLayout.SOUTH);
int width = 640;
int height = 480;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = screenSize.width - width;
int y = screenSize.height - height;
setSize(width, height);
setLocation(x / 2, y / 2);
setTitle("Chain selection dialog");
ActionListener actionListenerCombo = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox<File> source = (JComboBox<File>) e.getSource();
File file = (File) source.getSelectedItem();
Structure structure = PdbManager.getStructure(file);
if (structure == null) {
return;
}
JPanel panelReference;
if (source.equals(comboLeft)) {
panelReference = panelChainsLeft;
} else {
panelReference = panelChainsRight;
}
panelReference.removeAll();
for (Chain chain : structure.getChains()) {
panelReference.add(new JCheckBox(chain.getChainID()));
}
panelReference.revalidate();
}
};
comboLeft.addActionListener(actionListenerCombo);
comboRight.addActionListener(actionListenerCombo);
buttonOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
@SuppressWarnings("rawtypes")
JComboBox[] combos = new JComboBox[] { comboLeft, comboRight };
JPanel[] panels = new JPanel[] { panelChainsLeft,
panelChainsRight };
selectedStructures = new File[2];
selectedChains = new Chain[2][];
for (int i = 0; i < 2; i++) {
List<Chain> list = new ArrayList<>();
File pdb = (File) combos[i].getSelectedItem();
Structure structure = PdbManager.getStructure(pdb);
for (Component component : panels[i].getComponents()) {
if (component instanceof JCheckBox
&& ((JCheckBox) component).isSelected()) {
String chainId = ((JCheckBox) component).getText();
try {
list.add(structure.getChainByPDB(chainId));
} catch (StructureException e) {
ChainSelectionDialog.LOGGER.error(
"Failed to read chain " + chainId
+ " from structure: " + pdb, e);
}
}
}
selectedStructures[i] = pdb;
selectedChains[i] = list.toArray(new Chain[list.size()]);
}
dispose();
}
});
buttonCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectedChains = null;
dispose();
}
});
}
| ChainSelectionDialog(JFrame owner) {
super(owner, true);
modelLeft = new DefaultComboBoxModel<>();
final JComboBox<File> comboLeft = new JComboBox<>(modelLeft);
final JPanel panelChainsLeft = new JPanel();
panelChainsLeft.setLayout(new BoxLayout(panelChainsLeft,
BoxLayout.Y_AXIS));
panelChainsLeft.setBorder(BorderFactory
.createTitledBorder("Available chains:"));
final JPanel panelLeft = new JPanel();
panelLeft.setLayout(new BorderLayout());
panelLeft.add(comboLeft, BorderLayout.NORTH);
panelLeft.add(new JScrollPane(panelChainsLeft), BorderLayout.CENTER);
modelRight = new DefaultComboBoxModel<>();
final JComboBox<File> comboRight = new JComboBox<>(modelRight);
final JPanel panelChainsRight = new JPanel();
panelChainsRight.setLayout(new BoxLayout(panelChainsRight,
BoxLayout.Y_AXIS));
panelChainsRight.setBorder(BorderFactory
.createTitledBorder("Available chains:"));
JPanel panelRight = new JPanel();
panelRight.setLayout(new BorderLayout());
panelRight.add(comboRight, BorderLayout.NORTH);
panelRight.add(new JScrollPane(panelChainsRight), BorderLayout.CENTER);
JPanel panelBoth = new JPanel();
panelBoth.setLayout(new GridLayout(1, 2));
panelBoth.add(panelLeft);
panelBoth.add(panelRight);
JButton buttonOk = new JButton("OK");
JButton buttonCancel = new JButton("Cancel");
JPanel panelButtons = new JPanel();
panelButtons.add(buttonOk);
panelButtons.add(buttonCancel);
setLayout(new BorderLayout());
add(panelBoth, BorderLayout.CENTER);
add(panelButtons, BorderLayout.SOUTH);
int width = 640;
int height = 480;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = screenSize.width - width;
int y = screenSize.height - height;
setSize(width, height);
setLocation(x / 2, y / 2);
setTitle("Chain selection dialog");
ActionListener actionListenerCombo = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox<File> source = (JComboBox<File>) e.getSource();
File file = (File) source.getSelectedItem();
Structure structure = PdbManager.getStructure(file);
if (structure == null) {
return;
}
JPanel panelReference;
if (source.equals(comboLeft)) {
panelReference = panelChainsLeft;
} else {
panelReference = panelChainsRight;
}
panelReference.removeAll();
for (Chain chain : structure.getChains()) {
panelReference.add(new JCheckBox(chain.getChainID()));
}
panelReference.updateUI();
}
};
comboLeft.addActionListener(actionListenerCombo);
comboRight.addActionListener(actionListenerCombo);
buttonOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
@SuppressWarnings("rawtypes")
JComboBox[] combos = new JComboBox[] { comboLeft, comboRight };
JPanel[] panels = new JPanel[] { panelChainsLeft,
panelChainsRight };
selectedStructures = new File[2];
selectedChains = new Chain[2][];
for (int i = 0; i < 2; i++) {
List<Chain> list = new ArrayList<>();
File pdb = (File) combos[i].getSelectedItem();
Structure structure = PdbManager.getStructure(pdb);
for (Component component : panels[i].getComponents()) {
if (component instanceof JCheckBox
&& ((JCheckBox) component).isSelected()) {
String chainId = ((JCheckBox) component).getText();
try {
list.add(structure.getChainByPDB(chainId));
} catch (StructureException e) {
ChainSelectionDialog.LOGGER.error(
"Failed to read chain " + chainId
+ " from structure: " + pdb, e);
}
}
}
selectedStructures[i] = pdb;
selectedChains[i] = list.toArray(new Chain[list.size()]);
}
dispose();
}
});
buttonCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectedChains = null;
dispose();
}
});
}
|
public void paint(Graphics g){
g.setColor(new Color(0, 0, 0, 100));
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.drawImage(slot, this.getWidth()/2 - slot.getWidth()/2, 5, null);
Weapon w = player.getWeapons()[weaponIndex];
if(w != null) {
g.setColor(Color.WHITE);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < w.getKeys().length; i++) {
sb.append(Translator.getWeaponString(w.getKeys()[i]) + " ");
}
String text = sb.toString();
g.drawString(text, this.getWidth()/2 -
(int)g.getFontMetrics().getStringBounds(text, g).getWidth()/2, this.getHeight() - 4);
g.drawImage(textures[player.getWeapons()[weaponIndex].getIconNumber()], this.getWidth()/2 - slot.getWidth()/2, 5, null);
}
g.setColor(new Color(76, 76, 76));
g.drawRect(this.getWidth()/2 - slot.getWidth()/2, 5, slot.getWidth(), slot.getHeight());
if(player.getActiveWeapon() == player.getWeapons()[weaponIndex]){
g.setColor(Color.RED);
g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
}
}
| public void paint(Graphics g){
g.setColor(new Color(0, 0, 0, 100));
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.drawImage(slot, this.getWidth()/2 - slot.getWidth()/2, 5, null);
Weapon w = player.getWeapons()[weaponIndex];
if(w != null) {
g.setColor(Color.WHITE);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < w.getKeys().length; i++) {
sb.append(Translator.getWeaponString(w.getKeys()[i]));
}
String text = sb.toString();
g.drawString(text, this.getWidth()/2 -
(int)g.getFontMetrics().getStringBounds(text, g).getWidth()/2, this.getHeight() - 4);
g.drawImage(textures[player.getWeapons()[weaponIndex].getIconNumber()], this.getWidth()/2 - slot.getWidth()/2, 5, null);
}
g.setColor(new Color(76, 76, 76));
g.drawRect(this.getWidth()/2 - slot.getWidth()/2, 5, slot.getWidth(), slot.getHeight());
if(player.getActiveWeapon() == player.getWeapons()[weaponIndex]){
g.setColor(Color.RED);
g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
}
}
|
public void testViewRequisitionRegimenAndEmergencyStatus(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add("CREATE_REQUISITION");
rightsList.add("VIEW_REQUISITION");
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
dbWrapper.assignRight(STORE_IN_CHARGE, APPROVE_REQUISITION);
dbWrapper.assignRight(STORE_IN_CHARGE, CONVERT_TO_ORDER);
dbWrapper.assignRight(STORE_IN_CHARGE, VIEW_ORDER);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
HomePage homePage1 = initiateRnRPage.clickHome();
ViewRequisitionPage viewRequisitionPage = homePage1.navigateViewRequisition();
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
dbWrapper.insertValuesInRequisition(true);
dbWrapper.insertValuesInRegimenLineItems(patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(SUBMITTED, userSIC, "HIV");
viewRequisitionPage.enterViewSearchCriteria();
viewRequisitionPage.clickSearch();
viewRequisitionPage.verifyNoRequisitionFound();
dbWrapper.insertApprovedQuantity(10);
dbWrapper.updateRequisitionStatus(AUTHORIZED, userSIC, "HIV");
viewRequisitionPage.clickSearch();
viewRequisitionPage.clickRnRList();
viewRequisitionPage.verifyTotalFieldPostAuthorize();
HomePage homePageAuthorized = viewRequisitionPage.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPage.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewRequisitionPage viewRequisitionPageAuthorized = homePageAuthorized.navigateViewRequisition();
viewRequisitionPageAuthorized.enterViewSearchCriteria();
viewRequisitionPageAuthorized.clickSearch();
viewRequisitionPageAuthorized.verifyStatus(AUTHORIZED);
viewRequisitionPageAuthorized.verifyEmergencyStatus();
viewRequisitionPageAuthorized.clickRnRList();
HomePage homePageInApproval = viewRequisitionPageAuthorized.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(IN_APPROVAL, userSIC, "HIV");
ViewRequisitionPage viewRequisitionPageInApproval = homePageInApproval.navigateViewRequisition();
viewRequisitionPageInApproval.enterViewSearchCriteria();
viewRequisitionPageInApproval.clickSearch();
viewRequisitionPageInApproval.verifyStatus(IN_APPROVAL);
viewRequisitionPageInApproval.verifyEmergencyStatus();
ApprovePage approvePageTopSNUser = homePageInApproval.navigateToApprove();
approvePageTopSNUser.verifyEmergencyStatus();
approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCostViewRequisition("20");
approvePageTopSNUser.addComments("Dummy Comments");
approvePageTopSNUser.verifyTotalFieldPostAuthorize();
approvePageTopSNUser.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
ViewRequisitionPage viewRequisitionPageApproved = homePageInApproval.navigateViewRequisition();
viewRequisitionPageApproved.enterViewSearchCriteria();
viewRequisitionPageApproved.clickSearch();
viewRequisitionPageApproved.verifyStatus(APPROVED);
viewRequisitionPageApproved.verifyEmergencyStatus();
viewRequisitionPageApproved.clickRnRList();
viewRequisitionPageApproved.verifyTotalFieldPostAuthorize();
viewRequisitionPageApproved.verifyComment("Dummy Comments", userSIC, 1);
viewRequisitionPageApproved.verifyCommentBoxNotPresent();
HomePage homePageApproved = viewRequisitionPageApproved.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ConvertOrderPage convertOrderPage = homePageApproved.navigateConvertToOrder();
convertOrderPage.verifyEmergencyStatus();
convertOrderPage.convertToOrder();
ViewRequisitionPage viewRequisitionPageOrdered = homePageApproved.navigateViewRequisition();
viewRequisitionPageOrdered.enterViewSearchCriteria();
viewRequisitionPageOrdered.clickSearch();
viewRequisitionPageOrdered.verifyStatus(RELEASED);
viewRequisitionPageOrdered.verifyEmergencyStatus();
viewRequisitionPageOrdered.clickRnRList();
viewRequisitionPageOrdered.verifyTotalFieldPostAuthorize();
viewRequisitionPageOrdered.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageOrdered.verifyApprovedQuantityFieldPresent();
viewRequisitionPageOrdered.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewOrdersPage viewOrdersPage=homePageApproved.navigateViewOrders();
viewOrdersPage.verifyEmergencyStatus();
}
| public void testViewRequisitionRegimenAndEmergencyStatus(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add("CREATE_REQUISITION");
rightsList.add("VIEW_REQUISITION");
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
dbWrapper.assignRight(STORE_IN_CHARGE, APPROVE_REQUISITION);
dbWrapper.assignRight(STORE_IN_CHARGE, CONVERT_TO_ORDER);
dbWrapper.assignRight(STORE_IN_CHARGE, VIEW_ORDER);
dbWrapper.insertFulfilmentRoleAssignment(userSIC,STORE_IN_CHARGE,"F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
HomePage homePage1 = initiateRnRPage.clickHome();
ViewRequisitionPage viewRequisitionPage = homePage1.navigateViewRequisition();
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
dbWrapper.insertValuesInRequisition(true);
dbWrapper.insertValuesInRegimenLineItems(patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(SUBMITTED, userSIC, "HIV");
viewRequisitionPage.enterViewSearchCriteria();
viewRequisitionPage.clickSearch();
viewRequisitionPage.verifyNoRequisitionFound();
dbWrapper.insertApprovedQuantity(10);
dbWrapper.updateRequisitionStatus(AUTHORIZED, userSIC, "HIV");
viewRequisitionPage.clickSearch();
viewRequisitionPage.clickRnRList();
viewRequisitionPage.verifyTotalFieldPostAuthorize();
HomePage homePageAuthorized = viewRequisitionPage.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPage.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewRequisitionPage viewRequisitionPageAuthorized = homePageAuthorized.navigateViewRequisition();
viewRequisitionPageAuthorized.enterViewSearchCriteria();
viewRequisitionPageAuthorized.clickSearch();
viewRequisitionPageAuthorized.verifyStatus(AUTHORIZED);
viewRequisitionPageAuthorized.verifyEmergencyStatus();
viewRequisitionPageAuthorized.clickRnRList();
HomePage homePageInApproval = viewRequisitionPageAuthorized.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(IN_APPROVAL, userSIC, "HIV");
ViewRequisitionPage viewRequisitionPageInApproval = homePageInApproval.navigateViewRequisition();
viewRequisitionPageInApproval.enterViewSearchCriteria();
viewRequisitionPageInApproval.clickSearch();
viewRequisitionPageInApproval.verifyStatus(IN_APPROVAL);
viewRequisitionPageInApproval.verifyEmergencyStatus();
ApprovePage approvePageTopSNUser = homePageInApproval.navigateToApprove();
approvePageTopSNUser.verifyEmergencyStatus();
approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCostViewRequisition("20");
approvePageTopSNUser.addComments("Dummy Comments");
approvePageTopSNUser.verifyTotalFieldPostAuthorize();
approvePageTopSNUser.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
ViewRequisitionPage viewRequisitionPageApproved = homePageInApproval.navigateViewRequisition();
viewRequisitionPageApproved.enterViewSearchCriteria();
viewRequisitionPageApproved.clickSearch();
viewRequisitionPageApproved.verifyStatus(APPROVED);
viewRequisitionPageApproved.verifyEmergencyStatus();
viewRequisitionPageApproved.clickRnRList();
viewRequisitionPageApproved.verifyTotalFieldPostAuthorize();
viewRequisitionPageApproved.verifyComment("Dummy Comments", userSIC, 1);
viewRequisitionPageApproved.verifyCommentBoxNotPresent();
HomePage homePageApproved = viewRequisitionPageApproved.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ConvertOrderPage convertOrderPage = homePageApproved.navigateConvertToOrder();
convertOrderPage.verifyEmergencyStatus();
convertOrderPage.convertToOrder();
ViewRequisitionPage viewRequisitionPageOrdered = homePageApproved.navigateViewRequisition();
viewRequisitionPageOrdered.enterViewSearchCriteria();
viewRequisitionPageOrdered.clickSearch();
viewRequisitionPageOrdered.verifyStatus(RELEASED);
viewRequisitionPageOrdered.verifyEmergencyStatus();
viewRequisitionPageOrdered.clickRnRList();
viewRequisitionPageOrdered.verifyTotalFieldPostAuthorize();
viewRequisitionPageOrdered.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageOrdered.verifyApprovedQuantityFieldPresent();
viewRequisitionPageOrdered.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewOrdersPage viewOrdersPage=homePageApproved.navigateViewOrders();
viewOrdersPage.verifyEmergencyStatus();
}
|
private void refreshSubwayStations() {
List<DataStore.Fav> newSubwayFavList = DataManager.findFavsByTypeList(getContentResolver(),
DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION);
if (this.currentSubwayStationFavList == null
|| this.currentSubwayStationFavList.size() != newSubwayFavList.size()) {
this.subwayStationsLayout.removeAllViews();
this.currentBusStopFavList = newSubwayFavList;
if (this.currentBusStopFavList != null && this.currentBusStopFavList.size() > 0) {
for (Fav subwayFav : this.currentBusStopFavList) {
final SubwayStation station = StmManager.findSubwayStation(getContentResolver(),
subwayFav.getFkId());
if (station != null) {
List<SubwayLine> otherLinesId = StmManager.findSubwayStationLinesList(getContentResolver(),
station.getId());
if (this.subwayStationsLayout.getChildCount() > 0) {
this.subwayStationsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider,
null));
}
View view = getLayoutInflater().inflate(R.layout.fav_list_tab_subway_station_item, null);
((TextView) view.findViewById(R.id.station_name)).setText(station.getName());
if (otherLinesId != null && otherLinesId.size() > 0) {
int subwayLineImg1 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(0).getNumber());
((ImageView) view.findViewById(R.id.subway_img_1)).setImageResource(subwayLineImg1);
if (otherLinesId.size() > 1) {
int subwayLineImg2 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(1).getNumber());
((ImageView) view.findViewById(R.id.subway_img_2)).setImageResource(subwayLineImg2);
if (otherLinesId.size() > 2) {
int subwayLineImg3 = SubwayUtils
.getSubwayLineImgId(otherLinesId.get(2).getNumber());
((ImageView) view.findViewById(R.id.subway_img_3)).setImageResource(subwayLineImg3);
} else {
view.findViewById(R.id.subway_img_3).setVisibility(View.GONE);
}
} else {
view.findViewById(R.id.subway_img_2).setVisibility(View.GONE);
view.findViewById(R.id.subway_img_3).setVisibility(View.GONE);
}
} else {
view.findViewById(R.id.subway_img_1).setVisibility(View.GONE);
view.findViewById(R.id.subway_img_2).setVisibility(View.GONE);
view.findViewById(R.id.subway_img_3).setVisibility(View.GONE);
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyLog.v(TAG, "onClick(%s)", v.getId());
Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class);
intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId());
startActivity(intent);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
MyLog.v(TAG, "onLongClick(%s)", v.getId());
AlertDialog.Builder builder = new AlertDialog.Builder(FavListTab.this);
builder.setTitle(getString(R.string.subway_station_with_name_short, station.getName()));
CharSequence[] items = { getString(R.string.view_subway_station),
getString(R.string.remove_fav) };
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
MyLog.v(TAG, "onClick(%s)", item);
switch (item) {
case VIEW_CONTEXT_MENU_INDEX:
Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class);
intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId());
startActivity(intent);
break;
case DELETE_CONTEXT_MENU_INDEX:
Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(),
DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION, station.getId(), null);
DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId());
FavListTab.this.currentSubwayStationFavList = null;
refreshSubwayStations();
break;
default:
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
this.subwayStationsLayout.addView(view);
} else {
MyLog.w(TAG, "Can't find the favorite subway station (ID:%s)", subwayFav.getFkId());
}
}
} else {
TextView noFavTv = new TextView(this);
noFavTv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
noFavTv.setTextAppearance(this, android.R.attr.textAppearanceMedium);
noFavTv.setText(R.string.no_fav_subway_station_message);
this.subwayStationsLayout.addView(noFavTv);
}
}
}
| private void refreshSubwayStations() {
List<DataStore.Fav> newSubwayFavList = DataManager.findFavsByTypeList(getContentResolver(),
DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION);
if (this.currentSubwayStationFavList == null
|| this.currentSubwayStationFavList.size() != newSubwayFavList.size()) {
this.subwayStationsLayout.removeAllViews();
this.currentSubwayStationFavList = newSubwayFavList;
if (this.currentSubwayStationFavList != null && this.currentSubwayStationFavList.size() > 0) {
for (Fav subwayFav : this.currentSubwayStationFavList) {
final SubwayStation station = StmManager.findSubwayStation(getContentResolver(),
subwayFav.getFkId());
if (station != null) {
List<SubwayLine> otherLinesId = StmManager.findSubwayStationLinesList(getContentResolver(),
station.getId());
if (this.subwayStationsLayout.getChildCount() > 0) {
this.subwayStationsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider,
null));
}
View view = getLayoutInflater().inflate(R.layout.fav_list_tab_subway_station_item, null);
((TextView) view.findViewById(R.id.station_name)).setText(station.getName());
if (otherLinesId != null && otherLinesId.size() > 0) {
int subwayLineImg1 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(0).getNumber());
((ImageView) view.findViewById(R.id.subway_img_1)).setImageResource(subwayLineImg1);
if (otherLinesId.size() > 1) {
int subwayLineImg2 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(1).getNumber());
((ImageView) view.findViewById(R.id.subway_img_2)).setImageResource(subwayLineImg2);
if (otherLinesId.size() > 2) {
int subwayLineImg3 = SubwayUtils
.getSubwayLineImgId(otherLinesId.get(2).getNumber());
((ImageView) view.findViewById(R.id.subway_img_3)).setImageResource(subwayLineImg3);
} else {
view.findViewById(R.id.subway_img_3).setVisibility(View.GONE);
}
} else {
view.findViewById(R.id.subway_img_2).setVisibility(View.GONE);
view.findViewById(R.id.subway_img_3).setVisibility(View.GONE);
}
} else {
view.findViewById(R.id.subway_img_1).setVisibility(View.GONE);
view.findViewById(R.id.subway_img_2).setVisibility(View.GONE);
view.findViewById(R.id.subway_img_3).setVisibility(View.GONE);
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyLog.v(TAG, "onClick(%s)", v.getId());
Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class);
intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId());
startActivity(intent);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
MyLog.v(TAG, "onLongClick(%s)", v.getId());
AlertDialog.Builder builder = new AlertDialog.Builder(FavListTab.this);
builder.setTitle(getString(R.string.subway_station_with_name_short, station.getName()));
CharSequence[] items = { getString(R.string.view_subway_station),
getString(R.string.remove_fav) };
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
MyLog.v(TAG, "onClick(%s)", item);
switch (item) {
case VIEW_CONTEXT_MENU_INDEX:
Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class);
intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId());
startActivity(intent);
break;
case DELETE_CONTEXT_MENU_INDEX:
Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(),
DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION, station.getId(), null);
DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId());
FavListTab.this.currentSubwayStationFavList = null;
refreshSubwayStations();
break;
default:
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
this.subwayStationsLayout.addView(view);
} else {
MyLog.w(TAG, "Can't find the favorite subway station (ID:%s)", subwayFav.getFkId());
}
}
} else {
TextView noFavTv = new TextView(this);
noFavTv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
noFavTv.setTextAppearance(this, android.R.attr.textAppearanceMedium);
noFavTv.setText(R.string.no_fav_subway_station_message);
this.subwayStationsLayout.addView(noFavTv);
}
}
}
|
public void testUpdateUsers() throws IOException, SAXException, JSONException {
WebConversation webConversation = new WebConversation();
webConversation.setExceptionsThrownOnErrorStatus(false);
Map<String, String> params = new HashMap<String, String>();
params.put("login", "user_" + System.currentTimeMillis());
params.put("Name", "username_" + System.currentTimeMillis());
params.put("roles", "admin");
params.put("password", "pass_" + System.currentTimeMillis());
WebRequest request = getPostUsersRequest("", params, true);
WebResponse response = webConversation.getResponse(request);
assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
JSONObject updateBody = new JSONObject();
updateBody.put("Name", "usernameUpdate_" + System.currentTimeMillis());
updateBody.put("password", "passUpdate_" + System.currentTimeMillis());
updateBody.put("roles", "");
request = getPutUsersRequest(params.get("login"), updateBody, true);
response = webConversation.getResponse(request);
assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
request = getGetUsersRequest(params.get("login"), true);
response = webConversation.getResponse(request);
assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
JSONObject responseObject = new JSONObject(response.getText());
assertEquals("Invalid user login", params.get("login"), responseObject.getString("login"));
assertEquals("Invalid user name", updateBody.getString("Name"), responseObject.getString("Name"));
assertFalse("Response shouldn't contain password", responseObject.has("password"));
request = getGetUsersRequest("", true);
setAuthentication(request, params.get("login"), updateBody.getString("password"));
response = webConversation.getResponse(request);
assertEquals("User with no roles has admin privilegges", HttpURLConnection.HTTP_FORBIDDEN, response.getResponseCode());
request = getDeleteUsersRequest(params.get("login"), true);
response = webConversation.getResponse(request);
assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
}
| public void testUpdateUsers() throws IOException, SAXException, JSONException {
WebConversation webConversation = new WebConversation();
webConversation.setExceptionsThrownOnErrorStatus(false);
Map<String, String> params = new HashMap<String, String>();
params.put("login", "user_" + System.currentTimeMillis());
params.put("Name", "username_" + System.currentTimeMillis());
params.put("roles", "admin");
String oldPass = "pass_" + System.currentTimeMillis();
params.put("password", oldPass);
WebRequest request = getPostUsersRequest("", params, true);
WebResponse response = webConversation.getResponse(request);
assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
JSONObject updateBody = new JSONObject();
updateBody.put("Name", "usernameUpdate_" + System.currentTimeMillis());
updateBody.put("oldPassword", oldPass);
updateBody.put("password", "passUpdate_" + System.currentTimeMillis());
updateBody.put("roles", "");
request = getPutUsersRequest(params.get("login"), updateBody, true);
response = webConversation.getResponse(request);
assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
request = getGetUsersRequest(params.get("login"), true);
response = webConversation.getResponse(request);
assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
JSONObject responseObject = new JSONObject(response.getText());
assertEquals("Invalid user login", params.get("login"), responseObject.getString("login"));
assertEquals("Invalid user name", updateBody.getString("Name"), responseObject.getString("Name"));
assertFalse("Response shouldn't contain password", responseObject.has("password"));
request = getGetUsersRequest("", true);
setAuthentication(request, params.get("login"), updateBody.getString("password"));
response = webConversation.getResponse(request);
assertEquals("User with no roles has admin privilegges", HttpURLConnection.HTTP_FORBIDDEN, response.getResponseCode());
request = getDeleteUsersRequest(params.get("login"), true);
response = webConversation.getResponse(request);
assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
}
|
public void setActiveTab(Tab tab) {
super.setActiveTab(tab);
ScrollWebView view = (ScrollWebView) tab.getWebView();
if (view == null) {
Log.e(LOGTAG, "active tab with no webview detected");
return;
}
if (mUseQuickControls) {
mPieControl.forceToTop(mContentView);
view.setScrollListener(null);
mTabBar.showTitleBarIndicator(false);
} else {
view.setEmbeddedTitleBar(mTitleBar);
view.setScrollListener(this);
}
mTabBar.onSetActiveTab(tab);
if (tab.isInVoiceSearchMode()) {
showVoiceTitleBar(tab.getVoiceDisplayTitle());
} else {
revertVoiceTitleBar(tab);
}
updateLockIconToLatest(tab);
tab.getTopWindow().requestFocus();
}
| public void setActiveTab(Tab tab) {
if (mTitleBar.isEditingUrl()) {
mTitleBar.stopEditingUrl();
}
super.setActiveTab(tab);
ScrollWebView view = (ScrollWebView) tab.getWebView();
if (view == null) {
Log.e(LOGTAG, "active tab with no webview detected");
return;
}
if (mUseQuickControls) {
mPieControl.forceToTop(mContentView);
view.setScrollListener(null);
mTabBar.showTitleBarIndicator(false);
} else {
view.setEmbeddedTitleBar(mTitleBar);
view.setScrollListener(this);
}
mTabBar.onSetActiveTab(tab);
if (tab.isInVoiceSearchMode()) {
showVoiceTitleBar(tab.getVoiceDisplayTitle());
} else {
revertVoiceTitleBar(tab);
}
updateLockIconToLatest(tab);
tab.getTopWindow().requestFocus();
}
|
private void init() {
StyleContext styleContext = StyleContext.getDefaultStyleContext();
Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
StyleConstants.setFontFamily(defaultStyle,
StructuredSyntaxResources.EDITOR_FONT.getFamily());
StyleConstants.setFontSize(defaultStyle,
StructuredSyntaxResources.EDITOR_FONT.getSize());
Style comment = styleContext.addStyle(COMMENT, defaultStyle);
StyleConstants.setForeground(comment, COMMENT_COLOR);
StyleConstants.setItalic(comment, true);
Style quotes = styleContext.addStyle(QUOTES, defaultStyle);
StyleConstants.setForeground(quotes, Color.MAGENTA.darker().darker());
Style charQuotes = styleContext.addStyle(SINGLE_QUOTES, defaultStyle);
StyleConstants.setForeground(charQuotes, Color.GREEN.darker().darker());
Style slashyQuotes = styleContext.addStyle(SLASHY_QUOTES, defaultStyle);
StyleConstants.setForeground(slashyQuotes, Color.ORANGE.darker());
Style digit = styleContext.addStyle(DIGIT, defaultStyle);
StyleConstants.setForeground(digit, Color.RED.darker());
Style operation = styleContext.addStyle(OPERATION, defaultStyle);
StyleConstants.setBold(operation, true);
Style ident = styleContext.addStyle(IDENT, defaultStyle);
Style reservedWords = styleContext.addStyle(RESERVED_WORD, defaultStyle);
StyleConstants.setBold(reservedWords, true);
StyleConstants.setForeground(reservedWords, Color.BLUE.darker().darker());
Style leftParens = styleContext.addStyle(IDENT, defaultStyle);
getRootNode().putStyle(SLASH_STAR_COMMENT, comment);
getRootNode().putStyle(SLASH_SLASH_COMMENT, comment);
getRootNode().putStyle(QUOTES, quotes);
getRootNode().putStyle(SINGLE_QUOTES, charQuotes);
getRootNode().putStyle(SLASHY_QUOTES, slashyQuotes);
getRootNode().putStyle(DIGIT, digit);
getRootNode().putStyle(OPERATION, operation);
StructuredSyntaxDocumentFilter.LexerNode node = createLexerNode();
node.putStyle(RESERVED_WORDS, reservedWords);
node.putStyle(LEFT_PARENS, leftParens);
getRootNode().putChild(OPERATION, node);
getRootNode().putStyle(IDENT, ident);
node = createLexerNode();
node.putStyle(RESERVED_WORDS, reservedWords);
getRootNode().putChild(IDENT, node);
}
| private void init() {
StyleContext styleContext = StyleContext.getDefaultStyleContext();
Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
Style comment = styleContext.addStyle(COMMENT, defaultStyle);
StyleConstants.setForeground(comment, COMMENT_COLOR);
StyleConstants.setItalic(comment, true);
Style quotes = styleContext.addStyle(QUOTES, defaultStyle);
StyleConstants.setForeground(quotes, Color.MAGENTA.darker().darker());
Style charQuotes = styleContext.addStyle(SINGLE_QUOTES, defaultStyle);
StyleConstants.setForeground(charQuotes, Color.GREEN.darker().darker());
Style slashyQuotes = styleContext.addStyle(SLASHY_QUOTES, defaultStyle);
StyleConstants.setForeground(slashyQuotes, Color.ORANGE.darker());
Style digit = styleContext.addStyle(DIGIT, defaultStyle);
StyleConstants.setForeground(digit, Color.RED.darker());
Style operation = styleContext.addStyle(OPERATION, defaultStyle);
StyleConstants.setBold(operation, true);
Style ident = styleContext.addStyle(IDENT, defaultStyle);
Style reservedWords = styleContext.addStyle(RESERVED_WORD, defaultStyle);
StyleConstants.setBold(reservedWords, true);
StyleConstants.setForeground(reservedWords, Color.BLUE.darker().darker());
Style leftParens = styleContext.addStyle(IDENT, defaultStyle);
getRootNode().putStyle(SLASH_STAR_COMMENT, comment);
getRootNode().putStyle(SLASH_SLASH_COMMENT, comment);
getRootNode().putStyle(QUOTES, quotes);
getRootNode().putStyle(SINGLE_QUOTES, charQuotes);
getRootNode().putStyle(SLASHY_QUOTES, slashyQuotes);
getRootNode().putStyle(DIGIT, digit);
getRootNode().putStyle(OPERATION, operation);
StructuredSyntaxDocumentFilter.LexerNode node = createLexerNode();
node.putStyle(RESERVED_WORDS, reservedWords);
node.putStyle(LEFT_PARENS, leftParens);
getRootNode().putChild(OPERATION, node);
getRootNode().putStyle(IDENT, ident);
node = createLexerNode();
node.putStyle(RESERVED_WORDS, reservedWords);
getRootNode().putChild(IDENT, node);
}
|
static public void readTable(
Project project,
ProjectMetadata metadata,
ImportingJob job,
TableDataReader reader,
String fileSource,
int limit,
JSONObject options,
List<Exception> exceptions
) {
int ignoreLines = JSONUtilities.getInt(options, "ignoreLines", -1);
int headerLines = JSONUtilities.getInt(options, "headerLines", 1);
int skipDataLines = JSONUtilities.getInt(options, "skipDataLines", 0);
int limit2 = JSONUtilities.getInt(options, "limit", -1);
if (limit > 0) {
if (limit2 > 0) {
limit2 = Math.min(limit, limit2);
} else {
limit2 = limit;
}
}
boolean guessCellValueTypes = JSONUtilities.getBoolean(options, "guessCellValueTypes", true);
boolean storeBlankRows = JSONUtilities.getBoolean(options, "storeBlankRows", true);
boolean storeBlankCellsAsNulls = JSONUtilities.getBoolean(options, "storeBlankCellsAsNulls", true);
boolean includeFileSources = JSONUtilities.getBoolean(options, "includeFileSources", false);
String fileNameColumnName = "File";
if (includeFileSources) {
if (project.columnModel.getColumnByName(fileNameColumnName) == null) {
try {
project.columnModel.addColumn(
0, new Column(project.columnModel.allocateNewCellIndex(), fileNameColumnName), false);
} catch (ModelException e) {
logger.info("ModelException",e);
}
}
}
List<String> columnNames = new ArrayList<String>();
boolean hasOurOwnColumnNames = headerLines > 0;
List<Object> cells = null;
int rowsWithData = 0;
try {
while (!job.canceled && (cells = reader.getNextRowOfCells()) != null) {
if (ignoreLines > 0) {
ignoreLines--;
continue;
}
if (headerLines > 0) {
for (int c = 0; c < cells.size(); c++) {
Object cell = cells.get(c);
String columnName;
if (cell == null) {
columnName = "";
} else if (cell instanceof Cell) {
columnName = ((Cell) cell).value.toString().trim();
} else {
columnName = cell.toString().trim();
}
ImporterUtilities.appendColumnName(columnNames, c, columnName);
}
headerLines--;
if (headerLines == 0) {
ImporterUtilities.setupColumns(project, columnNames);
}
} else {
Row row = new Row(columnNames.size());
if (storeBlankRows) {
rowsWithData++;
} else if (cells.size() > 0) {
rowsWithData++;
}
if (skipDataLines <= 0 || rowsWithData > skipDataLines) {
boolean rowHasData = false;
for (int c = 0; c < cells.size(); c++) {
Column column = ImporterUtilities.getOrAllocateColumn(
project, columnNames, c, hasOurOwnColumnNames);
Object value = cells.get(c);
if (value != null && value instanceof Cell) {
row.setCell(column.getCellIndex(), (Cell) value);
rowHasData = true;
} else if (ExpressionUtils.isNonBlankData(value)) {
Serializable storedValue;
if (value instanceof String) {
storedValue = guessCellValueTypes ?
ImporterUtilities.parseCellValue((String) value) : (String) value;
} else {
storedValue = ExpressionUtils.wrapStorable(value);
}
row.setCell(column.getCellIndex(), new Cell(storedValue, null));
rowHasData = true;
} else if (!storeBlankCellsAsNulls) {
row.setCell(column.getCellIndex(), new Cell("", null));
} else {
row.setCell(column.getCellIndex(), null);
}
}
if (rowHasData || storeBlankRows) {
if (includeFileSources) {
row.setCell(
project.columnModel.getColumnByName(fileNameColumnName).getCellIndex(),
new Cell(fileSource, null));
}
project.rows.add(row);
}
if (limit2 > 0 && project.rows.size() >= limit2) {
break;
}
}
}
}
} catch (IOException e) {
exceptions.add(e);
}
}
| static public void readTable(
Project project,
ProjectMetadata metadata,
ImportingJob job,
TableDataReader reader,
String fileSource,
int limit,
JSONObject options,
List<Exception> exceptions
) {
int ignoreLines = JSONUtilities.getInt(options, "ignoreLines", -1);
int headerLines = JSONUtilities.getInt(options, "headerLines", 1);
int skipDataLines = JSONUtilities.getInt(options, "skipDataLines", 0);
int limit2 = JSONUtilities.getInt(options, "limit", -1);
if (limit > 0) {
if (limit2 > 0) {
limit2 = Math.min(limit, limit2);
} else {
limit2 = limit;
}
}
boolean guessCellValueTypes = JSONUtilities.getBoolean(options, "guessCellValueTypes", false);
boolean storeBlankRows = JSONUtilities.getBoolean(options, "storeBlankRows", true);
boolean storeBlankCellsAsNulls = JSONUtilities.getBoolean(options, "storeBlankCellsAsNulls", true);
boolean includeFileSources = JSONUtilities.getBoolean(options, "includeFileSources", false);
String fileNameColumnName = "File";
if (includeFileSources) {
if (project.columnModel.getColumnByName(fileNameColumnName) == null) {
try {
project.columnModel.addColumn(
0, new Column(project.columnModel.allocateNewCellIndex(), fileNameColumnName), false);
} catch (ModelException e) {
logger.info("ModelException",e);
}
}
}
List<String> columnNames = new ArrayList<String>();
boolean hasOurOwnColumnNames = headerLines > 0;
List<Object> cells = null;
int rowsWithData = 0;
try {
while (!job.canceled && (cells = reader.getNextRowOfCells()) != null) {
if (ignoreLines > 0) {
ignoreLines--;
continue;
}
if (headerLines > 0) {
for (int c = 0; c < cells.size(); c++) {
Object cell = cells.get(c);
String columnName;
if (cell == null) {
columnName = "";
} else if (cell instanceof Cell) {
columnName = ((Cell) cell).value.toString().trim();
} else {
columnName = cell.toString().trim();
}
ImporterUtilities.appendColumnName(columnNames, c, columnName);
}
headerLines--;
if (headerLines == 0) {
ImporterUtilities.setupColumns(project, columnNames);
}
} else {
Row row = new Row(columnNames.size());
if (storeBlankRows) {
rowsWithData++;
} else if (cells.size() > 0) {
rowsWithData++;
}
if (skipDataLines <= 0 || rowsWithData > skipDataLines) {
boolean rowHasData = false;
for (int c = 0; c < cells.size(); c++) {
Column column = ImporterUtilities.getOrAllocateColumn(
project, columnNames, c, hasOurOwnColumnNames);
Object value = cells.get(c);
if (value instanceof Cell) {
row.setCell(column.getCellIndex(), (Cell) value);
rowHasData = true;
} else if (ExpressionUtils.isNonBlankData(value)) {
Serializable storedValue;
if (value instanceof String) {
storedValue = guessCellValueTypes ?
ImporterUtilities.parseCellValue((String) value) : (String) value;
} else {
storedValue = ExpressionUtils.wrapStorable(value);
}
row.setCell(column.getCellIndex(), new Cell(storedValue, null));
rowHasData = true;
} else if (!storeBlankCellsAsNulls) {
row.setCell(column.getCellIndex(), new Cell("", null));
} else {
row.setCell(column.getCellIndex(), null);
}
}
if (rowHasData || storeBlankRows) {
if (includeFileSources) {
row.setCell(
project.columnModel.getColumnByName(fileNameColumnName).getCellIndex(),
new Cell(fileSource, null));
}
project.rows.add(row);
}
if (limit2 > 0 && project.rows.size() >= limit2) {
break;
}
}
}
}
} catch (IOException e) {
exceptions.add(e);
}
}
|
public void registerEvents() {
final PluginManager pm = getServer().getPluginManager();
final MapManager mm = mapManager;
{
BlockListener renderTrigger = new BlockListener() {
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if(event.isCancelled())
return;
if(onplace)
mm.touch(event.getBlockPlaced().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockBreak(BlockBreakEvent event) {
if(event.isCancelled())
return;
if(onbreak)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if(event.isCancelled())
return;
if(onleaves)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockBurn(BlockBurnEvent event) {
if(event.isCancelled())
return;
if(onburn)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockForm(BlockFormEvent event) {
if(event.isCancelled())
return;
if(onblockform)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockFade(BlockFadeEvent event) {
if(event.isCancelled())
return;
if(onblockfade)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockSpread(BlockSpreadEvent event) {
if(event.isCancelled())
return;
if(onblockspread)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
};
onplace = isTrigger("blockplaced");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_PLACE, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
onbreak = isTrigger("blockbreak");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_BREAK, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
if(isTrigger("snowform")) Log.info("The 'snowform' trigger has been deprecated due to Bukkit changes - use 'blockform'");
onleaves = isTrigger("leavesdecay");
pm.registerEvent(org.bukkit.event.Event.Type.LEAVES_DECAY, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
onburn = isTrigger("blockburn");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_BURN, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
onblockform = isTrigger("blockformed");
try {
Class cls = Class.forName("org.dynmap.event.block.BlockFormEvent");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_FORM, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
} catch (ClassNotFoundException cnfx) {
if(onblockform)
Log.info("BLOCK_FORM event not supported by this version of CraftBukkit - event disabled");
}
onblockfade = isTrigger("blockfaded");
try {
Class cls = Class.forName("org.dynmap.event.block.BlockFadeEvent");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_FADE, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
} catch (ClassNotFoundException cnfx) {
if(onblockfade)
Log.info("BLOCK_FADE event not supported by this version of CraftBukkit - event disabled");
}
onblockspread = isTrigger("blockspread");
try {
Class cls = Class.forName("org.dynmap.event.block.BlockSpreadEvent");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_SPREAD, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
} catch (ClassNotFoundException cnfx) {
if(onblockspread)
Log.info("BLOCK_SPREAD event not supported by this version of CraftBukkit - event disabled");
}
}
{
PlayerListener renderTrigger = new PlayerListener() {
@Override
public void onPlayerJoin(PlayerJoinEvent event) {
mm.touch(event.getPlayer().getLocation());
}
@Override
public void onPlayerMove(PlayerMoveEvent event) {
mm.touch(event.getPlayer().getLocation());
}
};
if (isTrigger("playerjoin"))
pm.registerEvent(org.bukkit.event.Event.Type.PLAYER_JOIN, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
if (isTrigger("playermove"))
pm.registerEvent(org.bukkit.event.Event.Type.PLAYER_MOVE, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
}
{
WorldListener renderTrigger = new WorldListener() {
@Override
public void onChunkLoad(ChunkLoadEvent event) {
if(ignore_chunk_loads)
return;
if(generate_only) {
if(!isNewChunk(event))
return;
int x = event.getChunk().getX() * 16;
int z = event.getChunk().getZ() * 16;
mm.touch(new Location(event.getWorld(), x, 0, z));
mm.touch(new Location(event.getWorld(), x+15, 127, z));
mm.touch(new Location(event.getWorld(), x+15, 0, z+15));
mm.touch(new Location(event.getWorld(), x, 127, z+15));
}
else {
int x = event.getChunk().getX() * 16 + 8;
int z = event.getChunk().getZ() * 16 + 8;
mm.touch(new Location(event.getWorld(), x, 127, z));
}
}
private boolean isNewChunk(ChunkLoadEvent event) {
return event.isNewChunk();
}
};
boolean ongenerate = isTrigger("chunkgenerated");
if(ongenerate) {
try {
ChunkLoadEvent.class.getDeclaredMethod("isNewChunk", new Class[0]);
} catch (NoSuchMethodException nsmx) {
Log.info("Warning: CraftBukkit build does not support function needed for 'chunkgenerated' trigger - disabling");
ongenerate = false;
}
}
if(isTrigger("chunkloaded")) {
generate_only = false;
pm.registerEvent(org.bukkit.event.Event.Type.CHUNK_LOAD, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
}
else if(ongenerate) {
generate_only = true;
pm.registerEvent(org.bukkit.event.Event.Type.CHUNK_LOAD, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
}
}
WorldListener worldListener = new WorldListener() {
@Override
public void onWorldLoad(WorldLoadEvent event) {
mm.activateWorld(event.getWorld());
}
};
pm.registerEvent(org.bukkit.event.Event.Type.WORLD_LOAD, worldListener, org.bukkit.event.Event.Priority.Monitor, this);
}
| public void registerEvents() {
final PluginManager pm = getServer().getPluginManager();
final MapManager mm = mapManager;
{
BlockListener renderTrigger = new BlockListener() {
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if(event.isCancelled())
return;
if(onplace)
mm.touch(event.getBlockPlaced().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockBreak(BlockBreakEvent event) {
if(event.isCancelled())
return;
if(onbreak)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if(event.isCancelled())
return;
if(onleaves)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockBurn(BlockBurnEvent event) {
if(event.isCancelled())
return;
if(onburn)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockForm(BlockFormEvent event) {
if(event.isCancelled())
return;
if(onblockform)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockFade(BlockFadeEvent event) {
if(event.isCancelled())
return;
if(onblockfade)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
@Override
public void onBlockSpread(BlockSpreadEvent event) {
if(event.isCancelled())
return;
if(onblockspread)
mm.touch(event.getBlock().getLocation());
mm.sscache.invalidateSnapshot(event.getBlock().getLocation());
}
};
onplace = isTrigger("blockplaced");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_PLACE, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
onbreak = isTrigger("blockbreak");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_BREAK, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
if(isTrigger("snowform")) Log.info("The 'snowform' trigger has been deprecated due to Bukkit changes - use 'blockformed'");
onleaves = isTrigger("leavesdecay");
pm.registerEvent(org.bukkit.event.Event.Type.LEAVES_DECAY, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
onburn = isTrigger("blockburn");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_BURN, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
onblockform = isTrigger("blockformed");
try {
Class cls = Class.forName("org.dynmap.event.block.BlockFormEvent");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_FORM, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
} catch (ClassNotFoundException cnfx) {
if(onblockform)
Log.info("BLOCK_FORM event not supported by this version of CraftBukkit - event disabled");
}
onblockfade = isTrigger("blockfaded");
try {
Class cls = Class.forName("org.dynmap.event.block.BlockFadeEvent");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_FADE, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
} catch (ClassNotFoundException cnfx) {
if(onblockfade)
Log.info("BLOCK_FADE event not supported by this version of CraftBukkit - event disabled");
}
onblockspread = isTrigger("blockspread");
try {
Class cls = Class.forName("org.dynmap.event.block.BlockSpreadEvent");
pm.registerEvent(org.bukkit.event.Event.Type.BLOCK_SPREAD, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
} catch (ClassNotFoundException cnfx) {
if(onblockspread)
Log.info("BLOCK_SPREAD event not supported by this version of CraftBukkit - event disabled");
}
}
{
PlayerListener renderTrigger = new PlayerListener() {
@Override
public void onPlayerJoin(PlayerJoinEvent event) {
mm.touch(event.getPlayer().getLocation());
}
@Override
public void onPlayerMove(PlayerMoveEvent event) {
mm.touch(event.getPlayer().getLocation());
}
};
if (isTrigger("playerjoin"))
pm.registerEvent(org.bukkit.event.Event.Type.PLAYER_JOIN, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
if (isTrigger("playermove"))
pm.registerEvent(org.bukkit.event.Event.Type.PLAYER_MOVE, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
}
{
WorldListener renderTrigger = new WorldListener() {
@Override
public void onChunkLoad(ChunkLoadEvent event) {
if(ignore_chunk_loads)
return;
if(generate_only) {
if(!isNewChunk(event))
return;
int x = event.getChunk().getX() * 16;
int z = event.getChunk().getZ() * 16;
mm.touch(new Location(event.getWorld(), x, 0, z));
mm.touch(new Location(event.getWorld(), x+15, 127, z));
mm.touch(new Location(event.getWorld(), x+15, 0, z+15));
mm.touch(new Location(event.getWorld(), x, 127, z+15));
}
else {
int x = event.getChunk().getX() * 16 + 8;
int z = event.getChunk().getZ() * 16 + 8;
mm.touch(new Location(event.getWorld(), x, 127, z));
}
}
private boolean isNewChunk(ChunkLoadEvent event) {
return event.isNewChunk();
}
};
boolean ongenerate = isTrigger("chunkgenerated");
if(ongenerate) {
try {
ChunkLoadEvent.class.getDeclaredMethod("isNewChunk", new Class[0]);
} catch (NoSuchMethodException nsmx) {
Log.info("Warning: CraftBukkit build does not support function needed for 'chunkgenerated' trigger - disabling");
ongenerate = false;
}
}
if(isTrigger("chunkloaded")) {
generate_only = false;
pm.registerEvent(org.bukkit.event.Event.Type.CHUNK_LOAD, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
}
else if(ongenerate) {
generate_only = true;
pm.registerEvent(org.bukkit.event.Event.Type.CHUNK_LOAD, renderTrigger, org.bukkit.event.Event.Priority.Monitor, this);
}
}
WorldListener worldListener = new WorldListener() {
@Override
public void onWorldLoad(WorldLoadEvent event) {
mm.activateWorld(event.getWorld());
}
};
pm.registerEvent(org.bukkit.event.Event.Type.WORLD_LOAD, worldListener, org.bukkit.event.Event.Priority.Monitor, this);
}
|
public void detectCommandInjection() throws Exception {
String[] files = {
getClassFilePath("testcode/CommandInjection")
};
EasyBugReporter reporter = spy(new EasyBugReporter());
analyze(files, reporter);
for (Integer line : Arrays.asList(18, 20, 25, 29)) {
verify(reporter).doReportBug(
bugDefinition()
.bugType("COMMAND_INJECTION")
.inClass("CommandInjection").inMethod("main").atLine(line)
.build()
);
}
}
| public void detectCommandInjection() throws Exception {
String[] files = {
getClassFilePath("testcode/CommandInjection")
};
EasyBugReporter reporter = spy(new EasyBugReporter());
analyze(files, reporter);
for (Integer line : Arrays.asList(18, 20, 24, 28)) {
verify(reporter).doReportBug(
bugDefinition()
.bugType("COMMAND_INJECTION")
.inClass("CommandInjection").inMethod("main").atLine(line)
.build()
);
}
}
|
void createSubSectionContents(final ChangeDetail changeDetail, final PatchSetDetail patchSetDetail,
PatchSetPublishDetail publishDetail, Section subSection) {
Composite composite = toolkit.createComposite(subSection);
GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);
subSection.setClient(composite);
Label authorLabel = new Label(composite, SWT.NONE);
authorLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
authorLabel.setText("Author");
Text authorText = new Text(composite, SWT.READ_ONLY);
authorText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getAuthor()));
Label committerLabel = new Label(composite, SWT.NONE);
committerLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
committerLabel.setText("Committer");
Text committerText = new Text(composite, SWT.READ_ONLY);
committerText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getCommitter()));
Label commitLabel = new Label(composite, SWT.NONE);
commitLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
commitLabel.setText("Commit");
Hyperlink commitLink = new Hyperlink(composite, SWT.READ_ONLY);
commitLink.setText(patchSetDetail.getPatchSet().getRevision().get());
commitLink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent event) {
GerritToGitMapping mapping = getRepository(changeDetail);
if (mapping != null) {
final FetchPatchSetJob job = new FetchPatchSetJob("Opening Commit Viewer", mapping.getRepository(),
mapping.getRemote(), patchSetDetail.getPatchSet());
job.schedule();
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
CommitEditor.openQuiet(job.getCommit());
}
});
}
});
}
}
});
Label refLabel = new Label(composite, SWT.NONE);
refLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
refLabel.setText("Ref");
Text refText = new Text(composite, SWT.READ_ONLY);
refText.setText(patchSetDetail.getPatchSet().getRefName());
final TableViewer viewer = new TableViewer(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL);
GridDataFactory.fillDefaults().span(2, 1).grab(true, true).hint(500, SWT.DEFAULT).applyTo(viewer.getControl());
viewer.setContentProvider(new IStructuredContentProvider() {
private EContentAdapter modelAdapter;
public void dispose() {
}
public Object[] getElements(Object inputElement) {
return getReviewItems(inputElement).toArray();
}
private List<IReviewItem> getReviewItems(Object inputElement) {
if (inputElement instanceof IReviewItemSet) {
return ((IReviewItemSet) inputElement).getItems();
}
return Collections.emptyList();
}
public void inputChanged(final Viewer viewer, Object oldInput, Object newInput) {
if (modelAdapter != null) {
for (IReviewItem item : getReviewItems(oldInput)) {
((EObject) item).eAdapters().remove(modelAdapter);
}
addedDrafts = 0;
}
if (newInput instanceof IReviewItemSet) {
modelAdapter = new EContentAdapter() {
@Override
public void notifyChanged(Notification notification) {
super.notifyChanged(notification);
if (notification.getFeatureID(IReviewItem.class) == ReviewsPackage.REVIEW_ITEM__TOPICS
&& notification.getEventType() == Notification.ADD) {
viewer.refresh();
addedDrafts++;
}
}
};
for (Object item : getReviewItems(newInput)) {
((EObject) item).eAdapters().add(modelAdapter);
}
}
}
});
viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new ReviewItemLabelProvider()));
viewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
IFileItem item = (IFileItem) selection.getFirstElement();
doOpen((IReviewItemSet) viewer.getInput(), item);
}
});
IReviewItemSet itemSet = GerritUtil.createInput(changeDetail, new GerritPatchSetContent(patchSetDetail), cache);
viewer.setInput(itemSet);
Composite actionComposite = createActions(changeDetail, patchSetDetail, publishDetail, composite);
GridDataFactory.fillDefaults().span(2, 1).applyTo(actionComposite);
subSectionExpanded(changeDetail, patchSetDetail, subSection, viewer);
EditorUtil.addScrollListener(viewer.getTable());
getTaskEditorPage().reflow();
}
| void createSubSectionContents(final ChangeDetail changeDetail, final PatchSetDetail patchSetDetail,
PatchSetPublishDetail publishDetail, Section subSection) {
Composite composite = toolkit.createComposite(subSection);
GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);
subSection.setClient(composite);
Label authorLabel = new Label(composite, SWT.NONE);
authorLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
authorLabel.setText("Author");
Text authorText = new Text(composite, SWT.READ_ONLY);
authorText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getAuthor()));
Label committerLabel = new Label(composite, SWT.NONE);
committerLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
committerLabel.setText("Committer");
Text committerText = new Text(composite, SWT.READ_ONLY);
committerText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getCommitter()));
Label commitLabel = new Label(composite, SWT.NONE);
commitLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
commitLabel.setText("Commit");
Hyperlink commitLink = new Hyperlink(composite, SWT.READ_ONLY);
commitLink.setText(patchSetDetail.getPatchSet().getRevision().get());
commitLink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent event) {
GerritToGitMapping mapping = getRepository(changeDetail);
if (mapping != null) {
final FetchPatchSetJob job = new FetchPatchSetJob("Opening Commit Viewer", mapping.getRepository(),
mapping.getRemote(), patchSetDetail.getPatchSet());
job.schedule();
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
CommitEditor.openQuiet(job.getCommit());
}
});
}
});
}
}
});
Label refLabel = new Label(composite, SWT.NONE);
refLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
refLabel.setText("Ref");
Text refText = new Text(composite, SWT.READ_ONLY);
refText.setText(patchSetDetail.getPatchSet().getRefName());
final TableViewer viewer = new TableViewer(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL);
GridDataFactory.fillDefaults().span(2, 1).grab(true, true).hint(500, SWT.DEFAULT).applyTo(viewer.getControl());
viewer.setContentProvider(new IStructuredContentProvider() {
private EContentAdapter modelAdapter;
public void dispose() {
}
public Object[] getElements(Object inputElement) {
return getReviewItems(inputElement).toArray();
}
private List<IReviewItem> getReviewItems(Object inputElement) {
if (inputElement instanceof IReviewItemSet) {
return ((IReviewItemSet) inputElement).getItems();
}
return Collections.emptyList();
}
public void inputChanged(final Viewer viewer, Object oldInput, Object newInput) {
if (modelAdapter != null) {
for (IReviewItem item : getReviewItems(oldInput)) {
((EObject) item).eAdapters().remove(modelAdapter);
}
addedDrafts = 0;
}
if (newInput instanceof IReviewItemSet) {
modelAdapter = new EContentAdapter() {
@Override
public void notifyChanged(Notification notification) {
super.notifyChanged(notification);
if (notification.getFeatureID(IReviewItem.class) == ReviewsPackage.REVIEW_ITEM__TOPICS
&& notification.getEventType() == Notification.ADD) {
viewer.refresh();
addedDrafts++;
}
}
};
for (Object item : getReviewItems(newInput)) {
((EObject) item).eAdapters().add(modelAdapter);
}
}
}
});
viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new ReviewItemLabelProvider()));
viewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
IFileItem item = (IFileItem) selection.getFirstElement();
if (item != null) {
doOpen((IReviewItemSet) viewer.getInput(), item);
}
}
});
IReviewItemSet itemSet = GerritUtil.createInput(changeDetail, new GerritPatchSetContent(patchSetDetail), cache);
viewer.setInput(itemSet);
Composite actionComposite = createActions(changeDetail, patchSetDetail, publishDetail, composite);
GridDataFactory.fillDefaults().span(2, 1).applyTo(actionComposite);
subSectionExpanded(changeDetail, patchSetDetail, subSection, viewer);
EditorUtil.addScrollListener(viewer.getTable());
getTaskEditorPage().reflow();
}
|
private void createBorderPaddingBackgroundProperties() {
PropertyMaker m;
BorderWidthPropertyMaker bwm;
CorrespondingPropertyMaker corr;
m = new EnumProperty.Maker(PR_BACKGROUND_ATTACHMENT);
m.setInherited(false);
m.addEnum("scroll", getEnumProperty(EN_SCROLL, "SCROLL"));
m.addEnum("fixed", getEnumProperty(EN_FIXED, "FIXED"));
m.setDefault("scroll");
addPropertyMaker("background-attachment", m);
m = new ColorTypeProperty.Maker(PR_BACKGROUND_COLOR) {
protected Property convertPropertyDatatype(
Property p, PropertyList propertyList, FObj fo) {
String nameval = p.getNCname();
if (nameval != null) {
return new ColorTypeProperty(nameval);
}
return super.convertPropertyDatatype(p, propertyList, fo);
}
};
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("transparent");
addPropertyMaker("background-color", m);
m = new StringProperty.Maker(PR_BACKGROUND_IMAGE);
m.setInherited(false);
m.setDefault("none");
addPropertyMaker("background-image", m);
m = new EnumProperty.Maker(PR_BACKGROUND_REPEAT);
m.setInherited(false);
m.addEnum("repeat", getEnumProperty(EN_REPEAT, "REPEAT"));
m.addEnum("repeat-x", getEnumProperty(EN_REPEATX, "REPEATX"));
m.addEnum("repeat-y", getEnumProperty(EN_REPEATY, "REPEATY"));
m.addEnum("no-repeat", getEnumProperty(EN_NOREPEAT, "NOREPEAT"));
m.setDefault("repeat");
addPropertyMaker("background-repeat", m);
m = new LengthProperty.Maker(PR_BACKGROUND_POSITION_HORIZONTAL);
m.setInherited(false);
m.setDefault("0%");
m.addKeyword("left", "0%");
m.addKeyword("center", "50%");
m.addKeyword("right", "100%");
m.setPercentBase(LengthBase.IMAGE_BACKGROUND_POSITION_HORIZONTAL);
addPropertyMaker("background-position-horizontal", m);
m = new LengthProperty.Maker(PR_BACKGROUND_POSITION_VERTICAL);
m.setInherited(false);
m.setDefault("0%");
m.addKeyword("top", "0%");
m.addKeyword("center", "50%");
m.addKeyword("bottom", "100%");
m.setPercentBase(LengthBase.IMAGE_BACKGROUND_POSITION_VERTICAL);
addPropertyMaker("background-position-vertical", m);
m = new ColorTypeProperty.Maker(PR_BORDER_BEFORE_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_TOP_COLOR, PR_BORDER_TOP_COLOR,
PR_BORDER_RIGHT_COLOR);
corr.setRelative(true);
addPropertyMaker("border-before-color", m);
m = new EnumProperty.Maker(PR_BORDER_BEFORE_STYLE);
m.useGeneric(genericBorderStyle);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_TOP_STYLE, PR_BORDER_TOP_STYLE,
PR_BORDER_RIGHT_STYLE);
corr.setRelative(true);
addPropertyMaker("border-before-style", m);
m = new CondLengthProperty.Maker(PR_BORDER_BEFORE_WIDTH);
m.useGeneric(genericCondBorderWidth);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_TOP_WIDTH, PR_BORDER_TOP_WIDTH,
PR_BORDER_RIGHT_WIDTH);
corr.setRelative(true);
addPropertyMaker("border-before-width", m);
m = new ColorTypeProperty.Maker(PR_BORDER_AFTER_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BOTTOM_COLOR, PR_BORDER_BOTTOM_COLOR,
PR_BORDER_LEFT_COLOR);
corr.setRelative(true);
addPropertyMaker("border-after-color", m);
m = new EnumProperty.Maker(PR_BORDER_AFTER_STYLE);
m.useGeneric(genericBorderStyle);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BOTTOM_STYLE, PR_BORDER_BOTTOM_STYLE,
PR_BORDER_LEFT_STYLE);
corr.setRelative(true);
addPropertyMaker("border-after-style", m);
m = new CondLengthProperty.Maker(PR_BORDER_AFTER_WIDTH);
m.useGeneric(genericCondBorderWidth);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BOTTOM_WIDTH, PR_BORDER_BOTTOM_WIDTH,
PR_BORDER_LEFT_WIDTH);
corr.setRelative(true);
addPropertyMaker("border-after-width", m);
m = new ColorTypeProperty.Maker(PR_BORDER_START_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_LEFT_COLOR, PR_BORDER_RIGHT_COLOR,
PR_BORDER_TOP_COLOR);
corr.setRelative(true);
addPropertyMaker("border-start-color", m);
m = new EnumProperty.Maker(PR_BORDER_START_STYLE);
m.useGeneric(genericBorderStyle);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_LEFT_STYLE, PR_BORDER_RIGHT_STYLE,
PR_BORDER_TOP_STYLE);
corr.setRelative(true);
addPropertyMaker("border-start-style", m);
m = new CondLengthProperty.Maker(PR_BORDER_START_WIDTH);
m.useGeneric(genericCondBorderWidth);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_LEFT_WIDTH, PR_BORDER_RIGHT_WIDTH,
PR_BORDER_TOP_WIDTH);
corr.setRelative(true);
addPropertyMaker("border-start-width", m);
m = new ColorTypeProperty.Maker(PR_BORDER_END_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_RIGHT_COLOR, PR_BORDER_LEFT_COLOR,
PR_BORDER_BOTTOM_COLOR);
corr.setRelative(true);
addPropertyMaker("border-end-color", m);
m = new EnumProperty.Maker(PR_BORDER_END_STYLE);
m.useGeneric(genericBorderStyle);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_RIGHT_STYLE, PR_BORDER_LEFT_STYLE,
PR_BORDER_BOTTOM_STYLE);
corr.setRelative(true);
addPropertyMaker("border-end-style", m);
m = new CondLengthProperty.Maker(PR_BORDER_END_WIDTH);
m.useGeneric(genericCondBorderWidth);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_RIGHT_WIDTH, PR_BORDER_LEFT_WIDTH,
PR_BORDER_BOTTOM_WIDTH);
corr.setRelative(true);
addPropertyMaker("border-end-width", m);
m = new ColorTypeProperty.Maker(PR_BORDER_TOP_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
m.addShorthand(s_generics[PR_BORDER_TOP]);
m.addShorthand(s_generics[PR_BORDER_COLOR]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BEFORE_COLOR, PR_BORDER_BEFORE_COLOR,
PR_BORDER_START_COLOR);
addPropertyMaker("border-top-color", m);
m = new EnumProperty.Maker(PR_BORDER_TOP_STYLE);
m.useGeneric(genericBorderStyle);
m.addShorthand(s_generics[PR_BORDER_TOP]);
m.addShorthand(s_generics[PR_BORDER_STYLE]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BEFORE_STYLE, PR_BORDER_BEFORE_STYLE,
PR_BORDER_START_STYLE);
addPropertyMaker("border-top-style", m);
bwm = new BorderWidthPropertyMaker(PR_BORDER_TOP_WIDTH);
bwm.useGeneric(genericBorderWidth);
bwm.setBorderStyleId(PR_BORDER_TOP_STYLE);
bwm.addShorthand(s_generics[PR_BORDER_TOP]);
bwm.addShorthand(s_generics[PR_BORDER_WIDTH]);
bwm.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(bwm);
corr.setCorresponding(PR_BORDER_BEFORE_WIDTH, PR_BORDER_BEFORE_WIDTH,
PR_BORDER_START_WIDTH);
addPropertyMaker("border-top-width", bwm);
m = new ColorTypeProperty.Maker(PR_BORDER_BOTTOM_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
m.addShorthand(s_generics[PR_BORDER_BOTTOM]);
m.addShorthand(s_generics[PR_BORDER_COLOR]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_AFTER_COLOR, PR_BORDER_AFTER_COLOR,
PR_BORDER_END_COLOR);
addPropertyMaker("border-bottom-color", m);
m = new EnumProperty.Maker(PR_BORDER_BOTTOM_STYLE);
m.useGeneric(genericBorderStyle);
m.addShorthand(s_generics[PR_BORDER_BOTTOM]);
m.addShorthand(s_generics[PR_BORDER_STYLE]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_AFTER_STYLE, PR_BORDER_AFTER_STYLE,
PR_BORDER_END_STYLE);
addPropertyMaker("border-bottom-style", m);
bwm = new BorderWidthPropertyMaker(PR_BORDER_BOTTOM_WIDTH);
bwm.useGeneric(genericBorderWidth);
bwm.setBorderStyleId(PR_BORDER_BOTTOM_STYLE);
bwm.addShorthand(s_generics[PR_BORDER_BOTTOM]);
bwm.addShorthand(s_generics[PR_BORDER_WIDTH]);
bwm.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(bwm);
corr.setCorresponding(PR_BORDER_AFTER_WIDTH, PR_BORDER_AFTER_WIDTH,
PR_BORDER_END_WIDTH);
addPropertyMaker("border-bottom-width", bwm);
m = new ColorTypeProperty.Maker(PR_BORDER_LEFT_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
m.addShorthand(s_generics[PR_BORDER_LEFT]);
m.addShorthand(s_generics[PR_BORDER_COLOR]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_START_COLOR, PR_BORDER_END_COLOR,
PR_BORDER_AFTER_COLOR);
addPropertyMaker("border-left-color", m);
m = new EnumProperty.Maker(PR_BORDER_LEFT_STYLE);
m.useGeneric(genericBorderStyle);
m.addShorthand(s_generics[PR_BORDER_LEFT]);
m.addShorthand(s_generics[PR_BORDER_STYLE]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_START_STYLE, PR_BORDER_END_STYLE,
PR_BORDER_AFTER_STYLE);
addPropertyMaker("border-left-style", m);
bwm = new BorderWidthPropertyMaker(PR_BORDER_LEFT_WIDTH);
bwm.useGeneric(genericBorderWidth);
bwm.setBorderStyleId(PR_BORDER_LEFT_STYLE);
bwm.addShorthand(s_generics[PR_BORDER_LEFT]);
bwm.addShorthand(s_generics[PR_BORDER_WIDTH]);
bwm.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(bwm);
corr.setCorresponding(PR_BORDER_START_WIDTH, PR_BORDER_END_WIDTH,
PR_BORDER_AFTER_WIDTH);
addPropertyMaker("border-left-width", bwm);
m = new ColorTypeProperty.Maker(PR_BORDER_RIGHT_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
m.addShorthand(s_generics[PR_BORDER_RIGHT]);
m.addShorthand(s_generics[PR_BORDER_COLOR]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_END_COLOR, PR_BORDER_START_COLOR,
PR_BORDER_BEFORE_COLOR);
addPropertyMaker("border-right-color", m);
m = new EnumProperty.Maker(PR_BORDER_RIGHT_STYLE);
m.useGeneric(genericBorderStyle);
m.addShorthand(s_generics[PR_BORDER_RIGHT]);
m.addShorthand(s_generics[PR_BORDER_STYLE]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_END_STYLE, PR_BORDER_START_STYLE,
PR_BORDER_BEFORE_STYLE);
addPropertyMaker("border-right-style", m);
bwm = new BorderWidthPropertyMaker(PR_BORDER_RIGHT_WIDTH);
bwm.useGeneric(genericBorderWidth);
bwm.setBorderStyleId(PR_BORDER_RIGHT_STYLE);
bwm.addShorthand(s_generics[PR_BORDER_RIGHT]);
bwm.addShorthand(s_generics[PR_BORDER_WIDTH]);
bwm.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(bwm);
corr.setCorresponding(PR_BORDER_END_WIDTH, PR_BORDER_START_WIDTH,
PR_BORDER_BEFORE_WIDTH);
addPropertyMaker("border-right-width", bwm);
m = new CondLengthProperty.Maker(PR_PADDING_BEFORE);
m.useGeneric(genericCondPadding);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("retain");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_TOP, PR_PADDING_TOP,
PR_PADDING_RIGHT);
corr.setRelative(true);
addPropertyMaker("padding-before", m);
m = new CondLengthProperty.Maker(PR_PADDING_AFTER);
m.useGeneric(genericCondPadding);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("retain");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_BOTTOM, PR_PADDING_BOTTOM,
PR_PADDING_LEFT);
corr.setRelative(true);
addPropertyMaker("padding-after", m);
m = new CondLengthProperty.Maker(PR_PADDING_START);
m.useGeneric(genericCondPadding);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_LEFT, PR_PADDING_RIGHT,
PR_PADDING_TOP);
corr.setRelative(true);
addPropertyMaker("padding-start", m);
m = new CondLengthProperty.Maker(PR_PADDING_END);
m.useGeneric(genericCondPadding);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_RIGHT, PR_PADDING_LEFT,
PR_PADDING_BOTTOM);
corr.setRelative(true);
addPropertyMaker("padding-end", m);
m = new LengthProperty.Maker(PR_PADDING_TOP);
m.useGeneric(genericPadding);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_BEFORE, PR_PADDING_BEFORE,
PR_PADDING_START);
addPropertyMaker("padding-top", m);
m = new LengthProperty.Maker(PR_PADDING_BOTTOM);
m.useGeneric(genericPadding);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_AFTER, PR_PADDING_AFTER,
PR_PADDING_END);
addPropertyMaker("padding-bottom", m);
m = new LengthProperty.Maker(PR_PADDING_LEFT);
m.useGeneric(genericPadding);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_START, PR_PADDING_END,
PR_PADDING_AFTER);
addPropertyMaker("padding-left", m);
m = new LengthProperty.Maker(PR_PADDING_RIGHT);
m.useGeneric(genericPadding);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_END, PR_PADDING_START,
PR_PADDING_BEFORE);
addPropertyMaker("padding-right", m);
}
| private void createBorderPaddingBackgroundProperties() {
PropertyMaker m;
BorderWidthPropertyMaker bwm;
CorrespondingPropertyMaker corr;
m = new EnumProperty.Maker(PR_BACKGROUND_ATTACHMENT);
m.setInherited(false);
m.addEnum("scroll", getEnumProperty(EN_SCROLL, "SCROLL"));
m.addEnum("fixed", getEnumProperty(EN_FIXED, "FIXED"));
m.setDefault("scroll");
addPropertyMaker("background-attachment", m);
m = new ColorTypeProperty.Maker(PR_BACKGROUND_COLOR) {
protected Property convertPropertyDatatype(
Property p, PropertyList propertyList, FObj fo) {
String nameval = p.getNCname();
if (nameval != null) {
return new ColorTypeProperty(nameval);
}
return super.convertPropertyDatatype(p, propertyList, fo);
}
};
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("transparent");
addPropertyMaker("background-color", m);
m = new StringProperty.Maker(PR_BACKGROUND_IMAGE);
m.setInherited(false);
m.setDefault("none");
addPropertyMaker("background-image", m);
m = new EnumProperty.Maker(PR_BACKGROUND_REPEAT);
m.setInherited(false);
m.addEnum("repeat", getEnumProperty(EN_REPEAT, "REPEAT"));
m.addEnum("repeat-x", getEnumProperty(EN_REPEATX, "REPEATX"));
m.addEnum("repeat-y", getEnumProperty(EN_REPEATY, "REPEATY"));
m.addEnum("no-repeat", getEnumProperty(EN_NOREPEAT, "NOREPEAT"));
m.setDefault("repeat");
addPropertyMaker("background-repeat", m);
m = new LengthProperty.Maker(PR_BACKGROUND_POSITION_HORIZONTAL);
m.setInherited(false);
m.setDefault("0%");
m.addKeyword("left", "0%");
m.addKeyword("center", "50%");
m.addKeyword("right", "100%");
m.setPercentBase(LengthBase.IMAGE_BACKGROUND_POSITION_HORIZONTAL);
addPropertyMaker("background-position-horizontal", m);
m = new LengthProperty.Maker(PR_BACKGROUND_POSITION_VERTICAL);
m.setInherited(false);
m.setDefault("0%");
m.addKeyword("top", "0%");
m.addKeyword("center", "50%");
m.addKeyword("bottom", "100%");
m.setPercentBase(LengthBase.IMAGE_BACKGROUND_POSITION_VERTICAL);
addPropertyMaker("background-position-vertical", m);
m = new ColorTypeProperty.Maker(PR_BORDER_BEFORE_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_TOP_COLOR, PR_BORDER_TOP_COLOR,
PR_BORDER_RIGHT_COLOR);
corr.setRelative(true);
addPropertyMaker("border-before-color", m);
m = new EnumProperty.Maker(PR_BORDER_BEFORE_STYLE);
m.useGeneric(genericBorderStyle);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_TOP_STYLE, PR_BORDER_TOP_STYLE,
PR_BORDER_RIGHT_STYLE);
corr.setRelative(true);
addPropertyMaker("border-before-style", m);
m = new CondLengthProperty.Maker(PR_BORDER_BEFORE_WIDTH);
m.useGeneric(genericCondBorderWidth);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_TOP_WIDTH, PR_BORDER_TOP_WIDTH,
PR_BORDER_RIGHT_WIDTH);
corr.setRelative(true);
addPropertyMaker("border-before-width", m);
m = new ColorTypeProperty.Maker(PR_BORDER_AFTER_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BOTTOM_COLOR, PR_BORDER_BOTTOM_COLOR,
PR_BORDER_LEFT_COLOR);
corr.setRelative(true);
addPropertyMaker("border-after-color", m);
m = new EnumProperty.Maker(PR_BORDER_AFTER_STYLE);
m.useGeneric(genericBorderStyle);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BOTTOM_STYLE, PR_BORDER_BOTTOM_STYLE,
PR_BORDER_LEFT_STYLE);
corr.setRelative(true);
addPropertyMaker("border-after-style", m);
m = new CondLengthProperty.Maker(PR_BORDER_AFTER_WIDTH);
m.useGeneric(genericCondBorderWidth);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BOTTOM_WIDTH, PR_BORDER_BOTTOM_WIDTH,
PR_BORDER_LEFT_WIDTH);
corr.setRelative(true);
addPropertyMaker("border-after-width", m);
m = new ColorTypeProperty.Maker(PR_BORDER_START_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_LEFT_COLOR, PR_BORDER_RIGHT_COLOR,
PR_BORDER_TOP_COLOR);
corr.setRelative(true);
addPropertyMaker("border-start-color", m);
m = new EnumProperty.Maker(PR_BORDER_START_STYLE);
m.useGeneric(genericBorderStyle);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_LEFT_STYLE, PR_BORDER_RIGHT_STYLE,
PR_BORDER_TOP_STYLE);
corr.setRelative(true);
addPropertyMaker("border-start-style", m);
m = new CondLengthProperty.Maker(PR_BORDER_START_WIDTH);
m.useGeneric(genericCondBorderWidth);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_LEFT_WIDTH, PR_BORDER_RIGHT_WIDTH,
PR_BORDER_TOP_WIDTH);
corr.setRelative(true);
addPropertyMaker("border-start-width", m);
m = new ColorTypeProperty.Maker(PR_BORDER_END_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_RIGHT_COLOR, PR_BORDER_LEFT_COLOR,
PR_BORDER_BOTTOM_COLOR);
corr.setRelative(true);
addPropertyMaker("border-end-color", m);
m = new EnumProperty.Maker(PR_BORDER_END_STYLE);
m.useGeneric(genericBorderStyle);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_RIGHT_STYLE, PR_BORDER_LEFT_STYLE,
PR_BORDER_BOTTOM_STYLE);
corr.setRelative(true);
addPropertyMaker("border-end-style", m);
m = new CondLengthProperty.Maker(PR_BORDER_END_WIDTH);
m.useGeneric(genericCondBorderWidth);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_RIGHT_WIDTH, PR_BORDER_LEFT_WIDTH,
PR_BORDER_BOTTOM_WIDTH);
corr.setRelative(true);
addPropertyMaker("border-end-width", m);
m = new ColorTypeProperty.Maker(PR_BORDER_TOP_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
m.addShorthand(s_generics[PR_BORDER_TOP]);
m.addShorthand(s_generics[PR_BORDER_COLOR]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BEFORE_COLOR, PR_BORDER_BEFORE_COLOR,
PR_BORDER_START_COLOR);
addPropertyMaker("border-top-color", m);
m = new EnumProperty.Maker(PR_BORDER_TOP_STYLE);
m.useGeneric(genericBorderStyle);
m.addShorthand(s_generics[PR_BORDER_TOP]);
m.addShorthand(s_generics[PR_BORDER_STYLE]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_BEFORE_STYLE, PR_BORDER_BEFORE_STYLE,
PR_BORDER_START_STYLE);
addPropertyMaker("border-top-style", m);
bwm = new BorderWidthPropertyMaker(PR_BORDER_TOP_WIDTH);
bwm.useGeneric(genericBorderWidth);
bwm.setBorderStyleId(PR_BORDER_TOP_STYLE);
bwm.addShorthand(s_generics[PR_BORDER_TOP]);
bwm.addShorthand(s_generics[PR_BORDER_WIDTH]);
bwm.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(bwm);
corr.setCorresponding(PR_BORDER_BEFORE_WIDTH, PR_BORDER_BEFORE_WIDTH,
PR_BORDER_START_WIDTH);
addPropertyMaker("border-top-width", bwm);
m = new ColorTypeProperty.Maker(PR_BORDER_BOTTOM_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
m.addShorthand(s_generics[PR_BORDER_BOTTOM]);
m.addShorthand(s_generics[PR_BORDER_COLOR]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_AFTER_COLOR, PR_BORDER_AFTER_COLOR,
PR_BORDER_END_COLOR);
addPropertyMaker("border-bottom-color", m);
m = new EnumProperty.Maker(PR_BORDER_BOTTOM_STYLE);
m.useGeneric(genericBorderStyle);
m.addShorthand(s_generics[PR_BORDER_BOTTOM]);
m.addShorthand(s_generics[PR_BORDER_STYLE]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_AFTER_STYLE, PR_BORDER_AFTER_STYLE,
PR_BORDER_END_STYLE);
addPropertyMaker("border-bottom-style", m);
bwm = new BorderWidthPropertyMaker(PR_BORDER_BOTTOM_WIDTH);
bwm.useGeneric(genericBorderWidth);
bwm.setBorderStyleId(PR_BORDER_BOTTOM_STYLE);
bwm.addShorthand(s_generics[PR_BORDER_BOTTOM]);
bwm.addShorthand(s_generics[PR_BORDER_WIDTH]);
bwm.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(bwm);
corr.setCorresponding(PR_BORDER_AFTER_WIDTH, PR_BORDER_AFTER_WIDTH,
PR_BORDER_END_WIDTH);
addPropertyMaker("border-bottom-width", bwm);
m = new ColorTypeProperty.Maker(PR_BORDER_LEFT_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
m.addShorthand(s_generics[PR_BORDER_LEFT]);
m.addShorthand(s_generics[PR_BORDER_COLOR]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_START_COLOR, PR_BORDER_END_COLOR,
PR_BORDER_AFTER_COLOR);
addPropertyMaker("border-left-color", m);
m = new EnumProperty.Maker(PR_BORDER_LEFT_STYLE);
m.useGeneric(genericBorderStyle);
m.addShorthand(s_generics[PR_BORDER_LEFT]);
m.addShorthand(s_generics[PR_BORDER_STYLE]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_START_STYLE, PR_BORDER_END_STYLE,
PR_BORDER_AFTER_STYLE);
addPropertyMaker("border-left-style", m);
bwm = new BorderWidthPropertyMaker(PR_BORDER_LEFT_WIDTH);
bwm.useGeneric(genericBorderWidth);
bwm.setBorderStyleId(PR_BORDER_LEFT_STYLE);
bwm.addShorthand(s_generics[PR_BORDER_LEFT]);
bwm.addShorthand(s_generics[PR_BORDER_WIDTH]);
bwm.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(bwm);
corr.setCorresponding(PR_BORDER_START_WIDTH, PR_BORDER_END_WIDTH,
PR_BORDER_AFTER_WIDTH);
addPropertyMaker("border-left-width", bwm);
m = new ColorTypeProperty.Maker(PR_BORDER_RIGHT_COLOR);
m.useGeneric(genericColor);
m.setInherited(false);
m.setDefault("black");
m.addShorthand(s_generics[PR_BORDER_RIGHT]);
m.addShorthand(s_generics[PR_BORDER_COLOR]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_END_COLOR, PR_BORDER_START_COLOR,
PR_BORDER_BEFORE_COLOR);
addPropertyMaker("border-right-color", m);
m = new EnumProperty.Maker(PR_BORDER_RIGHT_STYLE);
m.useGeneric(genericBorderStyle);
m.addShorthand(s_generics[PR_BORDER_RIGHT]);
m.addShorthand(s_generics[PR_BORDER_STYLE]);
m.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_BORDER_END_STYLE, PR_BORDER_START_STYLE,
PR_BORDER_BEFORE_STYLE);
addPropertyMaker("border-right-style", m);
bwm = new BorderWidthPropertyMaker(PR_BORDER_RIGHT_WIDTH);
bwm.useGeneric(genericBorderWidth);
bwm.setBorderStyleId(PR_BORDER_RIGHT_STYLE);
bwm.addShorthand(s_generics[PR_BORDER_RIGHT]);
bwm.addShorthand(s_generics[PR_BORDER_WIDTH]);
bwm.addShorthand(s_generics[PR_BORDER]);
corr = new CorrespondingPropertyMaker(bwm);
corr.setCorresponding(PR_BORDER_END_WIDTH, PR_BORDER_START_WIDTH,
PR_BORDER_BEFORE_WIDTH);
addPropertyMaker("border-right-width", bwm);
m = new CondLengthProperty.Maker(PR_PADDING_BEFORE);
m.useGeneric(genericCondPadding);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_TOP, PR_PADDING_TOP,
PR_PADDING_RIGHT);
corr.setRelative(true);
addPropertyMaker("padding-before", m);
m = new CondLengthProperty.Maker(PR_PADDING_AFTER);
m.useGeneric(genericCondPadding);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_BOTTOM, PR_PADDING_BOTTOM,
PR_PADDING_LEFT);
corr.setRelative(true);
addPropertyMaker("padding-after", m);
m = new CondLengthProperty.Maker(PR_PADDING_START);
m.useGeneric(genericCondPadding);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_LEFT, PR_PADDING_RIGHT,
PR_PADDING_TOP);
corr.setRelative(true);
addPropertyMaker("padding-start", m);
m = new CondLengthProperty.Maker(PR_PADDING_END);
m.useGeneric(genericCondPadding);
m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard");
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_RIGHT, PR_PADDING_LEFT,
PR_PADDING_BOTTOM);
corr.setRelative(true);
addPropertyMaker("padding-end", m);
m = new LengthProperty.Maker(PR_PADDING_TOP);
m.useGeneric(genericPadding);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_BEFORE, PR_PADDING_BEFORE,
PR_PADDING_START);
addPropertyMaker("padding-top", m);
m = new LengthProperty.Maker(PR_PADDING_BOTTOM);
m.useGeneric(genericPadding);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_AFTER, PR_PADDING_AFTER,
PR_PADDING_END);
addPropertyMaker("padding-bottom", m);
m = new LengthProperty.Maker(PR_PADDING_LEFT);
m.useGeneric(genericPadding);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_START, PR_PADDING_END,
PR_PADDING_AFTER);
addPropertyMaker("padding-left", m);
m = new LengthProperty.Maker(PR_PADDING_RIGHT);
m.useGeneric(genericPadding);
corr = new CorrespondingPropertyMaker(m);
corr.setCorresponding(PR_PADDING_END, PR_PADDING_START,
PR_PADDING_BEFORE);
addPropertyMaker("padding-right", m);
}
|
private JsonObject createValues() {
JsonObject dimensionMap = new JsonObject();
JsonObject boxDimensionMap = new JsonObject();
JsonObject imageMap = new JsonObject();
JsonObject gradientMap = new JsonObject();
JsonObject colorMap = new JsonObject();
JsonObject fontMap = new JsonObject();
JsonObject borderMap = new JsonObject();
QxType[] values = new QxType[ valueSet.size() ];
valueSet.toArray( values );
for( int i = 0; i < values.length; i++ ) {
QxType value = values[ i ];
String key = Theme.createCssKey( value );
if( value instanceof QxDimension ) {
QxDimension dim = ( QxDimension )value;
dimensionMap.append( key, dim.value );
} else if( value instanceof QxBoxDimensions ) {
QxBoxDimensions boxdim = ( QxBoxDimensions )value;
JsonArray boxArray = new JsonArray();
boxArray.append( boxdim.top );
boxArray.append( boxdim.right );
boxArray.append( boxdim.bottom );
boxArray.append( boxdim.left );
boxDimensionMap.append( key, boxArray );
} else if( value instanceof QxImage ) {
QxImage image = ( QxImage )value;
if( image.none ) {
if( image.gradientColors != null && image.gradientPercents != null ) {
JsonObject gradientObject = new JsonObject();
JsonArray percents = JsonArray.valueOf( image.gradientPercents );
gradientObject.append( "percents", percents );
JsonArray colors = JsonArray.valueOf( image.gradientColors );
gradientObject.append( "colors", colors );
gradientMap.append( key, gradientObject );
}
imageMap.append( key, JsonValue.NULL );
} else {
imageMap.append( key, key );
}
} else if( value instanceof QxColor ) {
QxColor color = ( QxColor )value;
if( color.transparent ) {
colorMap.append( key, "undefined" );
} else {
colorMap.append( key, QxColor.toHtmlString( color.red,
color.green,
color.blue ) );
}
} else if( value instanceof QxFont && true ) {
QxFont font = ( QxFont )value;
JsonObject fontObject = new JsonObject();
fontObject.append( "family", JsonArray.valueOf( font.family ) );
fontObject.append( "size", font.size );
fontObject.append( "bold", font.bold );
fontObject.append( "italic", font.italic );
fontMap.append( key, fontObject );
} else if( value instanceof QxBorder && true ) {
QxBorder border = ( QxBorder )value;
JsonObject borderObject = new JsonObject();
borderObject.append( "width", border.width );
borderObject.append( "style", border.style );
borderObject.append( "color", border.color );
borderMap.append( key, borderObject );
}
}
JsonObject valuesMap = new JsonObject();
valuesMap.append( "dimensions", dimensionMap );
valuesMap.append( "boxdims", boxDimensionMap );
valuesMap.append( "images", imageMap );
valuesMap.append( "gradients", gradientMap );
valuesMap.append( "colors", colorMap );
valuesMap.append( "fonts", fontMap );
valuesMap.append( "borders", borderMap );
return valuesMap;
}
| private JsonObject createValues() {
JsonObject dimensionMap = new JsonObject();
JsonObject boxDimensionMap = new JsonObject();
JsonObject imageMap = new JsonObject();
JsonObject gradientMap = new JsonObject();
JsonObject colorMap = new JsonObject();
JsonObject fontMap = new JsonObject();
JsonObject borderMap = new JsonObject();
QxType[] values = new QxType[ valueSet.size() ];
valueSet.toArray( values );
for( int i = 0; i < values.length; i++ ) {
QxType value = values[ i ];
String key = Theme.createCssKey( value );
if( value instanceof QxDimension ) {
QxDimension dim = ( QxDimension )value;
dimensionMap.append( key, dim.value );
} else if( value instanceof QxBoxDimensions ) {
QxBoxDimensions boxdim = ( QxBoxDimensions )value;
JsonArray boxArray = new JsonArray();
boxArray.append( boxdim.top );
boxArray.append( boxdim.right );
boxArray.append( boxdim.bottom );
boxArray.append( boxdim.left );
boxDimensionMap.append( key, boxArray );
} else if( value instanceof QxImage ) {
QxImage image = ( QxImage )value;
if( image.none ) {
if( image.gradientColors != null && image.gradientPercents != null ) {
JsonObject gradientObject = new JsonObject();
JsonArray percents = JsonArray.valueOf( image.gradientPercents );
gradientObject.append( "percents", percents );
JsonArray colors = JsonArray.valueOf( image.gradientColors );
gradientObject.append( "colors", colors );
gradientMap.append( key, gradientObject );
} else {
gradientMap.append( key, JsonValue.NULL );
}
imageMap.append( key, JsonValue.NULL );
} else {
imageMap.append( key, key );
gradientMap.append( key, JsonValue.NULL );
}
} else if( value instanceof QxColor ) {
QxColor color = ( QxColor )value;
if( color.transparent ) {
colorMap.append( key, "undefined" );
} else {
colorMap.append( key, QxColor.toHtmlString( color.red,
color.green,
color.blue ) );
}
} else if( value instanceof QxFont && true ) {
QxFont font = ( QxFont )value;
JsonObject fontObject = new JsonObject();
fontObject.append( "family", JsonArray.valueOf( font.family ) );
fontObject.append( "size", font.size );
fontObject.append( "bold", font.bold );
fontObject.append( "italic", font.italic );
fontMap.append( key, fontObject );
} else if( value instanceof QxBorder && true ) {
QxBorder border = ( QxBorder )value;
JsonObject borderObject = new JsonObject();
borderObject.append( "width", border.width );
borderObject.append( "style", border.style );
borderObject.append( "color", border.color );
borderMap.append( key, borderObject );
}
}
JsonObject valuesMap = new JsonObject();
valuesMap.append( "dimensions", dimensionMap );
valuesMap.append( "boxdims", boxDimensionMap );
valuesMap.append( "images", imageMap );
valuesMap.append( "gradients", gradientMap );
valuesMap.append( "colors", colorMap );
valuesMap.append( "fonts", fontMap );
valuesMap.append( "borders", borderMap );
return valuesMap;
}
|
protected Node normalizeNode (Node node){
int type = node.getNodeType();
boolean wellformed;
switch (type) {
case Node.DOCUMENT_TYPE_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{doctype}");
}
break;
}
case Node.ELEMENT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{element} "+node.getNodeName());
}
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0) &&
fDocument.isXMLVersionChanged()){
if(fNamespaceValidation){
wellformed = CoreDocumentImpl.isValidQName(node.getPrefix() , node.getLocalName(), fDocument.isXML11Version()) ;
}
else{
wellformed = CoreDocumentImpl.isXMLName(node.getNodeName() , fDocument.isXML11Version());
}
if (!wellformed){
String msg = DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"wf-invalid-character-in-node-name",
new Object[]{"Element", node.getNodeName()});
reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_ERROR, node,
"wf-invalid-character-in-node-name");
}
}
fNamespaceContext.pushContext();
fLocalNSBinder.reset();
ElementImpl elem = (ElementImpl)node;
if (elem.needsSyncChildren()) {
elem.synchronizeChildren();
}
AttributeMap attributes = (elem.hasAttributes()) ? (AttributeMap) elem.getAttributes() : null;
if ((fConfiguration.features & DOMConfigurationImpl.NAMESPACES) !=0) {
namespaceFixUp(elem, attributes);
} else {
if ( attributes!=null ) {
for ( int i=0; i<attributes.getLength(); ++i ) {
Attr attr = (Attr)attributes.item(i);
attr.normalize();
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0)){
isAttrValueWF(fErrorHandler, fError, fLocator, attributes, (AttrImpl)attr, attr.getValue(), fDocument.isXML11Version());
if (fDocument.isXMLVersionChanged()){
wellformed=CoreDocumentImpl.isXMLName(node.getNodeName() , fDocument.isXML11Version());
if (!wellformed){
String msg = DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"wf-invalid-character-in-node-name",
new Object[]{"Attr",node.getNodeName()});
reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_ERROR,
node, "wf-invalid-character-in-node-name");
}
}
}
}
}
}
if (fValidationHandler != null) {
fAttrProxy.setAttributes(attributes, fDocument, elem);
updateQName(elem, fQName);
fConfiguration.fErrorHandlerWrapper.fCurrentNode = node;
fCurrentNode = node;
fValidationHandler.startElement(fQName, fAttrProxy, null);
}
Node kid, next;
for (kid = elem.getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
kid = normalizeNode(kid);
if (kid !=null) {
next = kid;
}
}
if (DEBUG_ND) {
System.out.println("***The children of {"+node.getNodeName()+"} are normalized");
for (kid = elem.getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
System.out.println(kid.getNodeName() +"["+kid.getNodeValue()+"]");
}
}
if (fValidationHandler != null) {
updateQName(elem, fQName);
fConfiguration.fErrorHandlerWrapper.fCurrentNode = node;
fCurrentNode = node;
fValidationHandler.endElement(fQName, null);
}
fNamespaceContext.popContext();
break;
}
case Node.COMMENT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{comments}");
}
if ((fConfiguration.features & DOMConfigurationImpl.COMMENTS) == 0) {
Node prevSibling = node.getPreviousSibling();
Node parent = node.getParentNode();
parent.removeChild(node);
if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
Node nextSibling = prevSibling.getNextSibling();
if (nextSibling != null && nextSibling.getNodeType() == Node.TEXT_NODE) {
((TextImpl)nextSibling).insertData(0, prevSibling.getNodeValue());
parent.removeChild(prevSibling);
return nextSibling;
}
}
}
else {
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0)){
String commentdata = ((Comment)node).getData();
isCommentWF(fErrorHandler, fError, fLocator, commentdata, fDocument.isXML11Version());
}
}
break;
}
case Node.ENTITY_REFERENCE_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{entityRef} "+node.getNodeName());
}
if ((fConfiguration.features & DOMConfigurationImpl.ENTITIES) == 0) {
Node prevSibling = node.getPreviousSibling();
Node parent = node.getParentNode();
((EntityReferenceImpl)node).setReadOnly(false, true);
expandEntityRef (parent, node);
parent.removeChild(node);
Node next = (prevSibling != null)?prevSibling.getNextSibling():parent.getFirstChild();
if (prevSibling !=null && prevSibling.getNodeType() == Node.TEXT_NODE &&
next.getNodeType() == Node.TEXT_NODE) {
return prevSibling;
}
return next;
} else {
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0) &&
fDocument.isXMLVersionChanged()){
CoreDocumentImpl.isXMLName(node.getNodeName() , fDocument.isXML11Version());
}
}
break;
}
case Node.CDATA_SECTION_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{cdata}");
}
if ((fConfiguration.features & DOMConfigurationImpl.CDATA) == 0) {
Node prevSibling = node.getPreviousSibling();
if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE){
((Text)prevSibling).appendData(node.getNodeValue());
node.getParentNode().removeChild(node);
return prevSibling;
}
else {
Text text = fDocument.createTextNode(node.getNodeValue());
Node parent = node.getParentNode();
node = parent.replaceChild(text, node);
return text;
}
}
if (fValidationHandler != null) {
fConfiguration.fErrorHandlerWrapper.fCurrentNode = node;
fCurrentNode = node;
fValidationHandler.startCDATA(null);
fValidationHandler.characterData(node.getNodeValue(), null);
fValidationHandler.endCDATA(null);
}
String value = node.getNodeValue();
if ((fConfiguration.features & DOMConfigurationImpl.SPLITCDATA) != 0) {
int index;
Node parent = node.getParentNode();
isXMLCharWF(fErrorHandler, fError, fLocator, node.getNodeValue(), fDocument.isXML11Version());
while ( (index=value.indexOf("]]>")) >= 0 ) {
node.setNodeValue(value.substring(0, index+2));
value = value.substring(index +2);
Node firstSplitNode = node;
Node newChild = fDocument.createCDATASection(value);
parent.insertBefore(newChild, node.getNextSibling());
node = newChild;
String msg = DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"cdata-sections-splitted",
null);
reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_WARNING,
firstSplitNode, "cdata-sections-splitted");
}
}
else {
isCDataWF(fErrorHandler, fError, fLocator, value, fDocument.isXML11Version());
}
break;
}
case Node.TEXT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode(text):{"+node.getNodeValue()+"}");
}
Node next = node.getNextSibling();
if ( next!=null && next.getNodeType() == Node.TEXT_NODE ) {
((Text)node).appendData(next.getNodeValue());
node.getParentNode().removeChild( next );
return node;
} else if (node.getNodeValue().length()==0) {
node.getParentNode().removeChild( node );
} else {
short nextType = (next != null)?next.getNodeType():-1;
if (nextType == -1 || !(((fConfiguration.features & DOMConfigurationImpl.ENTITIES) == 0 &&
nextType == Node.ENTITY_NODE) ||
((fConfiguration.features & DOMConfigurationImpl.COMMENTS) == 0 &&
nextType == Node.COMMENT_NODE) ||
((fConfiguration.features & DOMConfigurationImpl.CDATA) == 0) &&
nextType == Node.CDATA_SECTION_NODE)) {
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0) ){
isXMLCharWF(fErrorHandler, fError, fLocator, node.getNodeValue(), fDocument.isXML11Version());
}
if (fValidationHandler != null) {
fConfiguration.fErrorHandlerWrapper.fCurrentNode = node;
fCurrentNode = node;
fValidationHandler.characterData(node.getNodeValue(), null);
if (DEBUG_ND) {
System.out.println("=====>characterData(),"+nextType);
}
}
}
else {
if (DEBUG_ND) {
System.out.println("=====>don't send characters(),"+nextType);
}
}
}
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
if((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0 ){
ProcessingInstruction pinode = (ProcessingInstruction)node ;
String target = pinode.getTarget();
if(fDocument.isXML11Version()){
wellformed = XML11Char.isXML11ValidName(target);
}
else{
wellformed = XMLChar.isValidName(target);
}
if (!wellformed) {
String msg = DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"wf-invalid-character-in-node-name",
new Object[]{"Element", node.getNodeName()});
reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_ERROR, null,
"wf-invalid-character-in-node-name");
}
isXMLCharWF(fErrorHandler, fError, fLocator, pinode.getData(), fDocument.isXML11Version());
}
}
}
return null;
}
| protected Node normalizeNode (Node node){
int type = node.getNodeType();
boolean wellformed;
switch (type) {
case Node.DOCUMENT_TYPE_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{doctype}");
}
break;
}
case Node.ELEMENT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{element} "+node.getNodeName());
}
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0) &&
fDocument.isXMLVersionChanged()){
if(fNamespaceValidation){
wellformed = CoreDocumentImpl.isValidQName(node.getPrefix() , node.getLocalName(), fDocument.isXML11Version()) ;
}
else{
wellformed = CoreDocumentImpl.isXMLName(node.getNodeName() , fDocument.isXML11Version());
}
if (!wellformed){
String msg = DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"wf-invalid-character-in-node-name",
new Object[]{"Element", node.getNodeName()});
reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_ERROR, node,
"wf-invalid-character-in-node-name");
}
}
fNamespaceContext.pushContext();
fLocalNSBinder.reset();
ElementImpl elem = (ElementImpl)node;
if (elem.needsSyncChildren()) {
elem.synchronizeChildren();
}
AttributeMap attributes = (elem.hasAttributes()) ? (AttributeMap) elem.getAttributes() : null;
if ((fConfiguration.features & DOMConfigurationImpl.NAMESPACES) !=0) {
namespaceFixUp(elem, attributes);
} else {
if ( attributes!=null ) {
for ( int i=0; i<attributes.getLength(); ++i ) {
Attr attr = (Attr)attributes.item(i);
attr.normalize();
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0)){
isAttrValueWF(fErrorHandler, fError, fLocator, attributes, (AttrImpl)attr, attr.getValue(), fDocument.isXML11Version());
if (fDocument.isXMLVersionChanged()){
wellformed=CoreDocumentImpl.isXMLName(node.getNodeName() , fDocument.isXML11Version());
if (!wellformed){
String msg = DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"wf-invalid-character-in-node-name",
new Object[]{"Attr",node.getNodeName()});
reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_ERROR,
node, "wf-invalid-character-in-node-name");
}
}
}
}
}
}
if (fValidationHandler != null) {
fAttrProxy.setAttributes(attributes, fDocument, elem);
updateQName(elem, fQName);
fConfiguration.fErrorHandlerWrapper.fCurrentNode = node;
fCurrentNode = node;
fValidationHandler.startElement(fQName, fAttrProxy, null);
}
Node kid, next;
for (kid = elem.getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
kid = normalizeNode(kid);
if (kid !=null) {
next = kid;
}
}
if (DEBUG_ND) {
System.out.println("***The children of {"+node.getNodeName()+"} are normalized");
for (kid = elem.getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
System.out.println(kid.getNodeName() +"["+kid.getNodeValue()+"]");
}
}
if (fValidationHandler != null) {
updateQName(elem, fQName);
fConfiguration.fErrorHandlerWrapper.fCurrentNode = node;
fCurrentNode = node;
fValidationHandler.endElement(fQName, null);
}
fNamespaceContext.popContext();
break;
}
case Node.COMMENT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{comments}");
}
if ((fConfiguration.features & DOMConfigurationImpl.COMMENTS) == 0) {
Node prevSibling = node.getPreviousSibling();
Node parent = node.getParentNode();
parent.removeChild(node);
if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
Node nextSibling = prevSibling.getNextSibling();
if (nextSibling != null && nextSibling.getNodeType() == Node.TEXT_NODE) {
((TextImpl)nextSibling).insertData(0, prevSibling.getNodeValue());
parent.removeChild(prevSibling);
return nextSibling;
}
}
}
else {
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0)){
String commentdata = ((Comment)node).getData();
isCommentWF(fErrorHandler, fError, fLocator, commentdata, fDocument.isXML11Version());
}
}
break;
}
case Node.ENTITY_REFERENCE_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{entityRef} "+node.getNodeName());
}
if ((fConfiguration.features & DOMConfigurationImpl.ENTITIES) == 0) {
Node prevSibling = node.getPreviousSibling();
Node parent = node.getParentNode();
((EntityReferenceImpl)node).setReadOnly(false, true);
expandEntityRef (parent, node);
parent.removeChild(node);
Node next = (prevSibling != null)?prevSibling.getNextSibling():parent.getFirstChild();
if (prevSibling != null && next != null && prevSibling.getNodeType() == Node.TEXT_NODE &&
next.getNodeType() == Node.TEXT_NODE) {
return prevSibling;
}
return next;
} else {
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0) &&
fDocument.isXMLVersionChanged()){
CoreDocumentImpl.isXMLName(node.getNodeName() , fDocument.isXML11Version());
}
}
break;
}
case Node.CDATA_SECTION_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{cdata}");
}
if ((fConfiguration.features & DOMConfigurationImpl.CDATA) == 0) {
Node prevSibling = node.getPreviousSibling();
if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE){
((Text)prevSibling).appendData(node.getNodeValue());
node.getParentNode().removeChild(node);
return prevSibling;
}
else {
Text text = fDocument.createTextNode(node.getNodeValue());
Node parent = node.getParentNode();
node = parent.replaceChild(text, node);
return text;
}
}
if (fValidationHandler != null) {
fConfiguration.fErrorHandlerWrapper.fCurrentNode = node;
fCurrentNode = node;
fValidationHandler.startCDATA(null);
fValidationHandler.characterData(node.getNodeValue(), null);
fValidationHandler.endCDATA(null);
}
String value = node.getNodeValue();
if ((fConfiguration.features & DOMConfigurationImpl.SPLITCDATA) != 0) {
int index;
Node parent = node.getParentNode();
isXMLCharWF(fErrorHandler, fError, fLocator, node.getNodeValue(), fDocument.isXML11Version());
while ( (index=value.indexOf("]]>")) >= 0 ) {
node.setNodeValue(value.substring(0, index+2));
value = value.substring(index +2);
Node firstSplitNode = node;
Node newChild = fDocument.createCDATASection(value);
parent.insertBefore(newChild, node.getNextSibling());
node = newChild;
String msg = DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"cdata-sections-splitted",
null);
reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_WARNING,
firstSplitNode, "cdata-sections-splitted");
}
}
else {
isCDataWF(fErrorHandler, fError, fLocator, value, fDocument.isXML11Version());
}
break;
}
case Node.TEXT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode(text):{"+node.getNodeValue()+"}");
}
Node next = node.getNextSibling();
if ( next!=null && next.getNodeType() == Node.TEXT_NODE ) {
((Text)node).appendData(next.getNodeValue());
node.getParentNode().removeChild( next );
return node;
} else if (node.getNodeValue().length()==0) {
node.getParentNode().removeChild( node );
} else {
short nextType = (next != null)?next.getNodeType():-1;
if (nextType == -1 || !(((fConfiguration.features & DOMConfigurationImpl.ENTITIES) == 0 &&
nextType == Node.ENTITY_NODE) ||
((fConfiguration.features & DOMConfigurationImpl.COMMENTS) == 0 &&
nextType == Node.COMMENT_NODE) ||
((fConfiguration.features & DOMConfigurationImpl.CDATA) == 0) &&
nextType == Node.CDATA_SECTION_NODE)) {
if ( ((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0) ){
isXMLCharWF(fErrorHandler, fError, fLocator, node.getNodeValue(), fDocument.isXML11Version());
}
if (fValidationHandler != null) {
fConfiguration.fErrorHandlerWrapper.fCurrentNode = node;
fCurrentNode = node;
fValidationHandler.characterData(node.getNodeValue(), null);
if (DEBUG_ND) {
System.out.println("=====>characterData(),"+nextType);
}
}
}
else {
if (DEBUG_ND) {
System.out.println("=====>don't send characters(),"+nextType);
}
}
}
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
if((fConfiguration.features & DOMConfigurationImpl.WELLFORMED) != 0 ){
ProcessingInstruction pinode = (ProcessingInstruction)node ;
String target = pinode.getTarget();
if(fDocument.isXML11Version()){
wellformed = XML11Char.isXML11ValidName(target);
}
else{
wellformed = XMLChar.isValidName(target);
}
if (!wellformed) {
String msg = DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"wf-invalid-character-in-node-name",
new Object[]{"Element", node.getNodeName()});
reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_ERROR, null,
"wf-invalid-character-in-node-name");
}
isXMLCharWF(fErrorHandler, fError, fLocator, pinode.getData(), fDocument.isXML11Version());
}
}
}
return null;
}
|
public void timerExpired(Object callbackData) {
State newState = state;
switch (state) {
case STATE_DOOR_CLOSING:
localDoorMotor.set(DoorCommand.NUDGE);
mDoorMotorCommand.set(DoorCommand.NUDGE);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
if (((networkAtFloorArray.getCurrentFloor() == mDesiredFloor.getFloor())
&& (Speed.isStopOrLevel(mDriveSpeed.getSpeed()) || (mDriveSpeed.getDirection() == Direction.STOP)))
|| ((mCarWeight.getWeight() >= Elevator.MaxCarCapacity)
&& (mDoorOpened.getValue() == false))
|| ((mDoorReversal.getValue() == true)
&& (mDoorOpened.getValue() == false))
) {
newState = State.STATE_DOOR_OPENING;
} else if (mDoorClosed.getValue() == true) {
newState = State.STATE_DOOR_CLOSED;
} else {
newState = state;
}
break;
case STATE_DOOR_CLOSED:
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
if (((networkAtFloorArray.getCurrentFloor() == mDesiredFloor.getFloor())
&& (Speed.isStopOrLevel(mDriveSpeed.getSpeed()) || (mDriveSpeed.getDirection() == Direction.STOP)))
|| ((mCarWeight.getWeight() >= Elevator.MaxCarCapacity)
&& (mDoorOpened.getValue() == false))
|| ((mDoorReversal.getValue() == true)
&& (mDoorOpened.getValue() == false))
) {
newState = State.STATE_DOOR_OPENING;
} else {
newState = state;
}
break;
case STATE_DOOR_OPENING:
localDoorMotor.set(DoorCommand.OPEN);
mDoorMotorCommand.set(DoorCommand.OPEN);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
if ((mDoorOpened.getValue() == true)
&& (mCarWeight.getWeight() < Elevator.MaxCarCapacity)
&& (mDoorReversal.getValue() == false)
) {
newState = State.STATE_DOOR_OPEN;
} else if ((mDoorOpened.getValue() == true)
&& ((mCarWeight.getWeight() >= Elevator.MaxCarCapacity)
|| (mDoorReversal.getValue() == true))
) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN:
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.subtract(countDown, period);
if (countDown.isLessThanOrEqual(SimTime.ZERO)) {
newState = State.STATE_DOOR_CLOSING;
} else if ((mCarWeight.getWeight() >= Elevator.MaxCarCapacity)
|| (mDoorReversal.getValue() == true)
) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN_E:
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
if ((mCarWeight.getWeight() < Elevator.MaxCarCapacity)
&& (mDoorReversal.getValue() == false)
) {
newState = State.STATE_DOOR_OPEN;
} else {
newState = state;
}
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
}
state = newState;
setState(STATE_KEY, newState.toString());
timer.start(period);
}
| public void timerExpired(Object callbackData) {
State newState = state;
switch (state) {
case STATE_DOOR_CLOSING:
localDoorMotor.set(DoorCommand.NUDGE);
mDoorMotorCommand.set(DoorCommand.NUDGE);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
if (((networkAtFloorArray.getCurrentFloor() == mDesiredFloor.getFloor())
&& (Speed.isStopOrLevel(mDriveSpeed.getSpeed()) || (mDriveSpeed.getDirection() == Direction.STOP))
&& (mDesiredFloor.getHallway() == hallway || mDesiredFloor.getHallway() == Hallway.BOTH))
|| ((mCarWeight.getWeight() >= Elevator.MaxCarCapacity)
&& (mDoorOpened.getValue() == false))
|| ((mDoorReversal.getValue() == true)
&& (mDoorOpened.getValue() == false))
) {
newState = State.STATE_DOOR_OPENING;
} else if (mDoorClosed.getValue() == true) {
newState = State.STATE_DOOR_CLOSED;
} else {
newState = state;
}
break;
case STATE_DOOR_CLOSED:
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
if (((networkAtFloorArray.getCurrentFloor() == mDesiredFloor.getFloor())
&& (Speed.isStopOrLevel(mDriveSpeed.getSpeed()) || (mDriveSpeed.getDirection() == Direction.STOP))
&& (mDesiredFloor.getHallway() == hallway || mDesiredFloor.getHallway() == Hallway.BOTH))
|| ((mCarWeight.getWeight() >= Elevator.MaxCarCapacity)
&& (mDoorOpened.getValue() == false))
|| ((mDoorReversal.getValue() == true)
&& (mDoorOpened.getValue() == false))
) {
newState = State.STATE_DOOR_OPENING;
} else {
newState = state;
}
break;
case STATE_DOOR_OPENING:
localDoorMotor.set(DoorCommand.OPEN);
mDoorMotorCommand.set(DoorCommand.OPEN);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
if ((mDoorOpened.getValue() == true)
&& (mCarWeight.getWeight() < Elevator.MaxCarCapacity)
&& (mDoorReversal.getValue() == false)
) {
newState = State.STATE_DOOR_OPEN;
} else if ((mDoorOpened.getValue() == true)
&& ((mCarWeight.getWeight() >= Elevator.MaxCarCapacity)
|| (mDoorReversal.getValue() == true))
) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN:
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.subtract(countDown, period);
if (countDown.isLessThanOrEqual(SimTime.ZERO)) {
newState = State.STATE_DOOR_CLOSING;
} else if ((mCarWeight.getWeight() >= Elevator.MaxCarCapacity)
|| (mDoorReversal.getValue() == true)
) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN_E:
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
if ((mCarWeight.getWeight() < Elevator.MaxCarCapacity)
&& (mDoorReversal.getValue() == false)
) {
newState = State.STATE_DOOR_OPEN;
} else {
newState = state;
}
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
}
state = newState;
setState(STATE_KEY, newState.toString());
timer.start(period);
}
|